account_test.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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.Subproblems, tc.err.Subproblems)
  356. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  357. } else {
  358. expB, err := json.Marshal(oidURLs)
  359. assert.FatalError(t, err)
  360. assert.Equals(t, bytes.TrimSpace(body), expB)
  361. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  362. }
  363. })
  364. }
  365. }
  366. func TestHandler_NewAccount(t *testing.T) {
  367. prov := newProv()
  368. escProvName := url.PathEscape(prov.GetName())
  369. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  370. provID := prov.GetID()
  371. type test struct {
  372. db acme.DB
  373. acc *acme.Account
  374. ctx context.Context
  375. statusCode int
  376. err *acme.Error
  377. }
  378. var tests = map[string]func(t *testing.T) test{
  379. "fail/no-payload": func(t *testing.T) test {
  380. return test{
  381. db: &acme.MockDB{},
  382. ctx: context.Background(),
  383. statusCode: 500,
  384. err: acme.NewErrorISE("payload expected in request context"),
  385. }
  386. },
  387. "fail/nil-payload": func(t *testing.T) test {
  388. ctx := context.WithValue(context.Background(), payloadContextKey, nil)
  389. return test{
  390. db: &acme.MockDB{},
  391. ctx: ctx,
  392. statusCode: 500,
  393. err: acme.NewErrorISE("payload expected in request context"),
  394. }
  395. },
  396. "fail/unmarshal-payload-error": func(t *testing.T) test {
  397. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{})
  398. return test{
  399. db: &acme.MockDB{},
  400. ctx: ctx,
  401. statusCode: 400,
  402. err: acme.NewError(acme.ErrorMalformedType, "failed to "+
  403. "unmarshal new-account request payload: unexpected end of JSON input"),
  404. }
  405. },
  406. "fail/malformed-payload-error": func(t *testing.T) test {
  407. nar := &NewAccountRequest{
  408. Contact: []string{"foo", ""},
  409. }
  410. b, err := json.Marshal(nar)
  411. assert.FatalError(t, err)
  412. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: b})
  413. return test{
  414. db: &acme.MockDB{},
  415. ctx: ctx,
  416. statusCode: 400,
  417. err: acme.NewError(acme.ErrorMalformedType, "contact cannot be empty string"),
  418. }
  419. },
  420. "fail/no-existing-account": func(t *testing.T) test {
  421. nar := &NewAccountRequest{
  422. OnlyReturnExisting: true,
  423. }
  424. b, err := json.Marshal(nar)
  425. assert.FatalError(t, err)
  426. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: b})
  427. ctx = acme.NewProvisionerContext(ctx, prov)
  428. return test{
  429. db: &acme.MockDB{},
  430. ctx: ctx,
  431. statusCode: 400,
  432. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  433. }
  434. },
  435. "fail/no-jwk": func(t *testing.T) test {
  436. nar := &NewAccountRequest{
  437. Contact: []string{"foo", "bar"},
  438. }
  439. b, err := json.Marshal(nar)
  440. assert.FatalError(t, err)
  441. ctx := acme.NewProvisionerContext(context.Background(), prov)
  442. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  443. return test{
  444. db: &acme.MockDB{},
  445. ctx: ctx,
  446. statusCode: 500,
  447. err: acme.NewErrorISE("jwk expected in request context"),
  448. }
  449. },
  450. "fail/nil-jwk": func(t *testing.T) test {
  451. nar := &NewAccountRequest{
  452. Contact: []string{"foo", "bar"},
  453. }
  454. b, err := json.Marshal(nar)
  455. assert.FatalError(t, err)
  456. ctx := acme.NewProvisionerContext(context.Background(), prov)
  457. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  458. ctx = context.WithValue(ctx, jwkContextKey, nil)
  459. return test{
  460. db: &acme.MockDB{},
  461. ctx: ctx,
  462. statusCode: 500,
  463. err: acme.NewErrorISE("jwk expected in request context"),
  464. }
  465. },
  466. "fail/new-account-no-eab-provided": func(t *testing.T) test {
  467. nar := &NewAccountRequest{
  468. Contact: []string{"foo", "bar"},
  469. ExternalAccountBinding: nil,
  470. }
  471. b, err := json.Marshal(nar)
  472. assert.FatalError(t, err)
  473. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  474. assert.FatalError(t, err)
  475. prov := newACMEProv(t)
  476. prov.RequireEAB = true
  477. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: b})
  478. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  479. ctx = acme.NewProvisionerContext(ctx, prov)
  480. return test{
  481. db: &acme.MockDB{},
  482. ctx: ctx,
  483. statusCode: 400,
  484. err: acme.NewError(acme.ErrorExternalAccountRequiredType, "no external account binding provided"),
  485. }
  486. },
  487. "fail/db.CreateAccount-error": func(t *testing.T) test {
  488. nar := &NewAccountRequest{
  489. Contact: []string{"foo", "bar"},
  490. }
  491. b, err := json.Marshal(nar)
  492. assert.FatalError(t, err)
  493. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  494. assert.FatalError(t, err)
  495. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: b})
  496. ctx = acme.NewProvisionerContext(ctx, prov)
  497. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  498. return test{
  499. db: &acme.MockDB{
  500. MockCreateAccount: func(ctx context.Context, acc *acme.Account) error {
  501. assert.Equals(t, acc.Contact, nar.Contact)
  502. assert.Equals(t, acc.Key, jwk)
  503. return acme.NewErrorISE("force")
  504. },
  505. },
  506. ctx: ctx,
  507. statusCode: 500,
  508. err: acme.NewErrorISE("force"),
  509. }
  510. },
  511. "fail/acmeProvisionerFromContext": func(t *testing.T) test {
  512. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  513. assert.FatalError(t, err)
  514. url := fmt.Sprintf("%s/acme/%s/account/new-account", baseURL.String(), escProvName)
  515. rawEABJWS, err := createRawEABJWS(jwk, []byte{1, 3, 3, 7}, "eakID", url)
  516. assert.FatalError(t, err)
  517. eab := &ExternalAccountBinding{}
  518. err = json.Unmarshal(rawEABJWS, &eab)
  519. assert.FatalError(t, err)
  520. nar := &NewAccountRequest{
  521. Contact: []string{"foo", "bar"},
  522. ExternalAccountBinding: eab,
  523. }
  524. b, err := json.Marshal(nar)
  525. assert.FatalError(t, err)
  526. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: b})
  527. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  528. ctx = acme.NewProvisionerContext(ctx, &fakeProvisioner{})
  529. return test{
  530. db: &acme.MockDB{},
  531. ctx: ctx,
  532. statusCode: 500,
  533. err: acme.NewError(acme.ErrorServerInternalType, "provisioner in context is not an ACME provisioner"),
  534. }
  535. },
  536. "fail/db.UpdateExternalAccountKey-error": func(t *testing.T) test {
  537. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  538. assert.FatalError(t, err)
  539. url := fmt.Sprintf("%s/acme/%s/account/new-account", baseURL.String(), escProvName)
  540. rawEABJWS, err := createRawEABJWS(jwk, []byte{1, 3, 3, 7}, "eakID", url)
  541. assert.FatalError(t, err)
  542. eab := &ExternalAccountBinding{}
  543. err = json.Unmarshal(rawEABJWS, &eab)
  544. assert.FatalError(t, err)
  545. nar := &NewAccountRequest{
  546. Contact: []string{"foo", "bar"},
  547. ExternalAccountBinding: eab,
  548. }
  549. payloadBytes, err := json.Marshal(nar)
  550. assert.FatalError(t, err)
  551. so := new(jose.SignerOptions)
  552. so.WithHeader("alg", jose.SignatureAlgorithm(jwk.Algorithm))
  553. so.WithHeader("url", url)
  554. signer, err := jose.NewSigner(jose.SigningKey{
  555. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  556. Key: jwk.Key,
  557. }, so)
  558. assert.FatalError(t, err)
  559. jws, err := signer.Sign(payloadBytes)
  560. assert.FatalError(t, err)
  561. raw, err := jws.CompactSerialize()
  562. assert.FatalError(t, err)
  563. parsedJWS, err := jose.ParseJWS(raw)
  564. assert.FatalError(t, err)
  565. prov := newACMEProv(t)
  566. prov.RequireEAB = true
  567. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: payloadBytes})
  568. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  569. ctx = acme.NewProvisionerContext(ctx, prov)
  570. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  571. eak := &acme.ExternalAccountKey{
  572. ID: "eakID",
  573. ProvisionerID: provID,
  574. Reference: "testeak",
  575. HmacKey: []byte{1, 3, 3, 7},
  576. CreatedAt: time.Now(),
  577. }
  578. return test{
  579. db: &acme.MockDB{
  580. MockCreateAccount: func(ctx context.Context, acc *acme.Account) error {
  581. acc.ID = "accountID"
  582. assert.Equals(t, acc.Contact, nar.Contact)
  583. assert.Equals(t, acc.Key, jwk)
  584. return nil
  585. },
  586. MockGetExternalAccountKey: func(ctx context.Context, provisionerName, keyID string) (*acme.ExternalAccountKey, error) {
  587. return eak, nil
  588. },
  589. MockUpdateExternalAccountKey: func(ctx context.Context, provisionerName string, eak *acme.ExternalAccountKey) error {
  590. return errors.New("force")
  591. },
  592. },
  593. acc: &acme.Account{
  594. ID: "accountID",
  595. Key: jwk,
  596. Status: acme.StatusValid,
  597. Contact: []string{"foo", "bar"},
  598. OrdersURL: fmt.Sprintf("%s/acme/%s/account/accountID/orders", baseURL.String(), escProvName),
  599. ExternalAccountBinding: eab,
  600. },
  601. ctx: ctx,
  602. statusCode: 500,
  603. err: acme.NewError(acme.ErrorServerInternalType, "error updating external account binding key"),
  604. }
  605. },
  606. "ok/new-account": func(t *testing.T) test {
  607. nar := &NewAccountRequest{
  608. Contact: []string{"foo", "bar"},
  609. }
  610. b, err := json.Marshal(nar)
  611. assert.FatalError(t, err)
  612. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  613. assert.FatalError(t, err)
  614. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: b})
  615. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  616. ctx = acme.NewProvisionerContext(ctx, prov)
  617. return test{
  618. db: &acme.MockDB{
  619. MockCreateAccount: func(ctx context.Context, acc *acme.Account) error {
  620. acc.ID = "accountID"
  621. assert.Equals(t, acc.Contact, nar.Contact)
  622. assert.Equals(t, acc.Key, jwk)
  623. return nil
  624. },
  625. },
  626. acc: &acme.Account{
  627. ID: "accountID",
  628. Key: jwk,
  629. Status: acme.StatusValid,
  630. Contact: []string{"foo", "bar"},
  631. OrdersURL: fmt.Sprintf("%s/acme/%s/account/accountID/orders", baseURL.String(), escProvName),
  632. },
  633. ctx: ctx,
  634. statusCode: 201,
  635. }
  636. },
  637. "ok/return-existing": func(t *testing.T) test {
  638. nar := &NewAccountRequest{
  639. OnlyReturnExisting: true,
  640. }
  641. b, err := json.Marshal(nar)
  642. assert.FatalError(t, err)
  643. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  644. assert.FatalError(t, err)
  645. acc := &acme.Account{
  646. ID: "accountID",
  647. Key: jwk,
  648. Status: acme.StatusValid,
  649. Contact: []string{"foo", "bar"},
  650. }
  651. ctx := acme.NewProvisionerContext(context.Background(), prov)
  652. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  653. ctx = context.WithValue(ctx, accContextKey, acc)
  654. return test{
  655. db: &acme.MockDB{},
  656. ctx: ctx,
  657. acc: acc,
  658. statusCode: 200,
  659. }
  660. },
  661. "ok/new-account-no-eab-required": func(t *testing.T) test {
  662. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  663. assert.FatalError(t, err)
  664. url := fmt.Sprintf("%s/acme/%s/account/new-account", baseURL.String(), escProvName)
  665. rawEABJWS, err := createRawEABJWS(jwk, []byte{1, 3, 3, 7}, "eakID", url)
  666. assert.FatalError(t, err)
  667. eab := &ExternalAccountBinding{}
  668. err = json.Unmarshal(rawEABJWS, &eab)
  669. assert.FatalError(t, err)
  670. nar := &NewAccountRequest{
  671. Contact: []string{"foo", "bar"},
  672. ExternalAccountBinding: eab,
  673. }
  674. b, err := json.Marshal(nar)
  675. assert.FatalError(t, err)
  676. prov := newACMEProv(t)
  677. prov.RequireEAB = false
  678. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: b})
  679. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  680. ctx = acme.NewProvisionerContext(ctx, prov)
  681. return test{
  682. db: &acme.MockDB{
  683. MockCreateAccount: func(ctx context.Context, acc *acme.Account) error {
  684. acc.ID = "accountID"
  685. assert.Equals(t, acc.Contact, nar.Contact)
  686. assert.Equals(t, acc.Key, jwk)
  687. return nil
  688. },
  689. },
  690. acc: &acme.Account{
  691. ID: "accountID",
  692. Key: jwk,
  693. Status: acme.StatusValid,
  694. Contact: []string{"foo", "bar"},
  695. OrdersURL: fmt.Sprintf("%s/acme/%s/account/accountID/orders", baseURL.String(), escProvName),
  696. },
  697. ctx: ctx,
  698. statusCode: 201,
  699. }
  700. },
  701. "ok/new-account-with-eab": func(t *testing.T) test {
  702. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  703. assert.FatalError(t, err)
  704. url := fmt.Sprintf("%s/acme/%s/account/new-account", baseURL.String(), escProvName)
  705. rawEABJWS, err := createRawEABJWS(jwk, []byte{1, 3, 3, 7}, "eakID", url)
  706. assert.FatalError(t, err)
  707. eab := &ExternalAccountBinding{}
  708. err = json.Unmarshal(rawEABJWS, &eab)
  709. assert.FatalError(t, err)
  710. nar := &NewAccountRequest{
  711. Contact: []string{"foo", "bar"},
  712. ExternalAccountBinding: eab,
  713. }
  714. payloadBytes, err := json.Marshal(nar)
  715. assert.FatalError(t, err)
  716. so := new(jose.SignerOptions)
  717. so.WithHeader("alg", jose.SignatureAlgorithm(jwk.Algorithm))
  718. so.WithHeader("url", url)
  719. signer, err := jose.NewSigner(jose.SigningKey{
  720. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  721. Key: jwk.Key,
  722. }, so)
  723. assert.FatalError(t, err)
  724. jws, err := signer.Sign(payloadBytes)
  725. assert.FatalError(t, err)
  726. raw, err := jws.CompactSerialize()
  727. assert.FatalError(t, err)
  728. parsedJWS, err := jose.ParseJWS(raw)
  729. assert.FatalError(t, err)
  730. prov := newACMEProv(t)
  731. prov.RequireEAB = true
  732. ctx := context.WithValue(context.Background(), payloadContextKey, &payloadInfo{value: payloadBytes})
  733. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  734. ctx = acme.NewProvisionerContext(ctx, prov)
  735. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  736. return test{
  737. db: &acme.MockDB{
  738. MockCreateAccount: func(ctx context.Context, acc *acme.Account) error {
  739. acc.ID = "accountID"
  740. assert.Equals(t, acc.Contact, nar.Contact)
  741. assert.Equals(t, acc.Key, jwk)
  742. return nil
  743. },
  744. MockGetExternalAccountKey: func(ctx context.Context, provisionerName, keyID string) (*acme.ExternalAccountKey, error) {
  745. return &acme.ExternalAccountKey{
  746. ID: "eakID",
  747. ProvisionerID: provID,
  748. Reference: "testeak",
  749. HmacKey: []byte{1, 3, 3, 7},
  750. CreatedAt: time.Now(),
  751. }, nil
  752. },
  753. MockUpdateExternalAccountKey: func(ctx context.Context, provisionerName string, eak *acme.ExternalAccountKey) error {
  754. return nil
  755. },
  756. },
  757. acc: &acme.Account{
  758. ID: "accountID",
  759. Key: jwk,
  760. Status: acme.StatusValid,
  761. Contact: []string{"foo", "bar"},
  762. OrdersURL: fmt.Sprintf("%s/acme/%s/account/accountID/orders", baseURL.String(), escProvName),
  763. ExternalAccountBinding: eab,
  764. },
  765. ctx: ctx,
  766. statusCode: 201,
  767. }
  768. },
  769. }
  770. for name, run := range tests {
  771. tc := run(t)
  772. t.Run(name, func(t *testing.T) {
  773. ctx := acme.NewContext(tc.ctx, tc.db, nil, acme.NewLinker("test.ca.smallstep.com", "acme"), nil)
  774. req := httptest.NewRequest("GET", "/foo/bar", nil)
  775. req = req.WithContext(ctx)
  776. w := httptest.NewRecorder()
  777. NewAccount(w, req)
  778. res := w.Result()
  779. assert.Equals(t, res.StatusCode, tc.statusCode)
  780. body, err := io.ReadAll(res.Body)
  781. res.Body.Close()
  782. assert.FatalError(t, err)
  783. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  784. var ae acme.Error
  785. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  786. assert.Equals(t, ae.Type, tc.err.Type)
  787. assert.Equals(t, ae.Detail, tc.err.Detail)
  788. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  789. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  790. } else {
  791. expB, err := json.Marshal(tc.acc)
  792. assert.FatalError(t, err)
  793. assert.Equals(t, bytes.TrimSpace(body), expB)
  794. assert.Equals(t, res.Header["Location"],
  795. []string{fmt.Sprintf("%s/acme/%s/account/%s", baseURL.String(),
  796. escProvName, "accountID")})
  797. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  798. }
  799. })
  800. }
  801. }
  802. func TestHandler_GetOrUpdateAccount(t *testing.T) {
  803. accID := "accountID"
  804. acc := acme.Account{
  805. ID: accID,
  806. Status: "valid",
  807. OrdersURL: fmt.Sprintf("https://ca.smallstep.com/acme/account/%s/orders", accID),
  808. }
  809. prov := newProv()
  810. escProvName := url.PathEscape(prov.GetName())
  811. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  812. type test struct {
  813. db acme.DB
  814. ctx context.Context
  815. statusCode int
  816. err *acme.Error
  817. }
  818. var tests = map[string]func(t *testing.T) test{
  819. "fail/no-account": func(t *testing.T) test {
  820. return test{
  821. db: &acme.MockDB{},
  822. ctx: context.Background(),
  823. statusCode: 400,
  824. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  825. }
  826. },
  827. "fail/nil-account": func(t *testing.T) test {
  828. ctx := context.WithValue(context.Background(), accContextKey, nil)
  829. return test{
  830. db: &acme.MockDB{},
  831. ctx: ctx,
  832. statusCode: 400,
  833. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account does not exist"),
  834. }
  835. },
  836. "fail/no-payload": func(t *testing.T) test {
  837. ctx := context.WithValue(context.Background(), accContextKey, &acc)
  838. return test{
  839. db: &acme.MockDB{},
  840. ctx: ctx,
  841. statusCode: 500,
  842. err: acme.NewErrorISE("payload expected in request context"),
  843. }
  844. },
  845. "fail/nil-payload": func(t *testing.T) test {
  846. ctx := context.WithValue(context.Background(), accContextKey, &acc)
  847. ctx = context.WithValue(ctx, payloadContextKey, nil)
  848. return test{
  849. db: &acme.MockDB{},
  850. ctx: ctx,
  851. statusCode: 500,
  852. err: acme.NewErrorISE("payload expected in request context"),
  853. }
  854. },
  855. "fail/unmarshal-payload-error": func(t *testing.T) test {
  856. ctx := context.WithValue(context.Background(), accContextKey, &acc)
  857. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{})
  858. return test{
  859. db: &acme.MockDB{},
  860. ctx: ctx,
  861. statusCode: 400,
  862. err: acme.NewError(acme.ErrorMalformedType, "failed to unmarshal new-account request payload: unexpected end of JSON input"),
  863. }
  864. },
  865. "fail/malformed-payload-error": func(t *testing.T) test {
  866. uar := &UpdateAccountRequest{
  867. Contact: []string{"foo", ""},
  868. }
  869. b, err := json.Marshal(uar)
  870. assert.FatalError(t, err)
  871. ctx := context.WithValue(context.Background(), accContextKey, &acc)
  872. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  873. return test{
  874. db: &acme.MockDB{},
  875. ctx: ctx,
  876. statusCode: 400,
  877. err: acme.NewError(acme.ErrorMalformedType, "contact cannot be empty string"),
  878. }
  879. },
  880. "fail/db.UpdateAccount-error": func(t *testing.T) test {
  881. uar := &UpdateAccountRequest{
  882. Status: "deactivated",
  883. }
  884. b, err := json.Marshal(uar)
  885. assert.FatalError(t, err)
  886. ctx := context.WithValue(context.Background(), accContextKey, &acc)
  887. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  888. return test{
  889. db: &acme.MockDB{
  890. MockUpdateAccount: func(ctx context.Context, upd *acme.Account) error {
  891. assert.Equals(t, upd.Status, acme.StatusDeactivated)
  892. assert.Equals(t, upd.ID, acc.ID)
  893. return acme.NewErrorISE("force")
  894. },
  895. },
  896. ctx: ctx,
  897. statusCode: 500,
  898. err: acme.NewErrorISE("force"),
  899. }
  900. },
  901. "ok/deactivate": func(t *testing.T) test {
  902. uar := &UpdateAccountRequest{
  903. Status: "deactivated",
  904. }
  905. b, err := json.Marshal(uar)
  906. assert.FatalError(t, err)
  907. ctx := acme.NewProvisionerContext(context.Background(), prov)
  908. ctx = context.WithValue(ctx, accContextKey, &acc)
  909. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  910. return test{
  911. db: &acme.MockDB{
  912. MockUpdateAccount: func(ctx context.Context, upd *acme.Account) error {
  913. assert.Equals(t, upd.Status, acme.StatusDeactivated)
  914. assert.Equals(t, upd.ID, acc.ID)
  915. return nil
  916. },
  917. },
  918. ctx: ctx,
  919. statusCode: 200,
  920. }
  921. },
  922. "ok/update-empty": func(t *testing.T) test {
  923. uar := &UpdateAccountRequest{}
  924. b, err := json.Marshal(uar)
  925. assert.FatalError(t, err)
  926. ctx := acme.NewProvisionerContext(context.Background(), prov)
  927. ctx = context.WithValue(ctx, accContextKey, &acc)
  928. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  929. return test{
  930. db: &acme.MockDB{},
  931. ctx: ctx,
  932. statusCode: 200,
  933. }
  934. },
  935. "ok/update-contacts": func(t *testing.T) test {
  936. uar := &UpdateAccountRequest{
  937. Contact: []string{"foo", "bar"},
  938. }
  939. b, err := json.Marshal(uar)
  940. assert.FatalError(t, err)
  941. ctx := acme.NewProvisionerContext(context.Background(), prov)
  942. ctx = context.WithValue(ctx, accContextKey, &acc)
  943. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  944. return test{
  945. db: &acme.MockDB{
  946. MockUpdateAccount: func(ctx context.Context, upd *acme.Account) error {
  947. assert.Equals(t, upd.Contact, uar.Contact)
  948. assert.Equals(t, upd.ID, acc.ID)
  949. return nil
  950. },
  951. },
  952. ctx: ctx,
  953. statusCode: 200,
  954. }
  955. },
  956. "ok/post-as-get": func(t *testing.T) test {
  957. ctx := acme.NewProvisionerContext(context.Background(), prov)
  958. ctx = context.WithValue(ctx, accContextKey, &acc)
  959. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isPostAsGet: true})
  960. return test{
  961. db: &acme.MockDB{},
  962. ctx: ctx,
  963. statusCode: 200,
  964. }
  965. },
  966. }
  967. for name, run := range tests {
  968. tc := run(t)
  969. t.Run(name, func(t *testing.T) {
  970. ctx := acme.NewContext(tc.ctx, tc.db, nil, acme.NewLinker("test.ca.smallstep.com", "acme"), nil)
  971. req := httptest.NewRequest("GET", "/foo/bar", nil)
  972. req = req.WithContext(ctx)
  973. w := httptest.NewRecorder()
  974. GetOrUpdateAccount(w, req)
  975. res := w.Result()
  976. assert.Equals(t, res.StatusCode, tc.statusCode)
  977. body, err := io.ReadAll(res.Body)
  978. res.Body.Close()
  979. assert.FatalError(t, err)
  980. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  981. var ae acme.Error
  982. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  983. assert.Equals(t, ae.Type, tc.err.Type)
  984. assert.Equals(t, ae.Detail, tc.err.Detail)
  985. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  986. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  987. } else {
  988. expB, err := json.Marshal(acc)
  989. assert.FatalError(t, err)
  990. assert.Equals(t, bytes.TrimSpace(body), expB)
  991. assert.Equals(t, res.Header["Location"],
  992. []string{fmt.Sprintf("%s/acme/%s/account/%s", baseURL.String(),
  993. escProvName, accID)})
  994. assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
  995. }
  996. })
  997. }
  998. }