middleware_test.go 49 KB

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