account_test.go 33 KB

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