revoke_test.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto"
  6. "crypto/ecdsa"
  7. "crypto/rand"
  8. "crypto/rsa"
  9. "crypto/x509"
  10. "crypto/x509/pkix"
  11. "encoding/base64"
  12. "encoding/json"
  13. "fmt"
  14. "io"
  15. "math/big"
  16. "net"
  17. "net/http"
  18. "net/http/httptest"
  19. "net/url"
  20. "testing"
  21. "time"
  22. "github.com/go-chi/chi/v5"
  23. "github.com/google/go-cmp/cmp"
  24. "github.com/pkg/errors"
  25. "golang.org/x/crypto/ocsp"
  26. "go.step.sm/crypto/jose"
  27. "go.step.sm/crypto/keyutil"
  28. "go.step.sm/crypto/x509util"
  29. "github.com/smallstep/assert"
  30. "github.com/smallstep/certificates/acme"
  31. "github.com/smallstep/certificates/authority"
  32. "github.com/smallstep/certificates/authority/provisioner"
  33. )
  34. // v is a utility function to return the pointer to an integer
  35. //
  36. //go:fix inline
  37. func v(v int) *int {
  38. return new(v)
  39. }
  40. func generateSerial() (*big.Int, error) {
  41. return rand.Int(rand.Reader, big.NewInt(1000000000000000000))
  42. }
  43. // generateCertKeyPair generates fresh x509 certificate/key pairs for testing
  44. func generateCertKeyPair() (*x509.Certificate, crypto.Signer, error) {
  45. pub, priv, err := keyutil.GenerateKeyPair("EC", "P-256", 0)
  46. if err != nil {
  47. return nil, nil, err
  48. }
  49. serial, err := generateSerial()
  50. if err != nil {
  51. return nil, nil, err
  52. }
  53. now := time.Now()
  54. template := &x509.Certificate{
  55. Subject: pkix.Name{CommonName: "127.0.0.1"},
  56. Issuer: pkix.Name{CommonName: "Test ACME Revoke Certificate"},
  57. IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
  58. IsCA: false,
  59. MaxPathLen: 0,
  60. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  61. NotBefore: now,
  62. NotAfter: now.Add(time.Hour),
  63. SerialNumber: serial,
  64. }
  65. signer, ok := priv.(crypto.Signer)
  66. if !ok {
  67. return nil, nil, errors.Errorf("result is not a crypto.Signer: type %T", priv)
  68. }
  69. cert, err := x509util.CreateCertificate(template, template, pub, signer)
  70. return cert, signer, err
  71. }
  72. var errUnsupportedKey = fmt.Errorf("unknown key type; only RSA and ECDSA are supported")
  73. // keyID is the account identity provided by a CA during registration.
  74. type keyID string
  75. // noKeyID indicates that jwsEncodeJSON should compute and use JWK instead of a KID.
  76. // See jwsEncodeJSON for details.
  77. const noKeyID = keyID("")
  78. // jwsEncodeJSON signs claimset using provided key and a nonce.
  79. // The result is serialized in JSON format containing either kid or jwk
  80. // fields based on the provided keyID value.
  81. //
  82. // If kid is non-empty, its quoted value is inserted in the protected head
  83. // as "kid" field value. Otherwise, JWK is computed using jwkEncode and inserted
  84. // as "jwk" field value. The "jwk" and "kid" fields are mutually exclusive.
  85. //
  86. // See https://tools.ietf.org/html/rfc7515#section-7.
  87. //
  88. // If nonce is empty, it will not be encoded into the header.
  89. // Implementation taken from github.com/mholt/acmez, which seems to be based on
  90. // https://github.com/golang/crypto/blob/master/acme/jws.go.
  91. func jwsEncodeJSON(claimset any, key crypto.Signer, kid keyID, nonce, u string) ([]byte, error) {
  92. alg, sha := jwsHasher(key.Public())
  93. if alg == "" || !sha.Available() {
  94. return nil, errUnsupportedKey
  95. }
  96. phead, err := jwsHead(alg, nonce, u, kid, key)
  97. if err != nil {
  98. return nil, err
  99. }
  100. var payload string
  101. if claimset != nil {
  102. cs, err := json.Marshal(claimset)
  103. if err != nil {
  104. return nil, err
  105. }
  106. payload = base64.RawURLEncoding.EncodeToString(cs)
  107. }
  108. payloadToSign := []byte(phead + "." + payload)
  109. hash := sha.New()
  110. _, _ = hash.Write(payloadToSign)
  111. digest := hash.Sum(nil)
  112. sig, err := jwsSign(key, sha, digest)
  113. if err != nil {
  114. return nil, err
  115. }
  116. return jwsFinal(sha, sig, phead, payload)
  117. }
  118. // jwsHasher indicates suitable JWS algorithm name and a hash function
  119. // to use for signing a digest with the provided key.
  120. // It returns ("", 0) if the key is not supported.
  121. // Implementation taken from github.com/mholt/acmez, which seems to be based on
  122. // https://github.com/golang/crypto/blob/master/acme/jws.go.
  123. func jwsHasher(pub crypto.PublicKey) (string, crypto.Hash) {
  124. switch pub := pub.(type) {
  125. case *rsa.PublicKey:
  126. return "RS256", crypto.SHA256
  127. case *ecdsa.PublicKey:
  128. switch pub.Params().Name {
  129. case "P-256":
  130. return "ES256", crypto.SHA256
  131. case "P-384":
  132. return "ES384", crypto.SHA384
  133. case "P-521":
  134. return "ES512", crypto.SHA512
  135. }
  136. }
  137. return "", 0
  138. }
  139. // jwsSign signs the digest using the given key.
  140. // The hash is unused for ECDSA keys.
  141. //
  142. // Note: non-stdlib crypto.Signer implementations are expected to return
  143. // the signature in the format as specified in RFC7518.
  144. // See https://tools.ietf.org/html/rfc7518 for more details.
  145. // Implementation taken from github.com/mholt/acmez, which seems to be based on
  146. // https://github.com/golang/crypto/blob/master/acme/jws.go.
  147. func jwsSign(key crypto.Signer, hash crypto.Hash, digest []byte) ([]byte, error) {
  148. if key, ok := key.(*ecdsa.PrivateKey); ok {
  149. // The key.Sign method of ecdsa returns ASN1-encoded signature.
  150. // So, we use the package Sign function instead
  151. // to get R and S values directly and format the result accordingly.
  152. r, s, err := ecdsa.Sign(rand.Reader, key, digest)
  153. if err != nil {
  154. return nil, err
  155. }
  156. rb, sb := r.Bytes(), s.Bytes()
  157. size := key.Params().BitSize / 8
  158. if size%8 > 0 {
  159. size++
  160. }
  161. sig := make([]byte, size*2)
  162. copy(sig[size-len(rb):], rb)
  163. copy(sig[size*2-len(sb):], sb)
  164. return sig, nil
  165. }
  166. return key.Sign(rand.Reader, digest, hash)
  167. }
  168. // jwsHead constructs the protected JWS header for the given fields.
  169. // Since jwk and kid are mutually-exclusive, the jwk will be encoded
  170. // only if kid is empty. If nonce is empty, it will not be encoded.
  171. // Implementation taken from github.com/mholt/acmez, which seems to be based on
  172. // https://github.com/golang/crypto/blob/master/acme/jws.go.
  173. func jwsHead(alg, nonce, u string, kid keyID, key crypto.Signer) (string, error) {
  174. phead := fmt.Sprintf(`{"alg":%q`, alg)
  175. if kid == noKeyID {
  176. jwk, err := jwkEncode(key.Public())
  177. if err != nil {
  178. return "", err
  179. }
  180. phead += fmt.Sprintf(`,"jwk":%s`, jwk)
  181. } else {
  182. phead += fmt.Sprintf(`,"kid":%q`, kid)
  183. }
  184. if nonce != "" {
  185. phead += fmt.Sprintf(`,"nonce":%q`, nonce)
  186. }
  187. phead += fmt.Sprintf(`,"url":%q}`, u)
  188. phead = base64.RawURLEncoding.EncodeToString([]byte(phead))
  189. return phead, nil
  190. }
  191. // jwkEncode encodes public part of an RSA or ECDSA key into a JWK.
  192. // The result is also suitable for creating a JWK thumbprint.
  193. // https://tools.ietf.org/html/rfc7517
  194. // Implementation taken from github.com/mholt/acmez, which seems to be based on
  195. // https://github.com/golang/crypto/blob/master/acme/jws.go.
  196. func jwkEncode(pub crypto.PublicKey) (string, error) {
  197. switch pub := pub.(type) {
  198. case *rsa.PublicKey:
  199. // https://tools.ietf.org/html/rfc7518#section-6.3.1
  200. n := pub.N
  201. e := big.NewInt(int64(pub.E))
  202. // Field order is important.
  203. // See https://tools.ietf.org/html/rfc7638#section-3.3 for details.
  204. return fmt.Sprintf(`{"e":%q,"kty":"RSA","n":%q}`,
  205. base64.RawURLEncoding.EncodeToString(e.Bytes()),
  206. base64.RawURLEncoding.EncodeToString(n.Bytes()),
  207. ), nil
  208. case *ecdsa.PublicKey:
  209. // https://tools.ietf.org/html/rfc7518#section-6.2.1
  210. p := pub.Curve.Params()
  211. n := p.BitSize / 8
  212. if p.BitSize%8 != 0 {
  213. n++
  214. }
  215. b, err := pub.Bytes()
  216. if err != nil {
  217. return "", err
  218. }
  219. x, y := b[1:n+1], b[n+1:]
  220. // Field order is important.
  221. // See https://tools.ietf.org/html/rfc7638#section-3.3 for details.
  222. return fmt.Sprintf(`{"crv":%q,"kty":"EC","x":%q,"y":%q}`,
  223. p.Name,
  224. base64.RawURLEncoding.EncodeToString(x),
  225. base64.RawURLEncoding.EncodeToString(y),
  226. ), nil
  227. }
  228. return "", errUnsupportedKey
  229. }
  230. // jwsFinal constructs the final JWS object.
  231. // Implementation taken from github.com/mholt/acmez, which seems to be based on
  232. // https://github.com/golang/crypto/blob/master/acme/jws.go.
  233. func jwsFinal(_ crypto.Hash, sig []byte, phead, payload string) ([]byte, error) {
  234. enc := struct {
  235. Protected string `json:"protected"`
  236. Payload string `json:"payload"`
  237. Sig string `json:"signature"`
  238. }{
  239. Protected: phead,
  240. Payload: payload,
  241. Sig: base64.RawURLEncoding.EncodeToString(sig),
  242. }
  243. result, err := json.Marshal(&enc)
  244. if err != nil {
  245. return nil, err
  246. }
  247. return result, nil
  248. }
  249. type mockCA struct {
  250. MockIsRevoked func(sn string) (bool, error)
  251. MockRevoke func(ctx context.Context, opts *authority.RevokeOptions) error
  252. MockAreSANsallowed func(ctx context.Context, sans []string) error
  253. MockGetBackdate func() *time.Duration
  254. }
  255. func (m *mockCA) SignWithContext(context.Context, *x509.CertificateRequest, provisioner.SignOptions, ...provisioner.SignOption) ([]*x509.Certificate, error) {
  256. return nil, nil
  257. }
  258. func (m *mockCA) AreSANsAllowed(ctx context.Context, sans []string) error {
  259. if m.MockAreSANsallowed != nil {
  260. return m.MockAreSANsallowed(ctx, sans)
  261. }
  262. return nil
  263. }
  264. func (m *mockCA) IsRevoked(sn string) (bool, error) {
  265. if m.MockIsRevoked != nil {
  266. return m.MockIsRevoked(sn)
  267. }
  268. return false, nil
  269. }
  270. func (m *mockCA) Revoke(ctx context.Context, opts *authority.RevokeOptions) error {
  271. if m.MockRevoke != nil {
  272. return m.MockRevoke(ctx, opts)
  273. }
  274. return nil
  275. }
  276. func (m *mockCA) LoadProvisionerByName(string) (provisioner.Interface, error) {
  277. return nil, nil
  278. }
  279. func (m *mockCA) GetBackdate() *time.Duration {
  280. if m.MockGetBackdate != nil {
  281. return m.MockGetBackdate()
  282. }
  283. return nil
  284. }
  285. func Test_validateReasonCode(t *testing.T) {
  286. tests := []struct {
  287. name string
  288. reasonCode *int
  289. want *acme.Error
  290. }{
  291. {
  292. name: "ok",
  293. reasonCode: v(ocsp.Unspecified),
  294. want: nil,
  295. },
  296. {
  297. name: "fail/too-low",
  298. reasonCode: new(-1),
  299. want: acme.NewError(acme.ErrorBadRevocationReasonType, "reasonCode out of bounds"),
  300. },
  301. {
  302. name: "fail/too-high",
  303. reasonCode: new(11),
  304. want: acme.NewError(acme.ErrorBadRevocationReasonType, "reasonCode out of bounds"),
  305. },
  306. {
  307. name: "fail/missing-7",
  308. reasonCode: new(7),
  309. want: acme.NewError(acme.ErrorBadRevocationReasonType, "reasonCode out of bounds"),
  310. },
  311. }
  312. for _, tt := range tests {
  313. t.Run(tt.name, func(t *testing.T) {
  314. err := validateReasonCode(tt.reasonCode)
  315. if (err != nil) != (tt.want != nil) {
  316. t.Errorf("validateReasonCode() = %v, want %v", err, tt.want)
  317. }
  318. if err != nil {
  319. assert.Equals(t, err.Type, tt.want.Type)
  320. assert.Equals(t, err.Detail, tt.want.Detail)
  321. assert.Equals(t, err.Status, tt.want.Status)
  322. assert.Equals(t, err.Err.Error(), tt.want.Err.Error())
  323. assert.Equals(t, err.Detail, tt.want.Detail)
  324. }
  325. })
  326. }
  327. }
  328. func Test_reason(t *testing.T) {
  329. tests := []struct {
  330. name string
  331. reasonCode int
  332. want string
  333. }{
  334. {
  335. name: "unspecified reason",
  336. reasonCode: ocsp.Unspecified,
  337. want: "unspecified reason",
  338. },
  339. {
  340. name: "key compromised",
  341. reasonCode: ocsp.KeyCompromise,
  342. want: "key compromised",
  343. },
  344. {
  345. name: "ca compromised",
  346. reasonCode: ocsp.CACompromise,
  347. want: "ca compromised",
  348. },
  349. {
  350. name: "affiliation changed",
  351. reasonCode: ocsp.AffiliationChanged,
  352. want: "affiliation changed",
  353. },
  354. {
  355. name: "superseded",
  356. reasonCode: ocsp.Superseded,
  357. want: "superseded",
  358. },
  359. {
  360. name: "cessation of operation",
  361. reasonCode: ocsp.CessationOfOperation,
  362. want: "cessation of operation",
  363. },
  364. {
  365. name: "certificate hold",
  366. reasonCode: ocsp.CertificateHold,
  367. want: "certificate hold",
  368. },
  369. {
  370. name: "remove from crl",
  371. reasonCode: ocsp.RemoveFromCRL,
  372. want: "remove from crl",
  373. },
  374. {
  375. name: "privilege withdrawn",
  376. reasonCode: ocsp.PrivilegeWithdrawn,
  377. want: "privilege withdrawn",
  378. },
  379. {
  380. name: "aa compromised",
  381. reasonCode: ocsp.AACompromise,
  382. want: "aa compromised",
  383. },
  384. {
  385. name: "default",
  386. reasonCode: -1,
  387. want: "unspecified reason",
  388. },
  389. }
  390. for _, tt := range tests {
  391. t.Run(tt.name, func(t *testing.T) {
  392. if got := reason(tt.reasonCode); got != tt.want {
  393. t.Errorf("reason() = %v, want %v", got, tt.want)
  394. }
  395. })
  396. }
  397. }
  398. func Test_revokeOptions(t *testing.T) {
  399. cert, _, err := generateCertKeyPair()
  400. assert.FatalError(t, err)
  401. type args struct {
  402. serial string
  403. certToBeRevoked *x509.Certificate
  404. reasonCode *int
  405. }
  406. tests := []struct {
  407. name string
  408. args args
  409. want *authority.RevokeOptions
  410. }{
  411. {
  412. name: "ok/no-reasoncode",
  413. args: args{
  414. serial: "1234",
  415. certToBeRevoked: cert,
  416. },
  417. want: &authority.RevokeOptions{
  418. Serial: "1234",
  419. Crt: cert,
  420. ACME: true,
  421. },
  422. },
  423. {
  424. name: "ok/including-reasoncode",
  425. args: args{
  426. serial: "1234",
  427. certToBeRevoked: cert,
  428. reasonCode: v(ocsp.KeyCompromise),
  429. },
  430. want: &authority.RevokeOptions{
  431. Serial: "1234",
  432. Crt: cert,
  433. ACME: true,
  434. ReasonCode: 1,
  435. Reason: "key compromised",
  436. },
  437. },
  438. }
  439. for _, tt := range tests {
  440. t.Run(tt.name, func(t *testing.T) {
  441. if got := revokeOptions(tt.args.serial, tt.args.certToBeRevoked, tt.args.reasonCode); !cmp.Equal(got, tt.want) {
  442. t.Errorf("revokeOptions() diff =\n%s", cmp.Diff(got, tt.want))
  443. }
  444. })
  445. }
  446. }
  447. func TestHandler_RevokeCert(t *testing.T) {
  448. prov := &provisioner.ACME{
  449. Type: "ACME",
  450. Name: "testprov",
  451. }
  452. escProvName := url.PathEscape(prov.GetName())
  453. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  454. chiCtx := chi.NewRouteContext()
  455. revokeURL := fmt.Sprintf("%s/acme/%s/revoke-cert", baseURL.String(), escProvName)
  456. cert, key, err := generateCertKeyPair()
  457. assert.FatalError(t, err)
  458. rp := &revokePayload{
  459. Certificate: base64.RawURLEncoding.EncodeToString(cert.Raw),
  460. }
  461. payloadBytes, err := json.Marshal(rp)
  462. assert.FatalError(t, err)
  463. jws := &jose.JSONWebSignature{
  464. Signatures: []jose.Signature{
  465. {
  466. Protected: jose.Header{
  467. Algorithm: jose.ES256,
  468. KeyID: "bar",
  469. ExtraHeaders: map[jose.HeaderKey]any{
  470. "url": revokeURL,
  471. },
  472. },
  473. },
  474. },
  475. }
  476. type test struct {
  477. db acme.DB
  478. ca acme.CertificateAuthority
  479. ctx context.Context
  480. statusCode int
  481. err *acme.Error
  482. }
  483. var tests = map[string]func(t *testing.T) test{
  484. "fail/no-jws": func(t *testing.T) test {
  485. ctx := context.Background()
  486. return test{
  487. db: &acme.MockDB{},
  488. ctx: ctx,
  489. statusCode: 500,
  490. err: acme.NewErrorISE("jws expected in request context"),
  491. }
  492. },
  493. "fail/nil-jws": func(t *testing.T) test {
  494. ctx := context.WithValue(context.Background(), jwsContextKey, nil)
  495. return test{
  496. db: &acme.MockDB{},
  497. ctx: ctx,
  498. statusCode: 500,
  499. err: acme.NewErrorISE("jws expected in request context"),
  500. }
  501. },
  502. "fail/no-provisioner": func(t *testing.T) test {
  503. ctx := context.WithValue(context.Background(), jwsContextKey, jws)
  504. return test{
  505. db: &acme.MockDB{},
  506. ctx: ctx,
  507. statusCode: 500,
  508. err: acme.NewErrorISE("provisioner does not exist"),
  509. }
  510. },
  511. "fail/nil-provisioner": func(t *testing.T) test {
  512. ctx := context.WithValue(context.Background(), jwsContextKey, jws)
  513. ctx = acme.NewProvisionerContext(ctx, nil)
  514. return test{
  515. db: &acme.MockDB{},
  516. ctx: ctx,
  517. statusCode: 500,
  518. err: acme.NewErrorISE("provisioner does not exist"),
  519. }
  520. },
  521. "fail/no-payload": func(t *testing.T) test {
  522. ctx := context.WithValue(context.Background(), jwsContextKey, jws)
  523. ctx = acme.NewProvisionerContext(ctx, prov)
  524. return test{
  525. db: &acme.MockDB{},
  526. ctx: ctx,
  527. statusCode: 500,
  528. err: acme.NewErrorISE("payload does not exist"),
  529. }
  530. },
  531. "fail/nil-payload": func(t *testing.T) test {
  532. ctx := context.WithValue(context.Background(), jwsContextKey, jws)
  533. ctx = acme.NewProvisionerContext(ctx, prov)
  534. ctx = context.WithValue(ctx, payloadContextKey, nil)
  535. return test{
  536. db: &acme.MockDB{},
  537. ctx: ctx,
  538. statusCode: 500,
  539. err: acme.NewErrorISE("payload does not exist"),
  540. }
  541. },
  542. "fail/unmarshal-payload": func(t *testing.T) test {
  543. malformedPayload := []byte(`{"payload":malformed?}`)
  544. ctx := context.WithValue(context.Background(), jwsContextKey, jws)
  545. ctx = acme.NewProvisionerContext(ctx, prov)
  546. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: malformedPayload})
  547. return test{
  548. db: &acme.MockDB{},
  549. ctx: ctx,
  550. statusCode: 500,
  551. err: acme.NewErrorISE("error unmarshaling payload"),
  552. }
  553. },
  554. "fail/wrong-certificate-encoding": func(t *testing.T) test {
  555. wrongPayload := &revokePayload{
  556. Certificate: base64.StdEncoding.EncodeToString(cert.Raw),
  557. }
  558. wronglyEncodedPayloadBytes, err := json.Marshal(wrongPayload)
  559. assert.FatalError(t, err)
  560. ctx := acme.NewProvisionerContext(context.Background(), prov)
  561. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: wronglyEncodedPayloadBytes})
  562. ctx = context.WithValue(ctx, jwsContextKey, jws)
  563. return test{
  564. db: &acme.MockDB{},
  565. ctx: ctx,
  566. statusCode: 400,
  567. err: &acme.Error{
  568. Type: "urn:ietf:params:acme:error:malformed",
  569. Status: 400,
  570. Detail: "The request message was malformed",
  571. },
  572. }
  573. },
  574. "fail/no-certificate-encoded": func(t *testing.T) test {
  575. emptyPayload := &revokePayload{
  576. Certificate: base64.RawURLEncoding.EncodeToString([]byte{}),
  577. }
  578. emptyPayloadBytes, err := json.Marshal(emptyPayload)
  579. assert.FatalError(t, err)
  580. ctx := acme.NewProvisionerContext(context.Background(), prov)
  581. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: emptyPayloadBytes})
  582. ctx = context.WithValue(ctx, jwsContextKey, jws)
  583. return test{
  584. db: &acme.MockDB{},
  585. ctx: ctx,
  586. statusCode: 400,
  587. err: &acme.Error{
  588. Type: "urn:ietf:params:acme:error:malformed",
  589. Status: 400,
  590. Detail: "The request message was malformed",
  591. },
  592. }
  593. },
  594. "fail/db.GetCertificateBySerial": func(t *testing.T) test {
  595. ctx := acme.NewProvisionerContext(context.Background(), prov)
  596. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  597. ctx = context.WithValue(ctx, jwsContextKey, jws)
  598. db := &acme.MockDB{
  599. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  600. return nil, errors.New("force")
  601. },
  602. }
  603. return test{
  604. db: db,
  605. ctx: ctx,
  606. statusCode: 500,
  607. err: acme.NewErrorISE("error retrieving certificate by serial"),
  608. }
  609. },
  610. "fail/different-certificate-contents": func(t *testing.T) test {
  611. aDifferentCert, _, err := generateCertKeyPair()
  612. assert.FatalError(t, err)
  613. ctx := acme.NewProvisionerContext(context.Background(), prov)
  614. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  615. ctx = context.WithValue(ctx, jwsContextKey, jws)
  616. db := &acme.MockDB{
  617. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  618. assert.Equals(t, cert.SerialNumber.String(), serial)
  619. return &acme.Certificate{
  620. Leaf: aDifferentCert,
  621. }, nil
  622. },
  623. }
  624. return test{
  625. db: db,
  626. ctx: ctx,
  627. statusCode: 500,
  628. err: acme.NewErrorISE("certificate raw bytes are not equal"),
  629. }
  630. },
  631. "fail/no-account": func(t *testing.T) test {
  632. ctx := acme.NewProvisionerContext(context.Background(), prov)
  633. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  634. ctx = context.WithValue(ctx, jwsContextKey, jws)
  635. db := &acme.MockDB{
  636. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  637. assert.Equals(t, cert.SerialNumber.String(), serial)
  638. return &acme.Certificate{
  639. Leaf: cert,
  640. }, nil
  641. },
  642. }
  643. return test{
  644. db: db,
  645. ctx: ctx,
  646. statusCode: 400,
  647. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account not in context"),
  648. }
  649. },
  650. "fail/nil-account": func(t *testing.T) test {
  651. ctx := acme.NewProvisionerContext(context.Background(), prov)
  652. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  653. ctx = context.WithValue(ctx, jwsContextKey, jws)
  654. ctx = context.WithValue(ctx, accContextKey, nil)
  655. db := &acme.MockDB{
  656. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  657. assert.Equals(t, cert.SerialNumber.String(), serial)
  658. return &acme.Certificate{
  659. Leaf: cert,
  660. }, nil
  661. },
  662. }
  663. return test{
  664. db: db,
  665. ctx: ctx,
  666. statusCode: 400,
  667. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account not in context"),
  668. }
  669. },
  670. "fail/account-not-valid": func(t *testing.T) test {
  671. acc := &acme.Account{ID: "accountID", Status: acme.StatusInvalid}
  672. ctx := acme.NewProvisionerContext(context.Background(), prov)
  673. ctx = context.WithValue(ctx, accContextKey, acc)
  674. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  675. ctx = context.WithValue(ctx, jwsContextKey, jws)
  676. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  677. db := &acme.MockDB{
  678. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  679. assert.Equals(t, cert.SerialNumber.String(), serial)
  680. return &acme.Certificate{
  681. AccountID: "accountID",
  682. Leaf: cert,
  683. }, nil
  684. },
  685. }
  686. ca := &mockCA{}
  687. return test{
  688. db: db,
  689. ca: ca,
  690. ctx: ctx,
  691. statusCode: 403,
  692. err: &acme.Error{
  693. Type: "urn:ietf:params:acme:error:unauthorized",
  694. Detail: "No authorization provided for name 127.0.0.1",
  695. Status: 403,
  696. },
  697. }
  698. },
  699. "fail/account-not-authorized": func(t *testing.T) test {
  700. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  701. ctx := acme.NewProvisionerContext(context.Background(), prov)
  702. ctx = context.WithValue(ctx, accContextKey, acc)
  703. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  704. ctx = context.WithValue(ctx, jwsContextKey, jws)
  705. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  706. db := &acme.MockDB{
  707. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  708. assert.Equals(t, cert.SerialNumber.String(), serial)
  709. return &acme.Certificate{
  710. AccountID: "differentAccountID",
  711. Leaf: cert,
  712. }, nil
  713. },
  714. MockGetAuthorizationsByAccountID: func(ctx context.Context, accountID string) ([]*acme.Authorization, error) {
  715. assert.Equals(t, "accountID", accountID)
  716. return []*acme.Authorization{
  717. {
  718. AccountID: "accountID",
  719. Status: acme.StatusValid,
  720. Identifier: acme.Identifier{
  721. Type: acme.IP,
  722. Value: "127.0.1.0",
  723. },
  724. },
  725. }, nil
  726. },
  727. }
  728. ca := &mockCA{}
  729. return test{
  730. db: db,
  731. ca: ca,
  732. ctx: ctx,
  733. statusCode: 403,
  734. err: &acme.Error{
  735. Type: "urn:ietf:params:acme:error:unauthorized",
  736. Detail: "No authorization provided for name 127.0.0.1",
  737. Status: 403,
  738. },
  739. }
  740. },
  741. "fail/unauthorized-certificate-key": func(t *testing.T) test {
  742. _, unauthorizedKey, err := generateCertKeyPair()
  743. assert.FatalError(t, err)
  744. jwsPayload := &revokePayload{
  745. Certificate: base64.RawURLEncoding.EncodeToString(cert.Raw),
  746. ReasonCode: new(2),
  747. }
  748. jwsBytes, err := jwsEncodeJSON(rp, unauthorizedKey, "", "nonce", revokeURL)
  749. assert.FatalError(t, err)
  750. parsedJWS, err := jose.ParseJWS(string(jwsBytes))
  751. assert.FatalError(t, err)
  752. unauthorizedPayloadBytes, err := json.Marshal(jwsPayload)
  753. assert.FatalError(t, err)
  754. ctx := acme.NewProvisionerContext(context.Background(), prov)
  755. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: unauthorizedPayloadBytes})
  756. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  757. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  758. db := &acme.MockDB{
  759. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  760. assert.Equals(t, cert.SerialNumber.String(), serial)
  761. return &acme.Certificate{
  762. AccountID: "accountID",
  763. Leaf: cert,
  764. }, nil
  765. },
  766. }
  767. ca := &mockCA{}
  768. acmeErr := acme.NewError(acme.ErrorUnauthorizedType, "verification of jws using certificate public key failed")
  769. acmeErr.Detail = "No authorization provided for name 127.0.0.1"
  770. return test{
  771. db: db,
  772. ca: ca,
  773. ctx: ctx,
  774. statusCode: 403,
  775. err: acmeErr,
  776. }
  777. },
  778. "fail/certificate-revoked-check-fails": func(t *testing.T) test {
  779. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  780. ctx := acme.NewProvisionerContext(context.Background(), prov)
  781. ctx = context.WithValue(ctx, accContextKey, acc)
  782. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  783. ctx = context.WithValue(ctx, jwsContextKey, jws)
  784. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  785. db := &acme.MockDB{
  786. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  787. assert.Equals(t, cert.SerialNumber.String(), serial)
  788. return &acme.Certificate{
  789. AccountID: "accountID",
  790. Leaf: cert,
  791. }, nil
  792. },
  793. }
  794. ca := &mockCA{
  795. MockIsRevoked: func(sn string) (bool, error) {
  796. return false, errors.New("force")
  797. },
  798. }
  799. return test{
  800. db: db,
  801. ca: ca,
  802. ctx: ctx,
  803. statusCode: 500,
  804. err: &acme.Error{
  805. Type: "urn:ietf:params:acme:error:serverInternal",
  806. Detail: "The server experienced an internal error",
  807. Status: 500,
  808. },
  809. }
  810. },
  811. "fail/certificate-already-revoked": func(t *testing.T) test {
  812. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  813. ctx := acme.NewProvisionerContext(context.Background(), prov)
  814. ctx = context.WithValue(ctx, accContextKey, acc)
  815. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  816. ctx = context.WithValue(ctx, jwsContextKey, jws)
  817. db := &acme.MockDB{
  818. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  819. assert.Equals(t, cert.SerialNumber.String(), serial)
  820. return &acme.Certificate{
  821. AccountID: "accountID",
  822. Leaf: cert,
  823. }, nil
  824. },
  825. }
  826. ca := &mockCA{
  827. MockIsRevoked: func(sn string) (bool, error) {
  828. return true, nil
  829. },
  830. }
  831. return test{
  832. db: db,
  833. ca: ca,
  834. ctx: ctx,
  835. statusCode: 400,
  836. err: &acme.Error{
  837. Type: "urn:ietf:params:acme:error:alreadyRevoked",
  838. Detail: "Certificate already revoked",
  839. Status: 400,
  840. },
  841. }
  842. },
  843. "fail/invalid-reasoncode": func(t *testing.T) test {
  844. invalidReasonPayload := &revokePayload{
  845. Certificate: base64.RawURLEncoding.EncodeToString(cert.Raw),
  846. ReasonCode: new(7),
  847. }
  848. invalidReasonCodePayloadBytes, err := json.Marshal(invalidReasonPayload)
  849. assert.FatalError(t, err)
  850. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  851. ctx := acme.NewProvisionerContext(context.Background(), prov)
  852. ctx = context.WithValue(ctx, accContextKey, acc)
  853. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: invalidReasonCodePayloadBytes})
  854. ctx = context.WithValue(ctx, jwsContextKey, jws)
  855. db := &acme.MockDB{
  856. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  857. assert.Equals(t, cert.SerialNumber.String(), serial)
  858. return &acme.Certificate{
  859. AccountID: "accountID",
  860. Leaf: cert,
  861. }, nil
  862. },
  863. }
  864. ca := &mockCA{
  865. MockIsRevoked: func(sn string) (bool, error) {
  866. return false, nil
  867. },
  868. }
  869. return test{
  870. db: db,
  871. ca: ca,
  872. ctx: ctx,
  873. statusCode: 400,
  874. err: &acme.Error{
  875. Type: "urn:ietf:params:acme:error:badRevocationReason",
  876. Detail: "The revocation reason provided is not allowed by the server",
  877. Status: 400,
  878. },
  879. }
  880. },
  881. "fail/prov.AuthorizeRevoke": func(t *testing.T) test {
  882. assert.FatalError(t, err)
  883. mockACMEProv := &acme.MockProvisioner{
  884. MauthorizeRevoke: func(ctx context.Context, token string) error {
  885. return errors.New("force")
  886. },
  887. }
  888. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  889. ctx := acme.NewProvisionerContext(context.Background(), mockACMEProv)
  890. ctx = context.WithValue(ctx, accContextKey, acc)
  891. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  892. ctx = context.WithValue(ctx, jwsContextKey, jws)
  893. db := &acme.MockDB{
  894. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  895. assert.Equals(t, cert.SerialNumber.String(), serial)
  896. return &acme.Certificate{
  897. AccountID: "accountID",
  898. Leaf: cert,
  899. }, nil
  900. },
  901. }
  902. ca := &mockCA{
  903. MockIsRevoked: func(sn string) (bool, error) {
  904. return false, nil
  905. },
  906. }
  907. return test{
  908. db: db,
  909. ca: ca,
  910. ctx: ctx,
  911. statusCode: 500,
  912. err: &acme.Error{
  913. Type: "urn:ietf:params:acme:error:serverInternal",
  914. Detail: "The server experienced an internal error",
  915. Status: 500,
  916. },
  917. }
  918. },
  919. "fail/ca.Revoke": func(t *testing.T) test {
  920. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  921. ctx := acme.NewProvisionerContext(context.Background(), prov)
  922. ctx = context.WithValue(ctx, accContextKey, acc)
  923. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  924. ctx = context.WithValue(ctx, jwsContextKey, jws)
  925. db := &acme.MockDB{
  926. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  927. assert.Equals(t, cert.SerialNumber.String(), serial)
  928. return &acme.Certificate{
  929. AccountID: "accountID",
  930. Leaf: cert,
  931. }, nil
  932. },
  933. }
  934. ca := &mockCA{
  935. MockRevoke: func(ctx context.Context, opts *authority.RevokeOptions) error {
  936. return errors.New("force")
  937. },
  938. }
  939. return test{
  940. db: db,
  941. ca: ca,
  942. ctx: ctx,
  943. statusCode: 500,
  944. err: &acme.Error{
  945. Type: "urn:ietf:params:acme:error:serverInternal",
  946. Detail: "The server experienced an internal error",
  947. Status: 500,
  948. },
  949. }
  950. },
  951. "fail/ca.Revoke-already-revoked": func(t *testing.T) test {
  952. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  953. ctx := acme.NewProvisionerContext(context.Background(), prov)
  954. ctx = context.WithValue(ctx, accContextKey, acc)
  955. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  956. ctx = context.WithValue(ctx, jwsContextKey, jws)
  957. db := &acme.MockDB{
  958. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  959. assert.Equals(t, cert.SerialNumber.String(), serial)
  960. return &acme.Certificate{
  961. AccountID: "accountID",
  962. Leaf: cert,
  963. }, nil
  964. },
  965. }
  966. ca := &mockCA{
  967. MockIsRevoked: func(sn string) (bool, error) {
  968. return false, nil
  969. },
  970. MockRevoke: func(ctx context.Context, opts *authority.RevokeOptions) error {
  971. return fmt.Errorf("certificate with serial number '%s' is already revoked", cert.SerialNumber.String())
  972. },
  973. }
  974. return test{
  975. db: db,
  976. ca: ca,
  977. ctx: ctx,
  978. statusCode: 400,
  979. err: acme.NewError(acme.ErrorAlreadyRevokedType, "certificate with serial number '%s' is already revoked", cert.SerialNumber.String()),
  980. }
  981. },
  982. "ok/using-account-key": func(t *testing.T) test {
  983. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  984. ctx := acme.NewProvisionerContext(context.Background(), prov)
  985. ctx = context.WithValue(ctx, accContextKey, acc)
  986. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  987. ctx = context.WithValue(ctx, jwsContextKey, jws)
  988. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  989. db := &acme.MockDB{
  990. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  991. assert.Equals(t, cert.SerialNumber.String(), serial)
  992. return &acme.Certificate{
  993. AccountID: "accountID",
  994. Leaf: cert,
  995. }, nil
  996. },
  997. }
  998. ca := &mockCA{}
  999. return test{
  1000. db: db,
  1001. ca: ca,
  1002. ctx: ctx,
  1003. statusCode: 200,
  1004. }
  1005. },
  1006. "ok/using-certificate-key": func(t *testing.T) test {
  1007. jwsBytes, err := jwsEncodeJSON(rp, key, "", "nonce", revokeURL)
  1008. assert.FatalError(t, err)
  1009. jws, err := jose.ParseJWS(string(jwsBytes))
  1010. assert.FatalError(t, err)
  1011. ctx := acme.NewProvisionerContext(context.Background(), prov)
  1012. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  1013. ctx = context.WithValue(ctx, jwsContextKey, jws)
  1014. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  1015. db := &acme.MockDB{
  1016. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  1017. assert.Equals(t, cert.SerialNumber.String(), serial)
  1018. return &acme.Certificate{
  1019. AccountID: "someDifferentAccountID",
  1020. Leaf: cert,
  1021. }, nil
  1022. },
  1023. }
  1024. ca := &mockCA{}
  1025. return test{
  1026. db: db,
  1027. ca: ca,
  1028. ctx: ctx,
  1029. statusCode: 200,
  1030. }
  1031. },
  1032. }
  1033. for name, setup := range tests {
  1034. tc := setup(t)
  1035. t.Run(name, func(t *testing.T) {
  1036. ctx := newBaseContext(tc.ctx, tc.db, acme.NewLinker("test.ca.smallstep.com", "acme"))
  1037. mockMustAuthority(t, tc.ca)
  1038. req := httptest.NewRequest("POST", revokeURL, http.NoBody)
  1039. req = req.WithContext(ctx)
  1040. w := httptest.NewRecorder()
  1041. RevokeCert(w, req)
  1042. res := w.Result()
  1043. assert.Equals(t, res.StatusCode, tc.statusCode)
  1044. body, err := io.ReadAll(res.Body)
  1045. res.Body.Close()
  1046. assert.FatalError(t, err)
  1047. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  1048. var ae acme.Error
  1049. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  1050. assert.Equals(t, ae.Type, tc.err.Type)
  1051. assert.Equals(t, ae.Detail, tc.err.Detail)
  1052. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  1053. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  1054. } else {
  1055. assert.True(t, bytes.Equal(bytes.TrimSpace(body), []byte{}))
  1056. assert.Equals(t, []string{fmt.Sprintf("<%s/acme/%s/directory>;rel=\"index\"", baseURL.String(), escProvName)}, res.Header["Link"])
  1057. }
  1058. })
  1059. }
  1060. }
  1061. func TestHandler_isAccountAuthorized(t *testing.T) {
  1062. type test struct {
  1063. db acme.DB
  1064. ctx context.Context
  1065. existingCert *acme.Certificate
  1066. certToBeRevoked *x509.Certificate
  1067. account *acme.Account
  1068. err *acme.Error
  1069. }
  1070. accountID := "accountID"
  1071. var tests = map[string]func(t *testing.T) test{
  1072. "fail/account-invalid": func(t *testing.T) test {
  1073. account := &acme.Account{
  1074. ID: accountID,
  1075. Status: acme.StatusInvalid,
  1076. }
  1077. certToBeRevoked := &x509.Certificate{
  1078. Subject: pkix.Name{
  1079. CommonName: "127.0.0.1",
  1080. },
  1081. }
  1082. return test{
  1083. ctx: context.TODO(),
  1084. certToBeRevoked: certToBeRevoked,
  1085. account: account,
  1086. err: &acme.Error{
  1087. Type: "urn:ietf:params:acme:error:unauthorized",
  1088. Status: http.StatusForbidden,
  1089. Detail: "No authorization provided for name 127.0.0.1",
  1090. Err: errors.New("account 'accountID' has status 'invalid'"),
  1091. },
  1092. }
  1093. },
  1094. "fail/different-account": func(t *testing.T) test {
  1095. account := &acme.Account{
  1096. ID: accountID,
  1097. Status: acme.StatusValid,
  1098. }
  1099. certToBeRevoked := &x509.Certificate{
  1100. IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
  1101. }
  1102. existingCert := &acme.Certificate{
  1103. AccountID: "differentAccountID",
  1104. }
  1105. return test{
  1106. db: &acme.MockDB{
  1107. MockGetAuthorizationsByAccountID: func(ctx context.Context, accountID string) ([]*acme.Authorization, error) {
  1108. assert.Equals(t, "accountID", accountID)
  1109. return []*acme.Authorization{
  1110. {
  1111. AccountID: accountID,
  1112. Status: acme.StatusValid,
  1113. Identifier: acme.Identifier{
  1114. Type: acme.IP,
  1115. Value: "127.0.0.1",
  1116. },
  1117. },
  1118. }, nil
  1119. },
  1120. },
  1121. ctx: context.TODO(),
  1122. existingCert: existingCert,
  1123. certToBeRevoked: certToBeRevoked,
  1124. account: account,
  1125. err: &acme.Error{
  1126. Type: "urn:ietf:params:acme:error:unauthorized",
  1127. Status: http.StatusForbidden,
  1128. Detail: "No authorization provided",
  1129. Err: errors.New("account 'accountID' is not authorized"),
  1130. },
  1131. }
  1132. },
  1133. "ok": func(t *testing.T) test {
  1134. account := &acme.Account{
  1135. ID: accountID,
  1136. Status: acme.StatusValid,
  1137. }
  1138. certToBeRevoked := &x509.Certificate{
  1139. IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
  1140. }
  1141. existingCert := &acme.Certificate{
  1142. AccountID: "accountID",
  1143. }
  1144. return test{
  1145. db: &acme.MockDB{
  1146. MockGetAuthorizationsByAccountID: func(ctx context.Context, accountID string) ([]*acme.Authorization, error) {
  1147. assert.Equals(t, "accountID", accountID)
  1148. return []*acme.Authorization{
  1149. {
  1150. AccountID: accountID,
  1151. Status: acme.StatusValid,
  1152. Identifier: acme.Identifier{
  1153. Type: acme.IP,
  1154. Value: "127.0.0.1",
  1155. },
  1156. },
  1157. }, nil
  1158. },
  1159. },
  1160. ctx: context.TODO(),
  1161. existingCert: existingCert,
  1162. certToBeRevoked: certToBeRevoked,
  1163. account: account,
  1164. err: nil,
  1165. }
  1166. },
  1167. }
  1168. for name, setup := range tests {
  1169. tc := setup(t)
  1170. t.Run(name, func(t *testing.T) {
  1171. // h := &Handler{db: tc.db}
  1172. acmeErr := isAccountAuthorized(tc.ctx, tc.existingCert, tc.certToBeRevoked, tc.account)
  1173. expectError := tc.err != nil
  1174. gotError := acmeErr != nil
  1175. if expectError != gotError {
  1176. t.Errorf("expected: %t, got: %t", expectError, gotError)
  1177. return
  1178. }
  1179. if !gotError {
  1180. return // nothing to check; return early
  1181. }
  1182. assert.Equals(t, acmeErr.Err.Error(), tc.err.Err.Error())
  1183. assert.Equals(t, acmeErr.Type, tc.err.Type)
  1184. assert.Equals(t, acmeErr.Status, tc.err.Status)
  1185. assert.Equals(t, acmeErr.Detail, tc.err.Detail)
  1186. assert.Equals(t, acmeErr.Subproblems, tc.err.Subproblems)
  1187. })
  1188. }
  1189. }
  1190. func Test_wrapUnauthorizedError(t *testing.T) {
  1191. type test struct {
  1192. cert *x509.Certificate
  1193. unauthorizedIdentifiers []acme.Identifier
  1194. msg string
  1195. err error
  1196. want *acme.Error
  1197. }
  1198. var tests = map[string]func(t *testing.T) test{
  1199. "unauthorizedIdentifiers": func(t *testing.T) test {
  1200. acmeErr := acme.NewError(acme.ErrorUnauthorizedType, "account 'accountID' is not authorized")
  1201. acmeErr.Status = http.StatusForbidden
  1202. acmeErr.Detail = "No authorization provided for name 127.0.0.1"
  1203. return test{
  1204. err: nil,
  1205. cert: nil,
  1206. unauthorizedIdentifiers: []acme.Identifier{
  1207. {
  1208. Type: acme.IP,
  1209. Value: "127.0.0.1",
  1210. },
  1211. },
  1212. msg: "account 'accountID' is not authorized",
  1213. want: acmeErr,
  1214. }
  1215. },
  1216. "subject": func(t *testing.T) test {
  1217. acmeErr := acme.NewError(acme.ErrorUnauthorizedType, "account 'accountID' is not authorized")
  1218. acmeErr.Status = http.StatusForbidden
  1219. acmeErr.Detail = "No authorization provided for name test.example.com"
  1220. cert := &x509.Certificate{
  1221. Subject: pkix.Name{
  1222. CommonName: "test.example.com",
  1223. },
  1224. }
  1225. return test{
  1226. err: nil,
  1227. cert: cert,
  1228. unauthorizedIdentifiers: []acme.Identifier{},
  1229. msg: "account 'accountID' is not authorized",
  1230. want: acmeErr,
  1231. }
  1232. },
  1233. "wrap-subject": func(t *testing.T) test {
  1234. acmeErr := acme.NewError(acme.ErrorUnauthorizedType, "verification of jws using certificate public key failed: go-jose/go-jose: error in cryptographic primitive")
  1235. acmeErr.Status = http.StatusForbidden
  1236. acmeErr.Detail = "No authorization provided for name test.example.com"
  1237. cert := &x509.Certificate{
  1238. Subject: pkix.Name{
  1239. CommonName: "test.example.com",
  1240. },
  1241. }
  1242. return test{
  1243. err: errors.New("go-jose/go-jose: error in cryptographic primitive"),
  1244. cert: cert,
  1245. unauthorizedIdentifiers: []acme.Identifier{},
  1246. msg: "verification of jws using certificate public key failed",
  1247. want: acmeErr,
  1248. }
  1249. },
  1250. "default": func(t *testing.T) test {
  1251. acmeErr := acme.NewError(acme.ErrorUnauthorizedType, "account 'accountID' is not authorized")
  1252. acmeErr.Status = http.StatusForbidden
  1253. acmeErr.Detail = "No authorization provided"
  1254. cert := &x509.Certificate{
  1255. Subject: pkix.Name{
  1256. CommonName: "",
  1257. },
  1258. }
  1259. return test{
  1260. err: nil,
  1261. cert: cert,
  1262. unauthorizedIdentifiers: []acme.Identifier{},
  1263. msg: "account 'accountID' is not authorized",
  1264. want: acmeErr,
  1265. }
  1266. },
  1267. }
  1268. for name, prep := range tests {
  1269. tc := prep(t)
  1270. t.Run(name, func(t *testing.T) {
  1271. acmeErr := wrapUnauthorizedError(tc.cert, tc.unauthorizedIdentifiers, tc.msg, tc.err)
  1272. assert.Equals(t, acmeErr.Err.Error(), tc.want.Err.Error())
  1273. assert.Equals(t, acmeErr.Type, tc.want.Type)
  1274. assert.Equals(t, acmeErr.Status, tc.want.Status)
  1275. assert.Equals(t, acmeErr.Detail, tc.want.Detail)
  1276. assert.Equals(t, acmeErr.Subproblems, tc.want.Subproblems)
  1277. })
  1278. }
  1279. }