acme.go 7.6 KB

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