account_test.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http/httptest"
  9. "net/url"
  10. "testing"
  11. "time"
  12. "github.com/go-chi/chi"
  13. "github.com/pkg/errors"
  14. "go.step.sm/crypto/jose"
  15. "github.com/smallstep/assert"
  16. "github.com/smallstep/certificates/acme"
  17. "github.com/smallstep/certificates/authority/provisioner"
  18. )
  19. var (
  20. defaultDisableRenewal = false
  21. globalProvisionerClaims = provisioner.Claims{
  22. MinTLSDur: &provisioner.Duration{Duration: 5 * time.Minute},
  23. MaxTLSDur: &provisioner.Duration{Duration: 24 * time.Hour},
  24. DefaultTLSDur: &provisioner.Duration{Duration: 24 * time.Hour},
  25. DisableRenewal: &defaultDisableRenewal,
  26. }
  27. )
  28. type fakeProvisioner struct{}
  29. func (*fakeProvisioner) AuthorizeOrderIdentifier(ctx context.Context, identifier provisioner.ACMEIdentifier) error {
  30. return nil
  31. }
  32. func (*fakeProvisioner) AuthorizeSign(ctx context.Context, token string) ([]provisioner.SignOption, error) {
  33. return nil, nil
  34. }
  35. func (*fakeProvisioner) AuthorizeRevoke(ctx context.Context, token string) error { return nil }
  36. func (*fakeProvisioner) AuthorizeChallenge(ctx context.Context, challenge string) error { return nil }
  37. func (*fakeProvisioner) GetID() string { return "" }
  38. func (*fakeProvisioner) GetName() string { return "" }
  39. func (*fakeProvisioner) DefaultTLSCertDuration() time.Duration { return 0 }
  40. func (*fakeProvisioner) GetOptions() *provisioner.Options { return nil }
  41. func newProv() acme.Provisioner {
  42. // Initialize provisioners
  43. p := &provisioner.ACME{
  44. Type: "ACME",
  45. Name: "test@acme-<test>provisioner.com",
  46. }
  47. if err := p.Init(provisioner.Config{Claims: globalProvisionerClaims}); err != nil {
  48. fmt.Printf("%v", err)
  49. }
  50. return p
  51. }
  52. func newProvWithOptions(options *provisioner.Options) acme.Provisioner {
  53. // Initialize provisioners
  54. p := &provisioner.ACME{
  55. Type: "ACME",
  56. Name: "test@acme-<test>provisioner.com",
  57. Options: options,
  58. }
  59. if err := p.Init(provisioner.Config{Claims: globalProvisionerClaims}); err != nil {
  60. fmt.Printf("%v", err)
  61. }
  62. return p
  63. }
  64. func newACMEProv(t *testing.T) *provisioner.ACME {
  65. p := newProv()
  66. a, ok := p.(*provisioner.ACME)
  67. if !ok {
  68. t.Fatal("not a valid ACME provisioner")
  69. }
  70. return a
  71. }
  72. func newACMEProvWithOptions(t *testing.T, options *provisioner.Options) *provisioner.ACME {
  73. p := newProvWithOptions(options)
  74. a, ok := p.(*provisioner.ACME)
  75. if !ok {
  76. t.Fatal("not a valid ACME provisioner")
  77. }
  78. return a
  79. }
  80. func createEABJWS(jwk *jose.JSONWebKey, hmacKey []byte, keyID, u string) (*jose.JSONWebSignature, error) {
  81. signer, err := jose.NewSigner(
  82. jose.SigningKey{
  83. Algorithm: jose.SignatureAlgorithm("HS256"),
  84. Key: hmacKey,
  85. },
  86. &jose.SignerOptions{
  87. ExtraHeaders: map[jose.HeaderKey]interface{}{
  88. "kid": keyID,
  89. "url": u,
  90. },
  91. EmbedJWK: false,
  92. },
  93. )
  94. if err != nil {
  95. return nil, err
  96. }
  97. jwkJSONBytes, err := jwk.Public().MarshalJSON()
  98. if err != nil {
  99. return nil, err
  100. }
  101. jws, err := signer.Sign(jwkJSONBytes)
  102. if err != nil {
  103. return nil, err
  104. }
  105. raw, err := jws.CompactSerialize()
  106. if err != nil {
  107. return nil, err
  108. }
  109. parsedJWS, err := jose.ParseJWS(raw)
  110. if err != nil {
  111. return nil, err
  112. }
  113. return parsedJWS, nil
  114. }
  115. func createRawEABJWS(jwk *jose.JSONWebKey, hmacKey []byte, keyID, u string) ([]byte, error) {
  116. jws, err := createEABJWS(jwk, hmacKey, keyID, u)
  117. if err != nil {
  118. return nil, err
  119. }
  120. rawJWS := jws.FullSerialize()
  121. return []byte(rawJWS), nil
  122. }
  123. func TestNewAccountRequest_Validate(t *testing.T) {
  124. type test struct {
  125. nar *NewAccountRequest
  126. err *acme.Error
  127. }
  128. var tests = map[string]func(t *testing.T) test{
  129. "fail/incompatible-input": func(t *testing.T) test {
  130. return test{
  131. nar: &NewAccountRequest{
  132. OnlyReturnExisting: true,
  133. Contact: []string{"foo", "bar"},
  134. },
  135. err: acme.NewError(acme.ErrorMalformedType, "incompatible input; onlyReturnExisting must be alone"),
  136. }
  137. },
  138. "fail/bad-contact": func(t *testing.T) test {
  139. return test{
  140. nar: &NewAccountRequest{
  141. Contact: []string{"foo", ""},
  142. },
  143. err: acme.NewError(acme.ErrorMalformedType, "contact cannot be empty string"),
  144. }
  145. },
  146. "ok": func(t *testing.T) test {
  147. return test{
  148. nar: &NewAccountRequest{
  149. Contact: []string{"foo", "bar"},
  150. },
  151. }
  152. },
  153. "ok/onlyReturnExisting": func(t *testing.T) test {
  154. return test{
  155. nar: &NewAccountRequest{
  156. OnlyReturnExisting: true,
  157. },
  158. }
  159. },
  160. }
  161. for name, run := range tests {
  162. tc := run(t)
  163. t.Run(name, func(t *testing.T) {
  164. if err := tc.nar.Validate(); err != nil {
  165. if assert.NotNil(t, err) {
  166. ae, ok := err.(*acme.Error)
  167. assert.True(t, ok)
  168. assert.HasPrefix(t, ae.Error(), tc.err.Error())
  169. assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
  170. assert.Equals(t, ae.Type, tc.err.Type)
  171. }
  172. } else {
  173. assert.Nil(t, tc.err)
  174. }
  175. })
  176. }
  177. }
  178. func TestUpdateAccountRequest_Validate(t *testing.T) {
  179. type test struct {
  180. uar *UpdateAccountRequest
  181. err *acme.Error
  182. }
  183. var tests = map[string]func(t *testing.T) test{
  184. "fail/incompatible-input": func(t *testing.T) test {
  185. return test{
  186. uar: &UpdateAccountRequest{
  187. Contact: []string{"foo", "bar"},
  188. Status: "foo",
  189. },
  190. err: acme.NewError(acme.ErrorMalformedType, "incompatible input; "+
  191. "contact and status updates are mutually exclusive"),
  192. }
  193. },
  194. "fail/bad-contact": func(t *testing.T) test {
  195. return test{
  196. uar: &UpdateAccountRequest{
  197. Contact: []string{"foo", ""},
  198. },
  199. err: acme.NewError(acme.ErrorMalformedType, "contact cannot be empty string"),
  200. }
  201. },
  202. "fail/bad-status": func(t *testing.T) test {
  203. return test{
  204. uar: &UpdateAccountRequest{
  205. Status: "foo",
  206. },
  207. err: acme.NewError(acme.ErrorMalformedType, "cannot update account "+
  208. "status to foo, only deactivated"),
  209. }
  210. },
  211. "ok/contact": func(t *testing.T) test {
  212. return test{
  213. uar: &UpdateAccountRequest{
  214. Contact: []string{"foo", "bar"},
  215. },
  216. }
  217. },
  218. "ok/status": func(t *testing.T) test {
  219. return test{
  220. uar: &UpdateAccountRequest{
  221. Status: "deactivated",
  222. },
  223. }
  224. },
  225. "ok/accept-empty": func(t *testing.T) test {
  226. return test{
  227. uar: &UpdateAccountRequest{},
  228. }
  229. },
  230. }
  231. for name, run := range tests {
  232. tc := run(t)
  233. t.Run(name, func(t *testing.T) {
  234. if err := tc.uar.Validate(); err != nil {
  235. if assert.NotNil(t, err) {
  236. ae, ok := err.(*acme.Error)
  237. assert.True(t, ok)
  238. assert.HasPrefix(t, ae.Error(), tc.err.Error())
  239. assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
  240. assert.Equals(t, ae.Type, tc.err.Type)
  241. }
  242. } else {
  243. assert.Nil(t, tc.err)
  244. }
  245. })
  246. }
  247. }
  248. func TestHandler_GetOrdersByAccountID(t *testing.T) {
  249. accID := "account-id"
  250. // Request with chi context
  251. chiCtx := chi.NewRouteContext()
  252. chiCtx.URLParams.Add("accID", accID)
  253. prov := newProv()
  254. provName := url.PathEscape(prov.GetName())
  255. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  256. u := fmt.Sprintf("http://ca.smallstep.com/acme/%s/account/%s/orders", provName, accID)
  257. oids := []string{"foo", "bar"}
  258. oidURLs := []string{
  259. fmt.Sprintf("%s/acme/%s/order/foo", baseURL.String(), provName),
  260. fmt.Sprintf("%s/acme/%s/order/bar", baseURL.String(), provName),
  261. }
  262. type test struct {
  263. db acme.DB
  264. ctx context.Context
  265. statusCode int
  266. err *acme.Error
  267. }
  268. var tests = map[string]func(t *testing.T) test{
  269. "fail/no-account": func(t *testing.T) test {
  270. return test{
  271. db: &acme.MockDB{},
  272. ctx: context.Background(),
  273. statusCode: 400,
  274. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  275. }
  276. },
  277. "fail/nil-account": func(t *testing.T) test {
  278. return test{
  279. db: &acme.MockDB{},
  280. ctx: context.WithValue(context.Background(), accContextKey, nil),
  281. statusCode: 400,
  282. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  283. }
  284. },
  285. "fail/account-id-mismatch": func(t *testing.T) test {
  286. acc := &acme.Account{ID: "foo"}
  287. ctx := context.WithValue(context.Background(), accContextKey, acc)
  288. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  289. return test{
  290. db: &acme.MockDB{},
  291. ctx: ctx,
  292. statusCode: 401,
  293. err: acme.NewError(acme.ErrorUnauthorizedType, "account ID does not match url param"),
  294. }
  295. },
  296. "fail/db.GetOrdersByAccountID-error": func(t *testing.T) test {
  297. acc := &acme.Account{ID: accID}
  298. ctx := context.WithValue(context.Background(), accContextKey, acc)
  299. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  300. return test{
  301. db: &acme.MockDB{
  302. MockError: acme.NewErrorISE("force"),
  303. },
  304. ctx: ctx,
  305. statusCode: 500,
  306. err: acme.NewErrorISE("force"),
  307. }
  308. },
  309. "ok": func(t *testing.T) test {
  310. acc := &acme.Account{ID: accID}
  311. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  312. ctx = acme.NewProvisionerContext(ctx, prov)
  313. ctx = context.WithValue(ctx, accContextKey, acc)
  314. return test{
  315. db: &acme.MockDB{
  316. MockGetOrdersByAccountID: func(ctx context.Context, id string) ([]string, error) {
  317. assert.Equals(t, id, acc.ID)
  318. return oids, nil
  319. },
  320. },
  321. ctx: ctx,
  322. statusCode: 200,
  323. }
  324. },
  325. }
  326. for name, run := range tests {
  327. tc := run(t)
  328. t.Run(name, func(t *testing.T) {
  329. ctx := acme.NewContext(tc.ctx, tc.db, nil, acme.NewLinker("test.ca.smallstep.com", "acme"), nil)
  330. req := httptest.NewRequest("GET", u, nil)
  331. req = req.WithContext(ctx)
  332. w := httptest.NewRecorder()
  333. GetOrdersByAccountID(w, req)
  334. res := w.Result()
  335. assert.Equals(t, res.StatusCode, tc.statusCode)
  336. body, err := io.ReadAll(res.Body)
  337. res.Body.Close()
  338. assert.FatalError(t, err)
  339. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  340. var ae acme.Error
  341. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  342. assert.Equals(t, ae.Type, tc.err.Type)
  343. assert.Equals(t, ae.Detail, tc.err.Detail)
  344. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  345. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  346. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  347. } else {
  348. expB, err := json.Marshal(oidURLs)
  349. assert.FatalError(t, err)
  350. assert.Equals(t, bytes.TrimSpace(body), expB)
  351. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  352. }
  353. })
  354. }
  355. }
  356. func TestHandler_NewAccount(t *testing.T) {
  357. prov := newProv()
  358. escProvName := url.PathEscape(prov.GetName())
  359. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  360. provID := prov.GetID()
  361. type test struct {
  362. db acme.DB
  363. acc *acme.Account
  364. ctx context.Context
  365. statusCode int
  366. err *acme.Error
  367. }
  368. var tests = map[string]func(t *testing.T) test{
  369. "fail/no-payload": func(t *testing.T) test {
  370. return test{
  371. db: &acme.MockDB{},
  372. ctx: context.Background(),
  373. statusCode: 500,
  374. err: acme.NewErrorISE("payload expected in request context"),
  375. }
  376. },
  377. "fail/nil-payload": func(t *testing.T) test {
  378. ctx := context.WithValue(context.Background(), payloadContextKey, nil)
  379. return test{
  380. db: &acme.MockDB{},
  381. ctx: ctx,
  382. statusCode: 500,
  383. err: acme.NewErrorISE("payload expected in request context"),
  384. }
  385. },
  386. "fail/unmarshal-payload-error": func(t *testing.T) test {
  387. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{})
  388. return test{
  389. db: &acme.MockDB{},
  390. ctx: ctx,
  391. statusCode: 400,
  392. err: acme.NewError(acme.ErrorMalformedType, "failed to "+
  393. "unmarshal new-account request payload: unexpected end of JSON input"),
  394. }
  395. },
  396. "fail/malformed-payload-error": func(t *testing.T) test {
  397. nar := &NewAccountRequest{
  398. Contact: []string{"foo", ""},
  399. }
  400. b, err := json.Marshal(nar)
  401. assert.FatalError(t, err)
  402. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: b})
  403. return test{
  404. db: &acme.MockDB{},
  405. ctx: ctx,
  406. statusCode: 400,
  407. err: acme.NewError(acme.ErrorMalformedType, "contact cannot be empty string"),
  408. }
  409. },
  410. "fail/no-existing-account": func(t *testing.T) test {
  411. nar := &NewAccountRequest{
  412. OnlyReturnExisting: true,
  413. }
  414. b, err := json.Marshal(nar)
  415. assert.FatalError(t, err)
  416. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: b})
  417. ctx = acme.NewProvisionerContext(ctx, prov)
  418. return test{
  419. db: &acme.MockDB{},
  420. ctx: ctx,
  421. statusCode: 400,
  422. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  423. }
  424. },
  425. "fail/no-jwk": func(t *testing.T) test {
  426. nar := &NewAccountRequest{
  427. Contact: []string{"foo", "bar"},
  428. }
  429. b, err := json.Marshal(nar)
  430. assert.FatalError(t, err)
  431. ctx := acme.NewProvisionerContext(context.Background(), prov)
  432. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  433. return test{
  434. db: &acme.MockDB{},
  435. ctx: ctx,
  436. statusCode: 500,
  437. err: acme.NewErrorISE("jwk expected in request context"),
  438. }
  439. },
  440. "fail/nil-jwk": func(t *testing.T) test {
  441. nar := &NewAccountRequest{
  442. Contact: []string{"foo", "bar"},
  443. }
  444. b, err := json.Marshal(nar)
  445. assert.FatalError(t, err)
  446. ctx := acme.NewProvisionerContext(context.Background(), prov)
  447. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  448. ctx = context.WithValue(ctx, jwkContextKey, nil)
  449. return test{
  450. db: &acme.MockDB{},
  451. ctx: ctx,
  452. statusCode: 500,
  453. err: acme.NewErrorISE("jwk expected in request context"),
  454. }
  455. },
  456. "fail/new-account-no-eab-provided": func(t *testing.T) test {
  457. nar := &NewAccountRequest{
  458. Contact: []string{"foo", "bar"},
  459. ExternalAccountBinding: nil,
  460. }
  461. b, err := json.Marshal(nar)
  462. assert.FatalError(t, err)
  463. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  464. assert.FatalError(t, err)
  465. prov := newACMEProv(t)
  466. prov.RequireEAB = true
  467. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: b})
  468. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  469. ctx = acme.NewProvisionerContext(ctx, prov)
  470. return test{
  471. db: &acme.MockDB{},
  472. ctx: ctx,
  473. statusCode: 400,
  474. err: acme.NewError(acme.ErrorExternalAccountRequiredType, "no external account binding provided"),
  475. }
  476. },
  477. "fail/db.CreateAccount-error": func(t *testing.T) test {
  478. nar := &NewAccountRequest{
  479. Contact: []string{"foo", "bar"},
  480. }
  481. b, err := json.Marshal(nar)
  482. assert.FatalError(t, err)
  483. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  484. assert.FatalError(t, err)
  485. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: b})
  486. ctx = acme.NewProvisionerContext(ctx, prov)
  487. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  488. return test{
  489. db: &acme.MockDB{
  490. MockCreateAccount: func(ctx context.Context, acc *acme.Account) error {
  491. assert.Equals(t, acc.Contact, nar.Contact)
  492. assert.Equals(t, acc.Key, jwk)
  493. return acme.NewErrorISE("force")
  494. },
  495. },
  496. ctx: ctx,
  497. statusCode: 500,
  498. err: acme.NewErrorISE("force"),
  499. }
  500. },
  501. "fail/acmeProvisionerFromContext": func(t *testing.T) test {
  502. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  503. assert.FatalError(t, err)
  504. url := fmt.Sprintf("%s/acme/%s/account/new-account", baseURL.String(), escProvName)
  505. rawEABJWS, err := createRawEABJWS(jwk, []byte{1, 3, 3, 7}, "eakID", url)
  506. assert.FatalError(t, err)
  507. eab := &ExternalAccountBinding{}
  508. err = json.Unmarshal(rawEABJWS, &eab)
  509. assert.FatalError(t, err)
  510. nar := &NewAccountRequest{
  511. Contact: []string{"foo", "bar"},
  512. ExternalAccountBinding: eab,
  513. }
  514. b, err := json.Marshal(nar)
  515. assert.FatalError(t, err)
  516. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: b})
  517. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  518. ctx = acme.NewProvisionerContext(ctx, &fakeProvisioner{})
  519. return test{
  520. db: &acme.MockDB{},
  521. ctx: ctx,
  522. statusCode: 500,
  523. err: acme.NewError(acme.ErrorServerInternalType, "provisioner in context is not an ACME provisioner"),
  524. }
  525. },
  526. "fail/db.UpdateExternalAccountKey-error": func(t *testing.T) test {
  527. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  528. assert.FatalError(t, err)
  529. url := fmt.Sprintf("%s/acme/%s/account/new-account", baseURL.String(), escProvName)
  530. rawEABJWS, err := createRawEABJWS(jwk, []byte{1, 3, 3, 7}, "eakID", url)
  531. assert.FatalError(t, err)
  532. eab := &ExternalAccountBinding{}
  533. err = json.Unmarshal(rawEABJWS, &eab)
  534. assert.FatalError(t, err)
  535. nar := &NewAccountRequest{
  536. Contact: []string{"foo", "bar"},
  537. ExternalAccountBinding: eab,
  538. }
  539. payloadBytes, err := json.Marshal(nar)
  540. assert.FatalError(t, err)
  541. so := new(jose.SignerOptions)
  542. so.WithHeader("alg", jose.SignatureAlgorithm(jwk.Algorithm))
  543. so.WithHeader("url", url)
  544. signer, err := jose.NewSigner(jose.SigningKey{
  545. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  546. Key: jwk.Key,
  547. }, so)
  548. assert.FatalError(t, err)
  549. jws, err := signer.Sign(payloadBytes)
  550. assert.FatalError(t, err)
  551. raw, err := jws.CompactSerialize()
  552. assert.FatalError(t, err)
  553. parsedJWS, err := jose.ParseJWS(raw)
  554. assert.FatalError(t, err)
  555. prov := newACMEProv(t)
  556. prov.RequireEAB = true
  557. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: payloadBytes})
  558. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  559. ctx = acme.NewProvisionerContext(ctx, prov)
  560. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  561. eak := &acme.ExternalAccountKey{
  562. ID: "eakID",
  563. ProvisionerID: provID,
  564. Reference: "testeak",
  565. HmacKey: []byte{1, 3, 3, 7},
  566. CreatedAt: time.Now(),
  567. }
  568. return test{
  569. db: &acme.MockDB{
  570. MockCreateAccount: func(ctx context.Context, acc *acme.Account) error {
  571. acc.ID = "accountID"
  572. assert.Equals(t, acc.Contact, nar.Contact)
  573. assert.Equals(t, acc.Key, jwk)
  574. return nil
  575. },
  576. MockGetExternalAccountKey: func(ctx context.Context, provisionerName, keyID string) (*acme.ExternalAccountKey, error) {
  577. return eak, nil
  578. },
  579. MockUpdateExternalAccountKey: func(ctx context.Context, provisionerName string, eak *acme.ExternalAccountKey) error {
  580. return errors.New("force")
  581. },
  582. },
  583. acc: &acme.Account{
  584. ID: "accountID",
  585. Key: jwk,
  586. Status: acme.StatusValid,
  587. Contact: []string{"foo", "bar"},
  588. OrdersURL: fmt.Sprintf("%s/acme/%s/account/accountID/orders", baseURL.String(), escProvName),
  589. ExternalAccountBinding: eab,
  590. },
  591. ctx: ctx,
  592. statusCode: 500,
  593. err: acme.NewError(acme.ErrorServerInternalType, "error updating external account binding key"),
  594. }
  595. },
  596. "ok/new-account": func(t *testing.T) test {
  597. nar := &NewAccountRequest{
  598. Contact: []string{"foo", "bar"},
  599. }
  600. b, err := json.Marshal(nar)
  601. assert.FatalError(t, err)
  602. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  603. assert.FatalError(t, err)
  604. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: b})
  605. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  606. ctx = acme.NewProvisionerContext(ctx, prov)
  607. return test{
  608. db: &acme.MockDB{
  609. MockCreateAccount: func(ctx context.Context, acc *acme.Account) error {
  610. acc.ID = "accountID"
  611. assert.Equals(t, acc.Contact, nar.Contact)
  612. assert.Equals(t, acc.Key, jwk)
  613. return nil
  614. },
  615. },
  616. acc: &acme.Account{
  617. ID: "accountID",
  618. Key: jwk,
  619. Status: acme.StatusValid,
  620. Contact: []string{"foo", "bar"},
  621. OrdersURL: fmt.Sprintf("%s/acme/%s/account/accountID/orders", baseURL.String(), escProvName),
  622. },
  623. ctx: ctx,
  624. statusCode: 201,
  625. }
  626. },
  627. "ok/return-existing": func(t *testing.T) test {
  628. nar := &NewAccountRequest{
  629. OnlyReturnExisting: true,
  630. }
  631. b, err := json.Marshal(nar)
  632. assert.FatalError(t, err)
  633. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  634. assert.FatalError(t, err)
  635. acc := &acme.Account{
  636. ID: "accountID",
  637. Key: jwk,
  638. Status: acme.StatusValid,
  639. Contact: []string{"foo", "bar"},
  640. }
  641. ctx := acme.NewProvisionerContext(context.Background(), prov)
  642. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  643. ctx = context.WithValue(ctx, accContextKey, acc)
  644. return test{
  645. db: &acme.MockDB{},
  646. ctx: ctx,
  647. acc: acc,
  648. statusCode: 200,
  649. }
  650. },
  651. "ok/new-account-no-eab-required": func(t *testing.T) test {
  652. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  653. assert.FatalError(t, err)
  654. url := fmt.Sprintf("%s/acme/%s/account/new-account", baseURL.String(), escProvName)
  655. rawEABJWS, err := createRawEABJWS(jwk, []byte{1, 3, 3, 7}, "eakID", url)
  656. assert.FatalError(t, err)
  657. eab := &ExternalAccountBinding{}
  658. err = json.Unmarshal(rawEABJWS, &eab)
  659. assert.FatalError(t, err)
  660. nar := &NewAccountRequest{
  661. Contact: []string{"foo", "bar"},
  662. ExternalAccountBinding: eab,
  663. }
  664. b, err := json.Marshal(nar)
  665. assert.FatalError(t, err)
  666. prov := newACMEProv(t)
  667. prov.RequireEAB = false
  668. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: b})
  669. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  670. ctx = acme.NewProvisionerContext(ctx, prov)
  671. return test{
  672. db: &acme.MockDB{
  673. MockCreateAccount: func(ctx context.Context, acc *acme.Account) error {
  674. acc.ID = "accountID"
  675. assert.Equals(t, acc.Contact, nar.Contact)
  676. assert.Equals(t, acc.Key, jwk)
  677. return nil
  678. },
  679. },
  680. acc: &acme.Account{
  681. ID: "accountID",
  682. Key: jwk,
  683. Status: acme.StatusValid,
  684. Contact: []string{"foo", "bar"},
  685. OrdersURL: fmt.Sprintf("%s/acme/%s/account/accountID/orders", baseURL.String(), escProvName),
  686. },
  687. ctx: ctx,
  688. statusCode: 201,
  689. }
  690. },
  691. "ok/new-account-with-eab": func(t *testing.T) test {
  692. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  693. assert.FatalError(t, err)
  694. url := fmt.Sprintf("%s/acme/%s/account/new-account", baseURL.String(), escProvName)
  695. rawEABJWS, err := createRawEABJWS(jwk, []byte{1, 3, 3, 7}, "eakID", url)
  696. assert.FatalError(t, err)
  697. eab := &ExternalAccountBinding{}
  698. err = json.Unmarshal(rawEABJWS, &eab)
  699. assert.FatalError(t, err)
  700. nar := &NewAccountRequest{
  701. Contact: []string{"foo", "bar"},
  702. ExternalAccountBinding: eab,
  703. }
  704. payloadBytes, err := json.Marshal(nar)
  705. assert.FatalError(t, err)
  706. so := new(jose.SignerOptions)
  707. so.WithHeader("alg", jose.SignatureAlgorithm(jwk.Algorithm))
  708. so.WithHeader("url", url)
  709. signer, err := jose.NewSigner(jose.SigningKey{
  710. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  711. Key: jwk.Key,
  712. }, so)
  713. assert.FatalError(t, err)
  714. jws, err := signer.Sign(payloadBytes)
  715. assert.FatalError(t, err)
  716. raw, err := jws.CompactSerialize()
  717. assert.FatalError(t, err)
  718. parsedJWS, err := jose.ParseJWS(raw)
  719. assert.FatalError(t, err)
  720. prov := newACMEProv(t)
  721. prov.RequireEAB = true
  722. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: payloadBytes})
  723. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  724. ctx = acme.NewProvisionerContext(ctx, prov)
  725. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  726. return test{
  727. db: &acme.MockDB{
  728. MockCreateAccount: func(ctx context.Context, acc *acme.Account) error {
  729. acc.ID = "accountID"
  730. assert.Equals(t, acc.Contact, nar.Contact)
  731. assert.Equals(t, acc.Key, jwk)
  732. return nil
  733. },
  734. MockGetExternalAccountKey: func(ctx context.Context, provisionerName, keyID string) (*acme.ExternalAccountKey, error) {
  735. return &acme.ExternalAccountKey{
  736. ID: "eakID",
  737. ProvisionerID: provID,
  738. Reference: "testeak",
  739. HmacKey: []byte{1, 3, 3, 7},
  740. CreatedAt: time.Now(),
  741. }, nil
  742. },
  743. MockUpdateExternalAccountKey: func(ctx context.Context, provisionerName string, eak *acme.ExternalAccountKey) error {
  744. return nil
  745. },
  746. },
  747. acc: &acme.Account{
  748. ID: "accountID",
  749. Key: jwk,
  750. Status: acme.StatusValid,
  751. Contact: []string{"foo", "bar"},
  752. OrdersURL: fmt.Sprintf("%s/acme/%s/account/accountID/orders", baseURL.String(), escProvName),
  753. ExternalAccountBinding: eab,
  754. },
  755. ctx: ctx,
  756. statusCode: 201,
  757. }
  758. },
  759. }
  760. for name, run := range tests {
  761. tc := run(t)
  762. t.Run(name, func(t *testing.T) {
  763. ctx := acme.NewContext(tc.ctx, tc.db, nil, acme.NewLinker("test.ca.smallstep.com", "acme"), nil)
  764. req := httptest.NewRequest("GET", "/foo/bar", nil)
  765. req = req.WithContext(ctx)
  766. w := httptest.NewRecorder()
  767. NewAccount(w, req)
  768. res := w.Result()
  769. assert.Equals(t, res.StatusCode, tc.statusCode)
  770. body, err := io.ReadAll(res.Body)
  771. res.Body.Close()
  772. assert.FatalError(t, err)
  773. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  774. var ae acme.Error
  775. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  776. assert.Equals(t, ae.Type, tc.err.Type)
  777. assert.Equals(t, ae.Detail, tc.err.Detail)
  778. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  779. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  780. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  781. } else {
  782. expB, err := json.Marshal(tc.acc)
  783. assert.FatalError(t, err)
  784. assert.Equals(t, bytes.TrimSpace(body), expB)
  785. assert.Equals(t, res.Header["Location"],
  786. []string{fmt.Sprintf("%s/acme/%s/account/%s", baseURL.String(),
  787. escProvName, "accountID")})
  788. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  789. }
  790. })
  791. }
  792. }
  793. func TestHandler_GetOrUpdateAccount(t *testing.T) {
  794. accID := "accountID"
  795. acc := acme.Account{
  796. ID: accID,
  797. Status: "valid",
  798. OrdersURL: fmt.Sprintf("https://ca.smallstep.com/acme/account/%s/orders", accID),
  799. }
  800. prov := newProv()
  801. escProvName := url.PathEscape(prov.GetName())
  802. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  803. type test struct {
  804. db acme.DB
  805. ctx context.Context
  806. statusCode int
  807. err *acme.Error
  808. }
  809. var tests = map[string]func(t *testing.T) test{
  810. "fail/no-account": func(t *testing.T) test {
  811. return test{
  812. db: &acme.MockDB{},
  813. ctx: context.Background(),
  814. statusCode: 400,
  815. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  816. }
  817. },
  818. "fail/nil-account": func(t *testing.T) test {
  819. ctx := context.WithValue(context.Background(), accContextKey, nil)
  820. return test{
  821. db: &acme.MockDB{},
  822. ctx: ctx,
  823. statusCode: 400,
  824. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  825. }
  826. },
  827. "fail/no-payload": func(t *testing.T) test {
  828. ctx := context.WithValue(context.Background(), accContextKey, &acc)
  829. return test{
  830. db: &acme.MockDB{},
  831. ctx: ctx,
  832. statusCode: 500,
  833. err: acme.NewErrorISE("payload expected in request context"),
  834. }
  835. },
  836. "fail/nil-payload": func(t *testing.T) test {
  837. ctx := context.WithValue(context.Background(), accContextKey, &acc)
  838. ctx = context.WithValue(ctx, payloadContextKey, nil)
  839. return test{
  840. db: &acme.MockDB{},
  841. ctx: ctx,
  842. statusCode: 500,
  843. err: acme.NewErrorISE("payload expected in request context"),
  844. }
  845. },
  846. "fail/unmarshal-payload-error": func(t *testing.T) test {
  847. ctx := context.WithValue(context.Background(), accContextKey, &acc)
  848. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{})
  849. return test{
  850. db: &acme.MockDB{},
  851. ctx: ctx,
  852. statusCode: 400,
  853. err: acme.NewError(acme.ErrorMalformedType, "failed to unmarshal new-account request payload: unexpected end of JSON input"),
  854. }
  855. },
  856. "fail/malformed-payload-error": func(t *testing.T) test {
  857. uar := &UpdateAccountRequest{
  858. Contact: []string{"foo", ""},
  859. }
  860. b, err := json.Marshal(uar)
  861. assert.FatalError(t, err)
  862. ctx := context.WithValue(context.Background(), accContextKey, &acc)
  863. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  864. return test{
  865. db: &acme.MockDB{},
  866. ctx: ctx,
  867. statusCode: 400,
  868. err: acme.NewError(acme.ErrorMalformedType, "contact cannot be empty string"),
  869. }
  870. },
  871. "fail/db.UpdateAccount-error": func(t *testing.T) test {
  872. uar := &UpdateAccountRequest{
  873. Status: "deactivated",
  874. }
  875. b, err := json.Marshal(uar)
  876. assert.FatalError(t, err)
  877. ctx := context.WithValue(context.Background(), accContextKey, &acc)
  878. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  879. return test{
  880. db: &acme.MockDB{
  881. MockUpdateAccount: func(ctx context.Context, upd *acme.Account) error {
  882. assert.Equals(t, upd.Status, acme.StatusDeactivated)
  883. assert.Equals(t, upd.ID, acc.ID)
  884. return acme.NewErrorISE("force")
  885. },
  886. },
  887. ctx: ctx,
  888. statusCode: 500,
  889. err: acme.NewErrorISE("force"),
  890. }
  891. },
  892. "ok/deactivate": func(t *testing.T) test {
  893. uar := &UpdateAccountRequest{
  894. Status: "deactivated",
  895. }
  896. b, err := json.Marshal(uar)
  897. assert.FatalError(t, err)
  898. ctx := acme.NewProvisionerContext(context.Background(), prov)
  899. ctx = context.WithValue(ctx, accContextKey, &acc)
  900. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  901. return test{
  902. db: &acme.MockDB{
  903. MockUpdateAccount: func(ctx context.Context, upd *acme.Account) error {
  904. assert.Equals(t, upd.Status, acme.StatusDeactivated)
  905. assert.Equals(t, upd.ID, acc.ID)
  906. return nil
  907. },
  908. },
  909. ctx: ctx,
  910. statusCode: 200,
  911. }
  912. },
  913. "ok/update-empty": func(t *testing.T) test {
  914. uar := &UpdateAccountRequest{}
  915. b, err := json.Marshal(uar)
  916. assert.FatalError(t, err)
  917. ctx := acme.NewProvisionerContext(context.Background(), prov)
  918. ctx = context.WithValue(ctx, accContextKey, &acc)
  919. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  920. return test{
  921. db: &acme.MockDB{},
  922. ctx: ctx,
  923. statusCode: 200,
  924. }
  925. },
  926. "ok/update-contacts": func(t *testing.T) test {
  927. uar := &UpdateAccountRequest{
  928. Contact: []string{"foo", "bar"},
  929. }
  930. b, err := json.Marshal(uar)
  931. assert.FatalError(t, err)
  932. ctx := acme.NewProvisionerContext(context.Background(), prov)
  933. ctx = context.WithValue(ctx, accContextKey, &acc)
  934. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  935. return test{
  936. db: &acme.MockDB{
  937. MockUpdateAccount: func(ctx context.Context, upd *acme.Account) error {
  938. assert.Equals(t, upd.Contact, uar.Contact)
  939. assert.Equals(t, upd.ID, acc.ID)
  940. return nil
  941. },
  942. },
  943. ctx: ctx,
  944. statusCode: 200,
  945. }
  946. },
  947. "ok/post-as-get": func(t *testing.T) test {
  948. ctx := acme.NewProvisionerContext(context.Background(), prov)
  949. ctx = context.WithValue(ctx, accContextKey, &acc)
  950. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isPostAsGet: true})
  951. return test{
  952. db: &acme.MockDB{},
  953. ctx: ctx,
  954. statusCode: 200,
  955. }
  956. },
  957. }
  958. for name, run := range tests {
  959. tc := run(t)
  960. t.Run(name, func(t *testing.T) {
  961. ctx := acme.NewContext(tc.ctx, tc.db, nil, acme.NewLinker("test.ca.smallstep.com", "acme"), nil)
  962. req := httptest.NewRequest("GET", "/foo/bar", nil)
  963. req = req.WithContext(ctx)
  964. w := httptest.NewRecorder()
  965. GetOrUpdateAccount(w, req)
  966. res := w.Result()
  967. assert.Equals(t, res.StatusCode, tc.statusCode)
  968. body, err := io.ReadAll(res.Body)
  969. res.Body.Close()
  970. assert.FatalError(t, err)
  971. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  972. var ae acme.Error
  973. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  974. assert.Equals(t, ae.Type, tc.err.Type)
  975. assert.Equals(t, ae.Detail, tc.err.Detail)
  976. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  977. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  978. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  979. } else {
  980. expB, err := json.Marshal(acc)
  981. assert.FatalError(t, err)
  982. assert.Equals(t, bytes.TrimSpace(body), expB)
  983. assert.Equals(t, res.Header["Location"],
  984. []string{fmt.Sprintf("%s/acme/%s/account/%s", baseURL.String(),
  985. escProvName, accID)})
  986. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  987. }
  988. })
  989. }
  990. }