handler_test.go 17 KB

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