revoke_test.go 41 KB

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