account_test.go 33 KB

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