4
0

middleware.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. package api
  2. import (
  3. "context"
  4. "crypto/rsa"
  5. "errors"
  6. "io"
  7. "net/http"
  8. "net/url"
  9. "path"
  10. "slices"
  11. "strings"
  12. "go.step.sm/crypto/jose"
  13. "go.step.sm/crypto/keyutil"
  14. "github.com/smallstep/certificates/acme"
  15. "github.com/smallstep/certificates/api/render"
  16. "github.com/smallstep/certificates/authority/provisioner"
  17. "github.com/smallstep/certificates/logging"
  18. )
  19. type nextHTTP = func(http.ResponseWriter, *http.Request)
  20. func logNonce(w http.ResponseWriter, nonce string) {
  21. if rl, ok := w.(logging.ResponseLogger); ok {
  22. m := map[string]any{
  23. "nonce": nonce,
  24. }
  25. rl.WithFields(m)
  26. }
  27. }
  28. // addNonce is a middleware that adds a nonce to the response header.
  29. func addNonce(next nextHTTP) nextHTTP {
  30. return func(w http.ResponseWriter, r *http.Request) {
  31. db := acme.MustDatabaseFromContext(r.Context())
  32. nonce, err := db.CreateNonce(r.Context())
  33. if err != nil {
  34. render.Error(w, r, err)
  35. return
  36. }
  37. w.Header().Set("Replay-Nonce", string(nonce))
  38. w.Header().Set("Cache-Control", "no-store")
  39. logNonce(w, string(nonce))
  40. next(w, r)
  41. }
  42. }
  43. // addDirLink is a middleware that adds a 'Link' response reader with the
  44. // directory index url.
  45. func addDirLink(next nextHTTP) nextHTTP {
  46. return func(w http.ResponseWriter, r *http.Request) {
  47. ctx := r.Context()
  48. linker := acme.MustLinkerFromContext(ctx)
  49. w.Header().Add("Link", link(linker.GetLink(ctx, acme.DirectoryLinkType), "index"))
  50. next(w, r)
  51. }
  52. }
  53. // verifyContentType is a middleware that verifies that content type is
  54. // application/jose+json.
  55. func verifyContentType(next nextHTTP) nextHTTP {
  56. return func(w http.ResponseWriter, r *http.Request) {
  57. p, err := provisionerFromContext(r.Context())
  58. if err != nil {
  59. render.Error(w, r, err)
  60. return
  61. }
  62. u := &url.URL{
  63. Path: acme.GetUnescapedPathSuffix(acme.CertificateLinkType, p.GetName(), ""),
  64. }
  65. var expected []string
  66. if strings.Contains(r.URL.String(), u.EscapedPath()) {
  67. // GET /certificate requests allow a greater range of content types.
  68. expected = []string{"application/jose+json", "application/pkix-cert", "application/pkcs7-mime"}
  69. } else {
  70. // By default every request should have content-type application/jose+json.
  71. expected = []string{"application/jose+json"}
  72. }
  73. ct := r.Header.Get("Content-Type")
  74. if slices.Contains(expected, ct) {
  75. next(w, r)
  76. return
  77. }
  78. render.Error(w, r, acme.NewError(acme.ErrorMalformedType,
  79. "expected content-type to be in %s, but got %s", expected, ct))
  80. }
  81. }
  82. // parseJWS is a middleware that parses a request body into a JSONWebSignature struct.
  83. func parseJWS(next nextHTTP) nextHTTP {
  84. return func(w http.ResponseWriter, r *http.Request) {
  85. body, err := io.ReadAll(r.Body)
  86. if err != nil {
  87. render.Error(w, r, acme.WrapErrorISE(err, "failed to read request body"))
  88. return
  89. }
  90. jws, err := jose.ParseJWS(string(body))
  91. if err != nil {
  92. render.Error(w, r, acme.WrapError(acme.ErrorMalformedType, err, "failed to parse JWS from request body"))
  93. return
  94. }
  95. ctx := context.WithValue(r.Context(), jwsContextKey, jws)
  96. next(w, r.WithContext(ctx))
  97. }
  98. }
  99. // validateJWS checks the request body for to verify that it meets ACME
  100. // requirements for a JWS.
  101. //
  102. // The JWS MUST NOT have multiple signatures
  103. // The JWS Unencoded Payload Option [RFC7797] MUST NOT be used
  104. // The JWS Unprotected Header [RFC7515] MUST NOT be used
  105. // The JWS Payload MUST NOT be detached
  106. // The JWS Protected Header MUST include the following fields:
  107. // - “alg” (Algorithm).
  108. // This field MUST NOT contain “none” or a Message Authentication Code
  109. // (MAC) algorithm (e.g. one in which the algorithm registry description
  110. // mentions MAC/HMAC).
  111. // - “nonce” (defined in Section 6.5)
  112. // - “url” (defined in Section 6.4)
  113. // - Either “jwk” (JSON Web Key) or “kid” (Key ID) as specified below<Paste>
  114. func validateJWS(next nextHTTP) nextHTTP {
  115. return func(w http.ResponseWriter, r *http.Request) {
  116. ctx := r.Context()
  117. db := acme.MustDatabaseFromContext(ctx)
  118. jws, err := jwsFromContext(ctx)
  119. if err != nil {
  120. render.Error(w, r, err)
  121. return
  122. }
  123. if len(jws.Signatures) == 0 {
  124. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "request body does not contain a signature"))
  125. return
  126. }
  127. if len(jws.Signatures) > 1 {
  128. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "request body contains more than one signature"))
  129. return
  130. }
  131. sig := jws.Signatures[0]
  132. uh := sig.Unprotected
  133. if uh.KeyID != "" ||
  134. uh.JSONWebKey != nil ||
  135. uh.Algorithm != "" ||
  136. uh.Nonce != "" ||
  137. len(uh.ExtraHeaders) > 0 {
  138. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "unprotected header must not be used"))
  139. return
  140. }
  141. hdr := sig.Protected
  142. switch hdr.Algorithm {
  143. case jose.RS256, jose.RS384, jose.RS512, jose.PS256, jose.PS384, jose.PS512:
  144. if hdr.JSONWebKey != nil {
  145. switch k := hdr.JSONWebKey.Key.(type) {
  146. case *rsa.PublicKey:
  147. if k.Size() < keyutil.MinRSAKeyBytes {
  148. render.Error(w, r, acme.NewError(acme.ErrorMalformedType,
  149. "rsa keys must be at least %d bits (%d bytes) in size",
  150. 8*keyutil.MinRSAKeyBytes, keyutil.MinRSAKeyBytes))
  151. return
  152. }
  153. default:
  154. render.Error(w, r, acme.NewError(acme.ErrorMalformedType,
  155. "jws key type and algorithm do not match"))
  156. return
  157. }
  158. }
  159. case jose.ES256, jose.ES384, jose.ES512, jose.EdDSA:
  160. // we good
  161. default:
  162. render.Error(w, r, acme.NewError(acme.ErrorBadSignatureAlgorithmType, "unsuitable algorithm: %s", hdr.Algorithm))
  163. return
  164. }
  165. // Check the validity/freshness of the Nonce.
  166. if err := db.DeleteNonce(ctx, acme.Nonce(hdr.Nonce)); err != nil {
  167. render.Error(w, r, err)
  168. return
  169. }
  170. // Check that the JWS url matches the requested url.
  171. jwsURL, ok := hdr.ExtraHeaders["url"].(string)
  172. if !ok {
  173. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "jws missing url protected header"))
  174. return
  175. }
  176. reqURL := &url.URL{Scheme: "https", Host: r.Host, Path: r.URL.Path}
  177. if jwsURL != reqURL.String() {
  178. render.Error(w, r, acme.NewError(acme.ErrorMalformedType,
  179. "url header in JWS (%s) does not match request url (%s)", jwsURL, reqURL))
  180. return
  181. }
  182. if hdr.JSONWebKey != nil && hdr.KeyID != "" {
  183. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "jwk and kid are mutually exclusive"))
  184. return
  185. }
  186. if hdr.JSONWebKey == nil && hdr.KeyID == "" {
  187. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "either jwk or kid must be defined in jws protected header"))
  188. return
  189. }
  190. next(w, r)
  191. }
  192. }
  193. // extractJWK is a middleware that extracts the JWK from the JWS and saves it
  194. // in the context. Make sure to parse and validate the JWS before running this
  195. // middleware.
  196. func extractJWK(next nextHTTP) nextHTTP {
  197. return func(w http.ResponseWriter, r *http.Request) {
  198. ctx := r.Context()
  199. db := acme.MustDatabaseFromContext(ctx)
  200. jws, err := jwsFromContext(ctx)
  201. if err != nil {
  202. render.Error(w, r, err)
  203. return
  204. }
  205. jwk := jws.Signatures[0].Protected.JSONWebKey
  206. if jwk == nil {
  207. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "jwk expected in protected header"))
  208. return
  209. }
  210. if !jwk.Valid() {
  211. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "invalid jwk in protected header"))
  212. return
  213. }
  214. // Overwrite KeyID with the JWK thumbprint.
  215. jwk.KeyID, err = acme.KeyToID(jwk)
  216. if err != nil {
  217. render.Error(w, r, acme.WrapErrorISE(err, "error getting KeyID from JWK"))
  218. return
  219. }
  220. // Store the JWK in the context.
  221. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  222. // Get Account OR continue to generate a new one OR continue Revoke with certificate private key
  223. acc, err := db.GetAccountByKeyID(ctx, jwk.KeyID)
  224. switch {
  225. case acme.IsErrNotFound(err):
  226. // For NewAccount and Revoke requests ...
  227. break
  228. case err != nil:
  229. render.Error(w, r, err)
  230. return
  231. default:
  232. if !acc.IsValid() {
  233. render.Error(w, r, acme.NewError(acme.ErrorUnauthorizedType, "account is not active"))
  234. return
  235. }
  236. ctx = context.WithValue(ctx, accContextKey, acc)
  237. }
  238. next(w, r.WithContext(ctx))
  239. }
  240. }
  241. // checkPrerequisites checks if all prerequisites for serving ACME
  242. // are met by the CA configuration.
  243. func checkPrerequisites(next nextHTTP) nextHTTP {
  244. return func(w http.ResponseWriter, r *http.Request) {
  245. ctx := r.Context()
  246. // If the function is not set assume that all prerequisites are met.
  247. checkFunc, ok := acme.PrerequisitesCheckerFromContext(ctx)
  248. if ok {
  249. ok, err := checkFunc(ctx)
  250. if err != nil {
  251. render.Error(w, r, acme.WrapErrorISE(err, "error checking acme provisioner prerequisites"))
  252. return
  253. }
  254. if !ok {
  255. render.Error(w, r, acme.NewError(acme.ErrorNotImplementedType, "acme provisioner configuration lacks prerequisites"))
  256. return
  257. }
  258. }
  259. next(w, r)
  260. }
  261. }
  262. // lookupJWK loads the JWK associated with the acme account referenced by the
  263. // kid parameter of the signed payload.
  264. // Make sure to parse and validate the JWS before running this middleware.
  265. func lookupJWK(next nextHTTP) nextHTTP {
  266. return func(w http.ResponseWriter, r *http.Request) {
  267. ctx := r.Context()
  268. db := acme.MustDatabaseFromContext(ctx)
  269. jws, err := jwsFromContext(ctx)
  270. if err != nil {
  271. render.Error(w, r, err)
  272. return
  273. }
  274. kid := jws.Signatures[0].Protected.KeyID
  275. if kid == "" {
  276. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "signature missing 'kid'"))
  277. return
  278. }
  279. accID := path.Base(kid)
  280. acc, err := db.GetAccount(ctx, accID)
  281. switch {
  282. case acme.IsErrNotFound(err):
  283. render.Error(w, r, acme.NewError(acme.ErrorAccountDoesNotExistType, "account with ID '%s' not found", accID))
  284. return
  285. case err != nil:
  286. render.Error(w, r, err)
  287. return
  288. default:
  289. if !acc.IsValid() {
  290. render.Error(w, r, acme.NewError(acme.ErrorUnauthorizedType, "account is not active"))
  291. return
  292. }
  293. if storedLocation := acc.GetLocation(); storedLocation != "" {
  294. if kid != storedLocation {
  295. // ACME accounts should have a stored location equivalent to the
  296. // kid in the ACME request.
  297. render.Error(w, r, acme.NewError(acme.ErrorUnauthorizedType,
  298. "kid does not match stored account location; expected %s, but got %s",
  299. storedLocation, kid))
  300. return
  301. }
  302. // Verify that the provisioner with which the account was created
  303. // matches the provisioner in the request URL.
  304. reqProv := acme.MustProvisionerFromContext(ctx)
  305. switch {
  306. case acc.ProvisionerID == "" && acc.ProvisionerName != reqProv.GetName():
  307. render.Error(w, r, acme.NewError(acme.ErrorUnauthorizedType,
  308. "account provisioner does not match requested provisioner; account provisioner = %s, requested provisioner = %s",
  309. acc.ProvisionerName, reqProv.GetName()))
  310. return
  311. case acc.ProvisionerID != "" && acc.ProvisionerID != reqProv.GetID():
  312. render.Error(w, r, acme.NewError(acme.ErrorUnauthorizedType,
  313. "account provisioner does not match requested provisioner; account provisioner = %s, requested provisioner = %s",
  314. acc.ProvisionerID, reqProv.GetID()))
  315. return
  316. }
  317. } else {
  318. // This code will only execute for old ACME accounts that do
  319. // not have a cached location. The following validation was
  320. // the original implementation of the `kid` check which has
  321. // since been deprecated. However, the code will remain to
  322. // ensure consistent behavior for old ACME accounts.
  323. linker := acme.MustLinkerFromContext(ctx)
  324. kidPrefix := linker.GetLink(ctx, acme.AccountLinkType, "")
  325. if !strings.HasPrefix(kid, kidPrefix) {
  326. render.Error(w, r, acme.NewError(acme.ErrorMalformedType,
  327. "kid does not have required prefix; expected %s, but got %s",
  328. kidPrefix, kid))
  329. return
  330. }
  331. }
  332. ctx = context.WithValue(ctx, accContextKey, acc)
  333. ctx = context.WithValue(ctx, jwkContextKey, acc.Key)
  334. next(w, r.WithContext(ctx))
  335. return
  336. }
  337. }
  338. }
  339. // extractOrLookupJWK forwards handling to either extractJWK or
  340. // lookupJWK based on the presence of a JWK or a KID, respectively.
  341. func extractOrLookupJWK(next nextHTTP) nextHTTP {
  342. return func(w http.ResponseWriter, r *http.Request) {
  343. ctx := r.Context()
  344. jws, err := jwsFromContext(ctx)
  345. if err != nil {
  346. render.Error(w, r, err)
  347. return
  348. }
  349. // at this point the JWS has already been verified (if correctly configured in middleware),
  350. // and it can be used to check if a JWK exists. This flow is used when the ACME client
  351. // signed the payload with a certificate private key.
  352. if canExtractJWKFrom(jws) {
  353. extractJWK(next)(w, r)
  354. return
  355. }
  356. // default to looking up the JWK based on KeyID. This flow is used when the ACME client
  357. // signed the payload with an account private key.
  358. lookupJWK(next)(w, r)
  359. }
  360. }
  361. // canExtractJWKFrom checks if the JWS has a JWK that can be extracted
  362. func canExtractJWKFrom(jws *jose.JSONWebSignature) bool {
  363. if jws == nil {
  364. return false
  365. }
  366. if len(jws.Signatures) == 0 {
  367. return false
  368. }
  369. return jws.Signatures[0].Protected.JSONWebKey != nil
  370. }
  371. // verifyAndExtractJWSPayload extracts the JWK from the JWS and saves it in the context.
  372. // Make sure to parse and validate the JWS before running this middleware.
  373. func verifyAndExtractJWSPayload(next nextHTTP) nextHTTP {
  374. return func(w http.ResponseWriter, r *http.Request) {
  375. ctx := r.Context()
  376. jws, err := jwsFromContext(ctx)
  377. if err != nil {
  378. render.Error(w, r, err)
  379. return
  380. }
  381. jwk, err := jwkFromContext(ctx)
  382. if err != nil {
  383. render.Error(w, r, err)
  384. return
  385. }
  386. if jwk.Algorithm != "" && jwk.Algorithm != jws.Signatures[0].Protected.Algorithm {
  387. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "verifier and signature algorithm do not match"))
  388. return
  389. }
  390. payload, err := jws.Verify(jwk)
  391. switch {
  392. case errors.Is(err, jose.ErrCryptoFailure):
  393. payload, err = retryVerificationWithPatchedSignatures(jws, jwk)
  394. if err != nil {
  395. render.Error(w, r, acme.WrapError(acme.ErrorMalformedType, err, "error verifying jws with patched signature(s)"))
  396. return
  397. }
  398. case err != nil:
  399. render.Error(w, r, acme.WrapError(acme.ErrorMalformedType, err, "error verifying jws"))
  400. return
  401. }
  402. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{
  403. value: payload,
  404. isPostAsGet: len(payload) == 0,
  405. isEmptyJSON: string(payload) == "{}",
  406. })
  407. next(w, r.WithContext(ctx))
  408. }
  409. }
  410. // retryVerificationWithPatchedSignatures retries verification of the JWS using
  411. // the JWK by patching the JWS signatures if they're determined to be too short.
  412. //
  413. // Generally this shouldn't happen, but we've observed this to be the case with
  414. // the macOS ACME client, which seems to omit (at least one) leading null
  415. // byte(s). The error returned is `go-jose/go-jose: error in cryptographic
  416. // primitive`, which is a sentinel error that hides the details of the actual
  417. // underlying error, which is as follows: `go-jose/go-jose: invalid signature
  418. // size, have 63 bytes, wanted 64`, for ES256.
  419. func retryVerificationWithPatchedSignatures(jws *jose.JSONWebSignature, jwk *jose.JSONWebKey) (data []byte, err error) {
  420. originalSignatureValues := make([][]byte, len(jws.Signatures))
  421. patched := false
  422. defer func() {
  423. if patched && err != nil {
  424. for i, sig := range jws.Signatures {
  425. sig.Signature = originalSignatureValues[i]
  426. jws.Signatures[i] = sig
  427. }
  428. }
  429. }()
  430. for i, sig := range jws.Signatures {
  431. var expectedSize int
  432. alg := strings.ToUpper(sig.Header.Algorithm)
  433. switch alg {
  434. case jose.ES256:
  435. expectedSize = 64
  436. case jose.ES384:
  437. expectedSize = 96
  438. case jose.ES512:
  439. expectedSize = 132
  440. default:
  441. // other cases are (currently) ignored
  442. continue
  443. }
  444. switch diff := expectedSize - len(sig.Signature); diff {
  445. case 0:
  446. // expected length; nothing to do; will result in just doing the
  447. // same verification (as done before calling this function) again,
  448. // and thus an error will be returned.
  449. continue
  450. case 1:
  451. patched = true
  452. original := make([]byte, expectedSize-diff)
  453. copy(original, sig.Signature)
  454. originalSignatureValues[i] = original
  455. patchedR := make([]byte, expectedSize)
  456. copy(patchedR[1:], original) // [0x00, R.0:31, S.0:32], for expectedSize 64
  457. sig.Signature = patchedR
  458. jws.Signatures[i] = sig
  459. // verify it with a patched R; return early if successful; continue
  460. // with patching S if not.
  461. data, err = jws.Verify(jwk)
  462. if err == nil {
  463. return
  464. }
  465. patchedS := make([]byte, expectedSize)
  466. halfSize := expectedSize / 2
  467. copy(patchedS, original[:halfSize]) // [R.0:32], for expectedSize 64
  468. copy(patchedS[halfSize+1:], original[halfSize:]) // [R.0:32, 0x00, S.0:31]
  469. sig.Signature = patchedS
  470. jws.Signatures[i] = sig
  471. case 2:
  472. // assumption is currently the Apple case, in which only the
  473. // first null byte of R and/or S are removed, and thus not a case in
  474. // which two first bytes of either R or S are removed.
  475. patched = true
  476. original := make([]byte, expectedSize-diff)
  477. copy(original, sig.Signature)
  478. originalSignatureValues[i] = original
  479. patchedRS := make([]byte, expectedSize)
  480. halfSize := expectedSize / 2
  481. copy(patchedRS[1:], original[:halfSize-1]) // [0x00, R.0:31], for expectedSize 64
  482. copy(patchedRS[halfSize+1:], original[halfSize-1:]) // [0x00, R.0:31, 0x00, S.0:31]
  483. sig.Signature = patchedRS
  484. jws.Signatures[i] = sig
  485. default:
  486. // Technically, there can be multiple null bytes in either R or S,
  487. // so when the difference is larger than 2, there is more than one
  488. // option to pick. Apple's ACME client seems to only cut off the
  489. // first null byte of either R or S, so we don't do anything in this
  490. // case. Will result in just doing the same verification (as done
  491. // before calling this function) again, and thus an error will be
  492. // returned.
  493. // TODO(hs): log this specific case? It might mean some other ACME
  494. // client is doing weird things.
  495. continue
  496. }
  497. }
  498. data, err = jws.Verify(jwk)
  499. return
  500. }
  501. // isPostAsGet asserts that the request is a PostAsGet (empty JWS payload).
  502. func isPostAsGet(next nextHTTP) nextHTTP {
  503. return func(w http.ResponseWriter, r *http.Request) {
  504. payload, err := payloadFromContext(r.Context())
  505. if err != nil {
  506. render.Error(w, r, err)
  507. return
  508. }
  509. if !payload.isPostAsGet {
  510. render.Error(w, r, acme.NewError(acme.ErrorMalformedType, "expected POST-as-GET"))
  511. return
  512. }
  513. next(w, r)
  514. }
  515. }
  516. // ContextKey is the key type for storing and searching for ACME request
  517. // essentials in the context of a request.
  518. type ContextKey string
  519. const (
  520. // accContextKey account key
  521. accContextKey = ContextKey("acc")
  522. // jwsContextKey jws key
  523. jwsContextKey = ContextKey("jws")
  524. // jwkContextKey jwk key
  525. jwkContextKey = ContextKey("jwk")
  526. // payloadContextKey payload key
  527. payloadContextKey = ContextKey("payload")
  528. )
  529. // accountFromContext searches the context for an ACME account. Returns the
  530. // account or an error.
  531. func accountFromContext(ctx context.Context) (*acme.Account, error) {
  532. val, ok := ctx.Value(accContextKey).(*acme.Account)
  533. if !ok || val == nil {
  534. return nil, acme.NewError(acme.ErrorAccountDoesNotExistType, "account not in context")
  535. }
  536. return val, nil
  537. }
  538. // jwkFromContext searches the context for a JWK. Returns the JWK or an error.
  539. func jwkFromContext(ctx context.Context) (*jose.JSONWebKey, error) {
  540. val, ok := ctx.Value(jwkContextKey).(*jose.JSONWebKey)
  541. if !ok || val == nil {
  542. return nil, acme.NewErrorISE("jwk expected in request context")
  543. }
  544. return val, nil
  545. }
  546. // jwsFromContext searches the context for a JWS. Returns the JWS or an error.
  547. func jwsFromContext(ctx context.Context) (*jose.JSONWebSignature, error) {
  548. val, ok := ctx.Value(jwsContextKey).(*jose.JSONWebSignature)
  549. if !ok || val == nil {
  550. return nil, acme.NewErrorISE("jws expected in request context")
  551. }
  552. return val, nil
  553. }
  554. // provisionerFromContext searches the context for a provisioner. Returns the
  555. // provisioner or an error.
  556. func provisionerFromContext(ctx context.Context) (acme.Provisioner, error) {
  557. p, ok := acme.ProvisionerFromContext(ctx)
  558. if !ok || p == nil {
  559. return nil, acme.NewErrorISE("provisioner expected in request context")
  560. }
  561. return p, nil
  562. }
  563. // acmeProvisionerFromContext searches the context for an ACME provisioner. Returns
  564. // pointer to an ACME provisioner or an error.
  565. func acmeProvisionerFromContext(ctx context.Context) (*provisioner.ACME, error) {
  566. p, err := provisionerFromContext(ctx)
  567. if err != nil {
  568. return nil, err
  569. }
  570. ap, ok := p.(*provisioner.ACME)
  571. if !ok {
  572. return nil, acme.NewErrorISE("provisioner in context is not an ACME provisioner")
  573. }
  574. return ap, nil
  575. }
  576. // payloadFromContext searches the context for a payload. Returns the payload
  577. // or an error.
  578. func payloadFromContext(ctx context.Context) (*payloadInfo, error) {
  579. val, ok := ctx.Value(payloadContextKey).(*payloadInfo)
  580. if !ok || val == nil {
  581. return nil, acme.NewErrorISE("payload expected in request context")
  582. }
  583. return val, nil
  584. }