account_test.go 33 KB

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