order_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/x509"
  6. "encoding/base64"
  7. "encoding/json"
  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/pkg/errors"
  16. "github.com/smallstep/assert"
  17. "github.com/smallstep/certificates/acme"
  18. "go.step.sm/crypto/pemutil"
  19. )
  20. func TestNewOrderRequestValidate(t *testing.T) {
  21. type test struct {
  22. nor *NewOrderRequest
  23. nbf, naf time.Time
  24. err *acme.Error
  25. }
  26. var tests = map[string]func(t *testing.T) test{
  27. "fail/no-identifiers": func(t *testing.T) test {
  28. return test{
  29. nor: &NewOrderRequest{},
  30. err: acme.MalformedErr(errors.Errorf("identifiers list cannot be empty")),
  31. }
  32. },
  33. "fail/bad-identifier": func(t *testing.T) test {
  34. return test{
  35. nor: &NewOrderRequest{
  36. Identifiers: []acme.Identifier{
  37. {Type: "dns", Value: "example.com"},
  38. {Type: "foo", Value: "bar.com"},
  39. },
  40. },
  41. err: acme.MalformedErr(errors.Errorf("identifier type unsupported: foo")),
  42. }
  43. },
  44. "ok": func(t *testing.T) test {
  45. nbf := time.Now().UTC().Add(time.Minute)
  46. naf := time.Now().UTC().Add(5 * time.Minute)
  47. return test{
  48. nor: &NewOrderRequest{
  49. Identifiers: []acme.Identifier{
  50. {Type: "dns", Value: "example.com"},
  51. {Type: "dns", Value: "bar.com"},
  52. },
  53. NotAfter: naf,
  54. NotBefore: nbf,
  55. },
  56. nbf: nbf,
  57. naf: naf,
  58. }
  59. },
  60. }
  61. for name, run := range tests {
  62. tc := run(t)
  63. t.Run(name, func(t *testing.T) {
  64. if err := tc.nor.Validate(); err != nil {
  65. if assert.NotNil(t, err) {
  66. ae, ok := err.(*acme.Error)
  67. assert.True(t, ok)
  68. assert.HasPrefix(t, ae.Error(), tc.err.Error())
  69. assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
  70. assert.Equals(t, ae.Type, tc.err.Type)
  71. }
  72. } else {
  73. if assert.Nil(t, tc.err) {
  74. if tc.nbf.IsZero() {
  75. assert.True(t, tc.nor.NotBefore.Before(time.Now().Add(time.Minute)))
  76. assert.True(t, tc.nor.NotBefore.After(time.Now().Add(-time.Minute)))
  77. } else {
  78. assert.Equals(t, tc.nor.NotBefore, tc.nbf)
  79. }
  80. if tc.naf.IsZero() {
  81. assert.True(t, tc.nor.NotAfter.Before(time.Now().Add(24*time.Hour)))
  82. assert.True(t, tc.nor.NotAfter.After(time.Now().Add(24*time.Hour-time.Minute)))
  83. } else {
  84. assert.Equals(t, tc.nor.NotAfter, tc.naf)
  85. }
  86. }
  87. }
  88. })
  89. }
  90. }
  91. func TestFinalizeRequestValidate(t *testing.T) {
  92. _csr, err := pemutil.Read("../../authority/testdata/certs/foo.csr")
  93. assert.FatalError(t, err)
  94. csr, ok := _csr.(*x509.CertificateRequest)
  95. assert.Fatal(t, ok)
  96. type test struct {
  97. fr *FinalizeRequest
  98. err *acme.Error
  99. }
  100. var tests = map[string]func(t *testing.T) test{
  101. "fail/parse-csr-error": func(t *testing.T) test {
  102. return test{
  103. fr: &FinalizeRequest{},
  104. err: acme.MalformedErr(errors.Errorf("unable to parse csr: asn1: syntax error: sequence truncated")),
  105. }
  106. },
  107. "fail/invalid-csr-signature": func(t *testing.T) test {
  108. b, err := pemutil.Read("../../authority/testdata/certs/badsig.csr")
  109. assert.FatalError(t, err)
  110. c, ok := b.(*x509.CertificateRequest)
  111. assert.Fatal(t, ok)
  112. return test{
  113. fr: &FinalizeRequest{
  114. CSR: base64.RawURLEncoding.EncodeToString(c.Raw),
  115. },
  116. err: acme.MalformedErr(errors.Errorf("csr failed signature check: x509: ECDSA verification failure")),
  117. }
  118. },
  119. "ok": func(t *testing.T) test {
  120. return test{
  121. fr: &FinalizeRequest{
  122. CSR: base64.RawURLEncoding.EncodeToString(csr.Raw),
  123. },
  124. }
  125. },
  126. }
  127. for name, run := range tests {
  128. tc := run(t)
  129. t.Run(name, func(t *testing.T) {
  130. if err := tc.fr.Validate(); err != nil {
  131. if assert.NotNil(t, err) {
  132. ae, ok := err.(*acme.Error)
  133. assert.True(t, ok)
  134. assert.HasPrefix(t, ae.Error(), tc.err.Error())
  135. assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
  136. assert.Equals(t, ae.Type, tc.err.Type)
  137. }
  138. } else {
  139. if assert.Nil(t, tc.err) {
  140. assert.Equals(t, tc.fr.csr.Raw, csr.Raw)
  141. }
  142. }
  143. })
  144. }
  145. }
  146. func TestHandlerGetOrder(t *testing.T) {
  147. expiry := time.Now().UTC().Add(6 * time.Hour)
  148. nbf := time.Now().UTC()
  149. naf := time.Now().UTC().Add(24 * time.Hour)
  150. o := acme.Order{
  151. ID: "orderID",
  152. Expires: expiry.Format(time.RFC3339),
  153. NotBefore: nbf.Format(time.RFC3339),
  154. NotAfter: naf.Format(time.RFC3339),
  155. Identifiers: []acme.Identifier{
  156. {
  157. Type: "dns",
  158. Value: "example.com",
  159. },
  160. {
  161. Type: "dns",
  162. Value: "*.smallstep.com",
  163. },
  164. },
  165. Status: "pending",
  166. Authorizations: []string{"foo", "bar"},
  167. }
  168. // Request with chi context
  169. chiCtx := chi.NewRouteContext()
  170. chiCtx.URLParams.Add("ordID", o.ID)
  171. prov := newProv()
  172. provName := url.PathEscape(prov.GetName())
  173. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  174. url := fmt.Sprintf("%s/acme/%s/order/%s",
  175. baseURL.String(), provName, o.ID)
  176. type test struct {
  177. auth acme.Interface
  178. ctx context.Context
  179. statusCode int
  180. problem *acme.Error
  181. }
  182. var tests = map[string]func(t *testing.T) test{
  183. "fail/no-account": func(t *testing.T) test {
  184. return test{
  185. auth: &mockAcmeAuthority{},
  186. ctx: context.WithValue(context.Background(), acme.ProvisionerContextKey, prov),
  187. statusCode: 400,
  188. problem: acme.AccountDoesNotExistErr(nil),
  189. }
  190. },
  191. "fail/nil-account": func(t *testing.T) test {
  192. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  193. ctx = context.WithValue(ctx, acme.AccContextKey, nil)
  194. return test{
  195. auth: &mockAcmeAuthority{},
  196. ctx: ctx,
  197. statusCode: 400,
  198. problem: acme.AccountDoesNotExistErr(nil),
  199. }
  200. },
  201. "fail/getOrder-error": func(t *testing.T) test {
  202. acc := &acme.Account{ID: "accID"}
  203. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  204. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  205. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  206. return test{
  207. auth: &mockAcmeAuthority{
  208. err: acme.ServerInternalErr(errors.New("force")),
  209. },
  210. ctx: ctx,
  211. statusCode: 500,
  212. problem: acme.ServerInternalErr(errors.New("force")),
  213. }
  214. },
  215. "ok": func(t *testing.T) test {
  216. acc := &acme.Account{ID: "accID"}
  217. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  218. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  219. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  220. ctx = context.WithValue(ctx, acme.BaseURLContextKey, baseURL)
  221. return test{
  222. auth: &mockAcmeAuthority{
  223. getOrder: func(ctx context.Context, accID, id string) (*acme.Order, error) {
  224. p, err := acme.ProvisionerFromContext(ctx)
  225. assert.FatalError(t, err)
  226. assert.Equals(t, p, prov)
  227. assert.Equals(t, accID, acc.ID)
  228. assert.Equals(t, id, o.ID)
  229. return &o, nil
  230. },
  231. getLink: func(ctx context.Context, typ acme.Link, abs bool, in ...string) string {
  232. assert.Equals(t, typ, acme.OrderLink)
  233. assert.True(t, abs)
  234. assert.Equals(t, in, []string{o.ID})
  235. return url
  236. },
  237. },
  238. ctx: ctx,
  239. statusCode: 200,
  240. }
  241. },
  242. }
  243. for name, run := range tests {
  244. tc := run(t)
  245. t.Run(name, func(t *testing.T) {
  246. h := New(tc.auth).(*Handler)
  247. req := httptest.NewRequest("GET", url, nil)
  248. req = req.WithContext(tc.ctx)
  249. w := httptest.NewRecorder()
  250. h.GetOrder(w, req)
  251. res := w.Result()
  252. assert.Equals(t, res.StatusCode, tc.statusCode)
  253. body, err := ioutil.ReadAll(res.Body)
  254. res.Body.Close()
  255. assert.FatalError(t, err)
  256. if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
  257. var ae acme.AError
  258. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  259. prob := tc.problem.ToACME()
  260. assert.Equals(t, ae.Type, prob.Type)
  261. assert.Equals(t, ae.Detail, prob.Detail)
  262. assert.Equals(t, ae.Identifier, prob.Identifier)
  263. assert.Equals(t, ae.Subproblems, prob.Subproblems)
  264. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  265. } else {
  266. expB, err := json.Marshal(o)
  267. assert.FatalError(t, err)
  268. assert.Equals(t, bytes.TrimSpace(body), expB)
  269. assert.Equals(t, res.Header["Location"], []string{url})
  270. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  271. }
  272. })
  273. }
  274. }
  275. func TestHandlerNewOrder(t *testing.T) {
  276. expiry := time.Now().UTC().Add(6 * time.Hour)
  277. nbf := time.Now().UTC().Add(5 * time.Hour)
  278. naf := nbf.Add(17 * time.Hour)
  279. o := acme.Order{
  280. ID: "orderID",
  281. Expires: expiry.Format(time.RFC3339),
  282. NotBefore: nbf.Format(time.RFC3339),
  283. NotAfter: naf.Format(time.RFC3339),
  284. Identifiers: []acme.Identifier{
  285. {Type: "dns", Value: "example.com"},
  286. {Type: "dns", Value: "bar.com"},
  287. },
  288. Status: "pending",
  289. Authorizations: []string{"foo", "bar"},
  290. }
  291. prov := newProv()
  292. provName := url.PathEscape(prov.GetName())
  293. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  294. url := fmt.Sprintf("%s/acme/%s/new-order",
  295. baseURL.String(), provName)
  296. type test struct {
  297. auth acme.Interface
  298. ctx context.Context
  299. statusCode int
  300. problem *acme.Error
  301. }
  302. var tests = map[string]func(t *testing.T) test{
  303. "fail/no-account": func(t *testing.T) test {
  304. return test{
  305. ctx: context.WithValue(context.Background(), acme.ProvisionerContextKey, prov),
  306. statusCode: 400,
  307. problem: acme.AccountDoesNotExistErr(nil),
  308. }
  309. },
  310. "fail/nil-account": func(t *testing.T) test {
  311. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  312. ctx = context.WithValue(ctx, acme.AccContextKey, nil)
  313. return test{
  314. ctx: ctx,
  315. statusCode: 400,
  316. problem: acme.AccountDoesNotExistErr(nil),
  317. }
  318. },
  319. "fail/no-payload": func(t *testing.T) test {
  320. acc := &acme.Account{ID: "accID"}
  321. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  322. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  323. return test{
  324. ctx: ctx,
  325. statusCode: 500,
  326. problem: acme.ServerInternalErr(errors.New("payload expected in request context")),
  327. }
  328. },
  329. "fail/nil-payload": func(t *testing.T) test {
  330. acc := &acme.Account{ID: "accID"}
  331. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  332. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  333. ctx = context.WithValue(ctx, acme.PayloadContextKey, nil)
  334. return test{
  335. ctx: ctx,
  336. statusCode: 500,
  337. problem: acme.ServerInternalErr(errors.New("payload expected in request context")),
  338. }
  339. },
  340. "fail/unmarshal-payload-error": func(t *testing.T) test {
  341. acc := &acme.Account{ID: "accID"}
  342. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  343. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  344. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{})
  345. return test{
  346. ctx: ctx,
  347. statusCode: 400,
  348. problem: acme.MalformedErr(errors.New("failed to unmarshal new-order request payload: unexpected end of JSON input")),
  349. }
  350. },
  351. "fail/malformed-payload-error": func(t *testing.T) test {
  352. acc := &acme.Account{ID: "accID"}
  353. nor := &NewOrderRequest{}
  354. b, err := json.Marshal(nor)
  355. assert.FatalError(t, err)
  356. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  357. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  358. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{value: b})
  359. return test{
  360. ctx: ctx,
  361. statusCode: 400,
  362. problem: acme.MalformedErr(errors.New("identifiers list cannot be empty")),
  363. }
  364. },
  365. "fail/NewOrder-error": func(t *testing.T) test {
  366. acc := &acme.Account{ID: "accID"}
  367. nor := &NewOrderRequest{
  368. Identifiers: []acme.Identifier{
  369. {Type: "dns", Value: "example.com"},
  370. {Type: "dns", Value: "bar.com"},
  371. },
  372. }
  373. b, err := json.Marshal(nor)
  374. assert.FatalError(t, err)
  375. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  376. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  377. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{value: b})
  378. return test{
  379. auth: &mockAcmeAuthority{
  380. newOrder: func(ctx context.Context, ops acme.OrderOptions) (*acme.Order, error) {
  381. p, err := acme.ProvisionerFromContext(ctx)
  382. assert.FatalError(t, err)
  383. assert.Equals(t, p, prov)
  384. assert.Equals(t, ops.AccountID, acc.ID)
  385. assert.Equals(t, ops.Identifiers, nor.Identifiers)
  386. return nil, acme.MalformedErr(errors.New("force"))
  387. },
  388. },
  389. ctx: ctx,
  390. statusCode: 400,
  391. problem: acme.MalformedErr(errors.New("force")),
  392. }
  393. },
  394. "ok": func(t *testing.T) test {
  395. acc := &acme.Account{ID: "accID"}
  396. nor := &NewOrderRequest{
  397. Identifiers: []acme.Identifier{
  398. {Type: "dns", Value: "example.com"},
  399. {Type: "dns", Value: "bar.com"},
  400. },
  401. NotBefore: nbf,
  402. NotAfter: naf,
  403. }
  404. b, err := json.Marshal(nor)
  405. assert.FatalError(t, err)
  406. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  407. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  408. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{value: b})
  409. ctx = context.WithValue(ctx, acme.BaseURLContextKey, baseURL)
  410. return test{
  411. auth: &mockAcmeAuthority{
  412. newOrder: func(ctx context.Context, ops acme.OrderOptions) (*acme.Order, error) {
  413. p, err := acme.ProvisionerFromContext(ctx)
  414. assert.FatalError(t, err)
  415. assert.Equals(t, p, prov)
  416. assert.Equals(t, ops.AccountID, acc.ID)
  417. assert.Equals(t, ops.Identifiers, nor.Identifiers)
  418. assert.Equals(t, ops.NotBefore, nbf)
  419. assert.Equals(t, ops.NotAfter, naf)
  420. return &o, nil
  421. },
  422. getLink: func(ctx context.Context, typ acme.Link, abs bool, in ...string) string {
  423. assert.Equals(t, typ, acme.OrderLink)
  424. assert.True(t, abs)
  425. assert.Equals(t, in, []string{o.ID})
  426. return fmt.Sprintf("%s/acme/%s/order/%s", baseURL.String(), provName, o.ID)
  427. },
  428. },
  429. ctx: ctx,
  430. statusCode: 201,
  431. }
  432. },
  433. "ok/default-naf-nbf": func(t *testing.T) test {
  434. acc := &acme.Account{ID: "accID"}
  435. nor := &NewOrderRequest{
  436. Identifiers: []acme.Identifier{
  437. {Type: "dns", Value: "example.com"},
  438. {Type: "dns", Value: "bar.com"},
  439. },
  440. }
  441. b, err := json.Marshal(nor)
  442. assert.FatalError(t, err)
  443. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  444. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  445. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{value: b})
  446. ctx = context.WithValue(ctx, acme.BaseURLContextKey, baseURL)
  447. return test{
  448. auth: &mockAcmeAuthority{
  449. newOrder: func(ctx context.Context, ops acme.OrderOptions) (*acme.Order, error) {
  450. p, err := acme.ProvisionerFromContext(ctx)
  451. assert.FatalError(t, err)
  452. assert.Equals(t, p, prov)
  453. assert.Equals(t, ops.AccountID, acc.ID)
  454. assert.Equals(t, ops.Identifiers, nor.Identifiers)
  455. assert.True(t, ops.NotBefore.IsZero())
  456. assert.True(t, ops.NotAfter.IsZero())
  457. return &o, nil
  458. },
  459. getLink: func(ctx context.Context, typ acme.Link, abs bool, in ...string) string {
  460. assert.Equals(t, typ, acme.OrderLink)
  461. assert.True(t, abs)
  462. assert.Equals(t, in, []string{o.ID})
  463. return fmt.Sprintf("%s/acme/%s/order/%s", baseURL.String(), provName, o.ID)
  464. },
  465. },
  466. ctx: ctx,
  467. statusCode: 201,
  468. }
  469. },
  470. }
  471. for name, run := range tests {
  472. tc := run(t)
  473. t.Run(name, func(t *testing.T) {
  474. h := New(tc.auth).(*Handler)
  475. req := httptest.NewRequest("GET", url, nil)
  476. req = req.WithContext(tc.ctx)
  477. w := httptest.NewRecorder()
  478. h.NewOrder(w, req)
  479. res := w.Result()
  480. assert.Equals(t, res.StatusCode, tc.statusCode)
  481. body, err := ioutil.ReadAll(res.Body)
  482. res.Body.Close()
  483. assert.FatalError(t, err)
  484. if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
  485. var ae acme.AError
  486. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  487. prob := tc.problem.ToACME()
  488. assert.Equals(t, ae.Type, prob.Type)
  489. assert.Equals(t, ae.Detail, prob.Detail)
  490. assert.Equals(t, ae.Identifier, prob.Identifier)
  491. assert.Equals(t, ae.Subproblems, prob.Subproblems)
  492. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  493. } else {
  494. expB, err := json.Marshal(o)
  495. assert.FatalError(t, err)
  496. assert.Equals(t, bytes.TrimSpace(body), expB)
  497. assert.Equals(t, res.Header["Location"],
  498. []string{fmt.Sprintf("%s/acme/%s/order/%s", baseURL.String(),
  499. provName, o.ID)})
  500. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  501. }
  502. })
  503. }
  504. }
  505. func TestHandlerFinalizeOrder(t *testing.T) {
  506. expiry := time.Now().UTC().Add(6 * time.Hour)
  507. nbf := time.Now().UTC().Add(5 * time.Hour)
  508. naf := nbf.Add(17 * time.Hour)
  509. o := acme.Order{
  510. ID: "orderID",
  511. Expires: expiry.Format(time.RFC3339),
  512. NotBefore: nbf.Format(time.RFC3339),
  513. NotAfter: naf.Format(time.RFC3339),
  514. Identifiers: []acme.Identifier{
  515. {Type: "dns", Value: "example.com"},
  516. {Type: "dns", Value: "bar.com"},
  517. },
  518. Status: "valid",
  519. Authorizations: []string{"foo", "bar"},
  520. Certificate: "https://ca.smallstep.com/acme/certificate/certID",
  521. }
  522. _csr, err := pemutil.Read("../../authority/testdata/certs/foo.csr")
  523. assert.FatalError(t, err)
  524. csr, ok := _csr.(*x509.CertificateRequest)
  525. assert.Fatal(t, ok)
  526. // Request with chi context
  527. chiCtx := chi.NewRouteContext()
  528. chiCtx.URLParams.Add("ordID", o.ID)
  529. prov := newProv()
  530. provName := url.PathEscape(prov.GetName())
  531. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  532. url := fmt.Sprintf("%s/acme/%s/order/%s/finalize",
  533. baseURL.String(), provName, o.ID)
  534. type test struct {
  535. auth acme.Interface
  536. ctx context.Context
  537. statusCode int
  538. problem *acme.Error
  539. }
  540. var tests = map[string]func(t *testing.T) test{
  541. "fail/no-account": func(t *testing.T) test {
  542. return test{
  543. auth: &mockAcmeAuthority{},
  544. ctx: context.WithValue(context.Background(), acme.ProvisionerContextKey, prov),
  545. statusCode: 400,
  546. problem: acme.AccountDoesNotExistErr(nil),
  547. }
  548. },
  549. "fail/nil-account": func(t *testing.T) test {
  550. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  551. ctx = context.WithValue(ctx, acme.AccContextKey, nil)
  552. return test{
  553. auth: &mockAcmeAuthority{},
  554. ctx: ctx,
  555. statusCode: 400,
  556. problem: acme.AccountDoesNotExistErr(nil),
  557. }
  558. },
  559. "fail/no-payload": func(t *testing.T) test {
  560. acc := &acme.Account{ID: "accID"}
  561. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  562. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  563. return test{
  564. ctx: ctx,
  565. statusCode: 500,
  566. problem: acme.ServerInternalErr(errors.New("payload expected in request context")),
  567. }
  568. },
  569. "fail/nil-payload": func(t *testing.T) test {
  570. acc := &acme.Account{ID: "accID"}
  571. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  572. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  573. ctx = context.WithValue(ctx, acme.PayloadContextKey, nil)
  574. return test{
  575. ctx: ctx,
  576. statusCode: 500,
  577. problem: acme.ServerInternalErr(errors.New("payload expected in request context")),
  578. }
  579. },
  580. "fail/unmarshal-payload-error": func(t *testing.T) test {
  581. acc := &acme.Account{ID: "accID"}
  582. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  583. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  584. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{})
  585. return test{
  586. ctx: ctx,
  587. statusCode: 400,
  588. problem: acme.MalformedErr(errors.New("failed to unmarshal finalize-order request payload: unexpected end of JSON input")),
  589. }
  590. },
  591. "fail/malformed-payload-error": func(t *testing.T) test {
  592. acc := &acme.Account{ID: "accID"}
  593. fr := &FinalizeRequest{}
  594. b, err := json.Marshal(fr)
  595. assert.FatalError(t, err)
  596. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  597. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  598. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{value: b})
  599. return test{
  600. ctx: ctx,
  601. statusCode: 400,
  602. problem: acme.MalformedErr(errors.New("unable to parse csr: asn1: syntax error: sequence truncated")),
  603. }
  604. },
  605. "fail/FinalizeOrder-error": func(t *testing.T) test {
  606. acc := &acme.Account{ID: "accID"}
  607. nor := &FinalizeRequest{
  608. CSR: base64.RawURLEncoding.EncodeToString(csr.Raw),
  609. }
  610. b, err := json.Marshal(nor)
  611. assert.FatalError(t, err)
  612. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  613. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  614. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{value: b})
  615. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  616. return test{
  617. auth: &mockAcmeAuthority{
  618. finalizeOrder: func(ctx context.Context, accID, id string, incsr *x509.CertificateRequest) (*acme.Order, error) {
  619. p, err := acme.ProvisionerFromContext(ctx)
  620. assert.FatalError(t, err)
  621. assert.Equals(t, p, prov)
  622. assert.Equals(t, accID, acc.ID)
  623. assert.Equals(t, id, o.ID)
  624. assert.Equals(t, incsr.Raw, csr.Raw)
  625. return nil, acme.MalformedErr(errors.New("force"))
  626. },
  627. },
  628. ctx: ctx,
  629. statusCode: 400,
  630. problem: acme.MalformedErr(errors.New("force")),
  631. }
  632. },
  633. "ok": func(t *testing.T) test {
  634. acc := &acme.Account{ID: "accID"}
  635. nor := &FinalizeRequest{
  636. CSR: base64.RawURLEncoding.EncodeToString(csr.Raw),
  637. }
  638. b, err := json.Marshal(nor)
  639. assert.FatalError(t, err)
  640. ctx := context.WithValue(context.Background(), acme.ProvisionerContextKey, prov)
  641. ctx = context.WithValue(ctx, acme.AccContextKey, acc)
  642. ctx = context.WithValue(ctx, acme.PayloadContextKey, &payloadInfo{value: b})
  643. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  644. ctx = context.WithValue(ctx, acme.BaseURLContextKey, baseURL)
  645. return test{
  646. auth: &mockAcmeAuthority{
  647. finalizeOrder: func(ctx context.Context, accID, id string, incsr *x509.CertificateRequest) (*acme.Order, error) {
  648. p, err := acme.ProvisionerFromContext(ctx)
  649. assert.FatalError(t, err)
  650. assert.Equals(t, p, prov)
  651. assert.Equals(t, accID, acc.ID)
  652. assert.Equals(t, id, o.ID)
  653. assert.Equals(t, incsr.Raw, csr.Raw)
  654. return &o, nil
  655. },
  656. getLink: func(ctx context.Context, typ acme.Link, abs bool, in ...string) string {
  657. assert.Equals(t, typ, acme.OrderLink)
  658. assert.True(t, abs)
  659. assert.Equals(t, in, []string{o.ID})
  660. return fmt.Sprintf("%s/acme/%s/order/%s",
  661. baseURL.String(), provName, o.ID)
  662. },
  663. },
  664. ctx: ctx,
  665. statusCode: 200,
  666. }
  667. },
  668. }
  669. for name, run := range tests {
  670. tc := run(t)
  671. t.Run(name, func(t *testing.T) {
  672. h := New(tc.auth).(*Handler)
  673. req := httptest.NewRequest("GET", url, nil)
  674. req = req.WithContext(tc.ctx)
  675. w := httptest.NewRecorder()
  676. h.FinalizeOrder(w, req)
  677. res := w.Result()
  678. assert.Equals(t, res.StatusCode, tc.statusCode)
  679. body, err := ioutil.ReadAll(res.Body)
  680. res.Body.Close()
  681. assert.FatalError(t, err)
  682. if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
  683. var ae acme.AError
  684. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  685. prob := tc.problem.ToACME()
  686. assert.Equals(t, ae.Type, prob.Type)
  687. assert.Equals(t, ae.Detail, prob.Detail)
  688. assert.Equals(t, ae.Identifier, prob.Identifier)
  689. assert.Equals(t, ae.Subproblems, prob.Subproblems)
  690. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  691. } else {
  692. expB, err := json.Marshal(o)
  693. assert.FatalError(t, err)
  694. assert.Equals(t, bytes.TrimSpace(body), expB)
  695. assert.Equals(t, res.Header["Location"],
  696. []string{fmt.Sprintf("%s/acme/%s/order/%s",
  697. baseURL, provName, o.ID)})
  698. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  699. }
  700. })
  701. }
  702. }