order_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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. "testing"
  12. "time"
  13. "github.com/go-chi/chi"
  14. "github.com/pkg/errors"
  15. "github.com/smallstep/assert"
  16. "github.com/smallstep/certificates/acme"
  17. "github.com/smallstep/certificates/authority/provisioner"
  18. "github.com/smallstep/cli/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. url := fmt.Sprintf("http://ca.smallstep.com/acme/%s/order/%s",
  173. acme.URLSafeProvisionerName(prov), o.ID)
  174. type test struct {
  175. auth acme.Interface
  176. ctx context.Context
  177. statusCode int
  178. problem *acme.Error
  179. }
  180. var tests = map[string]func(t *testing.T) test{
  181. "fail/no-provisioner": func(t *testing.T) test {
  182. return test{
  183. auth: &mockAcmeAuthority{},
  184. ctx: context.Background(),
  185. statusCode: 500,
  186. problem: acme.ServerInternalErr(errors.New("provisioner expected in request context")),
  187. }
  188. },
  189. "fail/nil-provisioner": func(t *testing.T) test {
  190. return test{
  191. auth: &mockAcmeAuthority{},
  192. ctx: context.WithValue(context.Background(), provisionerContextKey, nil),
  193. statusCode: 500,
  194. problem: acme.ServerInternalErr(errors.New("provisioner expected in request context")),
  195. }
  196. },
  197. "fail/no-account": func(t *testing.T) test {
  198. return test{
  199. auth: &mockAcmeAuthority{},
  200. ctx: context.WithValue(context.Background(), provisionerContextKey, prov),
  201. statusCode: 404,
  202. problem: acme.AccountDoesNotExistErr(nil),
  203. }
  204. },
  205. "fail/nil-account": func(t *testing.T) test {
  206. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  207. ctx = context.WithValue(ctx, accContextKey, nil)
  208. return test{
  209. auth: &mockAcmeAuthority{},
  210. ctx: ctx,
  211. statusCode: 404,
  212. problem: acme.AccountDoesNotExistErr(nil),
  213. }
  214. },
  215. "fail/getOrder-error": func(t *testing.T) test {
  216. acc := &acme.Account{ID: "accID"}
  217. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  218. ctx = context.WithValue(ctx, accContextKey, acc)
  219. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  220. return test{
  221. auth: &mockAcmeAuthority{
  222. err: acme.ServerInternalErr(errors.New("force")),
  223. },
  224. ctx: ctx,
  225. statusCode: 500,
  226. problem: acme.ServerInternalErr(errors.New("force")),
  227. }
  228. },
  229. "ok": func(t *testing.T) test {
  230. acc := &acme.Account{ID: "accID"}
  231. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  232. ctx = context.WithValue(ctx, accContextKey, acc)
  233. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  234. return test{
  235. auth: &mockAcmeAuthority{
  236. getOrder: func(p provisioner.Interface, accID, id string) (*acme.Order, error) {
  237. assert.Equals(t, p, prov)
  238. assert.Equals(t, accID, acc.ID)
  239. assert.Equals(t, id, o.ID)
  240. return &o, nil
  241. },
  242. getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
  243. assert.Equals(t, typ, acme.OrderLink)
  244. assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
  245. assert.True(t, abs)
  246. assert.Equals(t, in, []string{o.ID})
  247. return url
  248. },
  249. },
  250. ctx: ctx,
  251. statusCode: 200,
  252. }
  253. },
  254. }
  255. for name, run := range tests {
  256. tc := run(t)
  257. t.Run(name, func(t *testing.T) {
  258. h := New(tc.auth).(*Handler)
  259. req := httptest.NewRequest("GET", url, nil)
  260. req = req.WithContext(tc.ctx)
  261. w := httptest.NewRecorder()
  262. h.GetOrder(w, req)
  263. res := w.Result()
  264. assert.Equals(t, res.StatusCode, tc.statusCode)
  265. body, err := ioutil.ReadAll(res.Body)
  266. res.Body.Close()
  267. assert.FatalError(t, err)
  268. if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
  269. var ae acme.AError
  270. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  271. prob := tc.problem.ToACME()
  272. assert.Equals(t, ae.Type, prob.Type)
  273. assert.Equals(t, ae.Detail, prob.Detail)
  274. assert.Equals(t, ae.Identifier, prob.Identifier)
  275. assert.Equals(t, ae.Subproblems, prob.Subproblems)
  276. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  277. } else {
  278. expB, err := json.Marshal(o)
  279. assert.FatalError(t, err)
  280. assert.Equals(t, bytes.TrimSpace(body), expB)
  281. assert.Equals(t, res.Header["Location"], []string{url})
  282. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  283. }
  284. })
  285. }
  286. }
  287. func TestHandlerNewOrder(t *testing.T) {
  288. expiry := time.Now().UTC().Add(6 * time.Hour)
  289. nbf := time.Now().UTC().Add(5 * time.Hour)
  290. naf := nbf.Add(17 * time.Hour)
  291. o := acme.Order{
  292. ID: "orderID",
  293. Expires: expiry.Format(time.RFC3339),
  294. NotBefore: nbf.Format(time.RFC3339),
  295. NotAfter: naf.Format(time.RFC3339),
  296. Identifiers: []acme.Identifier{
  297. {Type: "dns", Value: "example.com"},
  298. {Type: "dns", Value: "bar.com"},
  299. },
  300. Status: "pending",
  301. Authorizations: []string{"foo", "bar"},
  302. }
  303. prov := newProv()
  304. url := fmt.Sprintf("https://ca.smallstep.com/acme/%s/new-order",
  305. acme.URLSafeProvisionerName(prov))
  306. type test struct {
  307. auth acme.Interface
  308. ctx context.Context
  309. statusCode int
  310. problem *acme.Error
  311. }
  312. var tests = map[string]func(t *testing.T) test{
  313. "fail/no-provisioner": func(t *testing.T) test {
  314. return test{
  315. auth: &mockAcmeAuthority{},
  316. ctx: context.Background(),
  317. statusCode: 500,
  318. problem: acme.ServerInternalErr(errors.New("provisioner expected in request context")),
  319. }
  320. },
  321. "fail/nil-provisioner": func(t *testing.T) test {
  322. return test{
  323. auth: &mockAcmeAuthority{},
  324. ctx: context.WithValue(context.Background(), provisionerContextKey, nil),
  325. statusCode: 500,
  326. problem: acme.ServerInternalErr(errors.New("provisioner expected in request context")),
  327. }
  328. },
  329. "fail/no-account": func(t *testing.T) test {
  330. return test{
  331. ctx: context.WithValue(context.Background(), provisionerContextKey, prov),
  332. statusCode: 404,
  333. problem: acme.AccountDoesNotExistErr(nil),
  334. }
  335. },
  336. "fail/nil-account": func(t *testing.T) test {
  337. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  338. ctx = context.WithValue(ctx, accContextKey, nil)
  339. return test{
  340. ctx: ctx,
  341. statusCode: 404,
  342. problem: acme.AccountDoesNotExistErr(nil),
  343. }
  344. },
  345. "fail/no-payload": func(t *testing.T) test {
  346. acc := &acme.Account{ID: "accID"}
  347. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  348. ctx = context.WithValue(ctx, accContextKey, acc)
  349. return test{
  350. ctx: ctx,
  351. statusCode: 500,
  352. problem: acme.ServerInternalErr(errors.New("payload expected in request context")),
  353. }
  354. },
  355. "fail/nil-payload": func(t *testing.T) test {
  356. acc := &acme.Account{ID: "accID"}
  357. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  358. ctx = context.WithValue(ctx, accContextKey, acc)
  359. ctx = context.WithValue(ctx, payloadContextKey, nil)
  360. return test{
  361. ctx: ctx,
  362. statusCode: 500,
  363. problem: acme.ServerInternalErr(errors.New("payload expected in request context")),
  364. }
  365. },
  366. "fail/unmarshal-payload-error": func(t *testing.T) test {
  367. acc := &acme.Account{ID: "accID"}
  368. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  369. ctx = context.WithValue(ctx, accContextKey, acc)
  370. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{})
  371. return test{
  372. ctx: ctx,
  373. statusCode: 400,
  374. problem: acme.MalformedErr(errors.New("failed to unmarshal new-order request payload: unexpected end of JSON input")),
  375. }
  376. },
  377. "fail/malformed-payload-error": func(t *testing.T) test {
  378. acc := &acme.Account{ID: "accID"}
  379. nor := &NewOrderRequest{}
  380. b, err := json.Marshal(nor)
  381. assert.FatalError(t, err)
  382. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  383. ctx = context.WithValue(ctx, accContextKey, acc)
  384. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  385. return test{
  386. ctx: ctx,
  387. statusCode: 400,
  388. problem: acme.MalformedErr(errors.New("identifiers list cannot be empty")),
  389. }
  390. },
  391. "fail/NewOrder-error": func(t *testing.T) test {
  392. acc := &acme.Account{ID: "accID"}
  393. nor := &NewOrderRequest{
  394. Identifiers: []acme.Identifier{
  395. {Type: "dns", Value: "example.com"},
  396. {Type: "dns", Value: "bar.com"},
  397. },
  398. }
  399. b, err := json.Marshal(nor)
  400. assert.FatalError(t, err)
  401. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  402. ctx = context.WithValue(ctx, accContextKey, acc)
  403. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  404. return test{
  405. auth: &mockAcmeAuthority{
  406. newOrder: func(p provisioner.Interface, ops acme.OrderOptions) (*acme.Order, error) {
  407. assert.Equals(t, p, prov)
  408. assert.Equals(t, ops.AccountID, acc.ID)
  409. assert.Equals(t, ops.Identifiers, nor.Identifiers)
  410. return nil, acme.MalformedErr(errors.New("force"))
  411. },
  412. },
  413. ctx: ctx,
  414. statusCode: 400,
  415. problem: acme.MalformedErr(errors.New("force")),
  416. }
  417. },
  418. "ok": func(t *testing.T) test {
  419. acc := &acme.Account{ID: "accID"}
  420. nor := &NewOrderRequest{
  421. Identifiers: []acme.Identifier{
  422. {Type: "dns", Value: "example.com"},
  423. {Type: "dns", Value: "bar.com"},
  424. },
  425. NotBefore: nbf,
  426. NotAfter: naf,
  427. }
  428. b, err := json.Marshal(nor)
  429. assert.FatalError(t, err)
  430. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  431. ctx = context.WithValue(ctx, accContextKey, acc)
  432. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  433. return test{
  434. auth: &mockAcmeAuthority{
  435. newOrder: func(p provisioner.Interface, ops acme.OrderOptions) (*acme.Order, error) {
  436. assert.Equals(t, p, prov)
  437. assert.Equals(t, ops.AccountID, acc.ID)
  438. assert.Equals(t, ops.Identifiers, nor.Identifiers)
  439. assert.Equals(t, ops.NotBefore, nbf)
  440. assert.Equals(t, ops.NotAfter, naf)
  441. return &o, nil
  442. },
  443. getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
  444. assert.Equals(t, typ, acme.OrderLink)
  445. assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
  446. assert.True(t, abs)
  447. assert.Equals(t, in, []string{o.ID})
  448. return fmt.Sprintf("https://ca.smallstep.com/acme/order/%s", o.ID)
  449. },
  450. },
  451. ctx: ctx,
  452. statusCode: 201,
  453. }
  454. },
  455. "ok/default-naf-nbf": func(t *testing.T) test {
  456. acc := &acme.Account{ID: "accID"}
  457. nor := &NewOrderRequest{
  458. Identifiers: []acme.Identifier{
  459. {Type: "dns", Value: "example.com"},
  460. {Type: "dns", Value: "bar.com"},
  461. },
  462. }
  463. b, err := json.Marshal(nor)
  464. assert.FatalError(t, err)
  465. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  466. ctx = context.WithValue(ctx, accContextKey, acc)
  467. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  468. return test{
  469. auth: &mockAcmeAuthority{
  470. newOrder: func(p provisioner.Interface, ops acme.OrderOptions) (*acme.Order, error) {
  471. assert.Equals(t, p, prov)
  472. assert.Equals(t, ops.AccountID, acc.ID)
  473. assert.Equals(t, ops.Identifiers, nor.Identifiers)
  474. assert.True(t, ops.NotBefore.IsZero())
  475. assert.True(t, ops.NotAfter.IsZero())
  476. return &o, nil
  477. },
  478. getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
  479. assert.Equals(t, typ, acme.OrderLink)
  480. assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
  481. assert.True(t, abs)
  482. assert.Equals(t, in, []string{o.ID})
  483. return fmt.Sprintf("https://ca.smallstep.com/acme/order/%s", o.ID)
  484. },
  485. },
  486. ctx: ctx,
  487. statusCode: 201,
  488. }
  489. },
  490. }
  491. for name, run := range tests {
  492. tc := run(t)
  493. t.Run(name, func(t *testing.T) {
  494. h := New(tc.auth).(*Handler)
  495. req := httptest.NewRequest("GET", url, nil)
  496. req = req.WithContext(tc.ctx)
  497. w := httptest.NewRecorder()
  498. h.NewOrder(w, req)
  499. res := w.Result()
  500. assert.Equals(t, res.StatusCode, tc.statusCode)
  501. body, err := ioutil.ReadAll(res.Body)
  502. res.Body.Close()
  503. assert.FatalError(t, err)
  504. if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
  505. var ae acme.AError
  506. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  507. prob := tc.problem.ToACME()
  508. assert.Equals(t, ae.Type, prob.Type)
  509. assert.Equals(t, ae.Detail, prob.Detail)
  510. assert.Equals(t, ae.Identifier, prob.Identifier)
  511. assert.Equals(t, ae.Subproblems, prob.Subproblems)
  512. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  513. } else {
  514. expB, err := json.Marshal(o)
  515. assert.FatalError(t, err)
  516. assert.Equals(t, bytes.TrimSpace(body), expB)
  517. assert.Equals(t, res.Header["Location"],
  518. []string{fmt.Sprintf("https://ca.smallstep.com/acme/order/%s", o.ID)})
  519. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  520. }
  521. })
  522. }
  523. }
  524. func TestHandlerFinalizeOrder(t *testing.T) {
  525. expiry := time.Now().UTC().Add(6 * time.Hour)
  526. nbf := time.Now().UTC().Add(5 * time.Hour)
  527. naf := nbf.Add(17 * time.Hour)
  528. o := acme.Order{
  529. ID: "orderID",
  530. Expires: expiry.Format(time.RFC3339),
  531. NotBefore: nbf.Format(time.RFC3339),
  532. NotAfter: naf.Format(time.RFC3339),
  533. Identifiers: []acme.Identifier{
  534. {Type: "dns", Value: "example.com"},
  535. {Type: "dns", Value: "bar.com"},
  536. },
  537. Status: "valid",
  538. Authorizations: []string{"foo", "bar"},
  539. Certificate: "https://ca.smallstep.com/acme/certificate/certID",
  540. }
  541. _csr, err := pemutil.Read("../../authority/testdata/certs/foo.csr")
  542. assert.FatalError(t, err)
  543. csr, ok := _csr.(*x509.CertificateRequest)
  544. assert.Fatal(t, ok)
  545. // Request with chi context
  546. chiCtx := chi.NewRouteContext()
  547. chiCtx.URLParams.Add("ordID", o.ID)
  548. prov := newProv()
  549. url := fmt.Sprintf("http://ca.smallstep.com/acme/%s/order/%s/finalize",
  550. acme.URLSafeProvisionerName(prov), o.ID)
  551. type test struct {
  552. auth acme.Interface
  553. ctx context.Context
  554. statusCode int
  555. problem *acme.Error
  556. }
  557. var tests = map[string]func(t *testing.T) test{
  558. "fail/no-provisioner": func(t *testing.T) test {
  559. return test{
  560. auth: &mockAcmeAuthority{},
  561. ctx: context.Background(),
  562. statusCode: 500,
  563. problem: acme.ServerInternalErr(errors.New("provisioner expected in request context")),
  564. }
  565. },
  566. "fail/nil-provisioner": func(t *testing.T) test {
  567. return test{
  568. auth: &mockAcmeAuthority{},
  569. ctx: context.WithValue(context.Background(), provisionerContextKey, nil),
  570. statusCode: 500,
  571. problem: acme.ServerInternalErr(errors.New("provisioner expected in request context")),
  572. }
  573. },
  574. "fail/no-account": func(t *testing.T) test {
  575. return test{
  576. auth: &mockAcmeAuthority{},
  577. ctx: context.WithValue(context.Background(), provisionerContextKey, prov),
  578. statusCode: 404,
  579. problem: acme.AccountDoesNotExistErr(nil),
  580. }
  581. },
  582. "fail/nil-account": func(t *testing.T) test {
  583. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  584. ctx = context.WithValue(ctx, accContextKey, nil)
  585. return test{
  586. auth: &mockAcmeAuthority{},
  587. ctx: ctx,
  588. statusCode: 404,
  589. problem: acme.AccountDoesNotExistErr(nil),
  590. }
  591. },
  592. "fail/no-payload": func(t *testing.T) test {
  593. acc := &acme.Account{ID: "accID"}
  594. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  595. ctx = context.WithValue(ctx, accContextKey, acc)
  596. return test{
  597. ctx: ctx,
  598. statusCode: 500,
  599. problem: acme.ServerInternalErr(errors.New("payload expected in request context")),
  600. }
  601. },
  602. "fail/nil-payload": func(t *testing.T) test {
  603. acc := &acme.Account{ID: "accID"}
  604. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  605. ctx = context.WithValue(ctx, accContextKey, acc)
  606. ctx = context.WithValue(ctx, payloadContextKey, nil)
  607. return test{
  608. ctx: ctx,
  609. statusCode: 500,
  610. problem: acme.ServerInternalErr(errors.New("payload expected in request context")),
  611. }
  612. },
  613. "fail/unmarshal-payload-error": func(t *testing.T) test {
  614. acc := &acme.Account{ID: "accID"}
  615. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  616. ctx = context.WithValue(ctx, accContextKey, acc)
  617. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{})
  618. return test{
  619. ctx: ctx,
  620. statusCode: 400,
  621. problem: acme.MalformedErr(errors.New("failed to unmarshal finalize-order request payload: unexpected end of JSON input")),
  622. }
  623. },
  624. "fail/malformed-payload-error": func(t *testing.T) test {
  625. acc := &acme.Account{ID: "accID"}
  626. fr := &FinalizeRequest{}
  627. b, err := json.Marshal(fr)
  628. assert.FatalError(t, err)
  629. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  630. ctx = context.WithValue(ctx, accContextKey, acc)
  631. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  632. return test{
  633. ctx: ctx,
  634. statusCode: 400,
  635. problem: acme.MalformedErr(errors.New("unable to parse csr: asn1: syntax error: sequence truncated")),
  636. }
  637. },
  638. "fail/FinalizeOrder-error": func(t *testing.T) test {
  639. acc := &acme.Account{ID: "accID"}
  640. nor := &FinalizeRequest{
  641. CSR: base64.RawURLEncoding.EncodeToString(csr.Raw),
  642. }
  643. b, err := json.Marshal(nor)
  644. assert.FatalError(t, err)
  645. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  646. ctx = context.WithValue(ctx, accContextKey, acc)
  647. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  648. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  649. return test{
  650. auth: &mockAcmeAuthority{
  651. finalizeOrder: func(p provisioner.Interface, accID, id string, incsr *x509.CertificateRequest) (*acme.Order, error) {
  652. assert.Equals(t, p, prov)
  653. assert.Equals(t, accID, acc.ID)
  654. assert.Equals(t, id, o.ID)
  655. assert.Equals(t, incsr.Raw, csr.Raw)
  656. return nil, acme.MalformedErr(errors.New("force"))
  657. },
  658. },
  659. ctx: ctx,
  660. statusCode: 400,
  661. problem: acme.MalformedErr(errors.New("force")),
  662. }
  663. },
  664. "ok": func(t *testing.T) test {
  665. acc := &acme.Account{ID: "accID"}
  666. nor := &FinalizeRequest{
  667. CSR: base64.RawURLEncoding.EncodeToString(csr.Raw),
  668. }
  669. b, err := json.Marshal(nor)
  670. assert.FatalError(t, err)
  671. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  672. ctx = context.WithValue(ctx, accContextKey, acc)
  673. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  674. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  675. return test{
  676. auth: &mockAcmeAuthority{
  677. finalizeOrder: func(p provisioner.Interface, accID, id string, incsr *x509.CertificateRequest) (*acme.Order, error) {
  678. assert.Equals(t, p, prov)
  679. assert.Equals(t, accID, acc.ID)
  680. assert.Equals(t, id, o.ID)
  681. assert.Equals(t, incsr.Raw, csr.Raw)
  682. return &o, nil
  683. },
  684. getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
  685. assert.Equals(t, typ, acme.OrderLink)
  686. assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
  687. assert.True(t, abs)
  688. assert.Equals(t, in, []string{o.ID})
  689. return fmt.Sprintf("https://ca.smallstep.com/acme/%s/order/%s",
  690. acme.URLSafeProvisionerName(prov), o.ID)
  691. },
  692. },
  693. ctx: ctx,
  694. statusCode: 200,
  695. }
  696. },
  697. }
  698. for name, run := range tests {
  699. tc := run(t)
  700. t.Run(name, func(t *testing.T) {
  701. h := New(tc.auth).(*Handler)
  702. req := httptest.NewRequest("GET", url, nil)
  703. req = req.WithContext(tc.ctx)
  704. w := httptest.NewRecorder()
  705. h.FinalizeOrder(w, req)
  706. res := w.Result()
  707. assert.Equals(t, res.StatusCode, tc.statusCode)
  708. body, err := ioutil.ReadAll(res.Body)
  709. res.Body.Close()
  710. assert.FatalError(t, err)
  711. if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
  712. var ae acme.AError
  713. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  714. prob := tc.problem.ToACME()
  715. assert.Equals(t, ae.Type, prob.Type)
  716. assert.Equals(t, ae.Detail, prob.Detail)
  717. assert.Equals(t, ae.Identifier, prob.Identifier)
  718. assert.Equals(t, ae.Subproblems, prob.Subproblems)
  719. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  720. } else {
  721. expB, err := json.Marshal(o)
  722. assert.FatalError(t, err)
  723. assert.Equals(t, bytes.TrimSpace(body), expB)
  724. assert.Equals(t, res.Header["Location"],
  725. []string{fmt.Sprintf("https://ca.smallstep.com/acme/%s/order/%s",
  726. acme.URLSafeProvisionerName(prov), o.ID)})
  727. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  728. }
  729. })
  730. }
  731. }