handler_test.go 24 KB

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