account_test.go 32 KB

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