account_test.go 33 KB

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