handler_test.go 22 KB

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