Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Protect admin api #145

Merged
merged 2 commits into from
Oct 1, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion Documentation/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,24 @@ dex needs a 32 byte base64-encoded key which will be used to encrypt the private

The dex overlord and workers allow multiple key secrets (separated by commas) to be passed but only the first will be used to encrypt data; the rest are there for decryption only; this scheme allows for the rotation of keys without downtime (assuming a rolling restart of workers).

# Generate an Admin API Secret

The dex overlord has a an API which is very powerful - you can create Admin users with it, so it needs to be protected somehow. This is accomplished by requiring that a secret is passed via the Authorization header of each request. This secret is 128 bytes base64 encoded, and should be sufficiently random so as to make guessing impractical:

`DEX_OVERLORD_ADMIN_API_SECRET=$(dd if=/dev/random bs=1 count=128 2>/dev/null | base64)`

# Start the overlord

The overlord is responsible for creating and rotating keys and some other adminsitrative tasks. In addition, the overlord is responsible for creating the necessary database tables (and when you update, performing schema migrations), so it must be started before we do anything else. Debug logging is turned on so we can see more of what's going on. Start it up.

`./bin/dex-overlord --db-url=$DEX_DB_URL --key-secrets=$DEX_KEY_SECRET --log-debug=true &`
`./bin/dex-overlord --admin-api-secret=$DEX_OVERLORD_ADMIN_API_SECRET --db-url=$DEX_DB_URL --key-secrets=$DEX_KEY_SECRET --log-debug=true &`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do the arguments need to be specified if the env variables are named DEX_OVERLORD_*?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nope, I'm just showing how it works with flags here. I talk about env var equivalency later.


## Environment Variables.

Note that parameters can be passed as flags or environment variables to dex components; an equivalent start with environment variables would be:

