4
0

handler_test.go 24 KB

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