account_test.go 32 KB

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