middleware_test.go 57 KB

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