```
export DEX_OVERLORD_ADMIN_API_SECRET=$DEX_OVERLORD_ADMIN_API_SECRET
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line is redundant, it just sets the env variable to it's current value.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes but it wasn't exported before.

export DEX_OVERLORD_DB_URL=$DEX_DB_URL
export DEX_OVERLORD_KEY_SECRETS=$DEX_KEY_SECRET
export DEX_OVERLORD_LOG_DEBUG=true
Expand Down
5 changes: 4 additions & 1 deletion cmd/dex-overlord/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ func main() {

adminListen := fs.String("admin-listen", "http://127.0.0.1:5557", "scheme, host and port for listening for administrative operation requests ")

adminAPISecret := pflag.NewBase64(server.AdminAPISecretLength)
fs.Var(adminAPISecret, "admin-api-secret", fmt.Sprintf("A base64-encoded %d byte string which is used to protect the Admin API.", server.AdminAPISecretLength))

localConnectorID := fs.String("local-connector", "local", "ID of the local connector")
logDebug := fs.Bool("log-debug", false, "log debug-level information")
logTimestamps := fs.Bool("log-timestamps", false, "prefix log lines with timestamps")
Expand Down Expand Up @@ -124,7 +127,7 @@ func main() {
}

krot := key.NewPrivateKeyRotator(kRepo, *keyPeriod)
s := server.NewAdminServer(adminAPI, krot)
s := server.NewAdminServer(adminAPI, krot, adminAPISecret.String())
h := s.HTTPHandler()
httpsrv := &http.Server{
Addr: adminURL.Host,
Expand Down
3 changes: 2 additions & 1 deletion contrib/standup-db.sh
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ DEX_KEY_SECRET=$(dd if=/dev/random bs=1 count=32 2>/dev/null | base64)
export DEX_OVERLORD_DB_URL=$DEX_DB_URL
export DEX_OVERLORD_KEY_SECRETS=$DEX_KEY_SECRET
export DEX_OVERLORD_KEY_PERIOD=1h
export DEX_OVERLORD_ADMIN_API_SECRET=$(dd if=/dev/random bs=1 count=128 2>/dev/null | base64)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You might want to set this up by DEX_KEY_SECRET, both for consistency and to allow users to specify their own known secrets if they ever want to use the API themselves.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a method to my madness. I set the DEX_KEY_SECRET over by itself because it is shared.

Then for each binary, I set the environment variables close to where the binary is invoked; I think it's more useful there, because it shows in a glance all the things one needs to start up an overlord or worker.

./bin/dex-overlord &
echo "Waiting for overlord to start..."
until $(curl --output /dev/null --silent --fail http://localhost:5557/health); do
Expand Down Expand Up @@ -79,5 +80,5 @@ done
./bin/example-app --client-id=$DEX_APP_CLIENT_ID --client-secret=$DEX_APP_CLIENT_SECRET --discovery=http://127.0.0.1:5556 &

# Create Admin User - the password is a hash of the word "password"
curl -X POST --data '{"email":"[email protected]","password":"$2a$04$J54iz31fhYfXIRVglUMmpufY6TKf/vvwc9pv8zWog7X/LFrFfkNQe" }' http://127.0.0.1:5557/api/v1/admin
curl -X POST --data '{"email":"[email protected]","password":"$2a$04$J54iz31fhYfXIRVglUMmpufY6TKf/vvwc9pv8zWog7X/LFrFfkNQe" }' --header "Authorization: $DEX_OVERLORD_ADMIN_API_SECRET" http://127.0.0.1:5557/api/v1/admin

35 changes: 33 additions & 2 deletions integration/admin_api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ import (
"github.com/coreos/dex/user"
)

const (
adminAPITestSecret = "admin_secret"
)

type adminAPITestFixtures struct {
ur user.UserRepo
pwr user.PasswordInfoRepo
Expand Down Expand Up @@ -58,16 +62,29 @@ var (
}
)

type adminAPITransport struct {
secret string
}

func (a *adminAPITransport) RoundTrip(r *http.Request) (*http.Response, error) {
r.Header.Set("Authorization", a.secret)
return http.DefaultTransport.RoundTrip(r)
}

func makeAdminAPITestFixtures() *adminAPITestFixtures {
f := &adminAPITestFixtures{}

ur, pwr, um := makeUserObjects(adminUsers, adminPasswords)
f.ur = ur
f.pwr = pwr
f.adAPI = admin.NewAdminAPI(um, f.ur, f.pwr, "local")
f.adSrv = server.NewAdminServer(f.adAPI, nil)
f.adSrv = server.NewAdminServer(f.adAPI, nil, adminAPITestSecret)
f.hSrv = httptest.NewServer(f.adSrv.HTTPHandler())
f.hc = &http.Client{}
f.hc = &http.Client{
Transport: &adminAPITransport{
secret: adminAPITestSecret,
},
}
f.adClient, _ = adminschema.NewWithBasePath(f.hc, f.hSrv.URL)

return f
Expand Down Expand Up @@ -129,6 +146,7 @@ func TestCreateAdmin(t *testing.T) {
tests := []struct {
admn *adminschema.Admin
errCode int
secret string
}{
{
admn: &adminschema.Admin{
Expand All @@ -137,6 +155,14 @@ func TestCreateAdmin(t *testing.T) {
},
errCode: -1,
},
{
admn: &adminschema.Admin{
Email: "[email protected]",
Password: "foopass",
},
errCode: http.StatusUnauthorized,
secret: "bad_secret",
},
{
// duplicate Email
admn: &adminschema.Admin{
Expand All @@ -156,6 +182,11 @@ func TestCreateAdmin(t *testing.T) {
for i, tt := range tests {
func() {
f := makeAdminAPITestFixtures()
if tt.secret != "" {
f.hc.Transport = &adminAPITransport{
secret: tt.secret,
}
}
defer f.close()

admn, err := f.adClient.Admin.Create(tt.admn).Do()
Expand Down
27 changes: 24 additions & 3 deletions server/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import (
)

const (
AdminAPIVersion = "v1"
AdminAPIVersion = "v1"
AdminAPISecretLength = 128
)

var (
Expand All @@ -28,16 +29,18 @@ var (
type AdminServer struct {
adminAPI *admin.AdminAPI
checker health.Checker
secret string
}

func NewAdminServer(adminAPI *admin.AdminAPI, rotator *key.PrivateKeyRotator) *AdminServer {
func NewAdminServer(adminAPI *admin.AdminAPI, rotator *key.PrivateKeyRotator, secret string) *AdminServer {
return &AdminServer{
adminAPI: adminAPI,
checker: health.Checker{
Checks: []health.Checkable{
rotator,
},
},
secret: secret,
}
}

Expand All @@ -48,7 +51,25 @@ func (s *AdminServer) HTTPHandler() http.Handler {
r.GET(AdminGetStateEndpoint, s.getState)
r.Handler("GET", httpPathHealth, s.checker)
r.HandlerFunc("GET", httpPathDebugVars, health.ExpvarHandler)
return r

return authorizer(r, s.secret, httpPathHealth, httpPathDebugVars)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a nice "middleware" approach to auth!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks! I originally had a "authorize()" call in each method, then re-did it this way because I knew I was being lazy :)

}

func authorizer(h http.Handler, secret string, public ...string) http.Handler {
publicSet := map[string]struct{}{}
for _, p := range public {
publicSet[p] = struct{}{}
}

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, isPublicPath := publicSet[r.URL.Path]

if !isPublicPath && r.Header.Get("Authorization") != secret {
writeAPIError(w, http.StatusUnauthorized, newAPIError(errorAccessDenied, ""))
return
}
h.ServeHTTP(w, r)
})
}

func (s *AdminServer) getAdmin(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
Expand Down