account_test.go 33 KB

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