middleware_test.go 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto"
  6. "encoding/base64"
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "net/http/httptest"
  12. "net/url"
  13. "strings"
  14. "testing"
  15. "github.com/pkg/errors"
  16. "github.com/smallstep/assert"
  17. "github.com/smallstep/certificates/acme"
  18. "github.com/smallstep/nosql/database"
  19. "go.step.sm/crypto/jose"
  20. )
  21. var testBody = []byte("foo")
  22. func testNext(w http.ResponseWriter, r *http.Request) {
  23. w.Write(testBody)
  24. }
  25. func newBaseContext(ctx context.Context, args ...interface{}) context.Context {
  26. for _, a := range args {
  27. switch v := a.(type) {
  28. case acme.DB:
  29. ctx = acme.NewDatabaseContext(ctx, v)
  30. case acme.Linker:
  31. ctx = acme.NewLinkerContext(ctx, v)
  32. case acme.PrerequisitesChecker:
  33. ctx = acme.NewPrerequisitesCheckerContext(ctx, v)
  34. }
  35. }
  36. return ctx
  37. }
  38. func TestHandler_addNonce(t *testing.T) {
  39. u := "https://ca.smallstep.com/acme/new-nonce"
  40. type test struct {
  41. db acme.DB
  42. err *acme.Error
  43. statusCode int
  44. }
  45. var tests = map[string]func(t *testing.T) test{
  46. "fail/AddNonce-error": func(t *testing.T) test {
  47. return test{
  48. db: &acme.MockDB{
  49. MockCreateNonce: func(ctx context.Context) (acme.Nonce, error) {
  50. return acme.Nonce(""), acme.NewErrorISE("force")
  51. },
  52. },
  53. statusCode: 500,
  54. err: acme.NewErrorISE("force"),
  55. }
  56. },
  57. "ok": func(t *testing.T) test {
  58. return test{
  59. db: &acme.MockDB{
  60. MockCreateNonce: func(ctx context.Context) (acme.Nonce, error) {
  61. return "bar", nil
  62. },
  63. },
  64. statusCode: 200,
  65. }
  66. },
  67. }
  68. for name, run := range tests {
  69. tc := run(t)
  70. t.Run(name, func(t *testing.T) {
  71. ctx := newBaseContext(context.Background(), tc.db)
  72. req := httptest.NewRequest("GET", u, nil).WithContext(ctx)
  73. w := httptest.NewRecorder()
  74. addNonce(testNext)(w, req)
  75. res := w.Result()
  76. assert.Equals(t, res.StatusCode, tc.statusCode)
  77. body, err := io.ReadAll(res.Body)
  78. res.Body.Close()
  79. assert.FatalError(t, err)
  80. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  81. var ae acme.Error
  82. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  83. assert.Equals(t, ae.Type, tc.err.Type)
  84. assert.Equals(t, ae.Detail, tc.err.Detail)
  85. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  86. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  87. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  88. } else {
  89. assert.Equals(t, res.Header["Replay-Nonce"], []string{"bar"})
  90. assert.Equals(t, res.Header["Cache-Control"], []string{"no-store"})
  91. assert.Equals(t, bytes.TrimSpace(body), testBody)
  92. }
  93. })
  94. }
  95. }
  96. func TestHandler_addDirLink(t *testing.T) {
  97. prov := newProv()
  98. provName := url.PathEscape(prov.GetName())
  99. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  100. type test struct {
  101. link string
  102. statusCode int
  103. ctx context.Context
  104. err *acme.Error
  105. }
  106. var tests = map[string]func(t *testing.T) test{
  107. "ok": func(t *testing.T) test {
  108. ctx := acme.NewProvisionerContext(context.Background(), prov)
  109. ctx = acme.NewLinkerContext(ctx, acme.NewLinker("test.ca.smallstep.com", "acme"))
  110. return test{
  111. ctx: ctx,
  112. link: fmt.Sprintf("%s/acme/%s/directory", baseURL.String(), provName),
  113. statusCode: 200,
  114. }
  115. },
  116. }
  117. for name, run := range tests {
  118. tc := run(t)
  119. t.Run(name, func(t *testing.T) {
  120. req := httptest.NewRequest("GET", "/foo", nil)
  121. req = req.WithContext(tc.ctx)
  122. w := httptest.NewRecorder()
  123. addDirLink(testNext)(w, req)
  124. res := w.Result()
  125. assert.Equals(t, res.StatusCode, tc.statusCode)
  126. body, err := io.ReadAll(res.Body)
  127. res.Body.Close()
  128. assert.FatalError(t, err)
  129. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  130. var ae acme.Error
  131. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  132. assert.Equals(t, ae.Type, tc.err.Type)
  133. assert.Equals(t, ae.Detail, tc.err.Detail)
  134. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  135. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  136. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  137. } else {
  138. assert.Equals(t, res.Header["Link"], []string{fmt.Sprintf("<%s>;rel=\"index\"", tc.link)})
  139. assert.Equals(t, bytes.TrimSpace(body), testBody)
  140. }
  141. })
  142. }
  143. }
  144. func TestHandler_verifyContentType(t *testing.T) {
  145. prov := newProv()
  146. escProvName := url.PathEscape(prov.GetName())
  147. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  148. u := fmt.Sprintf("%s/acme/%s/certificate/abc123", baseURL.String(), escProvName)
  149. type test struct {
  150. ctx context.Context
  151. contentType string
  152. err *acme.Error
  153. statusCode int
  154. url string
  155. }
  156. var tests = map[string]func(t *testing.T) test{
  157. "fail/provisioner-not-set": func(t *testing.T) test {
  158. return test{
  159. url: u,
  160. ctx: context.Background(),
  161. contentType: "foo",
  162. statusCode: 500,
  163. err: acme.NewErrorISE("provisioner expected in request context"),
  164. }
  165. },
  166. "fail/general-bad-content-type": func(t *testing.T) test {
  167. return test{
  168. url: u,
  169. ctx: acme.NewProvisionerContext(context.Background(), prov),
  170. contentType: "foo",
  171. statusCode: 400,
  172. err: acme.NewError(acme.ErrorMalformedType, "expected content-type to be in [application/jose+json], but got foo"),
  173. }
  174. },
  175. "fail/certificate-bad-content-type": func(t *testing.T) test {
  176. return test{
  177. ctx: acme.NewProvisionerContext(context.Background(), prov),
  178. contentType: "foo",
  179. statusCode: 400,
  180. err: acme.NewError(acme.ErrorMalformedType, "expected content-type to be in [application/jose+json application/pkix-cert application/pkcs7-mime], but got foo"),
  181. }
  182. },
  183. "ok": func(t *testing.T) test {
  184. return test{
  185. ctx: acme.NewProvisionerContext(context.Background(), prov),
  186. contentType: "application/jose+json",
  187. statusCode: 200,
  188. }
  189. },
  190. "ok/certificate/pkix-cert": func(t *testing.T) test {
  191. return test{
  192. ctx: acme.NewProvisionerContext(context.Background(), prov),
  193. contentType: "application/pkix-cert",
  194. statusCode: 200,
  195. }
  196. },
  197. "ok/certificate/jose+json": func(t *testing.T) test {
  198. return test{
  199. ctx: acme.NewProvisionerContext(context.Background(), prov),
  200. contentType: "application/jose+json",
  201. statusCode: 200,
  202. }
  203. },
  204. "ok/certificate/pkcs7-mime": func(t *testing.T) test {
  205. return test{
  206. ctx: acme.NewProvisionerContext(context.Background(), prov),
  207. contentType: "application/pkcs7-mime",
  208. statusCode: 200,
  209. }
  210. },
  211. }
  212. for name, run := range tests {
  213. tc := run(t)
  214. t.Run(name, func(t *testing.T) {
  215. _u := u
  216. if tc.url != "" {
  217. _u = tc.url
  218. }
  219. req := httptest.NewRequest("GET", _u, nil)
  220. req = req.WithContext(tc.ctx)
  221. req.Header.Add("Content-Type", tc.contentType)
  222. w := httptest.NewRecorder()
  223. verifyContentType(testNext)(w, req)
  224. res := w.Result()
  225. assert.Equals(t, res.StatusCode, tc.statusCode)
  226. body, err := io.ReadAll(res.Body)
  227. res.Body.Close()
  228. assert.FatalError(t, err)
  229. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  230. var ae acme.Error
  231. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  232. assert.Equals(t, ae.Type, tc.err.Type)
  233. assert.Equals(t, ae.Detail, tc.err.Detail)
  234. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  235. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  236. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  237. } else {
  238. assert.Equals(t, bytes.TrimSpace(body), testBody)
  239. }
  240. })
  241. }
  242. }
  243. func TestHandler_isPostAsGet(t *testing.T) {
  244. u := "https://ca.smallstep.com/acme/new-account"
  245. type test struct {
  246. ctx context.Context
  247. err *acme.Error
  248. statusCode int
  249. }
  250. var tests = map[string]func(t *testing.T) test{
  251. "fail/no-payload": func(t *testing.T) test {
  252. return test{
  253. ctx: context.Background(),
  254. statusCode: 500,
  255. err: acme.NewErrorISE("payload expected in request context"),
  256. }
  257. },
  258. "fail/nil-payload": func(t *testing.T) test {
  259. return test{
  260. ctx: context.WithValue(context.Background(), payloadContextKey, nil),
  261. statusCode: 500,
  262. err: acme.NewErrorISE("payload expected in request context"),
  263. }
  264. },
  265. "fail/not-post-as-get": func(t *testing.T) test {
  266. return test{
  267. ctx: context.WithValue(context.Background(), payloadContextKey, &payloadInfo{}),
  268. statusCode: 400,
  269. err: acme.NewError(acme.ErrorMalformedType, "expected POST-as-GET"),
  270. }
  271. },
  272. "ok": func(t *testing.T) test {
  273. return test{
  274. ctx: context.WithValue(context.Background(), payloadContextKey, &payloadInfo{isPostAsGet: true}),
  275. statusCode: 200,
  276. }
  277. },
  278. }
  279. for name, run := range tests {
  280. tc := run(t)
  281. t.Run(name, func(t *testing.T) {
  282. // h := &Handler{}
  283. req := httptest.NewRequest("GET", u, nil)
  284. req = req.WithContext(tc.ctx)
  285. w := httptest.NewRecorder()
  286. isPostAsGet(testNext)(w, req)
  287. res := w.Result()
  288. assert.Equals(t, res.StatusCode, tc.statusCode)
  289. body, err := io.ReadAll(res.Body)
  290. res.Body.Close()
  291. assert.FatalError(t, err)
  292. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  293. var ae acme.Error
  294. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  295. assert.Equals(t, ae.Type, tc.err.Type)
  296. assert.Equals(t, ae.Detail, tc.err.Detail)
  297. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  298. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  299. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  300. } else {
  301. assert.Equals(t, bytes.TrimSpace(body), testBody)
  302. }
  303. })
  304. }
  305. }
  306. type errReader int
  307. func (errReader) Read(p []byte) (n int, err error) {
  308. return 0, errors.New("force")
  309. }
  310. func (errReader) Close() error {
  311. return nil
  312. }
  313. func TestHandler_parseJWS(t *testing.T) {
  314. u := "https://ca.smallstep.com/acme/new-account"
  315. type test struct {
  316. next nextHTTP
  317. body io.Reader
  318. err *acme.Error
  319. statusCode int
  320. }
  321. var tests = map[string]func(t *testing.T) test{
  322. "fail/read-body-error": func(t *testing.T) test {
  323. return test{
  324. body: errReader(0),
  325. statusCode: 500,
  326. err: acme.NewErrorISE("failed to read request body: force"),
  327. }
  328. },
  329. "fail/parse-jws-error": func(t *testing.T) test {
  330. return test{
  331. body: strings.NewReader("foo"),
  332. statusCode: 400,
  333. err: acme.NewError(acme.ErrorMalformedType, "failed to parse JWS from request body: square/go-jose: compact JWS format must have three parts"),
  334. }
  335. },
  336. "ok": func(t *testing.T) test {
  337. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  338. assert.FatalError(t, err)
  339. signer, err := jose.NewSigner(jose.SigningKey{
  340. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  341. Key: jwk.Key,
  342. }, new(jose.SignerOptions))
  343. assert.FatalError(t, err)
  344. signed, err := signer.Sign([]byte("baz"))
  345. assert.FatalError(t, err)
  346. expRaw, err := signed.CompactSerialize()
  347. assert.FatalError(t, err)
  348. return test{
  349. body: strings.NewReader(expRaw),
  350. next: func(w http.ResponseWriter, r *http.Request) {
  351. jws, err := jwsFromContext(r.Context())
  352. assert.FatalError(t, err)
  353. gotRaw, err := jws.CompactSerialize()
  354. assert.FatalError(t, err)
  355. assert.Equals(t, gotRaw, expRaw)
  356. w.Write(testBody)
  357. },
  358. statusCode: 200,
  359. }
  360. },
  361. }
  362. for name, run := range tests {
  363. tc := run(t)
  364. t.Run(name, func(t *testing.T) {
  365. // h := &Handler{}
  366. req := httptest.NewRequest("GET", u, tc.body)
  367. w := httptest.NewRecorder()
  368. parseJWS(tc.next)(w, req)
  369. res := w.Result()
  370. assert.Equals(t, res.StatusCode, tc.statusCode)
  371. body, err := io.ReadAll(res.Body)
  372. res.Body.Close()
  373. assert.FatalError(t, err)
  374. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  375. var ae acme.Error
  376. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  377. assert.Equals(t, ae.Type, tc.err.Type)
  378. assert.Equals(t, ae.Detail, tc.err.Detail)
  379. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  380. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  381. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  382. } else {
  383. assert.Equals(t, bytes.TrimSpace(body), testBody)
  384. }
  385. })
  386. }
  387. }
  388. func TestHandler_verifyAndExtractJWSPayload(t *testing.T) {
  389. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  390. assert.FatalError(t, err)
  391. _pub := jwk.Public()
  392. pub := &_pub
  393. so := new(jose.SignerOptions)
  394. so.WithHeader("alg", jose.SignatureAlgorithm(jwk.Algorithm))
  395. signer, err := jose.NewSigner(jose.SigningKey{
  396. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  397. Key: jwk.Key,
  398. }, so)
  399. assert.FatalError(t, err)
  400. jws, err := signer.Sign([]byte("baz"))
  401. assert.FatalError(t, err)
  402. raw, err := jws.CompactSerialize()
  403. assert.FatalError(t, err)
  404. parsedJWS, err := jose.ParseJWS(raw)
  405. assert.FatalError(t, err)
  406. u := "https://ca.smallstep.com/acme/account/1234"
  407. type test struct {
  408. ctx context.Context
  409. next func(http.ResponseWriter, *http.Request)
  410. err *acme.Error
  411. statusCode int
  412. }
  413. var tests = map[string]func(t *testing.T) test{
  414. "fail/no-jws": func(t *testing.T) test {
  415. return test{
  416. ctx: context.Background(),
  417. statusCode: 500,
  418. err: acme.NewErrorISE("jws expected in request context"),
  419. }
  420. },
  421. "fail/nil-jws": func(t *testing.T) test {
  422. return test{
  423. ctx: context.WithValue(context.Background(), jwsContextKey, nil),
  424. statusCode: 500,
  425. err: acme.NewErrorISE("jws expected in request context"),
  426. }
  427. },
  428. "fail/no-jwk": func(t *testing.T) test {
  429. return test{
  430. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  431. statusCode: 500,
  432. err: acme.NewErrorISE("jwk expected in request context"),
  433. }
  434. },
  435. "fail/nil-jwk": func(t *testing.T) test {
  436. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  437. return test{
  438. ctx: context.WithValue(ctx, jwsContextKey, nil),
  439. statusCode: 500,
  440. err: acme.NewErrorISE("jwk expected in request context"),
  441. }
  442. },
  443. "fail/verify-jws-failure": func(t *testing.T) test {
  444. _jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  445. assert.FatalError(t, err)
  446. _pub := _jwk.Public()
  447. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  448. ctx = context.WithValue(ctx, jwkContextKey, &_pub)
  449. return test{
  450. ctx: ctx,
  451. statusCode: 400,
  452. err: acme.NewError(acme.ErrorMalformedType, "error verifying jws: square/go-jose: error in cryptographic primitive"),
  453. }
  454. },
  455. "fail/algorithm-mismatch": func(t *testing.T) test {
  456. _pub := *pub
  457. clone := &_pub
  458. clone.Algorithm = jose.HS256
  459. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  460. ctx = context.WithValue(ctx, jwkContextKey, clone)
  461. return test{
  462. ctx: ctx,
  463. statusCode: 400,
  464. err: acme.NewError(acme.ErrorMalformedType, "verifier and signature algorithm do not match"),
  465. }
  466. },
  467. "ok": func(t *testing.T) test {
  468. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  469. ctx = context.WithValue(ctx, jwkContextKey, pub)
  470. return test{
  471. ctx: ctx,
  472. statusCode: 200,
  473. next: func(w http.ResponseWriter, r *http.Request) {
  474. p, err := payloadFromContext(r.Context())
  475. assert.FatalError(t, err)
  476. if assert.NotNil(t, p) {
  477. assert.Equals(t, p.value, []byte("baz"))
  478. assert.False(t, p.isPostAsGet)
  479. assert.False(t, p.isEmptyJSON)
  480. }
  481. w.Write(testBody)
  482. },
  483. }
  484. },
  485. "ok/empty-algorithm-in-jwk": func(t *testing.T) test {
  486. _pub := *pub
  487. clone := &_pub
  488. clone.Algorithm = ""
  489. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  490. ctx = context.WithValue(ctx, jwkContextKey, pub)
  491. return test{
  492. ctx: ctx,
  493. statusCode: 200,
  494. next: func(w http.ResponseWriter, r *http.Request) {
  495. p, err := payloadFromContext(r.Context())
  496. assert.FatalError(t, err)
  497. if assert.NotNil(t, p) {
  498. assert.Equals(t, p.value, []byte("baz"))
  499. assert.False(t, p.isPostAsGet)
  500. assert.False(t, p.isEmptyJSON)
  501. }
  502. w.Write(testBody)
  503. },
  504. }
  505. },
  506. "ok/post-as-get": func(t *testing.T) test {
  507. _jws, err := signer.Sign([]byte(""))
  508. assert.FatalError(t, err)
  509. _raw, err := _jws.CompactSerialize()
  510. assert.FatalError(t, err)
  511. _parsed, err := jose.ParseJWS(_raw)
  512. assert.FatalError(t, err)
  513. ctx := context.WithValue(context.Background(), jwsContextKey, _parsed)
  514. ctx = context.WithValue(ctx, jwkContextKey, pub)
  515. return test{
  516. ctx: ctx,
  517. statusCode: 200,
  518. next: func(w http.ResponseWriter, r *http.Request) {
  519. p, err := payloadFromContext(r.Context())
  520. assert.FatalError(t, err)
  521. if assert.NotNil(t, p) {
  522. assert.Equals(t, p.value, []byte{})
  523. assert.True(t, p.isPostAsGet)
  524. assert.False(t, p.isEmptyJSON)
  525. }
  526. w.Write(testBody)
  527. },
  528. }
  529. },
  530. "ok/empty-json": func(t *testing.T) test {
  531. _jws, err := signer.Sign([]byte("{}"))
  532. assert.FatalError(t, err)
  533. _raw, err := _jws.CompactSerialize()
  534. assert.FatalError(t, err)
  535. _parsed, err := jose.ParseJWS(_raw)
  536. assert.FatalError(t, err)
  537. ctx := context.WithValue(context.Background(), jwsContextKey, _parsed)
  538. ctx = context.WithValue(ctx, jwkContextKey, pub)
  539. return test{
  540. ctx: ctx,
  541. statusCode: 200,
  542. next: func(w http.ResponseWriter, r *http.Request) {
  543. p, err := payloadFromContext(r.Context())
  544. assert.FatalError(t, err)
  545. if assert.NotNil(t, p) {
  546. assert.Equals(t, p.value, []byte("{}"))
  547. assert.False(t, p.isPostAsGet)
  548. assert.True(t, p.isEmptyJSON)
  549. }
  550. w.Write(testBody)
  551. },
  552. }
  553. },
  554. }
  555. for name, run := range tests {
  556. tc := run(t)
  557. t.Run(name, func(t *testing.T) {
  558. // h := &Handler{}
  559. req := httptest.NewRequest("GET", u, nil)
  560. req = req.WithContext(tc.ctx)
  561. w := httptest.NewRecorder()
  562. verifyAndExtractJWSPayload(tc.next)(w, req)
  563. res := w.Result()
  564. assert.Equals(t, res.StatusCode, tc.statusCode)
  565. body, err := io.ReadAll(res.Body)
  566. res.Body.Close()
  567. assert.FatalError(t, err)
  568. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  569. var ae acme.Error
  570. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  571. assert.Equals(t, ae.Type, tc.err.Type)
  572. assert.Equals(t, ae.Detail, tc.err.Detail)
  573. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  574. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  575. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  576. } else {
  577. assert.Equals(t, bytes.TrimSpace(body), testBody)
  578. }
  579. })
  580. }
  581. }
  582. func TestHandler_lookupJWK(t *testing.T) {
  583. prov := newProv()
  584. provName := url.PathEscape(prov.GetName())
  585. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  586. u := fmt.Sprintf("%s/acme/%s/account/1234",
  587. baseURL, provName)
  588. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  589. assert.FatalError(t, err)
  590. accID := "account-id"
  591. prefix := fmt.Sprintf("%s/acme/%s/account/",
  592. baseURL, provName)
  593. so := new(jose.SignerOptions)
  594. so.WithHeader("kid", fmt.Sprintf("%s%s", prefix, accID))
  595. signer, err := jose.NewSigner(jose.SigningKey{
  596. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  597. Key: jwk.Key,
  598. }, so)
  599. assert.FatalError(t, err)
  600. jws, err := signer.Sign([]byte("baz"))
  601. assert.FatalError(t, err)
  602. raw, err := jws.CompactSerialize()
  603. assert.FatalError(t, err)
  604. parsedJWS, err := jose.ParseJWS(raw)
  605. assert.FatalError(t, err)
  606. type test struct {
  607. linker acme.Linker
  608. db acme.DB
  609. ctx context.Context
  610. next func(http.ResponseWriter, *http.Request)
  611. err *acme.Error
  612. statusCode int
  613. }
  614. var tests = map[string]func(t *testing.T) test{
  615. "fail/no-jws": func(t *testing.T) test {
  616. return test{
  617. db: &acme.MockDB{},
  618. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  619. ctx: acme.NewProvisionerContext(context.Background(), prov),
  620. statusCode: 500,
  621. err: acme.NewErrorISE("jws expected in request context"),
  622. }
  623. },
  624. "fail/nil-jws": func(t *testing.T) test {
  625. ctx := acme.NewProvisionerContext(context.Background(), prov)
  626. ctx = context.WithValue(ctx, jwsContextKey, nil)
  627. return test{
  628. db: &acme.MockDB{},
  629. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  630. ctx: ctx,
  631. statusCode: 500,
  632. err: acme.NewErrorISE("jws expected in request context"),
  633. }
  634. },
  635. "fail/no-kid": func(t *testing.T) test {
  636. _signer, err := jose.NewSigner(jose.SigningKey{
  637. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  638. Key: jwk.Key,
  639. }, new(jose.SignerOptions))
  640. assert.FatalError(t, err)
  641. _jws, err := _signer.Sign([]byte("baz"))
  642. assert.FatalError(t, err)
  643. ctx := acme.NewProvisionerContext(context.Background(), prov)
  644. ctx = context.WithValue(ctx, jwsContextKey, _jws)
  645. return test{
  646. db: &acme.MockDB{},
  647. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  648. ctx: ctx,
  649. statusCode: 400,
  650. err: acme.NewError(acme.ErrorMalformedType, "kid does not have required prefix; expected %s, but got ", prefix),
  651. }
  652. },
  653. "fail/bad-kid-prefix": func(t *testing.T) test {
  654. _so := new(jose.SignerOptions)
  655. _so.WithHeader("kid", "foo")
  656. _signer, err := jose.NewSigner(jose.SigningKey{
  657. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  658. Key: jwk.Key,
  659. }, _so)
  660. assert.FatalError(t, err)
  661. _jws, err := _signer.Sign([]byte("baz"))
  662. assert.FatalError(t, err)
  663. _raw, err := _jws.CompactSerialize()
  664. assert.FatalError(t, err)
  665. _parsed, err := jose.ParseJWS(_raw)
  666. assert.FatalError(t, err)
  667. ctx := acme.NewProvisionerContext(context.Background(), prov)
  668. ctx = context.WithValue(ctx, jwsContextKey, _parsed)
  669. return test{
  670. db: &acme.MockDB{},
  671. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  672. ctx: ctx,
  673. statusCode: 400,
  674. err: acme.NewError(acme.ErrorMalformedType, "kid does not have required prefix; expected %s, but got foo", prefix),
  675. }
  676. },
  677. "fail/account-not-found": func(t *testing.T) test {
  678. ctx := acme.NewProvisionerContext(context.Background(), prov)
  679. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  680. return test{
  681. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  682. db: &acme.MockDB{
  683. MockGetAccount: func(ctx context.Context, accID string) (*acme.Account, error) {
  684. assert.Equals(t, accID, accID)
  685. return nil, database.ErrNotFound
  686. },
  687. },
  688. ctx: ctx,
  689. statusCode: 400,
  690. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  691. }
  692. },
  693. "fail/GetAccount-error": func(t *testing.T) test {
  694. ctx := acme.NewProvisionerContext(context.Background(), prov)
  695. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  696. return test{
  697. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  698. db: &acme.MockDB{
  699. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  700. assert.Equals(t, id, accID)
  701. return nil, acme.NewErrorISE("force")
  702. },
  703. },
  704. ctx: ctx,
  705. statusCode: 500,
  706. err: acme.NewErrorISE("force"),
  707. }
  708. },
  709. "fail/account-not-valid": func(t *testing.T) test {
  710. acc := &acme.Account{Status: "deactivated"}
  711. ctx := acme.NewProvisionerContext(context.Background(), prov)
  712. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  713. return test{
  714. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  715. db: &acme.MockDB{
  716. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  717. assert.Equals(t, id, accID)
  718. return acc, nil
  719. },
  720. },
  721. ctx: ctx,
  722. statusCode: 401,
  723. err: acme.NewError(acme.ErrorUnauthorizedType, "account is not active"),
  724. }
  725. },
  726. "ok": func(t *testing.T) test {
  727. acc := &acme.Account{Status: "valid", Key: jwk}
  728. ctx := acme.NewProvisionerContext(context.Background(), prov)
  729. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  730. return test{
  731. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  732. db: &acme.MockDB{
  733. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  734. assert.Equals(t, id, accID)
  735. return acc, nil
  736. },
  737. },
  738. ctx: ctx,
  739. next: func(w http.ResponseWriter, r *http.Request) {
  740. _acc, err := accountFromContext(r.Context())
  741. assert.FatalError(t, err)
  742. assert.Equals(t, _acc, acc)
  743. _jwk, err := jwkFromContext(r.Context())
  744. assert.FatalError(t, err)
  745. assert.Equals(t, _jwk, jwk)
  746. w.Write(testBody)
  747. },
  748. statusCode: 200,
  749. }
  750. },
  751. }
  752. for name, run := range tests {
  753. tc := run(t)
  754. t.Run(name, func(t *testing.T) {
  755. ctx := newBaseContext(tc.ctx, tc.db, tc.linker)
  756. req := httptest.NewRequest("GET", u, nil)
  757. req = req.WithContext(ctx)
  758. w := httptest.NewRecorder()
  759. lookupJWK(tc.next)(w, req)
  760. res := w.Result()
  761. assert.Equals(t, res.StatusCode, tc.statusCode)
  762. body, err := io.ReadAll(res.Body)
  763. res.Body.Close()
  764. assert.FatalError(t, err)
  765. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  766. var ae acme.Error
  767. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  768. assert.Equals(t, ae.Type, tc.err.Type)
  769. assert.Equals(t, ae.Detail, tc.err.Detail)
  770. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  771. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  772. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  773. } else {
  774. assert.Equals(t, bytes.TrimSpace(body), testBody)
  775. }
  776. })
  777. }
  778. }
  779. func TestHandler_extractJWK(t *testing.T) {
  780. prov := newProv()
  781. provName := url.PathEscape(prov.GetName())
  782. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  783. assert.FatalError(t, err)
  784. kid, err := jwk.Thumbprint(crypto.SHA256)
  785. assert.FatalError(t, err)
  786. pub := jwk.Public()
  787. pub.KeyID = base64.RawURLEncoding.EncodeToString(kid)
  788. so := new(jose.SignerOptions)
  789. so.WithHeader("jwk", pub)
  790. signer, err := jose.NewSigner(jose.SigningKey{
  791. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  792. Key: jwk.Key,
  793. }, so)
  794. assert.FatalError(t, err)
  795. jws, err := signer.Sign([]byte("baz"))
  796. assert.FatalError(t, err)
  797. raw, err := jws.CompactSerialize()
  798. assert.FatalError(t, err)
  799. parsedJWS, err := jose.ParseJWS(raw)
  800. assert.FatalError(t, err)
  801. u := fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/1234",
  802. provName)
  803. type test struct {
  804. db acme.DB
  805. ctx context.Context
  806. next func(http.ResponseWriter, *http.Request)
  807. err *acme.Error
  808. statusCode int
  809. }
  810. var tests = map[string]func(t *testing.T) test{
  811. "fail/no-jws": func(t *testing.T) test {
  812. return test{
  813. db: &acme.MockDB{},
  814. ctx: acme.NewProvisionerContext(context.Background(), prov),
  815. statusCode: 500,
  816. err: acme.NewErrorISE("jws expected in request context"),
  817. }
  818. },
  819. "fail/nil-jws": func(t *testing.T) test {
  820. ctx := acme.NewProvisionerContext(context.Background(), prov)
  821. ctx = context.WithValue(ctx, jwsContextKey, nil)
  822. return test{
  823. db: &acme.MockDB{},
  824. ctx: ctx,
  825. statusCode: 500,
  826. err: acme.NewErrorISE("jws expected in request context"),
  827. }
  828. },
  829. "fail/nil-jwk": func(t *testing.T) test {
  830. _jws := &jose.JSONWebSignature{
  831. Signatures: []jose.Signature{
  832. {
  833. Protected: jose.Header{
  834. JSONWebKey: nil,
  835. },
  836. },
  837. },
  838. }
  839. ctx := acme.NewProvisionerContext(context.Background(), prov)
  840. ctx = context.WithValue(ctx, jwsContextKey, _jws)
  841. return test{
  842. db: &acme.MockDB{},
  843. ctx: ctx,
  844. statusCode: 400,
  845. err: acme.NewError(acme.ErrorMalformedType, "jwk expected in protected header"),
  846. }
  847. },
  848. "fail/invalid-jwk": func(t *testing.T) test {
  849. _jws := &jose.JSONWebSignature{
  850. Signatures: []jose.Signature{
  851. {
  852. Protected: jose.Header{
  853. JSONWebKey: &jose.JSONWebKey{Key: "foo"},
  854. },
  855. },
  856. },
  857. }
  858. ctx := acme.NewProvisionerContext(context.Background(), prov)
  859. ctx = context.WithValue(ctx, jwsContextKey, _jws)
  860. return test{
  861. db: &acme.MockDB{},
  862. ctx: ctx,
  863. statusCode: 400,
  864. err: acme.NewError(acme.ErrorMalformedType, "invalid jwk in protected header"),
  865. }
  866. },
  867. "fail/GetAccountByKey-error": func(t *testing.T) test {
  868. ctx := acme.NewProvisionerContext(context.Background(), prov)
  869. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  870. return test{
  871. ctx: ctx,
  872. db: &acme.MockDB{
  873. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  874. assert.Equals(t, kid, pub.KeyID)
  875. return nil, acme.NewErrorISE("force")
  876. },
  877. },
  878. statusCode: 500,
  879. err: acme.NewErrorISE("force"),
  880. }
  881. },
  882. "fail/account-not-valid": func(t *testing.T) test {
  883. acc := &acme.Account{Status: "deactivated"}
  884. ctx := acme.NewProvisionerContext(context.Background(), prov)
  885. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  886. return test{
  887. ctx: ctx,
  888. db: &acme.MockDB{
  889. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  890. assert.Equals(t, kid, pub.KeyID)
  891. return acc, nil
  892. },
  893. },
  894. statusCode: 401,
  895. err: acme.NewError(acme.ErrorUnauthorizedType, "account is not active"),
  896. }
  897. },
  898. "ok": func(t *testing.T) test {
  899. acc := &acme.Account{Status: "valid"}
  900. ctx := acme.NewProvisionerContext(context.Background(), prov)
  901. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  902. return test{
  903. ctx: ctx,
  904. db: &acme.MockDB{
  905. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  906. assert.Equals(t, kid, pub.KeyID)
  907. return acc, nil
  908. },
  909. },
  910. next: func(w http.ResponseWriter, r *http.Request) {
  911. _acc, err := accountFromContext(r.Context())
  912. assert.FatalError(t, err)
  913. assert.Equals(t, _acc, acc)
  914. _jwk, err := jwkFromContext(r.Context())
  915. assert.FatalError(t, err)
  916. assert.Equals(t, _jwk.KeyID, pub.KeyID)
  917. w.Write(testBody)
  918. },
  919. statusCode: 200,
  920. }
  921. },
  922. "ok/no-account": func(t *testing.T) test {
  923. ctx := acme.NewProvisionerContext(context.Background(), prov)
  924. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  925. return test{
  926. ctx: ctx,
  927. db: &acme.MockDB{
  928. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  929. assert.Equals(t, kid, pub.KeyID)
  930. return nil, acme.ErrNotFound
  931. },
  932. },
  933. next: func(w http.ResponseWriter, r *http.Request) {
  934. _acc, err := accountFromContext(r.Context())
  935. assert.NotNil(t, err)
  936. assert.Nil(t, _acc)
  937. _jwk, err := jwkFromContext(r.Context())
  938. assert.FatalError(t, err)
  939. assert.Equals(t, _jwk.KeyID, pub.KeyID)
  940. w.Write(testBody)
  941. },
  942. statusCode: 200,
  943. }
  944. },
  945. }
  946. for name, run := range tests {
  947. tc := run(t)
  948. t.Run(name, func(t *testing.T) {
  949. ctx := newBaseContext(tc.ctx, tc.db)
  950. req := httptest.NewRequest("GET", u, nil)
  951. req = req.WithContext(ctx)
  952. w := httptest.NewRecorder()
  953. extractJWK(tc.next)(w, req)
  954. res := w.Result()
  955. assert.Equals(t, res.StatusCode, tc.statusCode)
  956. body, err := io.ReadAll(res.Body)
  957. res.Body.Close()
  958. assert.FatalError(t, err)
  959. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  960. var ae acme.Error
  961. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  962. assert.Equals(t, ae.Type, tc.err.Type)
  963. assert.Equals(t, ae.Detail, tc.err.Detail)
  964. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  965. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  966. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  967. } else {
  968. assert.Equals(t, bytes.TrimSpace(body), testBody)
  969. }
  970. })
  971. }
  972. }
  973. func TestHandler_validateJWS(t *testing.T) {
  974. u := "https://ca.smallstep.com/acme/account/1234"
  975. type test struct {
  976. db acme.DB
  977. ctx context.Context
  978. next func(http.ResponseWriter, *http.Request)
  979. err *acme.Error
  980. statusCode int
  981. }
  982. var tests = map[string]func(t *testing.T) test{
  983. "fail/no-jws": func(t *testing.T) test {
  984. return test{
  985. db: &acme.MockDB{},
  986. ctx: context.Background(),
  987. statusCode: 500,
  988. err: acme.NewErrorISE("jws expected in request context"),
  989. }
  990. },
  991. "fail/nil-jws": func(t *testing.T) test {
  992. return test{
  993. db: &acme.MockDB{},
  994. ctx: context.WithValue(context.Background(), jwsContextKey, nil),
  995. statusCode: 500,
  996. err: acme.NewErrorISE("jws expected in request context"),
  997. }
  998. },
  999. "fail/no-signature": func(t *testing.T) test {
  1000. return test{
  1001. db: &acme.MockDB{},
  1002. ctx: context.WithValue(context.Background(), jwsContextKey, &jose.JSONWebSignature{}),
  1003. statusCode: 400,
  1004. err: acme.NewError(acme.ErrorMalformedType, "request body does not contain a signature"),
  1005. }
  1006. },
  1007. "fail/more-than-one-signature": func(t *testing.T) test {
  1008. jws := &jose.JSONWebSignature{
  1009. Signatures: []jose.Signature{
  1010. {},
  1011. {},
  1012. },
  1013. }
  1014. return test{
  1015. db: &acme.MockDB{},
  1016. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1017. statusCode: 400,
  1018. err: acme.NewError(acme.ErrorMalformedType, "request body contains more than one signature"),
  1019. }
  1020. },
  1021. "fail/unprotected-header-not-empty": func(t *testing.T) test {
  1022. jws := &jose.JSONWebSignature{
  1023. Signatures: []jose.Signature{
  1024. {Unprotected: jose.Header{Nonce: "abc"}},
  1025. },
  1026. }
  1027. return test{
  1028. db: &acme.MockDB{},
  1029. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1030. statusCode: 400,
  1031. err: acme.NewError(acme.ErrorMalformedType, "unprotected header must not be used"),
  1032. }
  1033. },
  1034. "fail/unsuitable-algorithm-none": func(t *testing.T) test {
  1035. jws := &jose.JSONWebSignature{
  1036. Signatures: []jose.Signature{
  1037. {Protected: jose.Header{Algorithm: "none"}},
  1038. },
  1039. }
  1040. return test{
  1041. db: &acme.MockDB{},
  1042. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1043. statusCode: 400,
  1044. err: acme.NewError(acme.ErrorBadSignatureAlgorithmType, "unsuitable algorithm: none"),
  1045. }
  1046. },
  1047. "fail/unsuitable-algorithm-mac": func(t *testing.T) test {
  1048. jws := &jose.JSONWebSignature{
  1049. Signatures: []jose.Signature{
  1050. {Protected: jose.Header{Algorithm: jose.HS256}},
  1051. },
  1052. }
  1053. return test{
  1054. db: &acme.MockDB{},
  1055. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1056. statusCode: 400,
  1057. err: acme.NewError(acme.ErrorBadSignatureAlgorithmType, "unsuitable algorithm: %s", jose.HS256),
  1058. }
  1059. },
  1060. "fail/rsa-key-&-alg-mismatch": func(t *testing.T) test {
  1061. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  1062. assert.FatalError(t, err)
  1063. pub := jwk.Public()
  1064. jws := &jose.JSONWebSignature{
  1065. Signatures: []jose.Signature{
  1066. {
  1067. Protected: jose.Header{
  1068. Algorithm: jose.RS256,
  1069. JSONWebKey: &pub,
  1070. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1071. "url": u,
  1072. },
  1073. },
  1074. },
  1075. },
  1076. }
  1077. return test{
  1078. db: &acme.MockDB{
  1079. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1080. return nil
  1081. },
  1082. },
  1083. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1084. statusCode: 400,
  1085. err: acme.NewError(acme.ErrorMalformedType, "jws key type and algorithm do not match"),
  1086. }
  1087. },
  1088. "fail/rsa-key-too-small": func(t *testing.T) test {
  1089. jwk, err := jose.GenerateJWK("RSA", "", "", "sig", "", 1024)
  1090. assert.FatalError(t, err)
  1091. pub := jwk.Public()
  1092. jws := &jose.JSONWebSignature{
  1093. Signatures: []jose.Signature{
  1094. {
  1095. Protected: jose.Header{
  1096. Algorithm: jose.RS256,
  1097. JSONWebKey: &pub,
  1098. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1099. "url": u,
  1100. },
  1101. },
  1102. },
  1103. },
  1104. }
  1105. return test{
  1106. db: &acme.MockDB{
  1107. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1108. return nil
  1109. },
  1110. },
  1111. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1112. statusCode: 400,
  1113. err: acme.NewError(acme.ErrorMalformedType, "rsa keys must be at least 2048 bits (256 bytes) in size"),
  1114. }
  1115. },
  1116. "fail/UseNonce-error": func(t *testing.T) test {
  1117. jws := &jose.JSONWebSignature{
  1118. Signatures: []jose.Signature{
  1119. {Protected: jose.Header{Algorithm: jose.ES256}},
  1120. },
  1121. }
  1122. return test{
  1123. db: &acme.MockDB{
  1124. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1125. return acme.NewErrorISE("force")
  1126. },
  1127. },
  1128. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1129. statusCode: 500,
  1130. err: acme.NewErrorISE("force"),
  1131. }
  1132. },
  1133. "fail/no-url-header": func(t *testing.T) test {
  1134. jws := &jose.JSONWebSignature{
  1135. Signatures: []jose.Signature{
  1136. {Protected: jose.Header{Algorithm: jose.ES256}},
  1137. },
  1138. }
  1139. return test{
  1140. db: &acme.MockDB{
  1141. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1142. return nil
  1143. },
  1144. },
  1145. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1146. statusCode: 400,
  1147. err: acme.NewError(acme.ErrorMalformedType, "jws missing url protected header"),
  1148. }
  1149. },
  1150. "fail/url-mismatch": func(t *testing.T) test {
  1151. jws := &jose.JSONWebSignature{
  1152. Signatures: []jose.Signature{
  1153. {
  1154. Protected: jose.Header{
  1155. Algorithm: jose.ES256,
  1156. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1157. "url": "foo",
  1158. },
  1159. },
  1160. },
  1161. },
  1162. }
  1163. return test{
  1164. db: &acme.MockDB{
  1165. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1166. return nil
  1167. },
  1168. },
  1169. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1170. statusCode: 400,
  1171. err: acme.NewError(acme.ErrorMalformedType, "url header in JWS (foo) does not match request url (%s)", u),
  1172. }
  1173. },
  1174. "fail/both-jwk-kid": func(t *testing.T) test {
  1175. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  1176. assert.FatalError(t, err)
  1177. pub := jwk.Public()
  1178. jws := &jose.JSONWebSignature{
  1179. Signatures: []jose.Signature{
  1180. {
  1181. Protected: jose.Header{
  1182. Algorithm: jose.ES256,
  1183. KeyID: "bar",
  1184. JSONWebKey: &pub,
  1185. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1186. "url": u,
  1187. },
  1188. },
  1189. },
  1190. },
  1191. }
  1192. return test{
  1193. db: &acme.MockDB{
  1194. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1195. return nil
  1196. },
  1197. },
  1198. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1199. statusCode: 400,
  1200. err: acme.NewError(acme.ErrorMalformedType, "jwk and kid are mutually exclusive"),
  1201. }
  1202. },
  1203. "fail/no-jwk-kid": func(t *testing.T) test {
  1204. jws := &jose.JSONWebSignature{
  1205. Signatures: []jose.Signature{
  1206. {
  1207. Protected: jose.Header{
  1208. Algorithm: jose.ES256,
  1209. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1210. "url": u,
  1211. },
  1212. },
  1213. },
  1214. },
  1215. }
  1216. return test{
  1217. db: &acme.MockDB{
  1218. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1219. return nil
  1220. },
  1221. },
  1222. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1223. statusCode: 400,
  1224. err: acme.NewError(acme.ErrorMalformedType, "either jwk or kid must be defined in jws protected header"),
  1225. }
  1226. },
  1227. "ok/kid": func(t *testing.T) test {
  1228. jws := &jose.JSONWebSignature{
  1229. Signatures: []jose.Signature{
  1230. {
  1231. Protected: jose.Header{
  1232. Algorithm: jose.ES256,
  1233. KeyID: "bar",
  1234. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1235. "url": u,
  1236. },
  1237. },
  1238. },
  1239. },
  1240. }
  1241. return test{
  1242. db: &acme.MockDB{
  1243. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1244. return nil
  1245. },
  1246. },
  1247. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1248. next: func(w http.ResponseWriter, r *http.Request) {
  1249. w.Write(testBody)
  1250. },
  1251. statusCode: 200,
  1252. }
  1253. },
  1254. "ok/jwk/ecdsa": func(t *testing.T) test {
  1255. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  1256. assert.FatalError(t, err)
  1257. pub := jwk.Public()
  1258. jws := &jose.JSONWebSignature{
  1259. Signatures: []jose.Signature{
  1260. {
  1261. Protected: jose.Header{
  1262. Algorithm: jose.ES256,
  1263. JSONWebKey: &pub,
  1264. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1265. "url": u,
  1266. },
  1267. },
  1268. },
  1269. },
  1270. }
  1271. return test{
  1272. db: &acme.MockDB{
  1273. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1274. return nil
  1275. },
  1276. },
  1277. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1278. next: func(w http.ResponseWriter, r *http.Request) {
  1279. w.Write(testBody)
  1280. },
  1281. statusCode: 200,
  1282. }
  1283. },
  1284. "ok/jwk/rsa": func(t *testing.T) test {
  1285. jwk, err := jose.GenerateJWK("RSA", "", "", "sig", "", 2048)
  1286. assert.FatalError(t, err)
  1287. pub := jwk.Public()
  1288. jws := &jose.JSONWebSignature{
  1289. Signatures: []jose.Signature{
  1290. {
  1291. Protected: jose.Header{
  1292. Algorithm: jose.RS256,
  1293. JSONWebKey: &pub,
  1294. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1295. "url": u,
  1296. },
  1297. },
  1298. },
  1299. },
  1300. }
  1301. return test{
  1302. db: &acme.MockDB{
  1303. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1304. return nil
  1305. },
  1306. },
  1307. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1308. next: func(w http.ResponseWriter, r *http.Request) {
  1309. w.Write(testBody)
  1310. },
  1311. statusCode: 200,
  1312. }
  1313. },
  1314. }
  1315. for name, run := range tests {
  1316. tc := run(t)
  1317. t.Run(name, func(t *testing.T) {
  1318. ctx := newBaseContext(tc.ctx, tc.db)
  1319. req := httptest.NewRequest("GET", u, nil)
  1320. req = req.WithContext(ctx)
  1321. w := httptest.NewRecorder()
  1322. validateJWS(tc.next)(w, req)
  1323. res := w.Result()
  1324. assert.Equals(t, res.StatusCode, tc.statusCode)
  1325. body, err := io.ReadAll(res.Body)
  1326. res.Body.Close()
  1327. assert.FatalError(t, err)
  1328. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  1329. var ae acme.Error
  1330. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  1331. assert.Equals(t, ae.Type, tc.err.Type)
  1332. assert.Equals(t, ae.Detail, tc.err.Detail)
  1333. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  1334. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  1335. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  1336. } else {
  1337. assert.Equals(t, bytes.TrimSpace(body), testBody)
  1338. }
  1339. })
  1340. }
  1341. }
  1342. func Test_canExtractJWKFrom(t *testing.T) {
  1343. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  1344. assert.FatalError(t, err)
  1345. type args struct {
  1346. jws *jose.JSONWebSignature
  1347. }
  1348. tests := []struct {
  1349. name string
  1350. args args
  1351. want bool
  1352. }{
  1353. {
  1354. name: "no-jws",
  1355. args: args{
  1356. jws: nil,
  1357. },
  1358. want: false,
  1359. },
  1360. {
  1361. name: "no-signatures",
  1362. args: args{
  1363. jws: &jose.JSONWebSignature{
  1364. Signatures: []jose.Signature{},
  1365. },
  1366. },
  1367. want: false,
  1368. },
  1369. {
  1370. name: "no-jwk",
  1371. args: args{
  1372. jws: &jose.JSONWebSignature{
  1373. Signatures: []jose.Signature{
  1374. {
  1375. Protected: jose.Header{},
  1376. },
  1377. },
  1378. },
  1379. },
  1380. want: false,
  1381. },
  1382. {
  1383. name: "ok",
  1384. args: args{
  1385. jws: &jose.JSONWebSignature{
  1386. Signatures: []jose.Signature{
  1387. {
  1388. Protected: jose.Header{
  1389. JSONWebKey: jwk,
  1390. },
  1391. },
  1392. },
  1393. },
  1394. },
  1395. want: true,
  1396. },
  1397. }
  1398. for _, tt := range tests {
  1399. t.Run(tt.name, func(t *testing.T) {
  1400. if got := canExtractJWKFrom(tt.args.jws); got != tt.want {
  1401. t.Errorf("canExtractJWKFrom() = %v, want %v", got, tt.want)
  1402. }
  1403. })
  1404. }
  1405. }
  1406. func TestHandler_extractOrLookupJWK(t *testing.T) {
  1407. u := "https://ca.smallstep.com/acme/account"
  1408. type test struct {
  1409. db acme.DB
  1410. linker acme.Linker
  1411. statusCode int
  1412. ctx context.Context
  1413. err *acme.Error
  1414. next func(w http.ResponseWriter, r *http.Request)
  1415. }
  1416. var tests = map[string]func(t *testing.T) test{
  1417. "ok/extract": func(t *testing.T) test {
  1418. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  1419. assert.FatalError(t, err)
  1420. kid, err := jwk.Thumbprint(crypto.SHA256)
  1421. assert.FatalError(t, err)
  1422. pub := jwk.Public()
  1423. pub.KeyID = base64.RawURLEncoding.EncodeToString(kid)
  1424. so := new(jose.SignerOptions)
  1425. so.WithHeader("jwk", pub) // JWK for certificate private key flow
  1426. signer, err := jose.NewSigner(jose.SigningKey{
  1427. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  1428. Key: jwk.Key,
  1429. }, so)
  1430. assert.FatalError(t, err)
  1431. signed, err := signer.Sign([]byte("foo"))
  1432. assert.FatalError(t, err)
  1433. raw, err := signed.CompactSerialize()
  1434. assert.FatalError(t, err)
  1435. parsedJWS, err := jose.ParseJWS(raw)
  1436. assert.FatalError(t, err)
  1437. return test{
  1438. linker: acme.NewLinker("dns", "acme"),
  1439. db: &acme.MockDB{
  1440. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  1441. assert.Equals(t, kid, pub.KeyID)
  1442. return nil, acme.ErrNotFound
  1443. },
  1444. },
  1445. ctx: context.WithValue(context.Background(), jwsContextKey, parsedJWS),
  1446. statusCode: 200,
  1447. next: func(w http.ResponseWriter, r *http.Request) {
  1448. w.Write(testBody)
  1449. },
  1450. }
  1451. },
  1452. "ok/lookup": func(t *testing.T) test {
  1453. prov := newProv()
  1454. provName := url.PathEscape(prov.GetName())
  1455. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  1456. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  1457. assert.FatalError(t, err)
  1458. accID := "accID"
  1459. prefix := fmt.Sprintf("%s/acme/%s/account/", baseURL, provName)
  1460. so := new(jose.SignerOptions)
  1461. so.WithHeader("kid", fmt.Sprintf("%s%s", prefix, accID)) // KID for account private key flow
  1462. signer, err := jose.NewSigner(jose.SigningKey{
  1463. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  1464. Key: jwk.Key,
  1465. }, so)
  1466. assert.FatalError(t, err)
  1467. jws, err := signer.Sign([]byte("baz"))
  1468. assert.FatalError(t, err)
  1469. raw, err := jws.CompactSerialize()
  1470. assert.FatalError(t, err)
  1471. parsedJWS, err := jose.ParseJWS(raw)
  1472. assert.FatalError(t, err)
  1473. acc := &acme.Account{ID: "accID", Key: jwk, Status: "valid"}
  1474. ctx := acme.NewProvisionerContext(context.Background(), prov)
  1475. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  1476. return test{
  1477. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  1478. db: &acme.MockDB{
  1479. MockGetAccount: func(ctx context.Context, accID string) (*acme.Account, error) {
  1480. assert.Equals(t, accID, acc.ID)
  1481. return acc, nil
  1482. },
  1483. },
  1484. ctx: ctx,
  1485. statusCode: 200,
  1486. next: func(w http.ResponseWriter, r *http.Request) {
  1487. w.Write(testBody)
  1488. },
  1489. }
  1490. },
  1491. }
  1492. for name, prep := range tests {
  1493. tc := prep(t)
  1494. t.Run(name, func(t *testing.T) {
  1495. ctx := newBaseContext(tc.ctx, tc.db, tc.linker)
  1496. req := httptest.NewRequest("GET", u, nil)
  1497. req = req.WithContext(ctx)
  1498. w := httptest.NewRecorder()
  1499. extractOrLookupJWK(tc.next)(w, req)
  1500. res := w.Result()
  1501. assert.Equals(t, res.StatusCode, tc.statusCode)
  1502. body, err := io.ReadAll(res.Body)
  1503. res.Body.Close()
  1504. assert.FatalError(t, err)
  1505. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  1506. var ae acme.Error
  1507. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  1508. assert.Equals(t, ae.Type, tc.err.Type)
  1509. assert.Equals(t, ae.Detail, tc.err.Detail)
  1510. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  1511. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  1512. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  1513. } else {
  1514. assert.Equals(t, bytes.TrimSpace(body), testBody)
  1515. }
  1516. })
  1517. }
  1518. }
  1519. func TestHandler_checkPrerequisites(t *testing.T) {
  1520. prov := newProv()
  1521. provName := url.PathEscape(prov.GetName())
  1522. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  1523. u := fmt.Sprintf("%s/acme/%s/account/1234",
  1524. baseURL, provName)
  1525. type test struct {
  1526. linker acme.Linker
  1527. ctx context.Context
  1528. prerequisitesChecker func(context.Context) (bool, error)
  1529. next func(http.ResponseWriter, *http.Request)
  1530. err *acme.Error
  1531. statusCode int
  1532. }
  1533. var tests = map[string]func(t *testing.T) test{
  1534. "fail/error": func(t *testing.T) test {
  1535. ctx := acme.NewProvisionerContext(context.Background(), prov)
  1536. return test{
  1537. linker: acme.NewLinker("dns", "acme"),
  1538. ctx: ctx,
  1539. prerequisitesChecker: func(context.Context) (bool, error) { return false, errors.New("force") },
  1540. next: func(w http.ResponseWriter, r *http.Request) {
  1541. w.Write(testBody)
  1542. },
  1543. err: acme.WrapErrorISE(errors.New("force"), "error checking acme provisioner prerequisites"),
  1544. statusCode: 500,
  1545. }
  1546. },
  1547. "fail/prerequisites-nok": func(t *testing.T) test {
  1548. ctx := acme.NewProvisionerContext(context.Background(), prov)
  1549. return test{
  1550. linker: acme.NewLinker("dns", "acme"),
  1551. ctx: ctx,
  1552. prerequisitesChecker: func(context.Context) (bool, error) { return false, nil },
  1553. next: func(w http.ResponseWriter, r *http.Request) {
  1554. w.Write(testBody)
  1555. },
  1556. err: acme.NewError(acme.ErrorNotImplementedType, "acme provisioner configuration lacks prerequisites"),
  1557. statusCode: 501,
  1558. }
  1559. },
  1560. "ok": func(t *testing.T) test {
  1561. ctx := acme.NewProvisionerContext(context.Background(), prov)
  1562. return test{
  1563. linker: acme.NewLinker("dns", "acme"),
  1564. ctx: ctx,
  1565. prerequisitesChecker: func(context.Context) (bool, error) { return true, nil },
  1566. next: func(w http.ResponseWriter, r *http.Request) {
  1567. w.Write(testBody)
  1568. },
  1569. statusCode: 200,
  1570. }
  1571. },
  1572. }
  1573. for name, run := range tests {
  1574. tc := run(t)
  1575. t.Run(name, func(t *testing.T) {
  1576. ctx := acme.NewPrerequisitesCheckerContext(tc.ctx, tc.prerequisitesChecker)
  1577. req := httptest.NewRequest("GET", u, nil)
  1578. req = req.WithContext(ctx)
  1579. w := httptest.NewRecorder()
  1580. checkPrerequisites(tc.next)(w, req)
  1581. res := w.Result()
  1582. assert.Equals(t, res.StatusCode, tc.statusCode)
  1583. body, err := io.ReadAll(res.Body)
  1584. res.Body.Close()
  1585. assert.FatalError(t, err)
  1586. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  1587. var ae acme.Error
  1588. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  1589. assert.Equals(t, ae.Type, tc.err.Type)
  1590. assert.Equals(t, ae.Detail, tc.err.Detail)
  1591. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  1592. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  1593. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  1594. } else {
  1595. assert.Equals(t, bytes.TrimSpace(body), testBody)
  1596. }
  1597. })
  1598. }
  1599. }