handler_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  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.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. "ok": 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 certBytes, nil
  490. },
  491. },
  492. ctx: ctx,
  493. statusCode: 200,
  494. }
  495. },
  496. }
  497. for name, run := range tests {
  498. tc := run(t)
  499. t.Run(name, func(t *testing.T) {
  500. h := New(tc.auth).(*Handler)
  501. req := httptest.NewRequest("GET", url, nil)
  502. req = req.WithContext(tc.ctx)
  503. w := httptest.NewRecorder()
  504. h.GetCertificate(w, req)
  505. res := w.Result()
  506. assert.Equals(t, res.StatusCode, tc.statusCode)
  507. body, err := ioutil.ReadAll(res.Body)
  508. res.Body.Close()
  509. assert.FatalError(t, err)
  510. if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
  511. var ae acme.AError
  512. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  513. prob := tc.problem.ToACME()
  514. assert.Equals(t, ae.Type, prob.Type)
  515. assert.Equals(t, ae.Detail, prob.Detail)
  516. assert.Equals(t, ae.Identifier, prob.Identifier)
  517. assert.Equals(t, ae.Subproblems, prob.Subproblems)
  518. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  519. } else {
  520. assert.Equals(t, bytes.TrimSpace(body), bytes.TrimSpace(certBytes))
  521. assert.Equals(t, res.Header["Content-Type"], []string{"application/pem-certificate-chain; charset=utf-8"})
  522. }
  523. })
  524. }
  525. }
  526. func ch() acme.Challenge {
  527. return acme.Challenge{
  528. Type: "http-01",
  529. Status: "pending",
  530. Token: "tok2",
  531. URL: "https://ca.smallstep.com/acme/challenge/chID",
  532. ID: "chID",
  533. AuthzID: "authzID",
  534. }
  535. }
  536. func TestHandlerGetChallenge(t *testing.T) {
  537. chiCtx := chi.NewRouteContext()
  538. chiCtx.URLParams.Add("chID", "chID")
  539. prov := newProv()
  540. provName := url.PathEscape(prov.GetName())
  541. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  542. url := fmt.Sprintf("%s/acme/challenge/%s", baseURL, "chID")
  543. type test struct {
  544. auth acme.Interface
  545. ctx context.Context
  546. statusCode int
  547. ch acme.Challenge
  548. problem *acme.Error
  549. }
  550. var tests = map[string]func(t *testing.T) test{
  551. "fail/no-account": func(t *testing.T) test {
  552. return test{
  553. ctx: context.WithValue(context.Background(), acme.ProvisionerContextKey, prov),
  554. statusCode: 400,
  555. problem: acme.AccountDoesNotExistErr(nil),
  556. }
  557. },
  558. "fail/nil-account": func(t *testing.T) test {
  559. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  560. ctx = context.WithValue(ctx, acme.AccContextKey, nil)
  561. return test{
  562. ctx: ctx,
  563. statusCode: 400,
  564. problem: acme.AccountDoesNotExistErr(nil),
  565. }
  566. },
  567. "fail/no-payload": func(t *testing.T) test {
  568. acc := &acme.Account{ID: "accID"}
  569. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  570. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  571. return test{
  572. ctx: ctx,
  573. statusCode: 500,
  574. problem: acme.ServerInternalErr(errors.New("payload expected in request context")),
  575. }
  576. },
  577. "fail/nil-payload": func(t *testing.T) test {
  578. acc := &acme.Account{ID: "accID"}
  579. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  580. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  581. ctx = context.WithValue(ctx, acme.PayloadContextKey, nil)
  582. return test{
  583. ctx: ctx,
  584. statusCode: 500,
  585. problem: acme.ServerInternalErr(errors.New("payload expected in request context")),
  586. }
  587. },
  588. "fail/validate-challenge-error": func(t *testing.T) test {
  589. acc := &acme.Account{ID: "accID"}
  590. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  591. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  592. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{isEmptyJSON: true})
  593. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  594. return test{
  595. auth: &mockAcmeAuthority{
  596. err: acme.UnauthorizedErr(nil),
  597. },
  598. ctx: ctx,
  599. statusCode: 401,
  600. problem: acme.UnauthorizedErr(nil),
  601. }
  602. },
  603. "fail/get-challenge-error": func(t *testing.T) test {
  604. acc := &acme.Account{ID: "accID"}
  605. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  606. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  607. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{isPostAsGet: true})
  608. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  609. return test{
  610. auth: &mockAcmeAuthority{
  611. err: acme.UnauthorizedErr(nil),
  612. },
  613. ctx: ctx,
  614. statusCode: 401,
  615. problem: acme.UnauthorizedErr(nil),
  616. }
  617. },
  618. "ok/validate-challenge": func(t *testing.T) test {
  619. key, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  620. assert.FatalError(t, err)
  621. acc := &acme.Account{ID: "accID", Key: key}
  622. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  623. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  624. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{isEmptyJSON: true})
  625. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  626. ctx = context.WithValue(ctx, acme.BaseURLContextKey, baseURL)
  627. ch := ch()
  628. ch.Status = "valid"
  629. ch.Validated = time.Now().UTC().Format(time.RFC3339)
  630. count := 0
  631. return test{
  632. auth: &mockAcmeAuthority{
  633. validateChallenge: func(ctx context.Context, accID, id string, jwk *jose.JSONWebKey) (*acme.Challenge, error) {
  634. p, err := acme.ProvisionerFromContext(ctx)
  635. assert.FatalError(t, err)
  636. assert.Equals(t, p, prov)
  637. assert.Equals(t, accID, acc.ID)
  638. assert.Equals(t, id, ch.ID)
  639. assert.Equals(t, jwk.KeyID, key.KeyID)
  640. return &ch, nil
  641. },
  642. getLink: func(ctx context.Context, typ acme.Link, abs bool, in ...string) string {
  643. var ret string
  644. switch count {
  645. case 0:
  646. assert.Equals(t, typ, acme.AuthzLink)
  647. assert.True(t, abs)
  648. assert.Equals(t, in, []string{ch.AuthzID})
  649. ret = fmt.Sprintf("%s/acme/%s/authz/%s", baseURL.String(), provName, ch.AuthzID)
  650. case 1:
  651. assert.Equals(t, typ, acme.ChallengeLink)
  652. assert.True(t, abs)
  653. assert.Equals(t, in, []string{ch.ID})
  654. ret = url
  655. }
  656. count++
  657. return ret
  658. },
  659. },
  660. ctx: ctx,
  661. statusCode: 200,
  662. ch: ch,
  663. }
  664. },
  665. }
  666. for name, run := range tests {
  667. tc := run(t)
  668. t.Run(name, func(t *testing.T) {
  669. h := New(tc.auth).(*Handler)
  670. req := httptest.NewRequest("GET", url, nil)
  671. req = req.WithContext(tc.ctx)
  672. w := httptest.NewRecorder()
  673. h.GetChallenge(w, req)
  674. res := w.Result()
  675. assert.Equals(t, res.StatusCode, tc.statusCode)
  676. body, err := ioutil.ReadAll(res.Body)
  677. res.Body.Close()
  678. assert.FatalError(t, err)
  679. if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
  680. var ae acme.AError
  681. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  682. prob := tc.problem.ToACME()
  683. assert.Equals(t, ae.Type, prob.Type)
  684. assert.Equals(t, ae.Detail, prob.Detail)
  685. assert.Equals(t, ae.Identifier, prob.Identifier)
  686. assert.Equals(t, ae.Subproblems, prob.Subproblems)
  687. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  688. } else {
  689. expB, err := json.Marshal(tc.ch)
  690. assert.FatalError(t, err)
  691. assert.Equals(t, bytes.TrimSpace(body), expB)
  692. assert.Equals(t, res.Header["Link"], []string{fmt.Sprintf("<%s/acme/%s/authz/%s>;rel=\"up\"", baseURL, provName, tc.ch.AuthzID)})
  693. assert.Equals(t, res.Header["Location"], []string{url})
  694. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  695. }
  696. })
  697. }
  698. }