4
0

handler.go 7.3 KB

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