acme.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. package api
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "github.com/go-chi/chi"
  8. "github.com/smallstep/certificates/acme"
  9. "github.com/smallstep/certificates/api"
  10. "github.com/smallstep/certificates/authority/admin"
  11. "github.com/smallstep/certificates/authority/provisioner"
  12. "go.step.sm/linkedca"
  13. "google.golang.org/protobuf/types/known/timestamppb"
  14. )
  15. const (
  16. // provisionerContextKey provisioner key
  17. provisionerContextKey = ContextKey("provisioner")
  18. )
  19. // CreateExternalAccountKeyRequest is the type for POST /admin/acme/eab requests
  20. type CreateExternalAccountKeyRequest struct {
  21. Reference string `json:"reference"`
  22. }
  23. // Validate validates a new ACME EAB Key request body.
  24. func (r *CreateExternalAccountKeyRequest) Validate() error {
  25. if len(r.Reference) > 256 { // an arbitrary, but sensible (IMO), limit
  26. return fmt.Errorf("reference length %d exceeds the maximum (256)", len(r.Reference))
  27. }
  28. return nil
  29. }
  30. // GetExternalAccountKeysResponse is the type for GET /admin/acme/eab responses
  31. type GetExternalAccountKeysResponse struct {
  32. EAKs []*linkedca.EABKey `json:"eaks"`
  33. NextCursor string `json:"nextCursor"`
  34. }
  35. // requireEABEnabled is a middleware that ensures ACME EAB is enabled
  36. // before serving requests that act on ACME EAB credentials.
  37. func (h *Handler) requireEABEnabled(next nextHTTP) nextHTTP {
  38. return func(w http.ResponseWriter, r *http.Request) {
  39. ctx := r.Context()
  40. provName := chi.URLParam(r, "provisionerName")
  41. eabEnabled, prov, err := h.provisionerHasEABEnabled(ctx, provName)
  42. if err != nil {
  43. api.WriteError(w, err)
  44. return
  45. }
  46. if !eabEnabled {
  47. api.WriteError(w, admin.NewError(admin.ErrorBadRequestType, "ACME EAB not enabled for provisioner %s", prov.GetName()))
  48. return
  49. }
  50. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  51. next(w, r.WithContext(ctx))
  52. }
  53. }
  54. // provisionerHasEABEnabled determines if the "requireEAB" setting for an ACME
  55. // provisioner is set to true and thus has EAB enabled.
  56. func (h *Handler) provisionerHasEABEnabled(ctx context.Context, provisionerName string) (bool, *linkedca.Provisioner, error) {
  57. var (
  58. p provisioner.Interface
  59. err error
  60. )
  61. if p, err = h.auth.LoadProvisionerByName(provisionerName); err != nil {
  62. return false, nil, admin.WrapErrorISE(err, "error loading provisioner %s", provisionerName)
  63. }
  64. prov, err := h.db.GetProvisioner(ctx, p.GetID())
  65. if err != nil {
  66. return false, nil, admin.WrapErrorISE(err, "error getting provisioner with ID: %s", p.GetID())
  67. }
  68. details := prov.GetDetails()
  69. if details == nil {
  70. return false, nil, admin.NewErrorISE("error getting details for provisioner with ID: %s", p.GetID())
  71. }
  72. acmeProvisioner := details.GetACME()
  73. if acmeProvisioner == nil {
  74. return false, nil, admin.NewErrorISE("error getting ACME details for provisioner with ID: %s", p.GetID())
  75. }
  76. return acmeProvisioner.GetRequireEab(), prov, nil
  77. }
  78. // provisionerFromContext searches the context for a provisioner. Returns the
  79. // provisioner or an error.
  80. func provisionerFromContext(ctx context.Context) (*linkedca.Provisioner, error) {
  81. val := ctx.Value(provisionerContextKey)
  82. if val == nil {
  83. return nil, admin.NewErrorISE("provisioner expected in request context")
  84. }
  85. pval, ok := val.(*linkedca.Provisioner)
  86. if !ok || pval == nil {
  87. return nil, admin.NewErrorISE("provisioner in context is not a linkedca.Provisioner")
  88. }
  89. return pval, nil
  90. }
  91. // CreateExternalAccountKey creates a new External Account Binding key
  92. func (h *Handler) CreateExternalAccountKey(w http.ResponseWriter, r *http.Request) {
  93. var body CreateExternalAccountKeyRequest
  94. if err := api.ReadJSON(r.Body, &body); err != nil {
  95. api.WriteError(w, admin.WrapError(admin.ErrorBadRequestType, err, "error reading request body"))
  96. return
  97. }
  98. if err := body.Validate(); err != nil {
  99. api.WriteError(w, admin.WrapError(admin.ErrorBadRequestType, err, "error validating request body"))
  100. return
  101. }
  102. ctx := r.Context()
  103. prov, err := provisionerFromContext(ctx)
  104. if err != nil {
  105. api.WriteError(w, admin.WrapErrorISE(err, "error getting provisioner from context"))
  106. return
  107. }
  108. // check if a key with the reference does not exist (only when a reference was in the request)
  109. reference := body.Reference
  110. if reference != "" {
  111. k, err := h.acmeDB.GetExternalAccountKeyByReference(ctx, prov.GetId(), reference)
  112. // retrieving an EAB key from DB results in an error if it doesn't exist, which is what we're looking for,
  113. // but other errors can also happen. Return early if that happens; continuing if it was acme.ErrNotFound.
  114. if shouldWriteError := err != nil && !errors.Is(err, acme.ErrNotFound); shouldWriteError {
  115. api.WriteError(w, admin.WrapErrorISE(err, "could not lookup external account key by reference"))
  116. return
  117. }
  118. // if a key was found, return HTTP 409 conflict
  119. if k != nil {
  120. err := admin.NewError(admin.ErrorBadRequestType, "an ACME EAB key for provisioner '%s' with reference '%s' already exists", prov.GetName(), reference)
  121. err.Status = 409
  122. api.WriteError(w, err)
  123. return
  124. }
  125. // continue execution if no key was found for the reference
  126. }
  127. eak, err := h.acmeDB.CreateExternalAccountKey(ctx, prov.GetId(), reference)
  128. if err != nil {
  129. msg := fmt.Sprintf("error creating ACME EAB key for provisioner '%s'", prov.GetName())
  130. if reference != "" {
  131. msg += fmt.Sprintf(" and reference '%s'", reference)
  132. }
  133. api.WriteError(w, admin.WrapErrorISE(err, msg))
  134. return
  135. }
  136. response := &linkedca.EABKey{
  137. Id: eak.ID,
  138. HmacKey: eak.KeyBytes,
  139. Provisioner: prov.GetName(),
  140. Reference: eak.Reference,
  141. }
  142. api.ProtoJSONStatus(w, response, http.StatusCreated)
  143. }
  144. // DeleteExternalAccountKey deletes an ACME External Account Key.
  145. func (h *Handler) DeleteExternalAccountKey(w http.ResponseWriter, r *http.Request) {
  146. keyID := chi.URLParam(r, "id")
  147. ctx := r.Context()
  148. prov, err := provisionerFromContext(ctx)
  149. if err != nil {
  150. api.WriteError(w, admin.WrapErrorISE(err, "error getting provisioner from context"))
  151. return
  152. }
  153. if err := h.acmeDB.DeleteExternalAccountKey(ctx, prov.GetId(), keyID); err != nil {
  154. api.WriteError(w, admin.WrapErrorISE(err, "error deleting ACME EAB Key '%s'", keyID))
  155. return
  156. }
  157. api.JSON(w, &DeleteResponse{Status: "ok"})
  158. }
  159. // GetExternalAccountKeys returns ACME EAB Keys. If a reference is specified,
  160. // only the ExternalAccountKey with that reference is returned. Otherwise all
  161. // ExternalAccountKeys in the system for a specific provisioner are returned.
  162. func (h *Handler) GetExternalAccountKeys(w http.ResponseWriter, r *http.Request) {
  163. var (
  164. key *acme.ExternalAccountKey
  165. keys []*acme.ExternalAccountKey
  166. err error
  167. cursor string
  168. nextCursor string
  169. limit int
  170. )
  171. ctx := r.Context()
  172. prov, err := provisionerFromContext(ctx)
  173. if err != nil {
  174. api.WriteError(w, admin.WrapErrorISE(err, "error getting provisioner from context"))
  175. return
  176. }
  177. if cursor, limit, err = api.ParseCursor(r); err != nil {
  178. api.WriteError(w, admin.WrapError(admin.ErrorBadRequestType, err,
  179. "error parsing cursor and limit from query params"))
  180. return
  181. }
  182. reference := chi.URLParam(r, "reference")
  183. if reference != "" {
  184. if key, err = h.acmeDB.GetExternalAccountKeyByReference(ctx, prov.GetId(), reference); err != nil {
  185. api.WriteError(w, admin.WrapErrorISE(err, "error retrieving external account key with reference '%s'", reference))
  186. return
  187. }
  188. if key != nil {
  189. keys = []*acme.ExternalAccountKey{key}
  190. }
  191. } else {
  192. if keys, nextCursor, err = h.acmeDB.GetExternalAccountKeys(ctx, prov.GetId(), cursor, limit); err != nil {
  193. api.WriteError(w, admin.WrapErrorISE(err, "error retrieving external account keys"))
  194. return
  195. }
  196. }
  197. provisionerName := prov.GetName()
  198. eaks := make([]*linkedca.EABKey, len(keys))
  199. for i, k := range keys {
  200. eaks[i] = &linkedca.EABKey{
  201. Id: k.ID,
  202. HmacKey: []byte{},
  203. Provisioner: provisionerName,
  204. Reference: k.Reference,
  205. Account: k.AccountID,
  206. CreatedAt: timestamppb.New(k.CreatedAt),
  207. BoundAt: timestamppb.New(k.BoundAt),
  208. }
  209. }
  210. api.JSON(w, &GetExternalAccountKeysResponse{
  211. EAKs: eaks,
  212. NextCursor: nextCursor,
  213. })
  214. }