4
0

handler.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. package api
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "encoding/pem"
  6. "fmt"
  7. "net/http"
  8. "github.com/go-chi/chi"
  9. "github.com/pkg/errors"
  10. "github.com/smallstep/certificates/acme"
  11. "github.com/smallstep/certificates/api"
  12. )
  13. func link(url, typ string) string {
  14. return fmt.Sprintf("<%s>;rel=\"%s\"", url, typ)
  15. }
  16. type payloadInfo struct {
  17. value []byte
  18. isPostAsGet bool
  19. isEmptyJSON bool
  20. }
  21. // payloadFromContext searches the context for a payload. Returns the payload
  22. // or an error.
  23. func payloadFromContext(ctx context.Context) (*payloadInfo, error) {
  24. val, ok := ctx.Value(acme.PayloadContextKey).(*payloadInfo)
  25. if !ok || val == nil {
  26. return nil, acme.ServerInternalErr(errors.Errorf("payload expected in request context"))
  27. }
  28. return val, nil
  29. }
  30. // New returns a new ACME API router.
  31. func New(acmeAuth acme.Interface) api.RouterHandler {
  32. return &Handler{acmeAuth}
  33. }
  34. // Handler is the ACME request handler.
  35. type Handler struct {
  36. Auth acme.Interface
  37. }
  38. // Route traffic and implement the Router interface.
  39. func (h *Handler) Route(r api.Router) {
  40. getLink := h.Auth.GetLinkExplicit
  41. // Standard ACME API
  42. r.MethodFunc("GET", getLink(acme.NewNonceLink, "{provisionerID}", false, nil), h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.GetNonce))))
  43. r.MethodFunc("HEAD", getLink(acme.NewNonceLink, "{provisionerID}", false, nil), h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.GetNonce))))
  44. r.MethodFunc("GET", getLink(acme.DirectoryLink, "{provisionerID}", false, nil), h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.GetDirectory))))
  45. r.MethodFunc("HEAD", getLink(acme.DirectoryLink, "{provisionerID}", false, nil), h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.GetDirectory))))
  46. extractPayloadByJWK := func(next nextHTTP) nextHTTP {
  47. return h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.addDirLink(h.verifyContentType(h.parseJWS(h.validateJWS(h.extractJWK(h.verifyAndExtractJWSPayload(next)))))))))
  48. }
  49. extractPayloadByKid := func(next nextHTTP) nextHTTP {
  50. return h.baseURLFromRequest(h.lookupProvisioner(h.addNonce(h.addDirLink(h.verifyContentType(h.parseJWS(h.validateJWS(h.lookupJWK(h.verifyAndExtractJWSPayload(next)))))))))
  51. }
  52. r.MethodFunc("POST", getLink(acme.NewAccountLink, "{provisionerID}", false, nil), extractPayloadByJWK(h.NewAccount))
  53. r.MethodFunc("POST", getLink(acme.AccountLink, "{provisionerID}", false, nil, "{accID}"), extractPayloadByKid(h.GetUpdateAccount))
  54. r.MethodFunc("POST", getLink(acme.KeyChangeLink, "{provisionerID}", false, nil, "{accID}"), extractPayloadByKid(h.NotImplemented))
  55. r.MethodFunc("POST", getLink(acme.NewOrderLink, "{provisionerID}", false, nil), extractPayloadByKid(h.NewOrder))
  56. r.MethodFunc("POST", getLink(acme.OrderLink, "{provisionerID}", false, nil, "{ordID}"), extractPayloadByKid(h.isPostAsGet(h.GetOrder)))
  57. r.MethodFunc("POST", getLink(acme.OrdersByAccountLink, "{provisionerID}", false, nil, "{accID}"), extractPayloadByKid(h.isPostAsGet(h.GetOrdersByAccount)))
  58. r.MethodFunc("POST", getLink(acme.FinalizeLink, "{provisionerID}", false, nil, "{ordID}"), extractPayloadByKid(h.FinalizeOrder))
  59. r.MethodFunc("POST", getLink(acme.AuthzLink, "{provisionerID}", false, nil, "{authzID}"), extractPayloadByKid(h.isPostAsGet(h.GetAuthz)))
  60. r.MethodFunc("POST", getLink(acme.ChallengeLink, "{provisionerID}", false, nil, "{chID}"), extractPayloadByKid(h.GetChallenge))
  61. r.MethodFunc("POST", getLink(acme.CertificateLink, "{provisionerID}", false, nil, "{certID}"), extractPayloadByKid(h.isPostAsGet(h.GetCertificate)))
  62. }
  63. // GetNonce just sets the right header since a Nonce is added to each response
  64. // by middleware by default.
  65. func (h *Handler) GetNonce(w http.ResponseWriter, r *http.Request) {
  66. if r.Method == "HEAD" {
  67. w.WriteHeader(http.StatusOK)
  68. } else {
  69. w.WriteHeader(http.StatusNoContent)
  70. }
  71. }
  72. // GetDirectory is the ACME resource for returning a directory configuration
  73. // for client configuration.
  74. func (h *Handler) GetDirectory(w http.ResponseWriter, r *http.Request) {
  75. dir, err := h.Auth.GetDirectory(r.Context())
  76. if err != nil {
  77. api.WriteError(w, err)
  78. return
  79. }
  80. api.JSON(w, dir)
  81. }
  82. // NotImplemented returns a 501 and is generally a placeholder for functionality which
  83. // MAY be added at some point in the future but is not in any way a guarantee of such.
  84. func (h *Handler) NotImplemented(w http.ResponseWriter, r *http.Request) {
  85. api.WriteError(w, acme.NotImplemented(nil).ToACME())
  86. }
  87. // GetAuthz ACME api for retrieving an Authz.
  88. func (h *Handler) GetAuthz(w http.ResponseWriter, r *http.Request) {
  89. acc, err := acme.AccountFromContext(r.Context())
  90. if err != nil {
  91. api.WriteError(w, err)
  92. return
  93. }
  94. authz, err := h.Auth.GetAuthz(r.Context(), acc.GetID(), chi.URLParam(r, "authzID"))
  95. if err != nil {
  96. api.WriteError(w, err)
  97. return
  98. }
  99. w.Header().Set("Location", h.Auth.GetLink(r.Context(), acme.AuthzLink, true, authz.GetID()))
  100. api.JSON(w, authz)
  101. }
  102. // GetChallenge ACME api for retrieving a Challenge.
  103. func (h *Handler) GetChallenge(w http.ResponseWriter, r *http.Request) {
  104. acc, err := acme.AccountFromContext(r.Context())
  105. if err != nil {
  106. api.WriteError(w, err)
  107. return
  108. }
  109. // Just verify that the payload was set, since we're not strictly adhering
  110. // to ACME V2 spec for reasons specified below.
  111. _, err = payloadFromContext(r.Context())
  112. if err != nil {
  113. api.WriteError(w, err)
  114. return
  115. }
  116. // NOTE: We should be checking that the request is either a POST-as-GET, or
  117. // that the payload is an empty JSON block ({}). However, older ACME clients
  118. // still send a vestigial body (rather than an empty JSON block) and
  119. // strict enforcement would render these clients broken. For the time being
  120. // we'll just ignore the body.
  121. var (
  122. ch *acme.Challenge
  123. chID = chi.URLParam(r, "chID")
  124. )
  125. ch, err = h.Auth.ValidateChallenge(r.Context(), acc.GetID(), chID, acc.GetKey())
  126. if err != nil {
  127. api.WriteError(w, err)
  128. return
  129. }
  130. w.Header().Add("Link", link(h.Auth.GetLink(r.Context(), acme.AuthzLink, true, ch.GetAuthzID()), "up"))
  131. w.Header().Set("Location", h.Auth.GetLink(r.Context(), acme.ChallengeLink, true, ch.GetID()))
  132. api.JSON(w, ch)
  133. }
  134. // GetCertificate ACME api for retrieving a Certificate.
  135. func (h *Handler) GetCertificate(w http.ResponseWriter, r *http.Request) {
  136. acc, err := acme.AccountFromContext(r.Context())
  137. if err != nil {
  138. api.WriteError(w, err)
  139. return
  140. }
  141. certID := chi.URLParam(r, "certID")
  142. certBytes, err := h.Auth.GetCertificate(acc.GetID(), certID)
  143. if err != nil {
  144. api.WriteError(w, err)
  145. return
  146. }
  147. block, _ := pem.Decode(certBytes)
  148. if block == nil {
  149. api.WriteError(w, acme.ServerInternalErr(errors.New("failed to decode any certificates from generated certBytes")))
  150. return
  151. }
  152. cert, err := x509.ParseCertificate(block.Bytes)
  153. if err != nil {
  154. api.WriteError(w, acme.Wrap(err, "failed to parse generated leaf certificate"))
  155. return
  156. }
  157. api.LogCertificate(w, cert)
  158. w.Header().Set("Content-Type", "application/pem-certificate-chain; charset=utf-8")
  159. w.Write(certBytes)
  160. }