4
0

handler_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/x509"
  6. "encoding/json"
  7. "encoding/pem"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "net/http/httptest"
  12. "net/url"
  13. "testing"
  14. "time"
  15. "github.com/go-chi/chi"
  16. "github.com/google/go-cmp/cmp"
  17. "github.com/pkg/errors"
  18. "github.com/smallstep/assert"
  19. "github.com/smallstep/certificates/acme"
  20. "github.com/smallstep/certificates/authority/provisioner"
  21. "go.step.sm/crypto/jose"
  22. "go.step.sm/crypto/pemutil"
  23. )
  24. func TestHandler_GetNonce(t *testing.T) {
  25. tests := []struct {
  26. name string
  27. statusCode int
  28. }{
  29. {"GET", 204},
  30. {"HEAD", 200},
  31. }
  32. // Request with chi context
  33. req := httptest.NewRequest("GET", "http://ca.smallstep.com/nonce", nil)
  34. for _, tt := range tests {
  35. t.Run(tt.name, func(t *testing.T) {
  36. h := &Handler{}
  37. w := httptest.NewRecorder()
  38. req.Method = tt.name
  39. h.GetNonce(w, req)
  40. res := w.Result()
  41. if res.StatusCode != tt.statusCode {
  42. t.Errorf("Handler.GetNonce StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  43. }
  44. })
  45. }
  46. }
  47. func TestHandler_GetDirectory(t *testing.T) {
  48. linker := NewLinker("ca.smallstep.com", "acme")
  49. type test struct {
  50. ctx context.Context
  51. statusCode int
  52. dir Directory
  53. err *acme.Error
  54. }
  55. var tests = map[string]func(t *testing.T) test{
  56. "fail/no-provisioner": func(t *testing.T) test {
  57. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  58. ctx := context.WithValue(context.Background(), provisionerContextKey, nil)
  59. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  60. return test{
  61. ctx: ctx,
  62. statusCode: 500,
  63. err: acme.NewErrorISE("provisioner in context is not an ACME provisioner"),
  64. }
  65. },
  66. "fail/different-provisioner": func(t *testing.T) test {
  67. prov := &provisioner.SCEP{
  68. Type: "SCEP",
  69. Name: "test@scep-<test>provisioner.com",
  70. }
  71. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  72. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  73. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  74. return test{
  75. ctx: ctx,
  76. statusCode: 500,
  77. err: acme.NewErrorISE("provisioner in context is not an ACME provisioner"),
  78. }
  79. },
  80. "ok": func(t *testing.T) test {
  81. prov := newProv()
  82. provName := url.PathEscape(prov.GetName())
  83. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  84. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  85. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  86. expDir := Directory{
  87. NewNonce: fmt.Sprintf("%s/acme/%s/new-nonce", baseURL.String(), provName),
  88. NewAccount: fmt.Sprintf("%s/acme/%s/new-account", baseURL.String(), provName),
  89. NewOrder: fmt.Sprintf("%s/acme/%s/new-order", baseURL.String(), provName),
  90. RevokeCert: fmt.Sprintf("%s/acme/%s/revoke-cert", baseURL.String(), provName),
  91. KeyChange: fmt.Sprintf("%s/acme/%s/key-change", baseURL.String(), provName),
  92. }
  93. return test{
  94. ctx: ctx,
  95. dir: expDir,
  96. statusCode: 200,
  97. }
  98. },
  99. "ok/eab-required": func(t *testing.T) test {
  100. prov := newACMEProv(t)
  101. prov.RequireEAB = true
  102. provName := url.PathEscape(prov.GetName())
  103. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  104. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  105. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  106. expDir := Directory{
  107. NewNonce: fmt.Sprintf("%s/acme/%s/new-nonce", baseURL.String(), provName),
  108. NewAccount: fmt.Sprintf("%s/acme/%s/new-account", baseURL.String(), provName),
  109. NewOrder: fmt.Sprintf("%s/acme/%s/new-order", baseURL.String(), provName),
  110. RevokeCert: fmt.Sprintf("%s/acme/%s/revoke-cert", baseURL.String(), provName),
  111. KeyChange: fmt.Sprintf("%s/acme/%s/key-change", baseURL.String(), provName),
  112. Meta: Meta{
  113. ExternalAccountRequired: true,
  114. },
  115. }
  116. return test{
  117. ctx: ctx,
  118. dir: expDir,
  119. statusCode: 200,
  120. }
  121. },
  122. }
  123. for name, run := range tests {
  124. tc := run(t)
  125. t.Run(name, func(t *testing.T) {
  126. h := &Handler{linker: linker}
  127. req := httptest.NewRequest("GET", "/foo/bar", nil)
  128. req = req.WithContext(tc.ctx)
  129. w := httptest.NewRecorder()
  130. h.GetDirectory(w, req)
  131. res := w.Result()
  132. assert.Equals(t, res.StatusCode, tc.statusCode)
  133. body, err := io.ReadAll(res.Body)
  134. res.Body.Close()
  135. assert.FatalError(t, err)
  136. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  137. var ae acme.Error
  138. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  139. assert.Equals(t, ae.Type, tc.err.Type)
  140. assert.Equals(t, ae.Detail, tc.err.Detail)
  141. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  142. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  143. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  144. } else {
  145. var dir Directory
  146. json.Unmarshal(bytes.TrimSpace(body), &dir)
  147. if !cmp.Equal(tc.dir, dir) {
  148. t.Errorf("GetDirectory() diff =\n%s", cmp.Diff(tc.dir, dir))
  149. }
  150. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  151. }
  152. })
  153. }
  154. }
  155. func TestHandler_GetAuthorization(t *testing.T) {
  156. expiry := time.Now().UTC().Add(6 * time.Hour)
  157. az := acme.Authorization{
  158. ID: "authzID",
  159. AccountID: "accID",
  160. Identifier: acme.Identifier{
  161. Type: "dns",
  162. Value: "example.com",
  163. },
  164. Status: "pending",
  165. ExpiresAt: expiry,
  166. Wildcard: false,
  167. Challenges: []*acme.Challenge{
  168. {
  169. Type: "http-01",
  170. Status: "pending",
  171. Token: "tok2",
  172. URL: "https://ca.smallstep.com/acme/challenge/chHTTPID",
  173. ID: "chHTTP01ID",
  174. },
  175. {
  176. Type: "dns-01",
  177. Status: "pending",
  178. Token: "tok2",
  179. URL: "https://ca.smallstep.com/acme/challenge/chDNSID",
  180. ID: "chDNSID",
  181. },
  182. },
  183. }
  184. prov := newProv()
  185. provName := url.PathEscape(prov.GetName())
  186. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  187. // Request with chi context
  188. chiCtx := chi.NewRouteContext()
  189. chiCtx.URLParams.Add("authzID", az.ID)
  190. u := fmt.Sprintf("%s/acme/%s/authz/%s",
  191. baseURL.String(), provName, az.ID)
  192. type test struct {
  193. db acme.DB
  194. ctx context.Context
  195. statusCode int
  196. err *acme.Error
  197. }
  198. var tests = map[string]func(t *testing.T) test{
  199. "fail/no-account": func(t *testing.T) test {
  200. return test{
  201. db: &acme.MockDB{},
  202. ctx: context.Background(),
  203. statusCode: 400,
  204. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  205. }
  206. },
  207. "fail/nil-account": func(t *testing.T) test {
  208. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  209. ctx = context.WithValue(ctx, accContextKey, nil)
  210. return test{
  211. db: &acme.MockDB{},
  212. ctx: ctx,
  213. statusCode: 400,
  214. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  215. }
  216. },
  217. "fail/db.GetAuthorization-error": func(t *testing.T) test {
  218. acc := &acme.Account{ID: "accID"}
  219. ctx := context.WithValue(context.Background(), accContextKey, acc)
  220. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  221. return test{
  222. db: &acme.MockDB{
  223. MockError: acme.NewErrorISE("force"),
  224. },
  225. ctx: ctx,
  226. statusCode: 500,
  227. err: acme.NewErrorISE("force"),
  228. }
  229. },
  230. "fail/account-id-mismatch": func(t *testing.T) test {
  231. acc := &acme.Account{ID: "accID"}
  232. ctx := context.WithValue(context.Background(), accContextKey, acc)
  233. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  234. return test{
  235. db: &acme.MockDB{
  236. MockGetAuthorization: func(ctx context.Context, id string) (*acme.Authorization, error) {
  237. assert.Equals(t, id, az.ID)
  238. return &acme.Authorization{
  239. AccountID: "foo",
  240. }, nil
  241. },
  242. },
  243. ctx: ctx,
  244. statusCode: 401,
  245. err: acme.NewError(acme.ErrorUnauthorizedType, "account id mismatch"),
  246. }
  247. },
  248. "fail/db.UpdateAuthorization-error": func(t *testing.T) test {
  249. acc := &acme.Account{ID: "accID"}
  250. ctx := context.WithValue(context.Background(), accContextKey, acc)
  251. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  252. return test{
  253. db: &acme.MockDB{
  254. MockGetAuthorization: func(ctx context.Context, id string) (*acme.Authorization, error) {
  255. assert.Equals(t, id, az.ID)
  256. return &acme.Authorization{
  257. AccountID: "accID",
  258. Status: acme.StatusPending,
  259. ExpiresAt: time.Now().Add(-1 * time.Hour),
  260. }, nil
  261. },
  262. MockUpdateAuthorization: func(ctx context.Context, az *acme.Authorization) error {
  263. assert.Equals(t, az.Status, acme.StatusInvalid)
  264. return acme.NewErrorISE("force")
  265. },
  266. },
  267. ctx: ctx,
  268. statusCode: 500,
  269. err: acme.NewErrorISE("force"),
  270. }
  271. },
  272. "ok": func(t *testing.T) test {
  273. acc := &acme.Account{ID: "accID"}
  274. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  275. ctx = context.WithValue(ctx, accContextKey, acc)
  276. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  277. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  278. return test{
  279. db: &acme.MockDB{
  280. MockGetAuthorization: func(ctx context.Context, id string) (*acme.Authorization, error) {
  281. assert.Equals(t, id, az.ID)
  282. return &az, nil
  283. },
  284. },
  285. ctx: ctx,
  286. statusCode: 200,
  287. }
  288. },
  289. }
  290. for name, run := range tests {
  291. tc := run(t)
  292. t.Run(name, func(t *testing.T) {
  293. h := &Handler{db: tc.db, linker: NewLinker("dns", "acme")}
  294. req := httptest.NewRequest("GET", "/foo/bar", nil)
  295. req = req.WithContext(tc.ctx)
  296. w := httptest.NewRecorder()
  297. h.GetAuthorization(w, req)
  298. res := w.Result()
  299. assert.Equals(t, res.StatusCode, tc.statusCode)
  300. body, err := io.ReadAll(res.Body)
  301. res.Body.Close()
  302. assert.FatalError(t, err)
  303. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  304. var ae acme.Error
  305. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  306. assert.Equals(t, ae.Type, tc.err.Type)
  307. assert.Equals(t, ae.Detail, tc.err.Detail)
  308. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  309. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  310. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  311. } else {
  312. //var gotAz acme.Authz
  313. //assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &gotAz))
  314. expB, err := json.Marshal(az)
  315. assert.FatalError(t, err)
  316. assert.Equals(t, bytes.TrimSpace(body), expB)
  317. assert.Equals(t, res.Header["Location"], []string{u})
  318. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  319. }
  320. })
  321. }
  322. }
  323. func TestHandler_GetCertificate(t *testing.T) {
  324. leaf, err := pemutil.ReadCertificate("../../authority/testdata/certs/foo.crt")
  325. assert.FatalError(t, err)
  326. inter, err := pemutil.ReadCertificate("../../authority/testdata/certs/intermediate_ca.crt")
  327. assert.FatalError(t, err)
  328. root, err := pemutil.ReadCertificate("../../authority/testdata/certs/root_ca.crt")
  329. assert.FatalError(t, err)
  330. certBytes := append(pem.EncodeToMemory(&pem.Block{
  331. Type: "CERTIFICATE",
  332. Bytes: leaf.Raw,
  333. }), pem.EncodeToMemory(&pem.Block{
  334. Type: "CERTIFICATE",
  335. Bytes: inter.Raw,
  336. })...)
  337. certBytes = append(certBytes, pem.EncodeToMemory(&pem.Block{
  338. Type: "CERTIFICATE",
  339. Bytes: root.Raw,
  340. })...)
  341. certID := "certID"
  342. prov := newProv()
  343. provName := url.PathEscape(prov.GetName())
  344. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  345. // Request with chi context
  346. chiCtx := chi.NewRouteContext()
  347. chiCtx.URLParams.Add("certID", certID)
  348. u := fmt.Sprintf("%s/acme/%s/certificate/%s",
  349. baseURL.String(), provName, certID)
  350. type test struct {
  351. db acme.DB
  352. ctx context.Context
  353. statusCode int
  354. err *acme.Error
  355. }
  356. var tests = map[string]func(t *testing.T) test{
  357. "fail/no-account": func(t *testing.T) test {
  358. return test{
  359. db: &acme.MockDB{},
  360. ctx: context.Background(),
  361. statusCode: 400,
  362. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  363. }
  364. },
  365. "fail/nil-account": func(t *testing.T) test {
  366. ctx := context.WithValue(context.Background(), accContextKey, nil)
  367. return test{
  368. db: &acme.MockDB{},
  369. ctx: ctx,
  370. statusCode: 400,
  371. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  372. }
  373. },
  374. "fail/db.GetCertificate-error": func(t *testing.T) test {
  375. acc := &acme.Account{ID: "accID"}
  376. ctx := context.WithValue(context.Background(), accContextKey, acc)
  377. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  378. return test{
  379. db: &acme.MockDB{
  380. MockError: acme.NewErrorISE("force"),
  381. },
  382. ctx: ctx,
  383. statusCode: 500,
  384. err: acme.NewErrorISE("force"),
  385. }
  386. },
  387. "fail/account-id-mismatch": func(t *testing.T) test {
  388. acc := &acme.Account{ID: "accID"}
  389. ctx := context.WithValue(context.Background(), accContextKey, acc)
  390. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  391. return test{
  392. db: &acme.MockDB{
  393. MockGetCertificate: func(ctx context.Context, id string) (*acme.Certificate, error) {
  394. assert.Equals(t, id, certID)
  395. return &acme.Certificate{AccountID: "foo"}, nil
  396. },
  397. },
  398. ctx: ctx,
  399. statusCode: 401,
  400. err: acme.NewError(acme.ErrorUnauthorizedType, "account id mismatch"),
  401. }
  402. },
  403. "ok": func(t *testing.T) test {
  404. acc := &acme.Account{ID: "accID"}
  405. ctx := context.WithValue(context.Background(), accContextKey, acc)
  406. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  407. return test{
  408. db: &acme.MockDB{
  409. MockGetCertificate: func(ctx context.Context, id string) (*acme.Certificate, error) {
  410. assert.Equals(t, id, certID)
  411. return &acme.Certificate{
  412. AccountID: "accID",
  413. OrderID: "ordID",
  414. Leaf: leaf,
  415. Intermediates: []*x509.Certificate{inter, root},
  416. ID: id,
  417. }, nil
  418. },
  419. },
  420. ctx: ctx,
  421. statusCode: 200,
  422. }
  423. },
  424. }
  425. for name, run := range tests {
  426. tc := run(t)
  427. t.Run(name, func(t *testing.T) {
  428. h := &Handler{db: tc.db}
  429. req := httptest.NewRequest("GET", u, nil)
  430. req = req.WithContext(tc.ctx)
  431. w := httptest.NewRecorder()
  432. h.GetCertificate(w, req)
  433. res := w.Result()
  434. assert.Equals(t, res.StatusCode, tc.statusCode)
  435. body, err := io.ReadAll(res.Body)
  436. res.Body.Close()
  437. assert.FatalError(t, err)
  438. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  439. var ae acme.Error
  440. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  441. assert.Equals(t, ae.Type, tc.err.Type)
  442. assert.HasPrefix(t, ae.Detail, tc.err.Detail)
  443. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  444. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  445. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  446. } else {
  447. assert.Equals(t, bytes.TrimSpace(body), bytes.TrimSpace(certBytes))
  448. assert.Equals(t, res.Header["Content-Type"], []string{"application/pem-certificate-chain; charset=utf-8"})
  449. }
  450. })
  451. }
  452. }
  453. func TestHandler_GetChallenge(t *testing.T) {
  454. chiCtx := chi.NewRouteContext()
  455. chiCtx.URLParams.Add("chID", "chID")
  456. chiCtx.URLParams.Add("authzID", "authzID")
  457. prov := newProv()
  458. provName := url.PathEscape(prov.GetName())
  459. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  460. u := fmt.Sprintf("%s/acme/%s/challenge/%s/%s",
  461. baseURL.String(), provName, "authzID", "chID")
  462. type test struct {
  463. db acme.DB
  464. vco *acme.ValidateChallengeOptions
  465. ctx context.Context
  466. statusCode int
  467. ch *acme.Challenge
  468. err *acme.Error
  469. }
  470. var tests = map[string]func(t *testing.T) test{
  471. "fail/no-account": func(t *testing.T) test {
  472. return test{
  473. ctx: context.Background(),
  474. statusCode: 400,
  475. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  476. }
  477. },
  478. "fail/nil-account": func(t *testing.T) test {
  479. return test{
  480. ctx: context.WithValue(context.Background(), accContextKey, nil),
  481. statusCode: 400,
  482. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  483. }
  484. },
  485. "fail/no-payload": func(t *testing.T) test {
  486. acc := &acme.Account{ID: "accID"}
  487. ctx := context.WithValue(context.Background(), accContextKey, acc)
  488. return test{
  489. ctx: ctx,
  490. statusCode: 500,
  491. err: acme.NewErrorISE("payload expected in request context"),
  492. }
  493. },
  494. "fail/nil-payload": func(t *testing.T) test {
  495. acc := &acme.Account{ID: "accID"}
  496. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  497. ctx = context.WithValue(ctx, accContextKey, acc)
  498. ctx = context.WithValue(ctx, payloadContextKey, nil)
  499. return test{
  500. ctx: ctx,
  501. statusCode: 500,
  502. err: acme.NewErrorISE("payload expected in request context"),
  503. }
  504. },
  505. "fail/db.GetChallenge-error": func(t *testing.T) test {
  506. acc := &acme.Account{ID: "accID"}
  507. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  508. ctx = context.WithValue(ctx, accContextKey, acc)
  509. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  510. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  511. return test{
  512. db: &acme.MockDB{
  513. MockGetChallenge: func(ctx context.Context, chID, azID string) (*acme.Challenge, error) {
  514. assert.Equals(t, chID, "chID")
  515. assert.Equals(t, azID, "authzID")
  516. return nil, acme.NewErrorISE("force")
  517. },
  518. },
  519. ctx: ctx,
  520. statusCode: 500,
  521. err: acme.NewErrorISE("force"),
  522. }
  523. },
  524. "fail/account-id-mismatch": func(t *testing.T) test {
  525. acc := &acme.Account{ID: "accID"}
  526. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  527. ctx = context.WithValue(ctx, accContextKey, acc)
  528. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  529. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  530. return test{
  531. db: &acme.MockDB{
  532. MockGetChallenge: func(ctx context.Context, chID, azID string) (*acme.Challenge, error) {
  533. assert.Equals(t, chID, "chID")
  534. assert.Equals(t, azID, "authzID")
  535. return &acme.Challenge{AccountID: "foo"}, nil
  536. },
  537. },
  538. ctx: ctx,
  539. statusCode: 401,
  540. err: acme.NewError(acme.ErrorUnauthorizedType, "accout id mismatch"),
  541. }
  542. },
  543. "fail/no-jwk": func(t *testing.T) test {
  544. acc := &acme.Account{ID: "accID"}
  545. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  546. ctx = context.WithValue(ctx, accContextKey, acc)
  547. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  548. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  549. return test{
  550. db: &acme.MockDB{
  551. MockGetChallenge: func(ctx context.Context, chID, azID string) (*acme.Challenge, error) {
  552. assert.Equals(t, chID, "chID")
  553. assert.Equals(t, azID, "authzID")
  554. return &acme.Challenge{AccountID: "accID"}, nil
  555. },
  556. },
  557. ctx: ctx,
  558. statusCode: 500,
  559. err: acme.NewErrorISE("missing jwk"),
  560. }
  561. },
  562. "fail/nil-jwk": func(t *testing.T) test {
  563. acc := &acme.Account{ID: "accID"}
  564. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  565. ctx = context.WithValue(ctx, accContextKey, acc)
  566. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  567. ctx = context.WithValue(ctx, jwkContextKey, nil)
  568. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  569. return test{
  570. db: &acme.MockDB{
  571. MockGetChallenge: func(ctx context.Context, chID, azID string) (*acme.Challenge, error) {
  572. assert.Equals(t, chID, "chID")
  573. assert.Equals(t, azID, "authzID")
  574. return &acme.Challenge{AccountID: "accID"}, nil
  575. },
  576. },
  577. ctx: ctx,
  578. statusCode: 500,
  579. err: acme.NewErrorISE("nil jwk"),
  580. }
  581. },
  582. "fail/validate-challenge-error": func(t *testing.T) test {
  583. acc := &acme.Account{ID: "accID"}
  584. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  585. ctx = context.WithValue(ctx, accContextKey, acc)
  586. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  587. _jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  588. assert.FatalError(t, err)
  589. _pub := _jwk.Public()
  590. ctx = context.WithValue(ctx, jwkContextKey, &_pub)
  591. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  592. return test{
  593. db: &acme.MockDB{
  594. MockGetChallenge: func(ctx context.Context, chID, azID string) (*acme.Challenge, error) {
  595. assert.Equals(t, chID, "chID")
  596. assert.Equals(t, azID, "authzID")
  597. return &acme.Challenge{
  598. Status: acme.StatusPending,
  599. Type: acme.HTTP01,
  600. AccountID: "accID",
  601. }, nil
  602. },
  603. MockUpdateChallenge: func(ctx context.Context, ch *acme.Challenge) error {
  604. assert.Equals(t, ch.Status, acme.StatusPending)
  605. assert.Equals(t, ch.Type, acme.HTTP01)
  606. assert.Equals(t, ch.AccountID, "accID")
  607. assert.Equals(t, ch.AuthorizationID, "authzID")
  608. assert.HasSuffix(t, ch.Error.Type, acme.ErrorConnectionType.String())
  609. return acme.NewErrorISE("force")
  610. },
  611. },
  612. vco: &acme.ValidateChallengeOptions{
  613. HTTPGet: func(string) (*http.Response, error) {
  614. return nil, errors.New("force")
  615. },
  616. },
  617. ctx: ctx,
  618. statusCode: 500,
  619. err: acme.NewErrorISE("force"),
  620. }
  621. },
  622. "ok": func(t *testing.T) test {
  623. acc := &acme.Account{ID: "accID"}
  624. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  625. ctx = context.WithValue(ctx, accContextKey, acc)
  626. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  627. _jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  628. assert.FatalError(t, err)
  629. _pub := _jwk.Public()
  630. ctx = context.WithValue(ctx, jwkContextKey, &_pub)
  631. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  632. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  633. return test{
  634. db: &acme.MockDB{
  635. MockGetChallenge: func(ctx context.Context, chID, azID string) (*acme.Challenge, error) {
  636. assert.Equals(t, chID, "chID")
  637. assert.Equals(t, azID, "authzID")
  638. return &acme.Challenge{
  639. ID: "chID",
  640. Status: acme.StatusPending,
  641. Type: acme.HTTP01,
  642. AccountID: "accID",
  643. }, nil
  644. },
  645. MockUpdateChallenge: func(ctx context.Context, ch *acme.Challenge) error {
  646. assert.Equals(t, ch.Status, acme.StatusPending)
  647. assert.Equals(t, ch.Type, acme.HTTP01)
  648. assert.Equals(t, ch.AccountID, "accID")
  649. assert.Equals(t, ch.AuthorizationID, "authzID")
  650. assert.HasSuffix(t, ch.Error.Type, acme.ErrorConnectionType.String())
  651. return nil
  652. },
  653. },
  654. ch: &acme.Challenge{
  655. ID: "chID",
  656. Status: acme.StatusPending,
  657. AuthorizationID: "authzID",
  658. Type: acme.HTTP01,
  659. AccountID: "accID",
  660. URL: u,
  661. Error: acme.NewError(acme.ErrorConnectionType, "force"),
  662. },
  663. vco: &acme.ValidateChallengeOptions{
  664. HTTPGet: func(string) (*http.Response, error) {
  665. return nil, errors.New("force")
  666. },
  667. },
  668. ctx: ctx,
  669. statusCode: 200,
  670. }
  671. },
  672. }
  673. for name, run := range tests {
  674. tc := run(t)
  675. t.Run(name, func(t *testing.T) {
  676. h := &Handler{db: tc.db, linker: NewLinker("dns", "acme"), validateChallengeOptions: tc.vco}
  677. req := httptest.NewRequest("GET", u, nil)
  678. req = req.WithContext(tc.ctx)
  679. w := httptest.NewRecorder()
  680. h.GetChallenge(w, req)
  681. res := w.Result()
  682. assert.Equals(t, res.StatusCode, tc.statusCode)
  683. body, err := io.ReadAll(res.Body)
  684. res.Body.Close()
  685. assert.FatalError(t, err)
  686. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  687. var ae acme.Error
  688. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  689. assert.Equals(t, ae.Type, tc.err.Type)
  690. assert.Equals(t, ae.Detail, tc.err.Detail)
  691. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  692. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  693. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  694. } else {
  695. expB, err := json.Marshal(tc.ch)
  696. assert.FatalError(t, err)
  697. assert.Equals(t, bytes.TrimSpace(body), expB)
  698. assert.Equals(t, res.Header["Link"], []string{fmt.Sprintf("<%s/acme/%s/authz/%s>;rel=\"up\"", baseURL, provName, "authzID")})
  699. assert.Equals(t, res.Header["Location"], []string{u})
  700. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  701. }
  702. })
  703. }
  704. }