handler_test.go 26 KB

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