handler_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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"
  11. "net/http/httptest"
  12. "net/url"
  13. "testing"
  14. "time"
  15. "github.com/go-chi/chi"
  16. "github.com/pkg/errors"
  17. "github.com/smallstep/assert"
  18. "github.com/smallstep/certificates/acme"
  19. "go.step.sm/crypto/jose"
  20. "go.step.sm/crypto/pemutil"
  21. )
  22. func TestHandler_GetNonce(t *testing.T) {
  23. tests := []struct {
  24. name string
  25. statusCode int
  26. }{
  27. {"GET", 204},
  28. {"HEAD", 200},
  29. }
  30. // Request with chi context
  31. req := httptest.NewRequest("GET", "http://ca.smallstep.com/nonce", nil)
  32. for _, tt := range tests {
  33. t.Run(tt.name, func(t *testing.T) {
  34. h := &Handler{}
  35. w := httptest.NewRecorder()
  36. req.Method = tt.name
  37. h.GetNonce(w, req)
  38. res := w.Result()
  39. if res.StatusCode != tt.statusCode {
  40. t.Errorf("Handler.GetNonce StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  41. }
  42. })
  43. }
  44. }
  45. func TestHandler_GetDirectory(t *testing.T) {
  46. linker := NewLinker("ca.smallstep.com", "acme")
  47. prov := newProv()
  48. provName := url.PathEscape(prov.GetName())
  49. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  50. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  51. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  52. expDir := Directory{
  53. NewNonce: fmt.Sprintf("%s/acme/%s/new-nonce", baseURL.String(), provName),
  54. NewAccount: fmt.Sprintf("%s/acme/%s/new-account", baseURL.String(), provName),
  55. NewOrder: fmt.Sprintf("%s/acme/%s/new-order", baseURL.String(), provName),
  56. RevokeCert: fmt.Sprintf("%s/acme/%s/revoke-cert", baseURL.String(), provName),
  57. KeyChange: fmt.Sprintf("%s/acme/%s/key-change", baseURL.String(), provName),
  58. }
  59. type test struct {
  60. statusCode int
  61. err *acme.Error
  62. }
  63. var tests = map[string]func(t *testing.T) test{
  64. "ok": func(t *testing.T) test {
  65. return test{
  66. statusCode: 200,
  67. }
  68. },
  69. }
  70. for name, run := range tests {
  71. tc := run(t)
  72. t.Run(name, func(t *testing.T) {
  73. h := &Handler{linker: linker}
  74. req := httptest.NewRequest("GET", "/foo/bar", nil)
  75. req = req.WithContext(ctx)
  76. w := httptest.NewRecorder()
  77. h.GetDirectory(w, req)
  78. res := w.Result()
  79. assert.Equals(t, res.StatusCode, tc.statusCode)
  80. body, err := ioutil.ReadAll(res.Body)
  81. res.Body.Close()
  82. assert.FatalError(t, err)
  83. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  84. var ae acme.Error
  85. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  86. assert.Equals(t, ae.Type, tc.err.Type)
  87. assert.Equals(t, ae.Detail, tc.err.Detail)
  88. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  89. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  90. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  91. } else {
  92. var dir Directory
  93. json.Unmarshal(bytes.TrimSpace(body), &dir)
  94. assert.Equals(t, dir, expDir)
  95. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  96. }
  97. })
  98. }
  99. }
  100. func TestHandler_GetAuthorization(t *testing.T) {
  101. expiry := time.Now().UTC().Add(6 * time.Hour)
  102. az := acme.Authorization{
  103. ID: "authzID",
  104. AccountID: "accID",
  105. Identifier: acme.Identifier{
  106. Type: "dns",
  107. Value: "example.com",
  108. },
  109. Status: "pending",
  110. ExpiresAt: expiry,
  111. Wildcard: false,
  112. Challenges: []*acme.Challenge{
  113. {
  114. Type: "http-01",
  115. Status: "pending",
  116. Token: "tok2",
  117. URL: "https://ca.smallstep.com/acme/challenge/chHTTPID",
  118. ID: "chHTTP01ID",
  119. },
  120. {
  121. Type: "dns-01",
  122. Status: "pending",
  123. Token: "tok2",
  124. URL: "https://ca.smallstep.com/acme/challenge/chDNSID",
  125. ID: "chDNSID",
  126. },
  127. },
  128. }
  129. prov := newProv()
  130. provName := url.PathEscape(prov.GetName())
  131. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  132. // Request with chi context
  133. chiCtx := chi.NewRouteContext()
  134. chiCtx.URLParams.Add("authzID", az.ID)
  135. url := fmt.Sprintf("%s/acme/%s/authz/%s",
  136. baseURL.String(), provName, az.ID)
  137. type test struct {
  138. db acme.DB
  139. ctx context.Context
  140. statusCode int
  141. err *acme.Error
  142. }
  143. var tests = map[string]func(t *testing.T) test{
  144. "fail/no-account": func(t *testing.T) test {
  145. return test{
  146. db: &acme.MockDB{},
  147. ctx: context.Background(),
  148. statusCode: 400,
  149. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  150. }
  151. },
  152. "fail/nil-account": func(t *testing.T) test {
  153. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  154. ctx = context.WithValue(ctx, accContextKey, nil)
  155. return test{
  156. db: &acme.MockDB{},
  157. ctx: ctx,
  158. statusCode: 400,
  159. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  160. }
  161. },
  162. "fail/db.GetAuthorization-error": func(t *testing.T) test {
  163. acc := &acme.Account{ID: "accID"}
  164. ctx := context.WithValue(context.Background(), accContextKey, acc)
  165. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  166. return test{
  167. db: &acme.MockDB{
  168. MockError: acme.NewErrorISE("force"),
  169. },
  170. ctx: ctx,
  171. statusCode: 500,
  172. err: acme.NewErrorISE("force"),
  173. }
  174. },
  175. "fail/account-id-mismatch": func(t *testing.T) test {
  176. acc := &acme.Account{ID: "accID"}
  177. ctx := context.WithValue(context.Background(), accContextKey, acc)
  178. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  179. return test{
  180. db: &acme.MockDB{
  181. MockGetAuthorization: func(ctx context.Context, id string) (*acme.Authorization, error) {
  182. assert.Equals(t, id, az.ID)
  183. return &acme.Authorization{
  184. AccountID: "foo",
  185. }, nil
  186. },
  187. },
  188. ctx: ctx,
  189. statusCode: 401,
  190. err: acme.NewError(acme.ErrorUnauthorizedType, "account id mismatch"),
  191. }
  192. },
  193. "fail/db.UpdateAuthorization-error": func(t *testing.T) test {
  194. acc := &acme.Account{ID: "accID"}
  195. ctx := context.WithValue(context.Background(), accContextKey, acc)
  196. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  197. return test{
  198. db: &acme.MockDB{
  199. MockGetAuthorization: func(ctx context.Context, id string) (*acme.Authorization, error) {
  200. assert.Equals(t, id, az.ID)
  201. return &acme.Authorization{
  202. AccountID: "accID",
  203. Status: acme.StatusPending,
  204. ExpiresAt: time.Now().Add(-1 * time.Hour),
  205. }, nil
  206. },
  207. MockUpdateAuthorization: func(ctx context.Context, az *acme.Authorization) error {
  208. assert.Equals(t, az.Status, acme.StatusInvalid)
  209. return acme.NewErrorISE("force")
  210. },
  211. },
  212. ctx: ctx,
  213. statusCode: 500,
  214. err: acme.NewErrorISE("force"),
  215. }
  216. },
  217. "ok": func(t *testing.T) test {
  218. acc := &acme.Account{ID: "accID"}
  219. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  220. ctx = context.WithValue(ctx, accContextKey, acc)
  221. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  222. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  223. return test{
  224. db: &acme.MockDB{
  225. MockGetAuthorization: func(ctx context.Context, id string) (*acme.Authorization, error) {
  226. assert.Equals(t, id, az.ID)
  227. return &az, nil
  228. },
  229. },
  230. ctx: ctx,
  231. statusCode: 200,
  232. }
  233. },
  234. }
  235. for name, run := range tests {
  236. tc := run(t)
  237. t.Run(name, func(t *testing.T) {
  238. h := &Handler{db: tc.db, linker: NewLinker("dns", "acme")}
  239. req := httptest.NewRequest("GET", "/foo/bar", nil)
  240. req = req.WithContext(tc.ctx)
  241. w := httptest.NewRecorder()
  242. h.GetAuthorization(w, req)
  243. res := w.Result()
  244. assert.Equals(t, res.StatusCode, tc.statusCode)
  245. body, err := ioutil.ReadAll(res.Body)
  246. res.Body.Close()
  247. assert.FatalError(t, err)
  248. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  249. var ae acme.Error
  250. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  251. assert.Equals(t, ae.Type, tc.err.Type)
  252. assert.Equals(t, ae.Detail, tc.err.Detail)
  253. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  254. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  255. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  256. } else {
  257. //var gotAz acme.Authz
  258. //assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &gotAz))
  259. expB, err := json.Marshal(az)
  260. assert.FatalError(t, err)
  261. assert.Equals(t, bytes.TrimSpace(body), expB)
  262. assert.Equals(t, res.Header["Location"], []string{url})
  263. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  264. }
  265. })
  266. }
  267. }
  268. func TestHandler_GetCertificate(t *testing.T) {
  269. leaf, err := pemutil.ReadCertificate("../../authority/testdata/certs/foo.crt")
  270. assert.FatalError(t, err)
  271. inter, err := pemutil.ReadCertificate("../../authority/testdata/certs/intermediate_ca.crt")
  272. assert.FatalError(t, err)
  273. root, err := pemutil.ReadCertificate("../../authority/testdata/certs/root_ca.crt")
  274. assert.FatalError(t, err)
  275. certBytes := append(pem.EncodeToMemory(&pem.Block{
  276. Type: "CERTIFICATE",
  277. Bytes: leaf.Raw,
  278. }), pem.EncodeToMemory(&pem.Block{
  279. Type: "CERTIFICATE",
  280. Bytes: inter.Raw,
  281. })...)
  282. certBytes = append(certBytes, pem.EncodeToMemory(&pem.Block{
  283. Type: "CERTIFICATE",
  284. Bytes: root.Raw,
  285. })...)
  286. certID := "certID"
  287. prov := newProv()
  288. provName := url.PathEscape(prov.GetName())
  289. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  290. // Request with chi context
  291. chiCtx := chi.NewRouteContext()
  292. chiCtx.URLParams.Add("certID", certID)
  293. url := fmt.Sprintf("%s/acme/%s/certificate/%s",
  294. baseURL.String(), provName, certID)
  295. type test struct {
  296. db acme.DB
  297. ctx context.Context
  298. statusCode int
  299. err *acme.Error
  300. }
  301. var tests = map[string]func(t *testing.T) test{
  302. "fail/no-account": func(t *testing.T) test {
  303. return test{
  304. db: &acme.MockDB{},
  305. ctx: context.Background(),
  306. statusCode: 400,
  307. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  308. }
  309. },
  310. "fail/nil-account": func(t *testing.T) test {
  311. ctx := context.WithValue(context.Background(), accContextKey, nil)
  312. return test{
  313. db: &acme.MockDB{},
  314. ctx: ctx,
  315. statusCode: 400,
  316. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  317. }
  318. },
  319. "fail/db.GetCertificate-error": func(t *testing.T) test {
  320. acc := &acme.Account{ID: "accID"}
  321. ctx := context.WithValue(context.Background(), accContextKey, acc)
  322. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  323. return test{
  324. db: &acme.MockDB{
  325. MockError: acme.NewErrorISE("force"),
  326. },
  327. ctx: ctx,
  328. statusCode: 500,
  329. err: acme.NewErrorISE("force"),
  330. }
  331. },
  332. "fail/account-id-mismatch": func(t *testing.T) test {
  333. acc := &acme.Account{ID: "accID"}
  334. ctx := context.WithValue(context.Background(), accContextKey, acc)
  335. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  336. return test{
  337. db: &acme.MockDB{
  338. MockGetCertificate: func(ctx context.Context, id string) (*acme.Certificate, error) {
  339. assert.Equals(t, id, certID)
  340. return &acme.Certificate{AccountID: "foo"}, nil
  341. },
  342. },
  343. ctx: ctx,
  344. statusCode: 401,
  345. err: acme.NewError(acme.ErrorUnauthorizedType, "account id mismatch"),
  346. }
  347. },
  348. "ok": func(t *testing.T) test {
  349. acc := &acme.Account{ID: "accID"}
  350. ctx := context.WithValue(context.Background(), accContextKey, acc)
  351. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  352. return test{
  353. db: &acme.MockDB{
  354. MockGetCertificate: func(ctx context.Context, id string) (*acme.Certificate, error) {
  355. assert.Equals(t, id, certID)
  356. return &acme.Certificate{
  357. AccountID: "accID",
  358. OrderID: "ordID",
  359. Leaf: leaf,
  360. Intermediates: []*x509.Certificate{inter, root},
  361. ID: id,
  362. }, nil
  363. },
  364. },
  365. ctx: ctx,
  366. statusCode: 200,
  367. }
  368. },
  369. }
  370. for name, run := range tests {
  371. tc := run(t)
  372. t.Run(name, func(t *testing.T) {
  373. h := &Handler{db: tc.db}
  374. req := httptest.NewRequest("GET", url, nil)
  375. req = req.WithContext(tc.ctx)
  376. w := httptest.NewRecorder()
  377. h.GetCertificate(w, req)
  378. res := w.Result()
  379. assert.Equals(t, res.StatusCode, tc.statusCode)
  380. body, err := ioutil.ReadAll(res.Body)
  381. res.Body.Close()
  382. assert.FatalError(t, err)
  383. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  384. var ae acme.Error
  385. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  386. assert.Equals(t, ae.Type, tc.err.Type)
  387. assert.HasPrefix(t, ae.Detail, tc.err.Detail)
  388. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  389. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  390. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  391. } else {
  392. assert.Equals(t, bytes.TrimSpace(body), bytes.TrimSpace(certBytes))
  393. assert.Equals(t, res.Header["Content-Type"], []string{"application/pem-certificate-chain; charset=utf-8"})
  394. }
  395. })
  396. }
  397. }
  398. func TestHandler_GetChallenge(t *testing.T) {
  399. chiCtx := chi.NewRouteContext()
  400. chiCtx.URLParams.Add("chID", "chID")
  401. chiCtx.URLParams.Add("authzID", "authzID")
  402. prov := newProv()
  403. provName := url.PathEscape(prov.GetName())
  404. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  405. url := fmt.Sprintf("%s/acme/%s/challenge/%s/%s",
  406. baseURL.String(), provName, "authzID", "chID")
  407. type test struct {
  408. db acme.DB
  409. vco *acme.ValidateChallengeOptions
  410. ctx context.Context
  411. statusCode int
  412. ch *acme.Challenge
  413. err *acme.Error
  414. }
  415. var tests = map[string]func(t *testing.T) test{
  416. "fail/no-account": func(t *testing.T) test {
  417. return test{
  418. ctx: context.Background(),
  419. statusCode: 400,
  420. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  421. }
  422. },
  423. "fail/nil-account": func(t *testing.T) test {
  424. return test{
  425. ctx: context.WithValue(context.Background(), accContextKey, nil),
  426. statusCode: 400,
  427. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  428. }
  429. },
  430. "fail/no-payload": func(t *testing.T) test {
  431. acc := &acme.Account{ID: "accID"}
  432. ctx := context.WithValue(context.Background(), accContextKey, acc)
  433. return test{
  434. ctx: ctx,
  435. statusCode: 500,
  436. err: acme.NewErrorISE("payload expected in request context"),
  437. }
  438. },
  439. "fail/nil-payload": func(t *testing.T) test {
  440. acc := &acme.Account{ID: "accID"}
  441. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  442. ctx = context.WithValue(ctx, accContextKey, acc)
  443. ctx = context.WithValue(ctx, payloadContextKey, nil)
  444. return test{
  445. ctx: ctx,
  446. statusCode: 500,
  447. err: acme.NewErrorISE("payload expected in request context"),
  448. }
  449. },
  450. "fail/db.GetChallenge-error": func(t *testing.T) test {
  451. acc := &acme.Account{ID: "accID"}
  452. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  453. ctx = context.WithValue(ctx, accContextKey, acc)
  454. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  455. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  456. return test{
  457. db: &acme.MockDB{
  458. MockGetChallenge: func(ctx context.Context, chID, azID string) (*acme.Challenge, error) {
  459. assert.Equals(t, chID, "chID")
  460. assert.Equals(t, azID, "authzID")
  461. return nil, acme.NewErrorISE("force")
  462. },
  463. },
  464. ctx: ctx,
  465. statusCode: 500,
  466. err: acme.NewErrorISE("force"),
  467. }
  468. },
  469. "fail/account-id-mismatch": func(t *testing.T) test {
  470. acc := &acme.Account{ID: "accID"}
  471. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  472. ctx = context.WithValue(ctx, accContextKey, acc)
  473. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  474. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  475. return test{
  476. db: &acme.MockDB{
  477. MockGetChallenge: func(ctx context.Context, chID, azID string) (*acme.Challenge, error) {
  478. assert.Equals(t, chID, "chID")
  479. assert.Equals(t, azID, "authzID")
  480. return &acme.Challenge{AccountID: "foo"}, nil
  481. },
  482. },
  483. ctx: ctx,
  484. statusCode: 401,
  485. err: acme.NewError(acme.ErrorUnauthorizedType, "accout id mismatch"),
  486. }
  487. },
  488. "fail/no-jwk": func(t *testing.T) test {
  489. acc := &acme.Account{ID: "accID"}
  490. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  491. ctx = context.WithValue(ctx, accContextKey, acc)
  492. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  493. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  494. return test{
  495. db: &acme.MockDB{
  496. MockGetChallenge: func(ctx context.Context, chID, azID string) (*acme.Challenge, error) {
  497. assert.Equals(t, chID, "chID")
  498. assert.Equals(t, azID, "authzID")
  499. return &acme.Challenge{AccountID: "accID"}, nil
  500. },
  501. },
  502. ctx: ctx,
  503. statusCode: 500,
  504. err: acme.NewErrorISE("missing jwk"),
  505. }
  506. },
  507. "fail/nil-jwk": func(t *testing.T) test {
  508. acc := &acme.Account{ID: "accID"}
  509. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  510. ctx = context.WithValue(ctx, accContextKey, acc)
  511. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  512. ctx = context.WithValue(ctx, jwkContextKey, nil)
  513. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  514. return test{
  515. db: &acme.MockDB{
  516. MockGetChallenge: func(ctx context.Context, chID, azID string) (*acme.Challenge, error) {
  517. assert.Equals(t, chID, "chID")
  518. assert.Equals(t, azID, "authzID")
  519. return &acme.Challenge{AccountID: "accID"}, nil
  520. },
  521. },
  522. ctx: ctx,
  523. statusCode: 500,
  524. err: acme.NewErrorISE("nil jwk"),
  525. }
  526. },
  527. "fail/validate-challenge-error": func(t *testing.T) test {
  528. acc := &acme.Account{ID: "accID"}
  529. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  530. ctx = context.WithValue(ctx, accContextKey, acc)
  531. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  532. _jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  533. assert.FatalError(t, err)
  534. _pub := _jwk.Public()
  535. ctx = context.WithValue(ctx, jwkContextKey, &_pub)
  536. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  537. return test{
  538. db: &acme.MockDB{
  539. MockGetChallenge: func(ctx context.Context, chID, azID string) (*acme.Challenge, error) {
  540. assert.Equals(t, chID, "chID")
  541. assert.Equals(t, azID, "authzID")
  542. return &acme.Challenge{
  543. Status: acme.StatusPending,
  544. Type: acme.HTTP01,
  545. AccountID: "accID",
  546. }, nil
  547. },
  548. MockUpdateChallenge: func(ctx context.Context, ch *acme.Challenge) error {
  549. assert.Equals(t, ch.Status, acme.StatusPending)
  550. assert.Equals(t, ch.Type, acme.HTTP01)
  551. assert.Equals(t, ch.AccountID, "accID")
  552. assert.Equals(t, ch.AuthorizationID, "authzID")
  553. assert.HasSuffix(t, ch.Error.Type, acme.ErrorConnectionType.String())
  554. return acme.NewErrorISE("force")
  555. },
  556. },
  557. vco: &acme.ValidateChallengeOptions{
  558. HTTPGet: func(string) (*http.Response, error) {
  559. return nil, errors.New("force")
  560. },
  561. },
  562. ctx: ctx,
  563. statusCode: 500,
  564. err: acme.NewErrorISE("force"),
  565. }
  566. },
  567. "ok": func(t *testing.T) test {
  568. acc := &acme.Account{ID: "accID"}
  569. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  570. ctx = context.WithValue(ctx, accContextKey, acc)
  571. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
  572. _jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  573. assert.FatalError(t, err)
  574. _pub := _jwk.Public()
  575. ctx = context.WithValue(ctx, jwkContextKey, &_pub)
  576. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  577. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  578. return test{
  579. db: &acme.MockDB{
  580. MockGetChallenge: func(ctx context.Context, chID, azID string) (*acme.Challenge, error) {
  581. assert.Equals(t, chID, "chID")
  582. assert.Equals(t, azID, "authzID")
  583. return &acme.Challenge{
  584. ID: "chID",
  585. Status: acme.StatusPending,
  586. Type: acme.HTTP01,
  587. AccountID: "accID",
  588. }, nil
  589. },
  590. MockUpdateChallenge: func(ctx context.Context, ch *acme.Challenge) error {
  591. assert.Equals(t, ch.Status, acme.StatusPending)
  592. assert.Equals(t, ch.Type, acme.HTTP01)
  593. assert.Equals(t, ch.AccountID, "accID")
  594. assert.Equals(t, ch.AuthorizationID, "authzID")
  595. assert.HasSuffix(t, ch.Error.Type, acme.ErrorConnectionType.String())
  596. return nil
  597. },
  598. },
  599. ch: &acme.Challenge{
  600. ID: "chID",
  601. Status: acme.StatusPending,
  602. AuthorizationID: "authzID",
  603. Type: acme.HTTP01,
  604. AccountID: "accID",
  605. URL: url,
  606. Error: acme.NewError(acme.ErrorConnectionType, "force"),
  607. },
  608. vco: &acme.ValidateChallengeOptions{
  609. HTTPGet: func(string) (*http.Response, error) {
  610. return nil, errors.New("force")
  611. },
  612. },
  613. ctx: ctx,
  614. statusCode: 200,
  615. }
  616. },
  617. }
  618. for name, run := range tests {
  619. tc := run(t)
  620. t.Run(name, func(t *testing.T) {
  621. h := &Handler{db: tc.db, linker: NewLinker("dns", "acme"), validateChallengeOptions: tc.vco}
  622. req := httptest.NewRequest("GET", url, nil)
  623. req = req.WithContext(tc.ctx)
  624. w := httptest.NewRecorder()
  625. h.GetChallenge(w, req)
  626. res := w.Result()
  627. assert.Equals(t, res.StatusCode, tc.statusCode)
  628. body, err := ioutil.ReadAll(res.Body)
  629. res.Body.Close()
  630. assert.FatalError(t, err)
  631. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  632. var ae acme.Error
  633. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  634. assert.Equals(t, ae.Type, tc.err.Type)
  635. assert.Equals(t, ae.Detail, tc.err.Detail)
  636. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  637. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  638. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  639. } else {
  640. expB, err := json.Marshal(tc.ch)
  641. assert.FatalError(t, err)
  642. assert.Equals(t, bytes.TrimSpace(body), expB)
  643. assert.Equals(t, res.Header["Link"], []string{fmt.Sprintf("<%s/acme/%s/authz/%s>;rel=\"up\"", baseURL, provName, "authzID")})
  644. assert.Equals(t, res.Header["Location"], []string{url})
  645. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  646. }
  647. })
  648. }
  649. }