account_test.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  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(ctx context.Context, identifier provisioner.ACMEIdentifier) error {
  31. return nil
  32. }
  33. func (*fakeProvisioner) AuthorizeSign(ctx context.Context, token string) ([]provisioner.SignOption, error) {
  34. return nil, nil
  35. }
  36. func (*fakeProvisioner) IsChallengeEnabled(ctx context.Context, challenge provisioner.ACMEChallenge) bool {
  37. return true
  38. }
  39. func (*fakeProvisioner) IsAttestationFormatEnabled(ctx context.Context, format provisioner.ACMEAttestationFormat) bool {
  40. return true
  41. }
  42. func (*fakeProvisioner) GetAttestationRoots() (*x509.CertPool, bool) {
  43. return nil, false
  44. }
  45. func (*fakeProvisioner) AuthorizeRevoke(ctx context.Context, token 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 newProvWithOptions(options *provisioner.Options) acme.Provisioner {
  62. // Initialize provisioners
  63. p := &provisioner.ACME{
  64. Type: "ACME",
  65. Name: "test@acme-<test>provisioner.com",
  66. Options: options,
  67. }
  68. if err := p.Init(provisioner.Config{Claims: globalProvisionerClaims}); err != nil {
  69. fmt.Printf("%v", err)
  70. }
  71. return p
  72. }
  73. func newACMEProv(t *testing.T) *provisioner.ACME {
  74. p := newProv()
  75. a, ok := p.(*provisioner.ACME)
  76. if !ok {
  77. t.Fatal("not a valid ACME provisioner")
  78. }
  79. return a
  80. }
  81. func newACMEProvWithOptions(t *testing.T, options *provisioner.Options) *provisioner.ACME {
  82. p := newProvWithOptions(options)
  83. a, ok := p.(*provisioner.ACME)
  84. if !ok {
  85. t.Fatal("not a valid ACME provisioner")
  86. }
  87. return a
  88. }
  89. func createEABJWS(jwk *jose.JSONWebKey, hmacKey []byte, keyID, u string) (*jose.JSONWebSignature, error) {
  90. signer, err := jose.NewSigner(
  91. jose.SigningKey{
  92. Algorithm: jose.SignatureAlgorithm("HS256"),
  93. Key: hmacKey,
  94. },
  95. &jose.SignerOptions{
  96. ExtraHeaders: map[jose.HeaderKey]interface{}{
  97. "kid": keyID,
  98. "url": u,
  99. },
  100. EmbedJWK: false,
  101. },
  102. )
  103. if err != nil {
  104. return nil, err
  105. }
  106. jwkJSONBytes, err := jwk.Public().MarshalJSON()
  107. if err != nil {
  108. return nil, err
  109. }
  110. jws, err := signer.Sign(jwkJSONBytes)
  111. if err != nil {
  112. return nil, err
  113. }
  114. raw, err := jws.CompactSerialize()
  115. if err != nil {
  116. return nil, err
  117. }
  118. parsedJWS, err := jose.ParseJWS(raw)
  119. if err != nil {
  120. return nil, err
  121. }
  122. return parsedJWS, nil
  123. }
  124. func createRawEABJWS(jwk *jose.JSONWebKey, hmacKey []byte, keyID, u string) ([]byte, error) {
  125. jws, err := createEABJWS(jwk, hmacKey, keyID, u)
  126. if err != nil {
  127. return nil, err
  128. }
  129. rawJWS := jws.FullSerialize()
  130. return []byte(rawJWS), nil
  131. }
  132. func TestNewAccountRequest_Validate(t *testing.T) {
  133. type test struct {
  134. nar *NewAccountRequest
  135. err *acme.Error
  136. }
  137. var tests = map[string]func(t *testing.T) test{
  138. "fail/incompatible-input": func(t *testing.T) test {
  139. return test{
  140. nar: &NewAccountRequest{
  141. OnlyReturnExisting: true,
  142. Contact: []string{"foo", "bar"},
  143. },
  144. err: acme.NewError(acme.ErrorMalformedType, "incompatible input; onlyReturnExisting must be alone"),
  145. }
  146. },
  147. "fail/bad-contact": func(t *testing.T) test {
  148. return test{
  149. nar: &NewAccountRequest{
  150. Contact: []string{"foo", ""},
  151. },
  152. err: acme.NewError(acme.ErrorMalformedType, "contact cannot be empty string"),
  153. }
  154. },
  155. "ok": func(t *testing.T) test {
  156. return test{
  157. nar: &NewAccountRequest{
  158. Contact: []string{"foo", "bar"},
  159. },
  160. }
  161. },
  162. "ok/onlyReturnExisting": func(t *testing.T) test {
  163. return test{
  164. nar: &NewAccountRequest{
  165. OnlyReturnExisting: true,
  166. },
  167. }
  168. },
  169. }
  170. for name, run := range tests {
  171. tc := run(t)
  172. t.Run(name, func(t *testing.T) {
  173. if err := tc.nar.Validate(); err != nil {
  174. if assert.NotNil(t, err) {
  175. var ae *acme.Error
  176. if assert.True(t, errors.As(err, &ae)) {
  177. assert.HasPrefix(t, ae.Error(), tc.err.Error())
  178. assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
  179. assert.Equals(t, ae.Type, tc.err.Type)
  180. }
  181. }
  182. } else {
  183. assert.Nil(t, tc.err)
  184. }
  185. })
  186. }
  187. }
  188. func TestUpdateAccountRequest_Validate(t *testing.T) {
  189. type test struct {
  190. uar *UpdateAccountRequest
  191. err *acme.Error
  192. }
  193. var tests = map[string]func(t *testing.T) test{
  194. "fail/incompatible-input": func(t *testing.T) test {
  195. return test{
  196. uar: &UpdateAccountRequest{
  197. Contact: []string{"foo", "bar"},
  198. Status: "foo",
  199. },
  200. err: acme.NewError(acme.ErrorMalformedType, "incompatible input; "+
  201. "contact and status updates are mutually exclusive"),
  202. }
  203. },
  204. "fail/bad-contact": func(t *testing.T) test {
  205. return test{
  206. uar: &UpdateAccountRequest{
  207. Contact: []string{"foo", ""},
  208. },
  209. err: acme.NewError(acme.ErrorMalformedType, "contact cannot be empty string"),
  210. }
  211. },
  212. "fail/bad-status": func(t *testing.T) test {
  213. return test{
  214. uar: &UpdateAccountRequest{
  215. Status: "foo",
  216. },
  217. err: acme.NewError(acme.ErrorMalformedType, "cannot update account "+
  218. "status to foo, only deactivated"),
  219. }
  220. },
  221. "ok/contact": func(t *testing.T) test {
  222. return test{
  223. uar: &UpdateAccountRequest{
  224. Contact: []string{"foo", "bar"},
  225. },
  226. }
  227. },
  228. "ok/status": func(t *testing.T) test {
  229. return test{
  230. uar: &UpdateAccountRequest{
  231. Status: "deactivated",
  232. },
  233. }
  234. },
  235. "ok/accept-empty": func(t *testing.T) test {
  236. return test{
  237. uar: &UpdateAccountRequest{},
  238. }
  239. },
  240. }
  241. for name, run := range tests {
  242. tc := run(t)
  243. t.Run(name, func(t *testing.T) {
  244. if err := tc.uar.Validate(); err != nil {
  245. if assert.NotNil(t, err) {
  246. var ae *acme.Error
  247. if assert.True(t, errors.As(err, &ae)) {
  248. assert.HasPrefix(t, ae.Error(), tc.err.Error())
  249. assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
  250. assert.Equals(t, ae.Type, tc.err.Type)
  251. }
  252. }
  253. } else {
  254. assert.Nil(t, tc.err)
  255. }
  256. })
  257. }
  258. }
  259. func TestHandler_GetOrdersByAccountID(t *testing.T) {
  260. accID := "account-id"
  261. // Request with chi context
  262. chiCtx := chi.NewRouteContext()
  263. chiCtx.URLParams.Add("accID", accID)
  264. prov := newProv()
  265. provName := url.PathEscape(prov.GetName())
  266. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  267. u := fmt.Sprintf("http://ca.smallstep.com/acme/%s/account/%s/orders", provName, accID)
  268. oids := []string{"foo", "bar"}
  269. oidURLs := []string{
  270. fmt.Sprintf("%s/acme/%s/order/foo", baseURL.String(), provName),
  271. fmt.Sprintf("%s/acme/%s/order/bar", baseURL.String(), provName),
  272. }
  273. type test struct {
  274. db acme.DB
  275. ctx context.Context
  276. statusCode int
  277. err *acme.Error
  278. }
  279. var tests = map[string]func(t *testing.T) test{
  280. "fail/no-account": func(t *testing.T) test {
  281. return test{
  282. db: &acme.MockDB{},
  283. ctx: context.Background(),
  284. statusCode: 400,
  285. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  286. }
  287. },
  288. "fail/nil-account": func(t *testing.T) test {
  289. return test{
  290. db: &acme.MockDB{},
  291. ctx: context.WithValue(context.Background(), accContextKey, nil),
  292. statusCode: 400,
  293. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  294. }
  295. },
  296. "fail/account-id-mismatch": func(t *testing.T) test {
  297. acc := &acme.Account{ID: "foo"}
  298. ctx := context.WithValue(context.Background(), accContextKey, acc)
  299. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  300. return test{
  301. db: &acme.MockDB{},
  302. ctx: ctx,
  303. statusCode: 401,
  304. err: acme.NewError(acme.ErrorUnauthorizedType, "account ID does not match url param"),
  305. }
  306. },
  307. "fail/db.GetOrdersByAccountID-error": func(t *testing.T) test {
  308. acc := &acme.Account{ID: accID}
  309. ctx := context.WithValue(context.Background(), accContextKey, acc)
  310. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  311. return test{
  312. db: &acme.MockDB{
  313. MockError: acme.NewErrorISE("force"),
  314. },
  315. ctx: ctx,
  316. statusCode: 500,
  317. err: acme.NewErrorISE("force"),
  318. }
  319. },
  320. "ok": func(t *testing.T) test {
  321. acc := &acme.Account{ID: accID}
  322. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  323. ctx = acme.NewProvisionerContext(ctx, prov)
  324. ctx = context.WithValue(ctx, accContextKey, acc)
  325. return test{
  326. db: &acme.MockDB{
  327. MockGetOrdersByAccountID: func(ctx context.Context, id string) ([]string, error) {
  328. assert.Equals(t, id, acc.ID)
  329. return oids, nil
  330. },
  331. },
  332. ctx: ctx,
  333. statusCode: 200,
  334. }
  335. },
  336. }
  337. for name, run := range tests {
  338. tc := run(t)
  339. t.Run(name, func(t *testing.T) {
  340. ctx := acme.NewContext(tc.ctx, tc.db, nil, acme.NewLinker("test.ca.smallstep.com", "acme"), nil)
  341. req := httptest.NewRequest("GET", u, nil)
  342. req = req.WithContext(ctx)
  343. w := httptest.NewRecorder()
  344. GetOrdersByAccountID(w, req)
  345. res := w.Result()
  346. assert.Equals(t, res.StatusCode, tc.statusCode)
  347. body, err := io.ReadAll(res.Body)
  348. res.Body.Close()
  349. assert.FatalError(t, err)
  350. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  351. var ae acme.Error
  352. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  353. assert.Equals(t, ae.Type, tc.err.Type)
  354. assert.Equals(t, ae.Detail, tc.err.Detail)
  355. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  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", nil)
  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.Identifier, tc.err.Identifier)
  790. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  791. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  792. } else {
  793. expB, err := json.Marshal(tc.acc)
  794. assert.FatalError(t, err)
  795. assert.Equals(t, bytes.TrimSpace(body), expB)
  796. assert.Equals(t, res.Header["Location"],
  797. []string{fmt.Sprintf("%s/acme/%s/account/%s", baseURL.String(),
  798. escProvName, "accountID")})
  799. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  800. }
  801. })
  802. }
  803. }
  804. func TestHandler_GetOrUpdateAccount(t *testing.T) {
  805. accID := "accountID"
  806. acc := acme.Account{
  807. ID: accID,
  808. Status: "valid",
  809. OrdersURL: fmt.Sprintf("https://ca.smallstep.com/acme/account/%s/orders", accID),
  810. }
  811. prov := newProv()
  812. escProvName := url.PathEscape(prov.GetName())
  813. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  814. type test struct {
  815. db acme.DB
  816. ctx context.Context
  817. statusCode int
  818. err *acme.Error
  819. }
  820. var tests = map[string]func(t *testing.T) test{
  821. "fail/no-account": func(t *testing.T) test {
  822. return test{
  823. db: &acme.MockDB{},
  824. ctx: context.Background(),
  825. statusCode: 400,
  826. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  827. }
  828. },
  829. "fail/nil-account": func(t *testing.T) test {
  830. ctx := context.WithValue(context.Background(), accContextKey, nil)
  831. return test{
  832. db: &acme.MockDB{},
  833. ctx: ctx,
  834. statusCode: 400,
  835. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  836. }
  837. },
  838. "fail/no-payload": func(t *testing.T) test {
  839. ctx := context.WithValue(context.Background(), accContextKey, &acc)
  840. return test{
  841. db: &acme.MockDB{},
  842. ctx: ctx,
  843. statusCode: 500,
  844. err: acme.NewErrorISE("payload expected in request context"),
  845. }
  846. },
  847. "fail/nil-payload": func(t *testing.T) test {
  848. ctx := context.WithValue(context.Background(), accContextKey, &acc)
  849. ctx = context.WithValue(ctx, payloadContextKey, nil)
  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/unmarshal-payload-error": func(t *testing.T) test {
  858. ctx := context.WithValue(context.Background(), accContextKey, &acc)
  859. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{})
  860. return test{
  861. db: &acme.MockDB{},
  862. ctx: ctx,
  863. statusCode: 400,
  864. err: acme.NewError(acme.ErrorMalformedType, "failed to unmarshal new-account request payload: unexpected end of JSON input"),
  865. }
  866. },
  867. "fail/malformed-payload-error": func(t *testing.T) test {
  868. uar := &UpdateAccountRequest{
  869. Contact: []string{"foo", ""},
  870. }
  871. b, err := json.Marshal(uar)
  872. assert.FatalError(t, err)
  873. ctx := context.WithValue(context.Background(), accContextKey, &acc)
  874. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  875. return test{
  876. db: &acme.MockDB{},
  877. ctx: ctx,
  878. statusCode: 400,
  879. err: acme.NewError(acme.ErrorMalformedType, "contact cannot be empty string"),
  880. }
  881. },
  882. "fail/db.UpdateAccount-error": func(t *testing.T) test {
  883. uar := &UpdateAccountRequest{
  884. Status: "deactivated",
  885. }
  886. b, err := json.Marshal(uar)
  887. assert.FatalError(t, err)
  888. ctx := context.WithValue(context.Background(), accContextKey, &acc)
  889. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  890. return test{
  891. db: &acme.MockDB{
  892. MockUpdateAccount: func(ctx context.Context, upd *acme.Account) error {
  893. assert.Equals(t, upd.Status, acme.StatusDeactivated)
  894. assert.Equals(t, upd.ID, acc.ID)
  895. return acme.NewErrorISE("force")
  896. },
  897. },
  898. ctx: ctx,
  899. statusCode: 500,
  900. err: acme.NewErrorISE("force"),
  901. }
  902. },
  903. "ok/deactivate": func(t *testing.T) test {
  904. uar := &UpdateAccountRequest{
  905. Status: "deactivated",
  906. }
  907. b, err := json.Marshal(uar)
  908. assert.FatalError(t, err)
  909. ctx := acme.NewProvisionerContext(context.Background(), prov)
  910. ctx = context.WithValue(ctx, accContextKey, &acc)
  911. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  912. return test{
  913. db: &acme.MockDB{
  914. MockUpdateAccount: func(ctx context.Context, upd *acme.Account) error {
  915. assert.Equals(t, upd.Status, acme.StatusDeactivated)
  916. assert.Equals(t, upd.ID, acc.ID)
  917. return nil
  918. },
  919. },
  920. ctx: ctx,
  921. statusCode: 200,
  922. }
  923. },
  924. "ok/update-empty": func(t *testing.T) test {
  925. uar := &UpdateAccountRequest{}
  926. b, err := json.Marshal(uar)
  927. assert.FatalError(t, err)
  928. ctx := acme.NewProvisionerContext(context.Background(), prov)
  929. ctx = context.WithValue(ctx, accContextKey, &acc)
  930. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  931. return test{
  932. db: &acme.MockDB{},
  933. ctx: ctx,
  934. statusCode: 200,
  935. }
  936. },
  937. "ok/update-contacts": func(t *testing.T) test {
  938. uar := &UpdateAccountRequest{
  939. Contact: []string{"foo", "bar"},
  940. }
  941. b, err := json.Marshal(uar)
  942. assert.FatalError(t, err)
  943. ctx := acme.NewProvisionerContext(context.Background(), prov)
  944. ctx = context.WithValue(ctx, accContextKey, &acc)
  945. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  946. return test{
  947. db: &acme.MockDB{
  948. MockUpdateAccount: func(ctx context.Context, upd *acme.Account) error {
  949. assert.Equals(t, upd.Contact, uar.Contact)
  950. assert.Equals(t, upd.ID, acc.ID)
  951. return nil
  952. },
  953. },
  954. ctx: ctx,
  955. statusCode: 200,
  956. }
  957. },
  958. "ok/post-as-get": func(t *testing.T) test {
  959. ctx := acme.NewProvisionerContext(context.Background(), prov)
  960. ctx = context.WithValue(ctx, accContextKey, &acc)
  961. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isPostAsGet: true})
  962. return test{
  963. db: &acme.MockDB{},
  964. ctx: ctx,
  965. statusCode: 200,
  966. }
  967. },
  968. }
  969. for name, run := range tests {
  970. tc := run(t)
  971. t.Run(name, func(t *testing.T) {
  972. ctx := acme.NewContext(tc.ctx, tc.db, nil, acme.NewLinker("test.ca.smallstep.com", "acme"), nil)
  973. req := httptest.NewRequest("GET", "/foo/bar", nil)
  974. req = req.WithContext(ctx)
  975. w := httptest.NewRecorder()
  976. GetOrUpdateAccount(w, req)
  977. res := w.Result()
  978. assert.Equals(t, res.StatusCode, tc.statusCode)
  979. body, err := io.ReadAll(res.Body)
  980. res.Body.Close()
  981. assert.FatalError(t, err)
  982. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  983. var ae acme.Error
  984. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  985. assert.Equals(t, ae.Type, tc.err.Type)
  986. assert.Equals(t, ae.Detail, tc.err.Detail)
  987. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  988. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  989. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  990. } else {
  991. expB, err := json.Marshal(acc)
  992. assert.FatalError(t, err)
  993. assert.Equals(t, bytes.TrimSpace(body), expB)
  994. assert.Equals(t, res.Header["Location"],
  995. []string{fmt.Sprintf("%s/acme/%s/account/%s", baseURL.String(),
  996. escProvName, accID)})
  997. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  998. }
  999. })
  1000. }
  1001. }