middleware_test.go 48 KB

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