account_test.go 33 KB

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