diff --git a/authority/admin/db.go b/authority/admin/db.go index bf34a3c2..2da1a59a 100644 --- a/authority/admin/db.go +++ b/authority/admin/db.go @@ -71,6 +71,29 @@ type DB interface { DeleteAdmin(ctx context.Context, id string) error } +type dbKey struct{} + +// NewContext adds the given admin database to the context. +func NewContext(ctx context.Context, db DB) context.Context { + return context.WithValue(ctx, dbKey{}, db) +} + +// FromContext returns the current admin database from the given context. +func FromContext(ctx context.Context) (db DB, ok bool) { + db, ok = ctx.Value(dbKey{}).(DB) + return +} + +// MustFromContext returns the current admin database from the given context. It +// will panic if it's not in the context. +func MustFromContext(ctx context.Context) DB { + if db, ok := FromContext(ctx); !ok { + panic("admin database is not in the context") + } else { + return db + } +} + // MockDB is an implementation of the DB interface that should only be used as // a mock in tests. type MockDB struct { diff --git a/ca/ca.go b/ca/ca.go index 795fa77a..2df52555 100644 --- a/ca/ca.go +++ b/ca/ca.go @@ -20,6 +20,7 @@ import ( acmeNoSQL "github.com/smallstep/certificates/acme/db/nosql" "github.com/smallstep/certificates/api" "github.com/smallstep/certificates/authority" + "github.com/smallstep/certificates/authority/admin" adminAPI "github.com/smallstep/certificates/authority/admin/api" "github.com/smallstep/certificates/authority/config" "github.com/smallstep/certificates/db" @@ -280,7 +281,7 @@ func (ca *CA) Init(cfg *config.Config) (*CA, error) { insecureHandler = logger.Middleware(insecureHandler) } - // Add authority handler + // Create context with all the necessary values. baseContext := buildContext(auth) ca.srv = server.New(cfg.Address, handler, tlsConfig) @@ -304,9 +305,14 @@ func (ca *CA) Init(cfg *config.Config) (*CA, error) { return ca, nil } +// buildContext builds the server base context. func buildContext(a *authority.Authority) context.Context { ctx := authority.NewContext(context.Background(), a) + if db := a.GetAdminDatabase(); db != nil { + ctx = admin.NewContext(ctx, db) + } + return ctx }