handler_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  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. "github.com/smallstep/cli/crypto/pemutil"
  21. "github.com/smallstep/cli/jose"
  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.NewAuthority(new(db.MockNoSQLDB), "ca.smallstep.com", "acme", nil, 0)
  217. assert.FatalError(t, err)
  218. prov := newProv()
  219. provName := url.PathEscape(prov.GetName())
  220. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  221. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  222. ctx = context.WithValue(ctx, acme.BaseURLContextKey, baseURL)
  223. expDir := acme.Directory{
  224. NewNonce: fmt.Sprintf("%s/acme/%s/new-nonce", baseURL.String(), provName),
  225. NewAccount: fmt.Sprintf("%s/acme/%s/new-account", baseURL.String(), provName),
  226. NewOrder: fmt.Sprintf("%s/acme/%s/new-order", baseURL.String(), provName),
  227. RevokeCert: fmt.Sprintf("%s/acme/%s/revoke-cert", baseURL.String(), provName),
  228. KeyChange: fmt.Sprintf("%s/acme/%s/key-change", baseURL.String(), provName),
  229. }
  230. type test struct {
  231. statusCode int
  232. problem *acme.Error
  233. }
  234. var tests = map[string]func(t *testing.T) test{
  235. "ok": func(t *testing.T) test {
  236. return test{
  237. statusCode: 200,
  238. }
  239. },
  240. }
  241. for name, run := range tests {
  242. tc := run(t)
  243. t.Run(name, func(t *testing.T) {
  244. h := New(auth).(*Handler)
  245. req := httptest.NewRequest("GET", "/foo/bar", nil)
  246. req = req.WithContext(ctx)
  247. w := httptest.NewRecorder()
  248. h.GetDirectory(w, req)
  249. res := w.Result()
  250. assert.Equals(t, res.StatusCode, tc.statusCode)
  251. body, err := ioutil.ReadAll(res.Body)
  252. res.Body.Close()
  253. assert.FatalError(t, err)
  254. if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
  255. var ae acme.AError
  256. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  257. prob := tc.problem.ToACME()
  258. assert.Equals(t, ae.Type, prob.Type)
  259. assert.Equals(t, ae.Detail, prob.Detail)
  260. assert.Equals(t, ae.Identifier, prob.Identifier)
  261. assert.Equals(t, ae.Subproblems, prob.Subproblems)
  262. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  263. } else {
  264. var dir acme.Directory
  265. json.Unmarshal(bytes.TrimSpace(body), &dir)
  266. assert.Equals(t, dir, expDir)
  267. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  268. }
  269. })
  270. }
  271. }
  272. func TestHandlerGetAuthz(t *testing.T) {
  273. expiry := time.Now().UTC().Add(6 * time.Hour)
  274. az := acme.Authz{
  275. ID: "authzID",
  276. Identifier: acme.Identifier{
  277. Type: "dns",
  278. Value: "example.com",
  279. },
  280. Status: "pending",
  281. Expires: expiry.Format(time.RFC3339),
  282. Wildcard: false,
  283. Challenges: []*acme.Challenge{
  284. {
  285. Type: "http-01",
  286. Status: "pending",
  287. Token: "tok2",
  288. URL: "https://ca.smallstep.com/acme/challenge/chHTTPID",
  289. ID: "chHTTP01ID",
  290. AuthzID: "authzID",
  291. },
  292. {
  293. Type: "dns-01",
  294. Status: "pending",
  295. Token: "tok2",
  296. URL: "https://ca.smallstep.com/acme/challenge/chDNSID",
  297. ID: "chDNSID",
  298. AuthzID: "authzID",
  299. },
  300. },
  301. }
  302. prov := newProv()
  303. provName := url.PathEscape(prov.GetName())
  304. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  305. // Request with chi context
  306. chiCtx := chi.NewRouteContext()
  307. chiCtx.URLParams.Add("authzID", az.ID)
  308. url := fmt.Sprintf("%s/acme/%s/challenge/%s",
  309. baseURL.String(), provName, az.ID)
  310. type test struct {
  311. auth acme.Interface
  312. ctx context.Context
  313. statusCode int
  314. problem *acme.Error
  315. }
  316. var tests = map[string]func(t *testing.T) test{
  317. "fail/no-account": func(t *testing.T) test {
  318. return test{
  319. auth: &mockAcmeAuthority{},
  320. ctx: context.WithValue(context.Background(), acme.ProvisionerContextKey, prov),
  321. statusCode: 400,
  322. problem: acme.AccountDoesNotExistErr(nil),
  323. }
  324. },
  325. "fail/nil-account": func(t *testing.T) test {
  326. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  327. ctx = context.WithValue(ctx, acme.AccContextKey, nil)
  328. return test{
  329. auth: &mockAcmeAuthority{},
  330. ctx: ctx,
  331. statusCode: 400,
  332. problem: acme.AccountDoesNotExistErr(nil),
  333. }
  334. },
  335. "fail/getAuthz-error": func(t *testing.T) test {
  336. acc := &acme.Account{ID: "accID"}
  337. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  338. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  339. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  340. return test{
  341. auth: &mockAcmeAuthority{
  342. err: acme.ServerInternalErr(errors.New("force")),
  343. },
  344. ctx: ctx,
  345. statusCode: 500,
  346. problem: acme.ServerInternalErr(errors.New("force")),
  347. }
  348. },
  349. "ok": func(t *testing.T) test {
  350. acc := &acme.Account{ID: "accID"}
  351. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  352. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  353. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  354. ctx = context.WithValue(ctx, acme.BaseURLContextKey, baseURL)
  355. return test{
  356. auth: &mockAcmeAuthority{
  357. getAuthz: func(ctx context.Context, accID, id string) (*acme.Authz, error) {
  358. p, err := acme.ProvisionerFromContext(ctx)
  359. assert.FatalError(t, err)
  360. assert.Equals(t, p, prov)
  361. assert.Equals(t, accID, acc.ID)
  362. assert.Equals(t, id, az.ID)
  363. return &az, nil
  364. },
  365. getLink: func(ctx context.Context, typ acme.Link, abs bool, in ...string) string {
  366. assert.Equals(t, typ, acme.AuthzLink)
  367. assert.Equals(t, acme.BaseURLFromContext(ctx), baseURL)
  368. assert.True(t, abs)
  369. assert.Equals(t, in, []string{az.ID})
  370. return url
  371. },
  372. },
  373. ctx: ctx,
  374. statusCode: 200,
  375. }
  376. },
  377. }
  378. for name, run := range tests {
  379. tc := run(t)
  380. t.Run(name, func(t *testing.T) {
  381. h := New(tc.auth).(*Handler)
  382. req := httptest.NewRequest("GET", "/foo/bar", nil)
  383. req = req.WithContext(tc.ctx)
  384. w := httptest.NewRecorder()
  385. h.GetAuthz(w, req)
  386. res := w.Result()
  387. assert.Equals(t, res.StatusCode, tc.statusCode)
  388. body, err := ioutil.ReadAll(res.Body)
  389. res.Body.Close()
  390. assert.FatalError(t, err)
  391. if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
  392. var ae acme.AError
  393. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  394. prob := tc.problem.ToACME()
  395. assert.Equals(t, ae.Type, prob.Type)
  396. assert.Equals(t, ae.Detail, prob.Detail)
  397. assert.Equals(t, ae.Identifier, prob.Identifier)
  398. assert.Equals(t, ae.Subproblems, prob.Subproblems)
  399. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  400. } else {
  401. //var gotAz acme.Authz
  402. //assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &gotAz))
  403. expB, err := json.Marshal(az)
  404. assert.FatalError(t, err)
  405. assert.Equals(t, bytes.TrimSpace(body), expB)
  406. assert.Equals(t, res.Header["Location"], []string{url})
  407. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  408. }
  409. })
  410. }
  411. }
  412. func TestHandlerGetCertificate(t *testing.T) {
  413. leaf, err := pemutil.ReadCertificate("../../authority/testdata/certs/foo.crt")
  414. assert.FatalError(t, err)
  415. inter, err := pemutil.ReadCertificate("../../authority/testdata/certs/intermediate_ca.crt")
  416. assert.FatalError(t, err)
  417. root, err := pemutil.ReadCertificate("../../authority/testdata/certs/root_ca.crt")
  418. assert.FatalError(t, err)
  419. certBytes := append(pem.EncodeToMemory(&pem.Block{
  420. Type: "CERTIFICATE",
  421. Bytes: leaf.Raw,
  422. }), pem.EncodeToMemory(&pem.Block{
  423. Type: "CERTIFICATE",
  424. Bytes: inter.Raw,
  425. })...)
  426. certBytes = append(certBytes, pem.EncodeToMemory(&pem.Block{
  427. Type: "CERTIFICATE",
  428. Bytes: root.Raw,
  429. })...)
  430. certID := "certID"
  431. prov := newProv()
  432. provName := url.PathEscape(prov.GetName())
  433. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  434. // Request with chi context
  435. chiCtx := chi.NewRouteContext()
  436. chiCtx.URLParams.Add("certID", certID)
  437. url := fmt.Sprintf("%s/acme/%s/certificate/%s",
  438. baseURL.String(), provName, certID)
  439. type test struct {
  440. auth acme.Interface
  441. ctx context.Context
  442. statusCode int
  443. problem *acme.Error
  444. }
  445. var tests = map[string]func(t *testing.T) test{
  446. "fail/no-account": func(t *testing.T) test {
  447. return test{
  448. auth: &mockAcmeAuthority{},
  449. ctx: context.WithValue(context.Background(), acme.ProvisionerContextKey, prov),
  450. statusCode: 400,
  451. problem: acme.AccountDoesNotExistErr(nil),
  452. }
  453. },
  454. "fail/nil-account": func(t *testing.T) test {
  455. ctx := context.WithValue(context.Background(), acme.AccContextKey, nil)
  456. return test{
  457. auth: &mockAcmeAuthority{},
  458. ctx: ctx,
  459. statusCode: 400,
  460. problem: acme.AccountDoesNotExistErr(nil),
  461. }
  462. },
  463. "fail/getCertificate-error": func(t *testing.T) test {
  464. acc := &acme.Account{ID: "accID"}
  465. ctx := context.WithValue(context.Background(), acme.AccContextKey, acc)
  466. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  467. return test{
  468. auth: &mockAcmeAuthority{
  469. err: acme.ServerInternalErr(errors.New("force")),
  470. },
  471. ctx: ctx,
  472. statusCode: 500,
  473. problem: acme.ServerInternalErr(errors.New("force")),
  474. }
  475. },
  476. "ok": func(t *testing.T) test {
  477. acc := &acme.Account{ID: "accID"}
  478. ctx := context.WithValue(context.Background(), acme.AccContextKey, acc)
  479. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  480. return test{
  481. auth: &mockAcmeAuthority{
  482. getCertificate: func(accID, id string) ([]byte, error) {
  483. assert.Equals(t, accID, acc.ID)
  484. assert.Equals(t, id, certID)
  485. return certBytes, nil
  486. },
  487. },
  488. ctx: ctx,
  489. statusCode: 200,
  490. }
  491. },
  492. }
  493. for name, run := range tests {
  494. tc := run(t)
  495. t.Run(name, func(t *testing.T) {
  496. h := New(tc.auth).(*Handler)
  497. req := httptest.NewRequest("GET", url, nil)
  498. req = req.WithContext(tc.ctx)
  499. w := httptest.NewRecorder()
  500. h.GetCertificate(w, req)
  501. res := w.Result()
  502. assert.Equals(t, res.StatusCode, tc.statusCode)
  503. body, err := ioutil.ReadAll(res.Body)
  504. res.Body.Close()
  505. assert.FatalError(t, err)
  506. if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
  507. var ae acme.AError
  508. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  509. prob := tc.problem.ToACME()
  510. assert.Equals(t, ae.Type, prob.Type)
  511. assert.Equals(t, ae.Detail, prob.Detail)
  512. assert.Equals(t, ae.Identifier, prob.Identifier)
  513. assert.Equals(t, ae.Subproblems, prob.Subproblems)
  514. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  515. } else {
  516. assert.Equals(t, bytes.TrimSpace(body), bytes.TrimSpace(certBytes))
  517. assert.Equals(t, res.Header["Content-Type"], []string{"application/pem-certificate-chain; charset=utf-8"})
  518. }
  519. })
  520. }
  521. }
  522. func ch() acme.Challenge {
  523. return acme.Challenge{
  524. Type: "http-01",
  525. Status: "pending",
  526. Token: "tok2",
  527. URL: "https://ca.smallstep.com/acme/challenge/chID",
  528. ID: "chID",
  529. AuthzID: "authzID",
  530. }
  531. }
  532. func TestHandlerGetChallenge(t *testing.T) {
  533. chiCtx := chi.NewRouteContext()
  534. chiCtx.URLParams.Add("chID", "chID")
  535. prov := newProv()
  536. provName := url.PathEscape(prov.GetName())
  537. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  538. url := fmt.Sprintf("%s/acme/challenge/%s", baseURL, "chID")
  539. type test struct {
  540. auth acme.Interface
  541. ctx context.Context
  542. statusCode int
  543. ch acme.Challenge
  544. problem *acme.Error
  545. }
  546. var tests = map[string]func(t *testing.T) test{
  547. "fail/no-account": func(t *testing.T) test {
  548. return test{
  549. ctx: context.WithValue(context.Background(), acme.ProvisionerContextKey, prov),
  550. statusCode: 400,
  551. problem: acme.AccountDoesNotExistErr(nil),
  552. }
  553. },
  554. "fail/nil-account": func(t *testing.T) test {
  555. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  556. ctx = context.WithValue(ctx, acme.AccContextKey, nil)
  557. return test{
  558. ctx: ctx,
  559. statusCode: 400,
  560. problem: acme.AccountDoesNotExistErr(nil),
  561. }
  562. },
  563. "fail/no-payload": func(t *testing.T) test {
  564. acc := &acme.Account{ID: "accID"}
  565. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  566. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  567. return test{
  568. ctx: ctx,
  569. statusCode: 500,
  570. problem: acme.ServerInternalErr(errors.New("payload expected in request context")),
  571. }
  572. },
  573. "fail/nil-payload": func(t *testing.T) test {
  574. acc := &acme.Account{ID: "accID"}
  575. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  576. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  577. ctx = context.WithValue(ctx, acme.PayloadContextKey, nil)
  578. return test{
  579. ctx: ctx,
  580. statusCode: 500,
  581. problem: acme.ServerInternalErr(errors.New("payload expected in request context")),
  582. }
  583. },
  584. "fail/validate-challenge-error": func(t *testing.T) test {
  585. acc := &acme.Account{ID: "accID"}
  586. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  587. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  588. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{isEmptyJSON: true})
  589. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  590. return test{
  591. auth: &mockAcmeAuthority{
  592. err: acme.ServerInternalErr(nil),
  593. },
  594. ctx: ctx,
  595. statusCode: 500,
  596. problem: acme.ServerInternalErr(nil),
  597. }
  598. },
  599. "fail/get-challenge-error": func(t *testing.T) test {
  600. acc := &acme.Account{ID: "accID"}
  601. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  602. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  603. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{isPostAsGet: true})
  604. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  605. return test{
  606. auth: &mockAcmeAuthority{
  607. err: acme.UnauthorizedErr(nil),
  608. },
  609. ctx: ctx,
  610. statusCode: 401,
  611. problem: acme.UnauthorizedErr(nil),
  612. }
  613. },
  614. "ok/validate-challenge": func(t *testing.T) test {
  615. key, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  616. assert.FatalError(t, err)
  617. acc := &acme.Account{ID: "accID", Key: key}
  618. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  619. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  620. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{isEmptyJSON: true})
  621. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  622. ctx = context.WithValue(ctx, acme.BaseURLContextKey, baseURL)
  623. ch := ch()
  624. ch.Status = "valid"
  625. ch.Validated = time.Now().UTC().Format(time.RFC3339)
  626. count := 0
  627. return test{
  628. auth: &mockAcmeAuthority{
  629. validateChallenge: func(ctx context.Context, accID, id string, jwk *jose.JSONWebKey) (*acme.Challenge, error) {
  630. p, err := acme.ProvisionerFromContext(ctx)
  631. assert.FatalError(t, err)
  632. assert.Equals(t, p, prov)
  633. assert.Equals(t, accID, acc.ID)
  634. assert.Equals(t, id, ch.ID)
  635. assert.Equals(t, jwk.KeyID, key.KeyID)
  636. return &ch, nil
  637. },
  638. getLink: func(ctx context.Context, typ acme.Link, abs bool, in ...string) string {
  639. var ret string
  640. switch count {
  641. case 0:
  642. assert.Equals(t, typ, acme.AuthzLink)
  643. assert.True(t, abs)
  644. assert.Equals(t, in, []string{ch.AuthzID})
  645. ret = fmt.Sprintf("%s/acme/%s/authz/%s", baseURL.String(), provName, ch.AuthzID)
  646. case 1:
  647. assert.Equals(t, typ, acme.ChallengeLink)
  648. assert.True(t, abs)
  649. assert.Equals(t, in, []string{ch.ID})
  650. ret = url
  651. }
  652. count++
  653. return ret
  654. },
  655. },
  656. ctx: ctx,
  657. statusCode: 200,
  658. ch: ch,
  659. }
  660. },
  661. "ok/retry-after": func(t *testing.T) test {
  662. key, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  663. assert.FatalError(t, err)
  664. acc := &acme.Account{ID: "accID", Key: key}
  665. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  666. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  667. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{isEmptyJSON: true})
  668. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  669. ctx = context.WithValue(ctx, acme.BaseURLContextKey, baseURL)
  670. ch := ch()
  671. ch.Status = "processing"
  672. ch.RetryAfter = time.Now().Add(1 * time.Minute).UTC().Format(time.RFC3339)
  673. chJSON, err := json.Marshal(ch)
  674. assert.FatalError(t, err)
  675. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{value: chJSON})
  676. count := 0
  677. return test{
  678. auth: &mockAcmeAuthority{
  679. validateChallenge: func(ctx context.Context, accID, id string, jwk *jose.JSONWebKey) (*acme.Challenge, error) {
  680. p, err := acme.ProvisionerFromContext(ctx)
  681. assert.FatalError(t, err)
  682. assert.Equals(t, p, prov)
  683. assert.Equals(t, accID, acc.ID)
  684. assert.Equals(t, id, ch.ID)
  685. assert.Equals(t, jwk.KeyID, key.KeyID)
  686. return &ch, nil
  687. },
  688. getLink: func(ctx context.Context, typ acme.Link, abs bool, in ...string) string {
  689. var ret string
  690. switch count {
  691. case 0:
  692. assert.Equals(t, typ, acme.AuthzLink)
  693. assert.True(t, abs)
  694. assert.Equals(t, in, []string{ch.AuthzID})
  695. ret = fmt.Sprintf("%s/acme/%s/authz/%s", baseURL.String(), provName, ch.AuthzID)
  696. case 1:
  697. assert.Equals(t, typ, acme.ChallengeLink)
  698. assert.True(t, abs)
  699. assert.Equals(t, in, []string{ch.ID})
  700. ret = url
  701. }
  702. count++
  703. return ret
  704. },
  705. },
  706. ctx: ctx,
  707. statusCode: 200,
  708. ch: ch,
  709. }
  710. },
  711. }
  712. // Run the tests
  713. for name, run := range tests {
  714. tc := run(t)
  715. t.Run(name, func(t *testing.T) {
  716. h := New(tc.auth).(*Handler)
  717. req := httptest.NewRequest("GET", url, nil)
  718. req = req.WithContext(tc.ctx)
  719. w := httptest.NewRecorder()
  720. h.GetChallenge(w, req)
  721. res := w.Result()
  722. assert.Equals(t, res.StatusCode, tc.statusCode)
  723. body, err := ioutil.ReadAll(res.Body)
  724. res.Body.Close()
  725. assert.FatalError(t, err)
  726. if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
  727. var ae acme.AError
  728. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  729. prob := tc.problem.ToACME()
  730. assert.Equals(t, ae.Type, prob.Type)
  731. assert.Equals(t, ae.Detail, prob.Detail)
  732. assert.Equals(t, ae.Identifier, prob.Identifier)
  733. assert.Equals(t, ae.Subproblems, prob.Subproblems)
  734. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  735. } else if res.StatusCode >= 200 {
  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, tc.ch.AuthzID)})
  740. assert.Equals(t, res.Header["Location"], []string{url})
  741. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  742. switch tc.ch.Status {
  743. case "processing":
  744. assert.Equals(t, res.Header["Cache-Control"], []string{"no-cache"})
  745. assert.Equals(t, res.Header["Retry-After"], []string{tc.ch.RetryAfter})
  746. case "valid", "invalid":
  747. //
  748. }
  749. } else {
  750. assert.Fatal(t, false, "Unexpected Status Code")
  751. }
  752. })
  753. }
  754. }