handler_test.go 24 KB

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