handler_test.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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. "go.step.sm/crypto/jose"
  20. "go.step.sm/crypto/pemutil"
  21. "github.com/smallstep/assert"
  22. "github.com/smallstep/certificates/acme"
  23. "github.com/smallstep/certificates/authority/provisioner"
  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(u string) (*http.Response, error) { return m.get(u) }
  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. ctx := acme.NewProvisionerContext(context.Background(), &fakeProvisioner{})
  87. return test{
  88. ctx: ctx,
  89. statusCode: 500,
  90. err: acme.NewErrorISE("provisioner in context is not an ACME provisioner"),
  91. }
  92. },
  93. "ok": func(t *testing.T) test {
  94. prov := newProv()
  95. provName := url.PathEscape(prov.GetName())
  96. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  97. ctx := acme.NewProvisionerContext(context.Background(), prov)
  98. expDir := Directory{
  99. NewNonce: fmt.Sprintf("%s/acme/%s/new-nonce", baseURL.String(), provName),
  100. NewAccount: fmt.Sprintf("%s/acme/%s/new-account", baseURL.String(), provName),
  101. NewOrder: fmt.Sprintf("%s/acme/%s/new-order", baseURL.String(), provName),
  102. RevokeCert: fmt.Sprintf("%s/acme/%s/revoke-cert", baseURL.String(), provName),
  103. KeyChange: fmt.Sprintf("%s/acme/%s/key-change", baseURL.String(), provName),
  104. }
  105. return test{
  106. ctx: ctx,
  107. dir: expDir,
  108. statusCode: 200,
  109. }
  110. },
  111. "ok/eab-required": func(t *testing.T) test {
  112. prov := newACMEProv(t)
  113. prov.RequireEAB = true
  114. provName := url.PathEscape(prov.GetName())
  115. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  116. ctx := acme.NewProvisionerContext(context.Background(), prov)
  117. expDir := Directory{
  118. NewNonce: fmt.Sprintf("%s/acme/%s/new-nonce", baseURL.String(), provName),
  119. NewAccount: fmt.Sprintf("%s/acme/%s/new-account", baseURL.String(), provName),
  120. NewOrder: fmt.Sprintf("%s/acme/%s/new-order", baseURL.String(), provName),
  121. RevokeCert: fmt.Sprintf("%s/acme/%s/revoke-cert", baseURL.String(), provName),
  122. KeyChange: fmt.Sprintf("%s/acme/%s/key-change", baseURL.String(), provName),
  123. Meta: &Meta{
  124. ExternalAccountRequired: true,
  125. },
  126. }
  127. return test{
  128. ctx: ctx,
  129. dir: expDir,
  130. statusCode: 200,
  131. }
  132. },
  133. "ok/full-meta": func(t *testing.T) test {
  134. prov := newACMEProv(t)
  135. prov.TermsOfService = "https://terms.ca.local/"
  136. prov.Website = "https://ca.local/"
  137. prov.CaaIdentities = []string{"ca.local"}
  138. prov.RequireEAB = true
  139. provName := url.PathEscape(prov.GetName())
  140. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  141. ctx := acme.NewProvisionerContext(context.Background(), prov)
  142. expDir := Directory{
  143. NewNonce: fmt.Sprintf("%s/acme/%s/new-nonce", baseURL.String(), provName),
  144. NewAccount: fmt.Sprintf("%s/acme/%s/new-account", baseURL.String(), provName),
  145. NewOrder: fmt.Sprintf("%s/acme/%s/new-order", baseURL.String(), provName),
  146. RevokeCert: fmt.Sprintf("%s/acme/%s/revoke-cert", baseURL.String(), provName),
  147. KeyChange: fmt.Sprintf("%s/acme/%s/key-change", baseURL.String(), provName),
  148. Meta: &Meta{
  149. TermsOfService: "https://terms.ca.local/",
  150. Website: "https://ca.local/",
  151. CaaIdentities: []string{"ca.local"},
  152. ExternalAccountRequired: true,
  153. },
  154. }
  155. return test{
  156. ctx: ctx,
  157. dir: expDir,
  158. statusCode: 200,
  159. }
  160. },
  161. }
  162. for name, run := range tests {
  163. tc := run(t)
  164. t.Run(name, func(t *testing.T) {
  165. ctx := acme.NewLinkerContext(tc.ctx, acme.NewLinker("test.ca.smallstep.com", "acme"))
  166. req := httptest.NewRequest("GET", "/foo/bar", nil)
  167. req = req.WithContext(ctx)
  168. w := httptest.NewRecorder()
  169. GetDirectory(w, req)
  170. res := w.Result()
  171. assert.Equals(t, res.StatusCode, tc.statusCode)
  172. body, err := io.ReadAll(res.Body)
  173. res.Body.Close()
  174. assert.FatalError(t, err)
  175. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  176. var ae acme.Error
  177. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  178. assert.Equals(t, ae.Type, tc.err.Type)
  179. assert.Equals(t, ae.Detail, tc.err.Detail)
  180. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  181. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  182. } else {
  183. var dir Directory
  184. json.Unmarshal(bytes.TrimSpace(body), &dir)
  185. if !cmp.Equal(tc.dir, dir) {
  186. t.Errorf("GetDirectory() diff =\n%s", cmp.Diff(tc.dir, dir))
  187. }
  188. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  189. }
  190. })
  191. }
  192. }
  193. func TestHandler_GetAuthorization(t *testing.T) {
  194. expiry := time.Now().UTC().Add(6 * time.Hour)
  195. az := acme.Authorization{
  196. ID: "authzID",
  197. AccountID: "accID",
  198. Identifier: acme.Identifier{
  199. Type: "dns",
  200. Value: "example.com",
  201. },
  202. Status: "pending",
  203. ExpiresAt: expiry,
  204. Wildcard: false,
  205. Challenges: []*acme.Challenge{
  206. {
  207. Type: "http-01",
  208. Status: "pending",
  209. Token: "tok2",
  210. URL: "https://ca.smallstep.com/acme/challenge/chHTTPID",
  211. ID: "chHTTP01ID",
  212. },
  213. {
  214. Type: "dns-01",
  215. Status: "pending",
  216. Token: "tok2",
  217. URL: "https://ca.smallstep.com/acme/challenge/chDNSID",
  218. ID: "chDNSID",
  219. },
  220. },
  221. }
  222. prov := newProv()
  223. provName := url.PathEscape(prov.GetName())
  224. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  225. // Request with chi context
  226. chiCtx := chi.NewRouteContext()
  227. chiCtx.URLParams.Add("authzID", az.ID)
  228. u := fmt.Sprintf("%s/acme/%s/authz/%s",
  229. baseURL.String(), provName, az.ID)
  230. type test struct {
  231. db acme.DB
  232. ctx context.Context
  233. statusCode int
  234. err *acme.Error
  235. }
  236. var tests = map[string]func(t *testing.T) test{
  237. "fail/no-account": func(t *testing.T) test {
  238. return test{
  239. db: &acme.MockDB{},
  240. ctx: context.Background(),
  241. statusCode: 400,
  242. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  243. }
  244. },
  245. "fail/nil-account": func(t *testing.T) test {
  246. ctx := acme.NewProvisionerContext(context.Background(), prov)
  247. ctx = context.WithValue(ctx, accContextKey, nil)
  248. return test{
  249. db: &acme.MockDB{},
  250. ctx: ctx,
  251. statusCode: 400,
  252. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  253. }
  254. },
  255. "fail/db.GetAuthorization-error": func(t *testing.T) test {
  256. acc := &acme.Account{ID: "accID"}
  257. ctx := context.WithValue(context.Background(), accContextKey, acc)
  258. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  259. return test{
  260. db: &acme.MockDB{
  261. MockError: acme.NewErrorISE("force"),
  262. },
  263. ctx: ctx,
  264. statusCode: 500,
  265. err: acme.NewErrorISE("force"),
  266. }
  267. },
  268. "fail/account-id-mismatch": func(t *testing.T) test {
  269. acc := &acme.Account{ID: "accID"}
  270. ctx := context.WithValue(context.Background(), accContextKey, acc)
  271. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  272. return test{
  273. db: &acme.MockDB{
  274. MockGetAuthorization: func(ctx context.Context, id string) (*acme.Authorization, error) {
  275. assert.Equals(t, id, az.ID)
  276. return &acme.Authorization{
  277. AccountID: "foo",
  278. }, nil
  279. },
  280. },
  281. ctx: ctx,
  282. statusCode: 401,
  283. err: acme.NewError(acme.ErrorUnauthorizedType, "account id mismatch"),
  284. }
  285. },
  286. "fail/db.UpdateAuthorization-error": func(t *testing.T) test {
  287. acc := &acme.Account{ID: "accID"}
  288. ctx := context.WithValue(context.Background(), accContextKey, acc)
  289. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  290. return test{
  291. db: &acme.MockDB{
  292. MockGetAuthorization: func(ctx context.Context, id string) (*acme.Authorization, error) {
  293. assert.Equals(t, id, az.ID)
  294. return &acme.Authorization{
  295. AccountID: "accID",
  296. Status: acme.StatusPending,
  297. ExpiresAt: time.Now().Add(-1 * time.Hour),
  298. }, nil
  299. },
  300. MockUpdateAuthorization: func(ctx context.Context, az *acme.Authorization) error {
  301. assert.Equals(t, az.Status, acme.StatusInvalid)
  302. return acme.NewErrorISE("force")
  303. },
  304. },
  305. ctx: ctx,
  306. statusCode: 500,
  307. err: acme.NewErrorISE("force"),
  308. }
  309. },
  310. "ok": func(t *testing.T) test {
  311. acc := &acme.Account{ID: "accID"}
  312. ctx := acme.NewProvisionerContext(context.Background(), prov)
  313. ctx = context.WithValue(ctx, accContextKey, acc)
  314. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  315. return test{
  316. db: &acme.MockDB{
  317. MockGetAuthorization: func(ctx context.Context, id string) (*acme.Authorization, error) {
  318. assert.Equals(t, id, az.ID)
  319. return &az, nil
  320. },
  321. },
  322. ctx: ctx,
  323. statusCode: 200,
  324. }
  325. },
  326. }
  327. for name, run := range tests {
  328. tc := run(t)
  329. t.Run(name, func(t *testing.T) {
  330. ctx := acme.NewContext(tc.ctx, tc.db, nil, acme.NewLinker("test.ca.smallstep.com", "acme"), nil)
  331. req := httptest.NewRequest("GET", "/foo/bar", nil)
  332. req = req.WithContext(ctx)
  333. w := httptest.NewRecorder()
  334. GetAuthorization(w, req)
  335. res := w.Result()
  336. assert.Equals(t, res.StatusCode, tc.statusCode)
  337. body, err := io.ReadAll(res.Body)
  338. res.Body.Close()
  339. assert.FatalError(t, err)
  340. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  341. var ae acme.Error
  342. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  343. assert.Equals(t, ae.Type, tc.err.Type)
  344. assert.Equals(t, ae.Detail, tc.err.Detail)
  345. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  346. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  347. } else {
  348. //var gotAz acme.Authz
  349. //assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &gotAz))
  350. expB, err := json.Marshal(az)
  351. assert.FatalError(t, err)
  352. assert.Equals(t, bytes.TrimSpace(body), expB)
  353. assert.Equals(t, res.Header["Location"], []string{u})
  354. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  355. }
  356. })
  357. }
  358. }
  359. func TestHandler_GetCertificate(t *testing.T) {
  360. leaf, err := pemutil.ReadCertificate("../../authority/testdata/certs/foo.crt")
  361. assert.FatalError(t, err)
  362. inter, err := pemutil.ReadCertificate("../../authority/testdata/certs/intermediate_ca.crt")
  363. assert.FatalError(t, err)
  364. root, err := pemutil.ReadCertificate("../../authority/testdata/certs/root_ca.crt")
  365. assert.FatalError(t, err)
  366. certBytes := append(pem.EncodeToMemory(&pem.Block{
  367. Type: "CERTIFICATE",
  368. Bytes: leaf.Raw,
  369. }), pem.EncodeToMemory(&pem.Block{
  370. Type: "CERTIFICATE",
  371. Bytes: inter.Raw,
  372. })...)
  373. certBytes = append(certBytes, pem.EncodeToMemory(&pem.Block{
  374. Type: "CERTIFICATE",
  375. Bytes: root.Raw,
  376. })...)
  377. certID := "certID"
  378. prov := newProv()
  379. provName := url.PathEscape(prov.GetName())
  380. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  381. // Request with chi context
  382. chiCtx := chi.NewRouteContext()
  383. chiCtx.URLParams.Add("certID", certID)
  384. u := fmt.Sprintf("%s/acme/%s/certificate/%s",
  385. baseURL.String(), provName, certID)
  386. type test struct {
  387. db acme.DB
  388. ctx context.Context
  389. statusCode int
  390. err *acme.Error
  391. }
  392. var tests = map[string]func(t *testing.T) test{
  393. "fail/no-account": func(t *testing.T) test {
  394. return test{
  395. db: &acme.MockDB{},
  396. ctx: context.Background(),
  397. statusCode: 400,
  398. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  399. }
  400. },
  401. "fail/nil-account": func(t *testing.T) test {
  402. ctx := context.WithValue(context.Background(), accContextKey, nil)
  403. return test{
  404. db: &acme.MockDB{},
  405. ctx: ctx,
  406. statusCode: 400,
  407. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  408. }
  409. },
  410. "fail/db.GetCertificate-error": func(t *testing.T) test {
  411. acc := &acme.Account{ID: "accID"}
  412. ctx := context.WithValue(context.Background(), accContextKey, acc)
  413. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  414. return test{
  415. db: &acme.MockDB{
  416. MockError: acme.NewErrorISE("force"),
  417. },
  418. ctx: ctx,
  419. statusCode: 500,
  420. err: acme.NewErrorISE("force"),
  421. }
  422. },
  423. "fail/account-id-mismatch": func(t *testing.T) test {
  424. acc := &acme.Account{ID: "accID"}
  425. ctx := context.WithValue(context.Background(), accContextKey, acc)
  426. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  427. return test{
  428. db: &acme.MockDB{
  429. MockGetCertificate: func(ctx context.Context, id string) (*acme.Certificate, error) {
  430. assert.Equals(t, id, certID)
  431. return &acme.Certificate{AccountID: "foo"}, nil
  432. },
  433. },
  434. ctx: ctx,
  435. statusCode: 401,
  436. err: acme.NewError(acme.ErrorUnauthorizedType, "account id mismatch"),
  437. }
  438. },
  439. "ok": func(t *testing.T) test {
  440. acc := &acme.Account{ID: "accID"}
  441. ctx := context.WithValue(context.Background(), accContextKey, acc)
  442. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  443. return test{
  444. db: &acme.MockDB{
  445. MockGetCertificate: func(ctx context.Context, id string) (*acme.Certificate, error) {
  446. assert.Equals(t, id, certID)
  447. return &acme.Certificate{
  448. AccountID: "accID",
  449. OrderID: "ordID",
  450. Leaf: leaf,
  451. Intermediates: []*x509.Certificate{inter, root},
  452. ID: id,
  453. }, nil
  454. },
  455. },
  456. ctx: ctx,
  457. statusCode: 200,
  458. }
  459. },
  460. }
  461. for name, run := range tests {
  462. tc := run(t)
  463. t.Run(name, func(t *testing.T) {
  464. ctx := acme.NewDatabaseContext(tc.ctx, tc.db)
  465. req := httptest.NewRequest("GET", u, nil)
  466. req = req.WithContext(ctx)
  467. w := httptest.NewRecorder()
  468. GetCertificate(w, req)
  469. res := w.Result()
  470. assert.Equals(t, res.StatusCode, tc.statusCode)
  471. body, err := io.ReadAll(res.Body)
  472. res.Body.Close()
  473. assert.FatalError(t, err)
  474. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  475. var ae acme.Error
  476. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  477. assert.Equals(t, ae.Type, tc.err.Type)
  478. assert.HasPrefix(t, ae.Detail, tc.err.Detail)
  479. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  480. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  481. } else {
  482. assert.Equals(t, bytes.TrimSpace(body), bytes.TrimSpace(certBytes))
  483. assert.Equals(t, res.Header["Content-Type"], []string{"application/pem-certificate-chain"})
  484. }
  485. })
  486. }
  487. }
  488. func TestHandler_GetChallenge(t *testing.T) {
  489. chiCtx := chi.NewRouteContext()
  490. chiCtx.URLParams.Add("chID", "chID")
  491. chiCtx.URLParams.Add("authzID", "authzID")
  492. prov := newProv()
  493. provName := url.PathEscape(prov.GetName())
  494. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  495. u := fmt.Sprintf("%s/acme/%s/challenge/%s/%s",
  496. baseURL.String(), provName, "authzID", "chID")
  497. type test struct {
  498. db acme.DB
  499. vc acme.Client
  500. ctx context.Context
  501. statusCode int
  502. ch *acme.Challenge
  503. err *acme.Error
  504. }
  505. var tests = map[string]func(t *testing.T) test{
  506. "fail/no-account": func(t *testing.T) test {
  507. return test{
  508. db: &acme.MockDB{},
  509. ctx: context.Background(),
  510. statusCode: 400,
  511. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  512. }
  513. },
  514. "fail/nil-account": func(t *testing.T) test {
  515. return test{
  516. db: &acme.MockDB{},
  517. ctx: context.WithValue(context.Background(), accContextKey, nil),
  518. statusCode: 400,
  519. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  520. }
  521. },
  522. "fail/no-payload": func(t *testing.T) test {
  523. acc := &acme.Account{ID: "accID"}
  524. ctx := context.WithValue(context.Background(), accContextKey, acc)
  525. return test{
  526. db: &acme.MockDB{},
  527. ctx: ctx,
  528. statusCode: 500,
  529. err: acme.NewErrorISE("payload expected in request context"),
  530. }
  531. },
  532. "fail/nil-payload": func(t *testing.T) test {
  533. acc := &acme.Account{ID: "accID"}
  534. ctx := acme.NewProvisionerContext(context.Background(), prov)
  535. ctx = context.WithValue(ctx, accContextKey, acc)
  536. ctx = context.WithValue(ctx, payloadContextKey, nil)
  537. return test{
  538. db: &acme.MockDB{},
  539. ctx: ctx,
  540. statusCode: 500,
  541. err: acme.NewErrorISE("payload expected in request context"),
  542. }
  543. },
  544. "fail/db.GetChallenge-error": func(t *testing.T) test {
  545. acc := &acme.Account{ID: "accID"}
  546. ctx := acme.NewProvisionerContext(context.Background(), 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 nil, acme.NewErrorISE("force")
  556. },
  557. },
  558. ctx: ctx,
  559. statusCode: 500,
  560. err: acme.NewErrorISE("force"),
  561. }
  562. },
  563. "fail/account-id-mismatch": func(t *testing.T) test {
  564. acc := &acme.Account{ID: "accID"}
  565. ctx := acme.NewProvisionerContext(context.Background(), prov)
  566. ctx = context.WithValue(ctx, accContextKey, acc)
  567. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  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: "foo"}, nil
  575. },
  576. },
  577. ctx: ctx,
  578. statusCode: 401,
  579. err: acme.NewError(acme.ErrorUnauthorizedType, "accout id mismatch"),
  580. }
  581. },
  582. "fail/no-jwk": func(t *testing.T) test {
  583. acc := &acme.Account{ID: "accID"}
  584. ctx := acme.NewProvisionerContext(context.Background(), prov)
  585. ctx = context.WithValue(ctx, accContextKey, acc)
  586. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  587. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  588. return test{
  589. db: &acme.MockDB{
  590. MockGetChallenge: func(ctx context.Context, chID, azID string) (*acme.Challenge, error) {
  591. assert.Equals(t, chID, "chID")
  592. assert.Equals(t, azID, "authzID")
  593. return &acme.Challenge{AccountID: "accID"}, nil
  594. },
  595. },
  596. ctx: ctx,
  597. statusCode: 500,
  598. err: acme.NewErrorISE("missing jwk"),
  599. }
  600. },
  601. "fail/nil-jwk": func(t *testing.T) test {
  602. acc := &acme.Account{ID: "accID"}
  603. ctx := acme.NewProvisionerContext(context.Background(), prov)
  604. ctx = context.WithValue(ctx, accContextKey, acc)
  605. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  606. ctx = context.WithValue(ctx, jwkContextKey, nil)
  607. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  608. return test{
  609. db: &acme.MockDB{
  610. MockGetChallenge: func(ctx context.Context, chID, azID string) (*acme.Challenge, error) {
  611. assert.Equals(t, chID, "chID")
  612. assert.Equals(t, azID, "authzID")
  613. return &acme.Challenge{AccountID: "accID"}, nil
  614. },
  615. },
  616. ctx: ctx,
  617. statusCode: 500,
  618. err: acme.NewErrorISE("nil jwk"),
  619. }
  620. },
  621. "fail/validate-challenge-error": func(t *testing.T) test {
  622. acc := &acme.Account{ID: "accID"}
  623. ctx := acme.NewProvisionerContext(context.Background(), prov)
  624. ctx = context.WithValue(ctx, accContextKey, acc)
  625. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  626. _jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  627. assert.FatalError(t, err)
  628. _pub := _jwk.Public()
  629. ctx = context.WithValue(ctx, jwkContextKey, &_pub)
  630. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  631. return test{
  632. db: &acme.MockDB{
  633. MockGetChallenge: func(ctx context.Context, chID, azID string) (*acme.Challenge, error) {
  634. assert.Equals(t, chID, "chID")
  635. assert.Equals(t, azID, "authzID")
  636. return &acme.Challenge{
  637. Status: acme.StatusPending,
  638. Type: acme.HTTP01,
  639. AccountID: "accID",
  640. }, nil
  641. },
  642. MockUpdateChallenge: func(ctx context.Context, ch *acme.Challenge) error {
  643. assert.Equals(t, ch.Status, acme.StatusPending)
  644. assert.Equals(t, ch.Type, acme.HTTP01)
  645. assert.Equals(t, ch.AccountID, "accID")
  646. assert.Equals(t, ch.AuthorizationID, "authzID")
  647. assert.HasSuffix(t, ch.Error.Type, acme.ErrorConnectionType.String())
  648. return acme.NewErrorISE("force")
  649. },
  650. },
  651. vc: &mockClient{
  652. get: func(string) (*http.Response, error) {
  653. return nil, errors.New("force")
  654. },
  655. },
  656. ctx: ctx,
  657. statusCode: 500,
  658. err: acme.NewErrorISE("force"),
  659. }
  660. },
  661. "ok": func(t *testing.T) test {
  662. acc := &acme.Account{ID: "accID"}
  663. ctx := acme.NewProvisionerContext(context.Background(), prov)
  664. ctx = context.WithValue(ctx, accContextKey, acc)
  665. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  666. _jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  667. assert.FatalError(t, err)
  668. _pub := _jwk.Public()
  669. ctx = context.WithValue(ctx, jwkContextKey, &_pub)
  670. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  671. return test{
  672. db: &acme.MockDB{
  673. MockGetChallenge: func(ctx context.Context, chID, azID string) (*acme.Challenge, error) {
  674. assert.Equals(t, chID, "chID")
  675. assert.Equals(t, azID, "authzID")
  676. return &acme.Challenge{
  677. ID: "chID",
  678. Status: acme.StatusPending,
  679. Type: acme.HTTP01,
  680. AccountID: "accID",
  681. }, nil
  682. },
  683. MockUpdateChallenge: func(ctx context.Context, ch *acme.Challenge) error {
  684. assert.Equals(t, ch.Status, acme.StatusPending)
  685. assert.Equals(t, ch.Type, acme.HTTP01)
  686. assert.Equals(t, ch.AccountID, "accID")
  687. assert.Equals(t, ch.AuthorizationID, "authzID")
  688. assert.HasSuffix(t, ch.Error.Type, acme.ErrorConnectionType.String())
  689. return nil
  690. },
  691. },
  692. ch: &acme.Challenge{
  693. ID: "chID",
  694. Status: acme.StatusPending,
  695. AuthorizationID: "authzID",
  696. Type: acme.HTTP01,
  697. AccountID: "accID",
  698. URL: u,
  699. Error: acme.NewError(acme.ErrorConnectionType, "force"),
  700. },
  701. vc: &mockClient{
  702. get: func(string) (*http.Response, error) {
  703. return nil, errors.New("force")
  704. },
  705. },
  706. ctx: ctx,
  707. statusCode: 200,
  708. }
  709. },
  710. }
  711. for name, run := range tests {
  712. tc := run(t)
  713. t.Run(name, func(t *testing.T) {
  714. ctx := acme.NewContext(tc.ctx, tc.db, nil, acme.NewLinker("test.ca.smallstep.com", "acme"), nil)
  715. req := httptest.NewRequest("GET", u, nil)
  716. req = req.WithContext(ctx)
  717. w := httptest.NewRecorder()
  718. GetChallenge(w, req)
  719. res := w.Result()
  720. assert.Equals(t, res.StatusCode, tc.statusCode)
  721. body, err := io.ReadAll(res.Body)
  722. res.Body.Close()
  723. assert.FatalError(t, err)
  724. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  725. var ae acme.Error
  726. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  727. assert.Equals(t, ae.Type, tc.err.Type)
  728. assert.Equals(t, ae.Detail, tc.err.Detail)
  729. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  730. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  731. } else {
  732. expB, err := json.Marshal(tc.ch)
  733. assert.FatalError(t, err)
  734. assert.Equals(t, bytes.TrimSpace(body), expB)
  735. assert.Equals(t, res.Header["Link"], []string{fmt.Sprintf("<%s/acme/%s/authz/%s>;rel=\"up\"", baseURL, provName, "authzID")})
  736. assert.Equals(t, res.Header["Location"], []string{u})
  737. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  738. }
  739. })
  740. }
  741. }
  742. func Test_createMetaObject(t *testing.T) {
  743. tests := []struct {
  744. name string
  745. p *provisioner.ACME
  746. want *Meta
  747. }{
  748. {
  749. name: "no-meta",
  750. p: &provisioner.ACME{
  751. Type: "ACME",
  752. Name: "acme",
  753. },
  754. want: nil,
  755. },
  756. {
  757. name: "terms-of-service",
  758. p: &provisioner.ACME{
  759. Type: "ACME",
  760. Name: "acme",
  761. TermsOfService: "https://terms.ca.local",
  762. },
  763. want: &Meta{
  764. TermsOfService: "https://terms.ca.local",
  765. },
  766. },
  767. {
  768. name: "website",
  769. p: &provisioner.ACME{
  770. Type: "ACME",
  771. Name: "acme",
  772. Website: "https://ca.local",
  773. },
  774. want: &Meta{
  775. Website: "https://ca.local",
  776. },
  777. },
  778. {
  779. name: "caa",
  780. p: &provisioner.ACME{
  781. Type: "ACME",
  782. Name: "acme",
  783. CaaIdentities: []string{"ca.local", "ca.remote"},
  784. },
  785. want: &Meta{
  786. CaaIdentities: []string{"ca.local", "ca.remote"},
  787. },
  788. },
  789. {
  790. name: "require-eab",
  791. p: &provisioner.ACME{
  792. Type: "ACME",
  793. Name: "acme",
  794. RequireEAB: true,
  795. },
  796. want: &Meta{
  797. ExternalAccountRequired: true,
  798. },
  799. },
  800. {
  801. name: "full-meta",
  802. p: &provisioner.ACME{
  803. Type: "ACME",
  804. Name: "acme",
  805. TermsOfService: "https://terms.ca.local",
  806. Website: "https://ca.local",
  807. CaaIdentities: []string{"ca.local", "ca.remote"},
  808. RequireEAB: true,
  809. },
  810. want: &Meta{
  811. TermsOfService: "https://terms.ca.local",
  812. Website: "https://ca.local",
  813. CaaIdentities: []string{"ca.local", "ca.remote"},
  814. ExternalAccountRequired: true,
  815. },
  816. },
  817. }
  818. for _, tt := range tests {
  819. t.Run(tt.name, func(t *testing.T) {
  820. got := createMetaObject(tt.p)
  821. if !cmp.Equal(tt.want, got) {
  822. t.Errorf("createMetaObject() diff =\n%s", cmp.Diff(tt.want, got))
  823. }
  824. })
  825. }
  826. }