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. "go.step.sm/crypto/keyutil"
  21. )
  22. var testBody = []byte("foo")
  23. func testNext(w http.ResponseWriter, r *http.Request) {
  24. w.Write(testBody)
  25. }
  26. func newBaseContext(ctx context.Context, args ...interface{}) context.Context {
  27. for _, a := range args {
  28. switch v := a.(type) {
  29. case acme.DB:
  30. ctx = acme.NewDatabaseContext(ctx, v)
  31. case acme.Linker:
  32. ctx = acme.NewLinkerContext(ctx, v)
  33. case acme.PrerequisitesChecker:
  34. ctx = acme.NewPrerequisitesCheckerContext(ctx, v)
  35. }
  36. }
  37. return ctx
  38. }
  39. func TestHandler_addNonce(t *testing.T) {
  40. u := "https://ca.smallstep.com/acme/new-nonce"
  41. type test struct {
  42. db acme.DB
  43. err *acme.Error
  44. statusCode int
  45. }
  46. var tests = map[string]func(t *testing.T) test{
  47. "fail/AddNonce-error": func(t *testing.T) test {
  48. return test{
  49. db: &acme.MockDB{
  50. MockCreateNonce: func(ctx context.Context) (acme.Nonce, error) {
  51. return acme.Nonce(""), acme.NewErrorISE("force")
  52. },
  53. },
  54. statusCode: 500,
  55. err: acme.NewErrorISE("force"),
  56. }
  57. },
  58. "ok": func(t *testing.T) test {
  59. return test{
  60. db: &acme.MockDB{
  61. MockCreateNonce: func(ctx context.Context) (acme.Nonce, error) {
  62. return "bar", nil
  63. },
  64. },
  65. statusCode: 200,
  66. }
  67. },
  68. }
  69. for name, run := range tests {
  70. tc := run(t)
  71. t.Run(name, func(t *testing.T) {
  72. ctx := newBaseContext(context.Background(), tc.db)
  73. req := httptest.NewRequest("GET", u, nil).WithContext(ctx)
  74. w := httptest.NewRecorder()
  75. addNonce(testNext)(w, req)
  76. res := w.Result()
  77. assert.Equals(t, res.StatusCode, tc.statusCode)
  78. body, err := io.ReadAll(res.Body)
  79. res.Body.Close()
  80. assert.FatalError(t, err)
  81. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  82. var ae acme.Error
  83. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  84. assert.Equals(t, ae.Type, tc.err.Type)
  85. assert.Equals(t, ae.Detail, tc.err.Detail)
  86. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  87. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  88. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  89. } else {
  90. assert.Equals(t, res.Header["Replay-Nonce"], []string{"bar"})
  91. assert.Equals(t, res.Header["Cache-Control"], []string{"no-store"})
  92. assert.Equals(t, bytes.TrimSpace(body), testBody)
  93. }
  94. })
  95. }
  96. }
  97. func TestHandler_addDirLink(t *testing.T) {
  98. prov := newProv()
  99. provName := url.PathEscape(prov.GetName())
  100. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  101. type test struct {
  102. link string
  103. statusCode int
  104. ctx context.Context
  105. err *acme.Error
  106. }
  107. var tests = map[string]func(t *testing.T) test{
  108. "ok": func(t *testing.T) test {
  109. ctx := acme.NewProvisionerContext(context.Background(), prov)
  110. ctx = acme.NewLinkerContext(ctx, acme.NewLinker("test.ca.smallstep.com", "acme"))
  111. return test{
  112. ctx: ctx,
  113. link: fmt.Sprintf("%s/acme/%s/directory", baseURL.String(), provName),
  114. statusCode: 200,
  115. }
  116. },
  117. }
  118. for name, run := range tests {
  119. tc := run(t)
  120. t.Run(name, func(t *testing.T) {
  121. req := httptest.NewRequest("GET", "/foo", nil)
  122. req = req.WithContext(tc.ctx)
  123. w := httptest.NewRecorder()
  124. addDirLink(testNext)(w, req)
  125. res := w.Result()
  126. assert.Equals(t, res.StatusCode, tc.statusCode)
  127. body, err := io.ReadAll(res.Body)
  128. res.Body.Close()
  129. assert.FatalError(t, err)
  130. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  131. var ae acme.Error
  132. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  133. assert.Equals(t, ae.Type, tc.err.Type)
  134. assert.Equals(t, ae.Detail, tc.err.Detail)
  135. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  136. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  137. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  138. } else {
  139. assert.Equals(t, res.Header["Link"], []string{fmt.Sprintf("<%s>;rel=\"index\"", tc.link)})
  140. assert.Equals(t, bytes.TrimSpace(body), testBody)
  141. }
  142. })
  143. }
  144. }
  145. func TestHandler_verifyContentType(t *testing.T) {
  146. prov := newProv()
  147. escProvName := url.PathEscape(prov.GetName())
  148. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  149. u := fmt.Sprintf("%s/acme/%s/certificate/abc123", baseURL.String(), escProvName)
  150. type test struct {
  151. ctx context.Context
  152. contentType string
  153. err *acme.Error
  154. statusCode int
  155. url string
  156. }
  157. var tests = map[string]func(t *testing.T) test{
  158. "fail/provisioner-not-set": func(t *testing.T) test {
  159. return test{
  160. url: u,
  161. ctx: context.Background(),
  162. contentType: "foo",
  163. statusCode: 500,
  164. err: acme.NewErrorISE("provisioner expected in request context"),
  165. }
  166. },
  167. "fail/general-bad-content-type": func(t *testing.T) test {
  168. return test{
  169. url: u,
  170. ctx: acme.NewProvisionerContext(context.Background(), prov),
  171. contentType: "foo",
  172. statusCode: 400,
  173. err: acme.NewError(acme.ErrorMalformedType, "expected content-type to be in [application/jose+json], but got foo"),
  174. }
  175. },
  176. "fail/certificate-bad-content-type": func(t *testing.T) test {
  177. return test{
  178. ctx: acme.NewProvisionerContext(context.Background(), prov),
  179. contentType: "foo",
  180. statusCode: 400,
  181. err: acme.NewError(acme.ErrorMalformedType, "expected content-type to be in [application/jose+json application/pkix-cert application/pkcs7-mime], but got foo"),
  182. }
  183. },
  184. "ok": func(t *testing.T) test {
  185. return test{
  186. ctx: acme.NewProvisionerContext(context.Background(), prov),
  187. contentType: "application/jose+json",
  188. statusCode: 200,
  189. }
  190. },
  191. "ok/certificate/pkix-cert": func(t *testing.T) test {
  192. return test{
  193. ctx: acme.NewProvisionerContext(context.Background(), prov),
  194. contentType: "application/pkix-cert",
  195. statusCode: 200,
  196. }
  197. },
  198. "ok/certificate/jose+json": func(t *testing.T) test {
  199. return test{
  200. ctx: acme.NewProvisionerContext(context.Background(), prov),
  201. contentType: "application/jose+json",
  202. statusCode: 200,
  203. }
  204. },
  205. "ok/certificate/pkcs7-mime": func(t *testing.T) test {
  206. return test{
  207. ctx: acme.NewProvisionerContext(context.Background(), prov),
  208. contentType: "application/pkcs7-mime",
  209. statusCode: 200,
  210. }
  211. },
  212. }
  213. for name, run := range tests {
  214. tc := run(t)
  215. t.Run(name, func(t *testing.T) {
  216. _u := u
  217. if tc.url != "" {
  218. _u = tc.url
  219. }
  220. req := httptest.NewRequest("GET", _u, nil)
  221. req = req.WithContext(tc.ctx)
  222. req.Header.Add("Content-Type", tc.contentType)
  223. w := httptest.NewRecorder()
  224. verifyContentType(testNext)(w, req)
  225. res := w.Result()
  226. assert.Equals(t, res.StatusCode, tc.statusCode)
  227. body, err := io.ReadAll(res.Body)
  228. res.Body.Close()
  229. assert.FatalError(t, err)
  230. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  231. var ae acme.Error
  232. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  233. assert.Equals(t, ae.Type, tc.err.Type)
  234. assert.Equals(t, ae.Detail, tc.err.Detail)
  235. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  236. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  237. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  238. } else {
  239. assert.Equals(t, bytes.TrimSpace(body), testBody)
  240. }
  241. })
  242. }
  243. }
  244. func TestHandler_isPostAsGet(t *testing.T) {
  245. u := "https://ca.smallstep.com/acme/new-account"
  246. type test struct {
  247. ctx context.Context
  248. err *acme.Error
  249. statusCode int
  250. }
  251. var tests = map[string]func(t *testing.T) test{
  252. "fail/no-payload": func(t *testing.T) test {
  253. return test{
  254. ctx: context.Background(),
  255. statusCode: 500,
  256. err: acme.NewErrorISE("payload expected in request context"),
  257. }
  258. },
  259. "fail/nil-payload": func(t *testing.T) test {
  260. return test{
  261. ctx: context.WithValue(context.Background(), payloadContextKey, nil),
  262. statusCode: 500,
  263. err: acme.NewErrorISE("payload expected in request context"),
  264. }
  265. },
  266. "fail/not-post-as-get": func(t *testing.T) test {
  267. return test{
  268. ctx: context.WithValue(context.Background(), payloadContextKey, &payloadInfo{}),
  269. statusCode: 400,
  270. err: acme.NewError(acme.ErrorMalformedType, "expected POST-as-GET"),
  271. }
  272. },
  273. "ok": func(t *testing.T) test {
  274. return test{
  275. ctx: context.WithValue(context.Background(), payloadContextKey, &payloadInfo{isPostAsGet: true}),
  276. statusCode: 200,
  277. }
  278. },
  279. }
  280. for name, run := range tests {
  281. tc := run(t)
  282. t.Run(name, func(t *testing.T) {
  283. // h := &Handler{}
  284. req := httptest.NewRequest("GET", u, nil)
  285. req = req.WithContext(tc.ctx)
  286. w := httptest.NewRecorder()
  287. isPostAsGet(testNext)(w, req)
  288. res := w.Result()
  289. assert.Equals(t, res.StatusCode, tc.statusCode)
  290. body, err := io.ReadAll(res.Body)
  291. res.Body.Close()
  292. assert.FatalError(t, err)
  293. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  294. var ae acme.Error
  295. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  296. assert.Equals(t, ae.Type, tc.err.Type)
  297. assert.Equals(t, ae.Detail, tc.err.Detail)
  298. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  299. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  300. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  301. } else {
  302. assert.Equals(t, bytes.TrimSpace(body), testBody)
  303. }
  304. })
  305. }
  306. }
  307. type errReader int
  308. func (errReader) Read(p []byte) (n int, err error) {
  309. return 0, errors.New("force")
  310. }
  311. func (errReader) Close() error {
  312. return nil
  313. }
  314. func TestHandler_parseJWS(t *testing.T) {
  315. u := "https://ca.smallstep.com/acme/new-account"
  316. type test struct {
  317. next nextHTTP
  318. body io.Reader
  319. err *acme.Error
  320. statusCode int
  321. }
  322. var tests = map[string]func(t *testing.T) test{
  323. "fail/read-body-error": func(t *testing.T) test {
  324. return test{
  325. body: errReader(0),
  326. statusCode: 500,
  327. err: acme.NewErrorISE("failed to read request body: force"),
  328. }
  329. },
  330. "fail/parse-jws-error": func(t *testing.T) test {
  331. return test{
  332. body: strings.NewReader("foo"),
  333. statusCode: 400,
  334. err: acme.NewError(acme.ErrorMalformedType, "failed to parse JWS from request body: square/go-jose: compact JWS format must have three parts"),
  335. }
  336. },
  337. "ok": func(t *testing.T) test {
  338. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  339. assert.FatalError(t, err)
  340. signer, err := jose.NewSigner(jose.SigningKey{
  341. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  342. Key: jwk.Key,
  343. }, new(jose.SignerOptions))
  344. assert.FatalError(t, err)
  345. signed, err := signer.Sign([]byte("baz"))
  346. assert.FatalError(t, err)
  347. expRaw, err := signed.CompactSerialize()
  348. assert.FatalError(t, err)
  349. return test{
  350. body: strings.NewReader(expRaw),
  351. next: func(w http.ResponseWriter, r *http.Request) {
  352. jws, err := jwsFromContext(r.Context())
  353. assert.FatalError(t, err)
  354. gotRaw, err := jws.CompactSerialize()
  355. assert.FatalError(t, err)
  356. assert.Equals(t, gotRaw, expRaw)
  357. w.Write(testBody)
  358. },
  359. statusCode: 200,
  360. }
  361. },
  362. }
  363. for name, run := range tests {
  364. tc := run(t)
  365. t.Run(name, func(t *testing.T) {
  366. // h := &Handler{}
  367. req := httptest.NewRequest("GET", u, tc.body)
  368. w := httptest.NewRecorder()
  369. parseJWS(tc.next)(w, req)
  370. res := w.Result()
  371. assert.Equals(t, res.StatusCode, tc.statusCode)
  372. body, err := io.ReadAll(res.Body)
  373. res.Body.Close()
  374. assert.FatalError(t, err)
  375. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  376. var ae acme.Error
  377. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  378. assert.Equals(t, ae.Type, tc.err.Type)
  379. assert.Equals(t, ae.Detail, tc.err.Detail)
  380. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  381. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  382. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  383. } else {
  384. assert.Equals(t, bytes.TrimSpace(body), testBody)
  385. }
  386. })
  387. }
  388. }
  389. func TestHandler_verifyAndExtractJWSPayload(t *testing.T) {
  390. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  391. assert.FatalError(t, err)
  392. _pub := jwk.Public()
  393. pub := &_pub
  394. so := new(jose.SignerOptions)
  395. so.WithHeader("alg", jose.SignatureAlgorithm(jwk.Algorithm))
  396. signer, err := jose.NewSigner(jose.SigningKey{
  397. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  398. Key: jwk.Key,
  399. }, so)
  400. assert.FatalError(t, err)
  401. jws, err := signer.Sign([]byte("baz"))
  402. assert.FatalError(t, err)
  403. raw, err := jws.CompactSerialize()
  404. assert.FatalError(t, err)
  405. parsedJWS, err := jose.ParseJWS(raw)
  406. assert.FatalError(t, err)
  407. u := "https://ca.smallstep.com/acme/account/1234"
  408. type test struct {
  409. ctx context.Context
  410. next func(http.ResponseWriter, *http.Request)
  411. err *acme.Error
  412. statusCode int
  413. }
  414. var tests = map[string]func(t *testing.T) test{
  415. "fail/no-jws": func(t *testing.T) test {
  416. return test{
  417. ctx: context.Background(),
  418. statusCode: 500,
  419. err: acme.NewErrorISE("jws expected in request context"),
  420. }
  421. },
  422. "fail/nil-jws": func(t *testing.T) test {
  423. return test{
  424. ctx: context.WithValue(context.Background(), jwsContextKey, nil),
  425. statusCode: 500,
  426. err: acme.NewErrorISE("jws expected in request context"),
  427. }
  428. },
  429. "fail/no-jwk": func(t *testing.T) test {
  430. return test{
  431. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  432. statusCode: 500,
  433. err: acme.NewErrorISE("jwk expected in request context"),
  434. }
  435. },
  436. "fail/nil-jwk": func(t *testing.T) test {
  437. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  438. return test{
  439. ctx: context.WithValue(ctx, jwsContextKey, nil),
  440. statusCode: 500,
  441. err: acme.NewErrorISE("jwk expected in request context"),
  442. }
  443. },
  444. "fail/verify-jws-failure": func(t *testing.T) test {
  445. _jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  446. assert.FatalError(t, err)
  447. _pub := _jwk.Public()
  448. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  449. ctx = context.WithValue(ctx, jwkContextKey, &_pub)
  450. return test{
  451. ctx: ctx,
  452. statusCode: 400,
  453. err: acme.NewError(acme.ErrorMalformedType, "error verifying jws: square/go-jose: error in cryptographic primitive"),
  454. }
  455. },
  456. "fail/algorithm-mismatch": func(t *testing.T) test {
  457. _pub := *pub
  458. clone := &_pub
  459. clone.Algorithm = jose.HS256
  460. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  461. ctx = context.WithValue(ctx, jwkContextKey, clone)
  462. return test{
  463. ctx: ctx,
  464. statusCode: 400,
  465. err: acme.NewError(acme.ErrorMalformedType, "verifier and signature algorithm do not match"),
  466. }
  467. },
  468. "ok": func(t *testing.T) test {
  469. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  470. ctx = context.WithValue(ctx, jwkContextKey, pub)
  471. return test{
  472. ctx: ctx,
  473. statusCode: 200,
  474. next: func(w http.ResponseWriter, r *http.Request) {
  475. p, err := payloadFromContext(r.Context())
  476. assert.FatalError(t, err)
  477. if assert.NotNil(t, p) {
  478. assert.Equals(t, p.value, []byte("baz"))
  479. assert.False(t, p.isPostAsGet)
  480. assert.False(t, p.isEmptyJSON)
  481. }
  482. w.Write(testBody)
  483. },
  484. }
  485. },
  486. "ok/empty-algorithm-in-jwk": func(t *testing.T) test {
  487. ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
  488. ctx = context.WithValue(ctx, jwkContextKey, pub)
  489. return test{
  490. ctx: ctx,
  491. statusCode: 200,
  492. next: func(w http.ResponseWriter, r *http.Request) {
  493. p, err := payloadFromContext(r.Context())
  494. assert.FatalError(t, err)
  495. if assert.NotNil(t, p) {
  496. assert.Equals(t, p.value, []byte("baz"))
  497. assert.False(t, p.isPostAsGet)
  498. assert.False(t, p.isEmptyJSON)
  499. }
  500. w.Write(testBody)
  501. },
  502. }
  503. },
  504. "ok/post-as-get": func(t *testing.T) test {
  505. _jws, err := signer.Sign([]byte(""))
  506. assert.FatalError(t, err)
  507. _raw, err := _jws.CompactSerialize()
  508. assert.FatalError(t, err)
  509. _parsed, err := jose.ParseJWS(_raw)
  510. assert.FatalError(t, err)
  511. ctx := context.WithValue(context.Background(), jwsContextKey, _parsed)
  512. ctx = context.WithValue(ctx, jwkContextKey, pub)
  513. return test{
  514. ctx: ctx,
  515. statusCode: 200,
  516. next: func(w http.ResponseWriter, r *http.Request) {
  517. p, err := payloadFromContext(r.Context())
  518. assert.FatalError(t, err)
  519. if assert.NotNil(t, p) {
  520. assert.Equals(t, p.value, []byte{})
  521. assert.True(t, p.isPostAsGet)
  522. assert.False(t, p.isEmptyJSON)
  523. }
  524. w.Write(testBody)
  525. },
  526. }
  527. },
  528. "ok/empty-json": func(t *testing.T) test {
  529. _jws, err := signer.Sign([]byte("{}"))
  530. assert.FatalError(t, err)
  531. _raw, err := _jws.CompactSerialize()
  532. assert.FatalError(t, err)
  533. _parsed, err := jose.ParseJWS(_raw)
  534. assert.FatalError(t, err)
  535. ctx := context.WithValue(context.Background(), jwsContextKey, _parsed)
  536. ctx = context.WithValue(ctx, jwkContextKey, pub)
  537. return test{
  538. ctx: ctx,
  539. statusCode: 200,
  540. next: func(w http.ResponseWriter, r *http.Request) {
  541. p, err := payloadFromContext(r.Context())
  542. assert.FatalError(t, err)
  543. if assert.NotNil(t, p) {
  544. assert.Equals(t, p.value, []byte("{}"))
  545. assert.False(t, p.isPostAsGet)
  546. assert.True(t, p.isEmptyJSON)
  547. }
  548. w.Write(testBody)
  549. },
  550. }
  551. },
  552. }
  553. for name, run := range tests {
  554. tc := run(t)
  555. t.Run(name, func(t *testing.T) {
  556. // h := &Handler{}
  557. req := httptest.NewRequest("GET", u, nil)
  558. req = req.WithContext(tc.ctx)
  559. w := httptest.NewRecorder()
  560. verifyAndExtractJWSPayload(tc.next)(w, req)
  561. res := w.Result()
  562. assert.Equals(t, res.StatusCode, tc.statusCode)
  563. body, err := io.ReadAll(res.Body)
  564. res.Body.Close()
  565. assert.FatalError(t, err)
  566. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  567. var ae acme.Error
  568. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  569. assert.Equals(t, ae.Type, tc.err.Type)
  570. assert.Equals(t, ae.Detail, tc.err.Detail)
  571. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  572. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  573. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  574. } else {
  575. assert.Equals(t, bytes.TrimSpace(body), testBody)
  576. }
  577. })
  578. }
  579. }
  580. func TestHandler_lookupJWK(t *testing.T) {
  581. prov := newProv()
  582. provName := url.PathEscape(prov.GetName())
  583. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  584. u := fmt.Sprintf("%s/acme/%s/account/1234",
  585. baseURL, provName)
  586. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  587. assert.FatalError(t, err)
  588. accID := "account-id"
  589. prefix := fmt.Sprintf("%s/acme/%s/account/",
  590. baseURL, provName)
  591. so := new(jose.SignerOptions)
  592. so.WithHeader("kid", fmt.Sprintf("%s%s", prefix, accID))
  593. signer, err := jose.NewSigner(jose.SigningKey{
  594. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  595. Key: jwk.Key,
  596. }, so)
  597. assert.FatalError(t, err)
  598. jws, err := signer.Sign([]byte("baz"))
  599. assert.FatalError(t, err)
  600. raw, err := jws.CompactSerialize()
  601. assert.FatalError(t, err)
  602. parsedJWS, err := jose.ParseJWS(raw)
  603. assert.FatalError(t, err)
  604. type test struct {
  605. linker acme.Linker
  606. db acme.DB
  607. ctx context.Context
  608. next func(http.ResponseWriter, *http.Request)
  609. err *acme.Error
  610. statusCode int
  611. }
  612. var tests = map[string]func(t *testing.T) test{
  613. "fail/no-jws": func(t *testing.T) test {
  614. return test{
  615. db: &acme.MockDB{},
  616. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  617. ctx: acme.NewProvisionerContext(context.Background(), prov),
  618. statusCode: 500,
  619. err: acme.NewErrorISE("jws expected in request context"),
  620. }
  621. },
  622. "fail/nil-jws": func(t *testing.T) test {
  623. ctx := acme.NewProvisionerContext(context.Background(), prov)
  624. ctx = context.WithValue(ctx, jwsContextKey, nil)
  625. return test{
  626. db: &acme.MockDB{},
  627. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  628. ctx: ctx,
  629. statusCode: 500,
  630. err: acme.NewErrorISE("jws expected in request context"),
  631. }
  632. },
  633. "fail/no-kid": func(t *testing.T) test {
  634. _signer, err := jose.NewSigner(jose.SigningKey{
  635. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  636. Key: jwk.Key,
  637. }, new(jose.SignerOptions))
  638. assert.FatalError(t, err)
  639. _jws, err := _signer.Sign([]byte("baz"))
  640. assert.FatalError(t, err)
  641. ctx := acme.NewProvisionerContext(context.Background(), prov)
  642. ctx = context.WithValue(ctx, jwsContextKey, _jws)
  643. return test{
  644. db: &acme.MockDB{},
  645. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  646. ctx: ctx,
  647. statusCode: 400,
  648. err: acme.NewError(acme.ErrorMalformedType, "kid does not have required prefix; expected %s, but got ", prefix),
  649. }
  650. },
  651. "fail/bad-kid-prefix": func(t *testing.T) test {
  652. _so := new(jose.SignerOptions)
  653. _so.WithHeader("kid", "foo")
  654. _signer, err := jose.NewSigner(jose.SigningKey{
  655. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  656. Key: jwk.Key,
  657. }, _so)
  658. assert.FatalError(t, err)
  659. _jws, err := _signer.Sign([]byte("baz"))
  660. assert.FatalError(t, err)
  661. _raw, err := _jws.CompactSerialize()
  662. assert.FatalError(t, err)
  663. _parsed, err := jose.ParseJWS(_raw)
  664. assert.FatalError(t, err)
  665. ctx := acme.NewProvisionerContext(context.Background(), prov)
  666. ctx = context.WithValue(ctx, jwsContextKey, _parsed)
  667. return test{
  668. db: &acme.MockDB{},
  669. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  670. ctx: ctx,
  671. statusCode: 400,
  672. err: acme.NewError(acme.ErrorMalformedType, "kid does not have required prefix; expected %s, but got foo", prefix),
  673. }
  674. },
  675. "fail/account-not-found": func(t *testing.T) test {
  676. ctx := acme.NewProvisionerContext(context.Background(), prov)
  677. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  678. return test{
  679. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  680. db: &acme.MockDB{
  681. MockGetAccount: func(ctx context.Context, accID string) (*acme.Account, error) {
  682. assert.Equals(t, accID, accID)
  683. return nil, database.ErrNotFound
  684. },
  685. },
  686. ctx: ctx,
  687. statusCode: 400,
  688. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  689. }
  690. },
  691. "fail/GetAccount-error": func(t *testing.T) test {
  692. ctx := acme.NewProvisionerContext(context.Background(), prov)
  693. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  694. return test{
  695. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  696. db: &acme.MockDB{
  697. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  698. assert.Equals(t, id, accID)
  699. return nil, acme.NewErrorISE("force")
  700. },
  701. },
  702. ctx: ctx,
  703. statusCode: 500,
  704. err: acme.NewErrorISE("force"),
  705. }
  706. },
  707. "fail/account-not-valid": func(t *testing.T) test {
  708. acc := &acme.Account{Status: "deactivated"}
  709. ctx := acme.NewProvisionerContext(context.Background(), prov)
  710. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  711. return test{
  712. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  713. db: &acme.MockDB{
  714. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  715. assert.Equals(t, id, accID)
  716. return acc, nil
  717. },
  718. },
  719. ctx: ctx,
  720. statusCode: 401,
  721. err: acme.NewError(acme.ErrorUnauthorizedType, "account is not active"),
  722. }
  723. },
  724. "ok": func(t *testing.T) test {
  725. acc := &acme.Account{Status: "valid", Key: jwk}
  726. ctx := acme.NewProvisionerContext(context.Background(), prov)
  727. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  728. return test{
  729. linker: acme.NewLinker("test.ca.smallstep.com", "acme"),
  730. db: &acme.MockDB{
  731. MockGetAccount: func(ctx context.Context, id string) (*acme.Account, error) {
  732. assert.Equals(t, id, accID)
  733. return acc, nil
  734. },
  735. },
  736. ctx: ctx,
  737. next: func(w http.ResponseWriter, r *http.Request) {
  738. _acc, err := accountFromContext(r.Context())
  739. assert.FatalError(t, err)
  740. assert.Equals(t, _acc, acc)
  741. _jwk, err := jwkFromContext(r.Context())
  742. assert.FatalError(t, err)
  743. assert.Equals(t, _jwk, jwk)
  744. w.Write(testBody)
  745. },
  746. statusCode: 200,
  747. }
  748. },
  749. }
  750. for name, run := range tests {
  751. tc := run(t)
  752. t.Run(name, func(t *testing.T) {
  753. ctx := newBaseContext(tc.ctx, tc.db, tc.linker)
  754. req := httptest.NewRequest("GET", u, nil)
  755. req = req.WithContext(ctx)
  756. w := httptest.NewRecorder()
  757. lookupJWK(tc.next)(w, req)
  758. res := w.Result()
  759. assert.Equals(t, res.StatusCode, tc.statusCode)
  760. body, err := io.ReadAll(res.Body)
  761. res.Body.Close()
  762. assert.FatalError(t, err)
  763. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  764. var ae acme.Error
  765. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  766. assert.Equals(t, ae.Type, tc.err.Type)
  767. assert.Equals(t, ae.Detail, tc.err.Detail)
  768. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  769. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  770. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  771. } else {
  772. assert.Equals(t, bytes.TrimSpace(body), testBody)
  773. }
  774. })
  775. }
  776. }
  777. func TestHandler_extractJWK(t *testing.T) {
  778. prov := newProv()
  779. provName := url.PathEscape(prov.GetName())
  780. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  781. assert.FatalError(t, err)
  782. kid, err := jwk.Thumbprint(crypto.SHA256)
  783. assert.FatalError(t, err)
  784. pub := jwk.Public()
  785. pub.KeyID = base64.RawURLEncoding.EncodeToString(kid)
  786. so := new(jose.SignerOptions)
  787. so.WithHeader("jwk", pub)
  788. signer, err := jose.NewSigner(jose.SigningKey{
  789. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  790. Key: jwk.Key,
  791. }, so)
  792. assert.FatalError(t, err)
  793. jws, err := signer.Sign([]byte("baz"))
  794. assert.FatalError(t, err)
  795. raw, err := jws.CompactSerialize()
  796. assert.FatalError(t, err)
  797. parsedJWS, err := jose.ParseJWS(raw)
  798. assert.FatalError(t, err)
  799. u := fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/1234",
  800. provName)
  801. type test struct {
  802. db acme.DB
  803. ctx context.Context
  804. next func(http.ResponseWriter, *http.Request)
  805. err *acme.Error
  806. statusCode int
  807. }
  808. var tests = map[string]func(t *testing.T) test{
  809. "fail/no-jws": func(t *testing.T) test {
  810. return test{
  811. db: &acme.MockDB{},
  812. ctx: acme.NewProvisionerContext(context.Background(), prov),
  813. statusCode: 500,
  814. err: acme.NewErrorISE("jws expected in request context"),
  815. }
  816. },
  817. "fail/nil-jws": func(t *testing.T) test {
  818. ctx := acme.NewProvisionerContext(context.Background(), prov)
  819. ctx = context.WithValue(ctx, jwsContextKey, nil)
  820. return test{
  821. db: &acme.MockDB{},
  822. ctx: ctx,
  823. statusCode: 500,
  824. err: acme.NewErrorISE("jws expected in request context"),
  825. }
  826. },
  827. "fail/nil-jwk": func(t *testing.T) test {
  828. _jws := &jose.JSONWebSignature{
  829. Signatures: []jose.Signature{
  830. {
  831. Protected: jose.Header{
  832. JSONWebKey: nil,
  833. },
  834. },
  835. },
  836. }
  837. ctx := acme.NewProvisionerContext(context.Background(), prov)
  838. ctx = context.WithValue(ctx, jwsContextKey, _jws)
  839. return test{
  840. db: &acme.MockDB{},
  841. ctx: ctx,
  842. statusCode: 400,
  843. err: acme.NewError(acme.ErrorMalformedType, "jwk expected in protected header"),
  844. }
  845. },
  846. "fail/invalid-jwk": func(t *testing.T) test {
  847. _jws := &jose.JSONWebSignature{
  848. Signatures: []jose.Signature{
  849. {
  850. Protected: jose.Header{
  851. JSONWebKey: &jose.JSONWebKey{Key: "foo"},
  852. },
  853. },
  854. },
  855. }
  856. ctx := acme.NewProvisionerContext(context.Background(), prov)
  857. ctx = context.WithValue(ctx, jwsContextKey, _jws)
  858. return test{
  859. db: &acme.MockDB{},
  860. ctx: ctx,
  861. statusCode: 400,
  862. err: acme.NewError(acme.ErrorMalformedType, "invalid jwk in protected header"),
  863. }
  864. },
  865. "fail/GetAccountByKey-error": func(t *testing.T) test {
  866. ctx := acme.NewProvisionerContext(context.Background(), prov)
  867. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  868. return test{
  869. ctx: ctx,
  870. db: &acme.MockDB{
  871. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  872. assert.Equals(t, kid, pub.KeyID)
  873. return nil, acme.NewErrorISE("force")
  874. },
  875. },
  876. statusCode: 500,
  877. err: acme.NewErrorISE("force"),
  878. }
  879. },
  880. "fail/account-not-valid": func(t *testing.T) test {
  881. acc := &acme.Account{Status: "deactivated"}
  882. ctx := acme.NewProvisionerContext(context.Background(), prov)
  883. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  884. return test{
  885. ctx: ctx,
  886. db: &acme.MockDB{
  887. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  888. assert.Equals(t, kid, pub.KeyID)
  889. return acc, nil
  890. },
  891. },
  892. statusCode: 401,
  893. err: acme.NewError(acme.ErrorUnauthorizedType, "account is not active"),
  894. }
  895. },
  896. "ok": func(t *testing.T) test {
  897. acc := &acme.Account{Status: "valid"}
  898. ctx := acme.NewProvisionerContext(context.Background(), prov)
  899. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  900. return test{
  901. ctx: ctx,
  902. db: &acme.MockDB{
  903. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  904. assert.Equals(t, kid, pub.KeyID)
  905. return acc, nil
  906. },
  907. },
  908. next: func(w http.ResponseWriter, r *http.Request) {
  909. _acc, err := accountFromContext(r.Context())
  910. assert.FatalError(t, err)
  911. assert.Equals(t, _acc, acc)
  912. _jwk, err := jwkFromContext(r.Context())
  913. assert.FatalError(t, err)
  914. assert.Equals(t, _jwk.KeyID, pub.KeyID)
  915. w.Write(testBody)
  916. },
  917. statusCode: 200,
  918. }
  919. },
  920. "ok/no-account": func(t *testing.T) test {
  921. ctx := acme.NewProvisionerContext(context.Background(), prov)
  922. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  923. return test{
  924. ctx: ctx,
  925. db: &acme.MockDB{
  926. MockGetAccountByKeyID: func(ctx context.Context, kid string) (*acme.Account, error) {
  927. assert.Equals(t, kid, pub.KeyID)
  928. return nil, acme.ErrNotFound
  929. },
  930. },
  931. next: func(w http.ResponseWriter, r *http.Request) {
  932. _acc, err := accountFromContext(r.Context())
  933. assert.NotNil(t, err)
  934. assert.Nil(t, _acc)
  935. _jwk, err := jwkFromContext(r.Context())
  936. assert.FatalError(t, err)
  937. assert.Equals(t, _jwk.KeyID, pub.KeyID)
  938. w.Write(testBody)
  939. },
  940. statusCode: 200,
  941. }
  942. },
  943. }
  944. for name, run := range tests {
  945. tc := run(t)
  946. t.Run(name, func(t *testing.T) {
  947. ctx := newBaseContext(tc.ctx, tc.db)
  948. req := httptest.NewRequest("GET", u, nil)
  949. req = req.WithContext(ctx)
  950. w := httptest.NewRecorder()
  951. extractJWK(tc.next)(w, req)
  952. res := w.Result()
  953. assert.Equals(t, res.StatusCode, tc.statusCode)
  954. body, err := io.ReadAll(res.Body)
  955. res.Body.Close()
  956. assert.FatalError(t, err)
  957. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  958. var ae acme.Error
  959. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  960. assert.Equals(t, ae.Type, tc.err.Type)
  961. assert.Equals(t, ae.Detail, tc.err.Detail)
  962. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  963. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  964. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  965. } else {
  966. assert.Equals(t, bytes.TrimSpace(body), testBody)
  967. }
  968. })
  969. }
  970. }
  971. func TestHandler_validateJWS(t *testing.T) {
  972. u := "https://ca.smallstep.com/acme/account/1234"
  973. type test struct {
  974. db acme.DB
  975. ctx context.Context
  976. next func(http.ResponseWriter, *http.Request)
  977. err *acme.Error
  978. statusCode int
  979. }
  980. var tests = map[string]func(t *testing.T) test{
  981. "fail/no-jws": func(t *testing.T) test {
  982. return test{
  983. db: &acme.MockDB{},
  984. ctx: context.Background(),
  985. statusCode: 500,
  986. err: acme.NewErrorISE("jws expected in request context"),
  987. }
  988. },
  989. "fail/nil-jws": func(t *testing.T) test {
  990. return test{
  991. db: &acme.MockDB{},
  992. ctx: context.WithValue(context.Background(), jwsContextKey, nil),
  993. statusCode: 500,
  994. err: acme.NewErrorISE("jws expected in request context"),
  995. }
  996. },
  997. "fail/no-signature": func(t *testing.T) test {
  998. return test{
  999. db: &acme.MockDB{},
  1000. ctx: context.WithValue(context.Background(), jwsContextKey, &jose.JSONWebSignature{}),
  1001. statusCode: 400,
  1002. err: acme.NewError(acme.ErrorMalformedType, "request body does not contain a signature"),
  1003. }
  1004. },
  1005. "fail/more-than-one-signature": func(t *testing.T) test {
  1006. jws := &jose.JSONWebSignature{
  1007. Signatures: []jose.Signature{
  1008. {},
  1009. {},
  1010. },
  1011. }
  1012. return test{
  1013. db: &acme.MockDB{},
  1014. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1015. statusCode: 400,
  1016. err: acme.NewError(acme.ErrorMalformedType, "request body contains more than one signature"),
  1017. }
  1018. },
  1019. "fail/unprotected-header-not-empty": func(t *testing.T) test {
  1020. jws := &jose.JSONWebSignature{
  1021. Signatures: []jose.Signature{
  1022. {Unprotected: jose.Header{Nonce: "abc"}},
  1023. },
  1024. }
  1025. return test{
  1026. db: &acme.MockDB{},
  1027. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1028. statusCode: 400,
  1029. err: acme.NewError(acme.ErrorMalformedType, "unprotected header must not be used"),
  1030. }
  1031. },
  1032. "fail/unsuitable-algorithm-none": func(t *testing.T) test {
  1033. jws := &jose.JSONWebSignature{
  1034. Signatures: []jose.Signature{
  1035. {Protected: jose.Header{Algorithm: "none"}},
  1036. },
  1037. }
  1038. return test{
  1039. db: &acme.MockDB{},
  1040. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1041. statusCode: 400,
  1042. err: acme.NewError(acme.ErrorBadSignatureAlgorithmType, "unsuitable algorithm: none"),
  1043. }
  1044. },
  1045. "fail/unsuitable-algorithm-mac": func(t *testing.T) test {
  1046. jws := &jose.JSONWebSignature{
  1047. Signatures: []jose.Signature{
  1048. {Protected: jose.Header{Algorithm: jose.HS256}},
  1049. },
  1050. }
  1051. return test{
  1052. db: &acme.MockDB{},
  1053. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1054. statusCode: 400,
  1055. err: acme.NewError(acme.ErrorBadSignatureAlgorithmType, "unsuitable algorithm: %s", jose.HS256),
  1056. }
  1057. },
  1058. "fail/rsa-key-&-alg-mismatch": func(t *testing.T) test {
  1059. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  1060. assert.FatalError(t, err)
  1061. pub := jwk.Public()
  1062. jws := &jose.JSONWebSignature{
  1063. Signatures: []jose.Signature{
  1064. {
  1065. Protected: jose.Header{
  1066. Algorithm: jose.RS256,
  1067. JSONWebKey: &pub,
  1068. ExtraHeaders: map[jose.HeaderKey]interface{}{
  1069. "url": u,
  1070. },
  1071. },
  1072. },
  1073. },
  1074. }
  1075. return test{
  1076. db: &acme.MockDB{
  1077. MockDeleteNonce: func(ctx context.Context, n acme.Nonce) error {
  1078. return nil
  1079. },
  1080. },
  1081. ctx: context.WithValue(context.Background(), jwsContextKey, jws),
  1082. statusCode: 400,
  1083. err: acme.NewError(acme.ErrorMalformedType, "jws key type and algorithm do not match"),
  1084. }
  1085. },
  1086. "fail/rsa-key-too-small": func(t *testing.T) test {
  1087. revert := keyutil.Insecure()
  1088. defer revert()
  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. }