4
0

handler_test.go 24 KB

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