revoke_test.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  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"
  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(sha 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) Sign(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...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. ctx: ctx,
  482. statusCode: 500,
  483. err: acme.NewErrorISE("jws expected in request context"),
  484. }
  485. },
  486. "fail/nil-jws": func(t *testing.T) test {
  487. ctx := context.WithValue(context.Background(), jwsContextKey, nil)
  488. return test{
  489. ctx: ctx,
  490. statusCode: 500,
  491. err: acme.NewErrorISE("jws expected in request context"),
  492. }
  493. },
  494. "fail/no-provisioner": func(t *testing.T) test {
  495. ctx := context.WithValue(context.Background(), jwsContextKey, jws)
  496. return test{
  497. ctx: ctx,
  498. statusCode: 500,
  499. err: acme.NewErrorISE("provisioner does not exist"),
  500. }
  501. },
  502. "fail/nil-provisioner": func(t *testing.T) test {
  503. ctx := context.WithValue(context.Background(), jwsContextKey, jws)
  504. ctx = context.WithValue(ctx, provisionerContextKey, nil)
  505. return test{
  506. ctx: ctx,
  507. statusCode: 500,
  508. err: acme.NewErrorISE("provisioner does not exist"),
  509. }
  510. },
  511. "fail/no-payload": func(t *testing.T) test {
  512. ctx := context.WithValue(context.Background(), jwsContextKey, jws)
  513. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  514. return test{
  515. ctx: ctx,
  516. statusCode: 500,
  517. err: acme.NewErrorISE("payload does not exist"),
  518. }
  519. },
  520. "fail/nil-payload": func(t *testing.T) test {
  521. ctx := context.WithValue(context.Background(), jwsContextKey, jws)
  522. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  523. ctx = context.WithValue(ctx, payloadContextKey, nil)
  524. return test{
  525. ctx: ctx,
  526. statusCode: 500,
  527. err: acme.NewErrorISE("payload does not exist"),
  528. }
  529. },
  530. "fail/unmarshal-payload": func(t *testing.T) test {
  531. malformedPayload := []byte(`{"payload":malformed?}`)
  532. ctx := context.WithValue(context.Background(), jwsContextKey, jws)
  533. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  534. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: malformedPayload})
  535. return test{
  536. ctx: ctx,
  537. statusCode: 500,
  538. err: acme.NewErrorISE("error unmarshaling payload"),
  539. }
  540. },
  541. "fail/wrong-certificate-encoding": func(t *testing.T) test {
  542. wrongPayload := &revokePayload{
  543. Certificate: base64.StdEncoding.EncodeToString(cert.Raw),
  544. }
  545. wronglyEncodedPayloadBytes, err := json.Marshal(wrongPayload)
  546. assert.FatalError(t, err)
  547. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  548. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: wronglyEncodedPayloadBytes})
  549. ctx = context.WithValue(ctx, jwsContextKey, jws)
  550. return test{
  551. ctx: ctx,
  552. statusCode: 400,
  553. err: &acme.Error{
  554. Type: "urn:ietf:params:acme:error:malformed",
  555. Status: 400,
  556. Detail: "The request message was malformed",
  557. },
  558. }
  559. },
  560. "fail/no-certificate-encoded": func(t *testing.T) test {
  561. emptyPayload := &revokePayload{
  562. Certificate: base64.RawURLEncoding.EncodeToString([]byte{}),
  563. }
  564. emptyPayloadBytes, err := json.Marshal(emptyPayload)
  565. assert.FatalError(t, err)
  566. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  567. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: emptyPayloadBytes})
  568. ctx = context.WithValue(ctx, jwsContextKey, jws)
  569. return test{
  570. ctx: ctx,
  571. statusCode: 400,
  572. err: &acme.Error{
  573. Type: "urn:ietf:params:acme:error:malformed",
  574. Status: 400,
  575. Detail: "The request message was malformed",
  576. },
  577. }
  578. },
  579. "fail/db.GetCertificateBySerial": func(t *testing.T) test {
  580. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  581. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  582. ctx = context.WithValue(ctx, jwsContextKey, jws)
  583. db := &acme.MockDB{
  584. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  585. return nil, errors.New("force")
  586. },
  587. }
  588. return test{
  589. db: db,
  590. ctx: ctx,
  591. statusCode: 500,
  592. err: acme.NewErrorISE("error retrieving certificate by serial"),
  593. }
  594. },
  595. "fail/different-certificate-contents": func(t *testing.T) test {
  596. aDifferentCert, _, err := generateCertKeyPair()
  597. assert.FatalError(t, err)
  598. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  599. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  600. ctx = context.WithValue(ctx, jwsContextKey, jws)
  601. db := &acme.MockDB{
  602. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  603. assert.Equals(t, cert.SerialNumber.String(), serial)
  604. return &acme.Certificate{
  605. Leaf: aDifferentCert,
  606. }, nil
  607. },
  608. }
  609. return test{
  610. db: db,
  611. ctx: ctx,
  612. statusCode: 500,
  613. err: acme.NewErrorISE("certificate raw bytes are not equal"),
  614. }
  615. },
  616. "fail/no-account": func(t *testing.T) test {
  617. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  618. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  619. ctx = context.WithValue(ctx, jwsContextKey, jws)
  620. db := &acme.MockDB{
  621. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  622. assert.Equals(t, cert.SerialNumber.String(), serial)
  623. return &acme.Certificate{
  624. Leaf: cert,
  625. }, nil
  626. },
  627. }
  628. return test{
  629. db: db,
  630. ctx: ctx,
  631. statusCode: 400,
  632. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account not in context"),
  633. }
  634. },
  635. "fail/nil-account": func(t *testing.T) test {
  636. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  637. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  638. ctx = context.WithValue(ctx, jwsContextKey, jws)
  639. ctx = context.WithValue(ctx, accContextKey, nil)
  640. db := &acme.MockDB{
  641. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  642. assert.Equals(t, cert.SerialNumber.String(), serial)
  643. return &acme.Certificate{
  644. Leaf: cert,
  645. }, nil
  646. },
  647. }
  648. return test{
  649. db: db,
  650. ctx: ctx,
  651. statusCode: 400,
  652. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account not in context"),
  653. }
  654. },
  655. "fail/account-not-valid": func(t *testing.T) test {
  656. acc := &acme.Account{ID: "accountID", Status: acme.StatusInvalid}
  657. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  658. ctx = context.WithValue(ctx, accContextKey, acc)
  659. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  660. ctx = context.WithValue(ctx, jwsContextKey, jws)
  661. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  662. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  663. db := &acme.MockDB{
  664. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  665. assert.Equals(t, cert.SerialNumber.String(), serial)
  666. return &acme.Certificate{
  667. AccountID: "accountID",
  668. Leaf: cert,
  669. }, nil
  670. },
  671. }
  672. ca := &mockCA{}
  673. return test{
  674. db: db,
  675. ca: ca,
  676. ctx: ctx,
  677. statusCode: 403,
  678. err: &acme.Error{
  679. Type: "urn:ietf:params:acme:error:unauthorized",
  680. Detail: "No authorization provided for name 127.0.0.1",
  681. Status: 403,
  682. },
  683. }
  684. },
  685. "fail/account-not-authorized": func(t *testing.T) test {
  686. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  687. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  688. ctx = context.WithValue(ctx, accContextKey, acc)
  689. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  690. ctx = context.WithValue(ctx, jwsContextKey, jws)
  691. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  692. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  693. db := &acme.MockDB{
  694. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  695. assert.Equals(t, cert.SerialNumber.String(), serial)
  696. return &acme.Certificate{
  697. AccountID: "differentAccountID",
  698. Leaf: cert,
  699. }, nil
  700. },
  701. MockGetAuthorizationsByAccountID: func(ctx context.Context, accountID string) ([]*acme.Authorization, error) {
  702. assert.Equals(t, "accountID", accountID)
  703. return []*acme.Authorization{
  704. {
  705. AccountID: "accountID",
  706. Status: acme.StatusValid,
  707. Identifier: acme.Identifier{
  708. Type: acme.IP,
  709. Value: "127.0.1.0",
  710. },
  711. },
  712. }, nil
  713. },
  714. }
  715. ca := &mockCA{}
  716. return test{
  717. db: db,
  718. ca: ca,
  719. ctx: ctx,
  720. statusCode: 403,
  721. err: &acme.Error{
  722. Type: "urn:ietf:params:acme:error:unauthorized",
  723. Detail: "No authorization provided for name 127.0.0.1",
  724. Status: 403,
  725. },
  726. }
  727. },
  728. "fail/unauthorized-certificate-key": func(t *testing.T) test {
  729. _, unauthorizedKey, err := generateCertKeyPair()
  730. assert.FatalError(t, err)
  731. jwsPayload := &revokePayload{
  732. Certificate: base64.RawURLEncoding.EncodeToString(cert.Raw),
  733. ReasonCode: v(2),
  734. }
  735. jwsBytes, err := jwsEncodeJSON(rp, unauthorizedKey, "", "nonce", revokeURL)
  736. assert.FatalError(t, err)
  737. parsedJWS, err := jose.ParseJWS(string(jwsBytes))
  738. assert.FatalError(t, err)
  739. unauthorizedPayloadBytes, err := json.Marshal(jwsPayload)
  740. assert.FatalError(t, err)
  741. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  742. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: unauthorizedPayloadBytes})
  743. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  744. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  745. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  746. db := &acme.MockDB{
  747. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  748. assert.Equals(t, cert.SerialNumber.String(), serial)
  749. return &acme.Certificate{
  750. AccountID: "accountID",
  751. Leaf: cert,
  752. }, nil
  753. },
  754. }
  755. ca := &mockCA{}
  756. acmeErr := acme.NewError(acme.ErrorUnauthorizedType, "verification of jws using certificate public key failed")
  757. acmeErr.Detail = "No authorization provided for name 127.0.0.1"
  758. return test{
  759. db: db,
  760. ca: ca,
  761. ctx: ctx,
  762. statusCode: 403,
  763. err: acmeErr,
  764. }
  765. },
  766. "fail/certificate-revoked-check-fails": func(t *testing.T) test {
  767. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  768. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  769. ctx = context.WithValue(ctx, accContextKey, acc)
  770. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  771. ctx = context.WithValue(ctx, jwsContextKey, jws)
  772. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  773. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  774. db := &acme.MockDB{
  775. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  776. assert.Equals(t, cert.SerialNumber.String(), serial)
  777. return &acme.Certificate{
  778. AccountID: "accountID",
  779. Leaf: cert,
  780. }, nil
  781. },
  782. }
  783. ca := &mockCA{
  784. MockIsRevoked: func(sn string) (bool, error) {
  785. return false, errors.New("force")
  786. },
  787. }
  788. return test{
  789. db: db,
  790. ca: ca,
  791. ctx: ctx,
  792. statusCode: 500,
  793. err: &acme.Error{
  794. Type: "urn:ietf:params:acme:error:serverInternal",
  795. Detail: "The server experienced an internal error",
  796. Status: 500,
  797. },
  798. }
  799. },
  800. "fail/certificate-already-revoked": func(t *testing.T) test {
  801. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  802. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  803. ctx = context.WithValue(ctx, accContextKey, acc)
  804. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  805. ctx = context.WithValue(ctx, jwsContextKey, jws)
  806. db := &acme.MockDB{
  807. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  808. assert.Equals(t, cert.SerialNumber.String(), serial)
  809. return &acme.Certificate{
  810. AccountID: "accountID",
  811. Leaf: cert,
  812. }, nil
  813. },
  814. }
  815. ca := &mockCA{
  816. MockIsRevoked: func(sn string) (bool, error) {
  817. return true, nil
  818. },
  819. }
  820. return test{
  821. db: db,
  822. ca: ca,
  823. ctx: ctx,
  824. statusCode: 400,
  825. err: &acme.Error{
  826. Type: "urn:ietf:params:acme:error:alreadyRevoked",
  827. Detail: "Certificate already revoked",
  828. Status: 400,
  829. },
  830. }
  831. },
  832. "fail/invalid-reasoncode": func(t *testing.T) test {
  833. invalidReasonPayload := &revokePayload{
  834. Certificate: base64.RawURLEncoding.EncodeToString(cert.Raw),
  835. ReasonCode: v(7),
  836. }
  837. invalidReasonCodePayloadBytes, err := json.Marshal(invalidReasonPayload)
  838. assert.FatalError(t, err)
  839. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  840. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  841. ctx = context.WithValue(ctx, accContextKey, acc)
  842. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: invalidReasonCodePayloadBytes})
  843. ctx = context.WithValue(ctx, jwsContextKey, jws)
  844. db := &acme.MockDB{
  845. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  846. assert.Equals(t, cert.SerialNumber.String(), serial)
  847. return &acme.Certificate{
  848. AccountID: "accountID",
  849. Leaf: cert,
  850. }, nil
  851. },
  852. }
  853. ca := &mockCA{
  854. MockIsRevoked: func(sn string) (bool, error) {
  855. return false, nil
  856. },
  857. }
  858. return test{
  859. db: db,
  860. ca: ca,
  861. ctx: ctx,
  862. statusCode: 400,
  863. err: &acme.Error{
  864. Type: "urn:ietf:params:acme:error:badRevocationReason",
  865. Detail: "The revocation reason provided is not allowed by the server",
  866. Status: 400,
  867. },
  868. }
  869. },
  870. "fail/prov.AuthorizeRevoke": func(t *testing.T) test {
  871. assert.FatalError(t, err)
  872. mockACMEProv := &acme.MockProvisioner{
  873. MauthorizeRevoke: func(ctx context.Context, token string) error {
  874. return errors.New("force")
  875. },
  876. }
  877. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  878. ctx := context.WithValue(context.Background(), provisionerContextKey, mockACMEProv)
  879. ctx = context.WithValue(ctx, accContextKey, acc)
  880. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  881. ctx = context.WithValue(ctx, jwsContextKey, jws)
  882. db := &acme.MockDB{
  883. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  884. assert.Equals(t, cert.SerialNumber.String(), serial)
  885. return &acme.Certificate{
  886. AccountID: "accountID",
  887. Leaf: cert,
  888. }, nil
  889. },
  890. }
  891. ca := &mockCA{
  892. MockIsRevoked: func(sn string) (bool, error) {
  893. return false, nil
  894. },
  895. }
  896. return test{
  897. db: db,
  898. ca: ca,
  899. ctx: ctx,
  900. statusCode: 500,
  901. err: &acme.Error{
  902. Type: "urn:ietf:params:acme:error:serverInternal",
  903. Detail: "The server experienced an internal error",
  904. Status: 500,
  905. },
  906. }
  907. },
  908. "fail/ca.Revoke": func(t *testing.T) test {
  909. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  910. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  911. ctx = context.WithValue(ctx, accContextKey, acc)
  912. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  913. ctx = context.WithValue(ctx, jwsContextKey, jws)
  914. db := &acme.MockDB{
  915. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  916. assert.Equals(t, cert.SerialNumber.String(), serial)
  917. return &acme.Certificate{
  918. AccountID: "accountID",
  919. Leaf: cert,
  920. }, nil
  921. },
  922. }
  923. ca := &mockCA{
  924. MockRevoke: func(ctx context.Context, opts *authority.RevokeOptions) error {
  925. return errors.New("force")
  926. },
  927. }
  928. return test{
  929. db: db,
  930. ca: ca,
  931. ctx: ctx,
  932. statusCode: 500,
  933. err: &acme.Error{
  934. Type: "urn:ietf:params:acme:error:serverInternal",
  935. Detail: "The server experienced an internal error",
  936. Status: 500,
  937. },
  938. }
  939. },
  940. "fail/ca.Revoke-already-revoked": func(t *testing.T) test {
  941. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  942. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  943. ctx = context.WithValue(ctx, accContextKey, acc)
  944. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  945. ctx = context.WithValue(ctx, jwsContextKey, jws)
  946. db := &acme.MockDB{
  947. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  948. assert.Equals(t, cert.SerialNumber.String(), serial)
  949. return &acme.Certificate{
  950. AccountID: "accountID",
  951. Leaf: cert,
  952. }, nil
  953. },
  954. }
  955. ca := &mockCA{
  956. MockIsRevoked: func(sn string) (bool, error) {
  957. return false, nil
  958. },
  959. MockRevoke: func(ctx context.Context, opts *authority.RevokeOptions) error {
  960. return fmt.Errorf("certificate with serial number '%s' is already revoked", cert.SerialNumber.String())
  961. },
  962. }
  963. return test{
  964. db: db,
  965. ca: ca,
  966. ctx: ctx,
  967. statusCode: 400,
  968. err: acme.NewError(acme.ErrorAlreadyRevokedType, "certificate with serial number '%s' is already revoked", cert.SerialNumber.String()),
  969. }
  970. },
  971. "ok/using-account-key": func(t *testing.T) test {
  972. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  973. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  974. ctx = context.WithValue(ctx, accContextKey, acc)
  975. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  976. ctx = context.WithValue(ctx, jwsContextKey, jws)
  977. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  978. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  979. db := &acme.MockDB{
  980. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  981. assert.Equals(t, cert.SerialNumber.String(), serial)
  982. return &acme.Certificate{
  983. AccountID: "accountID",
  984. Leaf: cert,
  985. }, nil
  986. },
  987. }
  988. ca := &mockCA{}
  989. return test{
  990. db: db,
  991. ca: ca,
  992. ctx: ctx,
  993. statusCode: 200,
  994. }
  995. },
  996. "ok/using-certificate-key": func(t *testing.T) test {
  997. jwsBytes, err := jwsEncodeJSON(rp, key, "", "nonce", revokeURL)
  998. assert.FatalError(t, err)
  999. jws, err := jose.ParseJWS(string(jwsBytes))
  1000. assert.FatalError(t, err)
  1001. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  1002. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  1003. ctx = context.WithValue(ctx, jwsContextKey, jws)
  1004. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  1005. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  1006. db := &acme.MockDB{
  1007. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  1008. assert.Equals(t, cert.SerialNumber.String(), serial)
  1009. return &acme.Certificate{
  1010. AccountID: "someDifferentAccountID",
  1011. Leaf: cert,
  1012. }, nil
  1013. },
  1014. }
  1015. ca := &mockCA{}
  1016. return test{
  1017. db: db,
  1018. ca: ca,
  1019. ctx: ctx,
  1020. statusCode: 200,
  1021. }
  1022. },
  1023. }
  1024. for name, setup := range tests {
  1025. tc := setup(t)
  1026. t.Run(name, func(t *testing.T) {
  1027. h := &Handler{linker: NewLinker("dns", "acme"), db: tc.db, ca: tc.ca}
  1028. req := httptest.NewRequest("POST", revokeURL, nil)
  1029. req = req.WithContext(tc.ctx)
  1030. w := httptest.NewRecorder()
  1031. h.RevokeCert(w, req)
  1032. res := w.Result()
  1033. assert.Equals(t, res.StatusCode, tc.statusCode)
  1034. body, err := io.ReadAll(res.Body)
  1035. res.Body.Close()
  1036. assert.FatalError(t, err)
  1037. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  1038. var ae acme.Error
  1039. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  1040. assert.Equals(t, ae.Type, tc.err.Type)
  1041. assert.Equals(t, ae.Detail, tc.err.Detail)
  1042. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  1043. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  1044. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  1045. } else {
  1046. assert.True(t, bytes.Equal(bytes.TrimSpace(body), []byte{}))
  1047. assert.Equals(t, int64(0), req.ContentLength)
  1048. assert.Equals(t, []string{fmt.Sprintf("<%s/acme/%s/directory>;rel=\"index\"", baseURL.String(), escProvName)}, res.Header["Link"])
  1049. }
  1050. })
  1051. }
  1052. }
  1053. func TestHandler_isAccountAuthorized(t *testing.T) {
  1054. type test struct {
  1055. db acme.DB
  1056. ctx context.Context
  1057. existingCert *acme.Certificate
  1058. certToBeRevoked *x509.Certificate
  1059. account *acme.Account
  1060. err *acme.Error
  1061. }
  1062. accountID := "accountID"
  1063. var tests = map[string]func(t *testing.T) test{
  1064. "fail/account-invalid": func(t *testing.T) test {
  1065. account := &acme.Account{
  1066. ID: accountID,
  1067. Status: acme.StatusInvalid,
  1068. }
  1069. certToBeRevoked := &x509.Certificate{
  1070. Subject: pkix.Name{
  1071. CommonName: "127.0.0.1",
  1072. },
  1073. }
  1074. return test{
  1075. ctx: context.TODO(),
  1076. certToBeRevoked: certToBeRevoked,
  1077. account: account,
  1078. err: &acme.Error{
  1079. Type: "urn:ietf:params:acme:error:unauthorized",
  1080. Status: http.StatusForbidden,
  1081. Detail: "No authorization provided for name 127.0.0.1",
  1082. Err: errors.New("account 'accountID' has status 'invalid'"),
  1083. },
  1084. }
  1085. },
  1086. "fail/different-account": func(t *testing.T) test {
  1087. account := &acme.Account{
  1088. ID: accountID,
  1089. Status: acme.StatusValid,
  1090. }
  1091. certToBeRevoked := &x509.Certificate{
  1092. IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
  1093. }
  1094. existingCert := &acme.Certificate{
  1095. AccountID: "differentAccountID",
  1096. }
  1097. return test{
  1098. db: &acme.MockDB{
  1099. MockGetAuthorizationsByAccountID: func(ctx context.Context, accountID string) ([]*acme.Authorization, error) {
  1100. assert.Equals(t, "accountID", accountID)
  1101. return []*acme.Authorization{
  1102. {
  1103. AccountID: accountID,
  1104. Status: acme.StatusValid,
  1105. Identifier: acme.Identifier{
  1106. Type: acme.IP,
  1107. Value: "127.0.0.1",
  1108. },
  1109. },
  1110. }, nil
  1111. },
  1112. },
  1113. ctx: context.TODO(),
  1114. existingCert: existingCert,
  1115. certToBeRevoked: certToBeRevoked,
  1116. account: account,
  1117. err: &acme.Error{
  1118. Type: "urn:ietf:params:acme:error:unauthorized",
  1119. Status: http.StatusForbidden,
  1120. Detail: "No authorization provided",
  1121. Err: errors.New("account 'accountID' is not authorized"),
  1122. },
  1123. }
  1124. },
  1125. "ok": func(t *testing.T) test {
  1126. account := &acme.Account{
  1127. ID: accountID,
  1128. Status: acme.StatusValid,
  1129. }
  1130. certToBeRevoked := &x509.Certificate{
  1131. IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
  1132. }
  1133. existingCert := &acme.Certificate{
  1134. AccountID: "accountID",
  1135. }
  1136. return test{
  1137. db: &acme.MockDB{
  1138. MockGetAuthorizationsByAccountID: func(ctx context.Context, accountID string) ([]*acme.Authorization, error) {
  1139. assert.Equals(t, "accountID", accountID)
  1140. return []*acme.Authorization{
  1141. {
  1142. AccountID: accountID,
  1143. Status: acme.StatusValid,
  1144. Identifier: acme.Identifier{
  1145. Type: acme.IP,
  1146. Value: "127.0.0.1",
  1147. },
  1148. },
  1149. }, nil
  1150. },
  1151. },
  1152. ctx: context.TODO(),
  1153. existingCert: existingCert,
  1154. certToBeRevoked: certToBeRevoked,
  1155. account: account,
  1156. err: nil,
  1157. }
  1158. },
  1159. }
  1160. for name, setup := range tests {
  1161. tc := setup(t)
  1162. t.Run(name, func(t *testing.T) {
  1163. h := &Handler{db: tc.db}
  1164. acmeErr := h.isAccountAuthorized(tc.ctx, tc.existingCert, tc.certToBeRevoked, tc.account)
  1165. expectError := tc.err != nil
  1166. gotError := acmeErr != nil
  1167. if expectError != gotError {
  1168. t.Errorf("expected: %t, got: %t", expectError, gotError)
  1169. return
  1170. }
  1171. if !gotError {
  1172. return // nothing to check; return early
  1173. }
  1174. assert.Equals(t, acmeErr.Err.Error(), tc.err.Err.Error())
  1175. assert.Equals(t, acmeErr.Type, tc.err.Type)
  1176. assert.Equals(t, acmeErr.Status, tc.err.Status)
  1177. assert.Equals(t, acmeErr.Detail, tc.err.Detail)
  1178. assert.Equals(t, acmeErr.Identifier, tc.err.Identifier)
  1179. assert.Equals(t, acmeErr.Subproblems, tc.err.Subproblems)
  1180. })
  1181. }
  1182. }
  1183. func Test_wrapUnauthorizedError(t *testing.T) {
  1184. type test struct {
  1185. cert *x509.Certificate
  1186. unauthorizedIdentifiers []acme.Identifier
  1187. msg string
  1188. err error
  1189. want *acme.Error
  1190. }
  1191. var tests = map[string]func(t *testing.T) test{
  1192. "unauthorizedIdentifiers": func(t *testing.T) test {
  1193. acmeErr := acme.NewError(acme.ErrorUnauthorizedType, "account 'accountID' is not authorized")
  1194. acmeErr.Status = http.StatusForbidden
  1195. acmeErr.Detail = "No authorization provided for name 127.0.0.1"
  1196. return test{
  1197. err: nil,
  1198. cert: nil,
  1199. unauthorizedIdentifiers: []acme.Identifier{
  1200. {
  1201. Type: acme.IP,
  1202. Value: "127.0.0.1",
  1203. },
  1204. },
  1205. msg: "account 'accountID' is not authorized",
  1206. want: acmeErr,
  1207. }
  1208. },
  1209. "subject": func(t *testing.T) test {
  1210. acmeErr := acme.NewError(acme.ErrorUnauthorizedType, "account 'accountID' is not authorized")
  1211. acmeErr.Status = http.StatusForbidden
  1212. acmeErr.Detail = "No authorization provided for name test.example.com"
  1213. cert := &x509.Certificate{
  1214. Subject: pkix.Name{
  1215. CommonName: "test.example.com",
  1216. },
  1217. }
  1218. return test{
  1219. err: nil,
  1220. cert: cert,
  1221. unauthorizedIdentifiers: []acme.Identifier{},
  1222. msg: "account 'accountID' is not authorized",
  1223. want: acmeErr,
  1224. }
  1225. },
  1226. "wrap-subject": func(t *testing.T) test {
  1227. acmeErr := acme.NewError(acme.ErrorUnauthorizedType, "verification of jws using certificate public key failed: square/go-jose: error in cryptographic primitive")
  1228. acmeErr.Status = http.StatusForbidden
  1229. acmeErr.Detail = "No authorization provided for name test.example.com"
  1230. cert := &x509.Certificate{
  1231. Subject: pkix.Name{
  1232. CommonName: "test.example.com",
  1233. },
  1234. }
  1235. return test{
  1236. err: errors.New("square/go-jose: error in cryptographic primitive"),
  1237. cert: cert,
  1238. unauthorizedIdentifiers: []acme.Identifier{},
  1239. msg: "verification of jws using certificate public key failed",
  1240. want: acmeErr,
  1241. }
  1242. },
  1243. "default": func(t *testing.T) test {
  1244. acmeErr := acme.NewError(acme.ErrorUnauthorizedType, "account 'accountID' is not authorized")
  1245. acmeErr.Status = http.StatusForbidden
  1246. acmeErr.Detail = "No authorization provided"
  1247. cert := &x509.Certificate{
  1248. Subject: pkix.Name{
  1249. CommonName: "",
  1250. },
  1251. }
  1252. return test{
  1253. err: nil,
  1254. cert: cert,
  1255. unauthorizedIdentifiers: []acme.Identifier{},
  1256. msg: "account 'accountID' is not authorized",
  1257. want: acmeErr,
  1258. }
  1259. },
  1260. }
  1261. for name, prep := range tests {
  1262. tc := prep(t)
  1263. t.Run(name, func(t *testing.T) {
  1264. acmeErr := wrapUnauthorizedError(tc.cert, tc.unauthorizedIdentifiers, tc.msg, tc.err)
  1265. assert.Equals(t, acmeErr.Err.Error(), tc.want.Err.Error())
  1266. assert.Equals(t, acmeErr.Type, tc.want.Type)
  1267. assert.Equals(t, acmeErr.Status, tc.want.Status)
  1268. assert.Equals(t, acmeErr.Detail, tc.want.Detail)
  1269. assert.Equals(t, acmeErr.Identifier, tc.want.Identifier)
  1270. assert.Equals(t, acmeErr.Subproblems, tc.want.Subproblems)
  1271. })
  1272. }
  1273. }