4
0

handler_test.go 25 KB

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