handler.go 6.4 KB

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