handler_test.go 27 KB

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