handler_test.go 24 KB

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