revoke_test.go 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  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. "github.com/smallstep/assert"
  26. "github.com/smallstep/certificates/acme"
  27. "github.com/smallstep/certificates/authority"
  28. "github.com/smallstep/certificates/authority/provisioner"
  29. "go.step.sm/crypto/jose"
  30. "go.step.sm/crypto/keyutil"
  31. "go.step.sm/crypto/x509util"
  32. "golang.org/x/crypto/ocsp"
  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. }
  254. func (m *mockCA) Sign(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error) {
  255. return nil, nil
  256. }
  257. func (m *mockCA) IsRevoked(sn string) (bool, error) {
  258. if m.MockIsRevoked != nil {
  259. return m.MockIsRevoked(sn)
  260. }
  261. return false, nil
  262. }
  263. func (m *mockCA) Revoke(ctx context.Context, opts *authority.RevokeOptions) error {
  264. if m.MockRevoke != nil {
  265. return m.MockRevoke(ctx, opts)
  266. }
  267. return nil
  268. }
  269. func (m *mockCA) LoadProvisionerByName(string) (provisioner.Interface, error) {
  270. return nil, nil
  271. }
  272. func Test_validateReasonCode(t *testing.T) {
  273. tests := []struct {
  274. name string
  275. reasonCode *int
  276. want *acme.Error
  277. }{
  278. {
  279. name: "ok",
  280. reasonCode: v(ocsp.Unspecified),
  281. want: nil,
  282. },
  283. {
  284. name: "fail/too-low",
  285. reasonCode: v(-1),
  286. want: acme.NewError(acme.ErrorBadRevocationReasonType, "reasonCode out of bounds"),
  287. },
  288. {
  289. name: "fail/too-high",
  290. reasonCode: v(11),
  291. want: acme.NewError(acme.ErrorBadRevocationReasonType, "reasonCode out of bounds"),
  292. },
  293. {
  294. name: "fail/missing-7",
  295. reasonCode: v(7),
  296. want: acme.NewError(acme.ErrorBadRevocationReasonType, "reasonCode out of bounds"),
  297. },
  298. }
  299. for _, tt := range tests {
  300. t.Run(tt.name, func(t *testing.T) {
  301. err := validateReasonCode(tt.reasonCode)
  302. if (err != nil) != (tt.want != nil) {
  303. t.Errorf("validateReasonCode() = %v, want %v", err, tt.want)
  304. }
  305. if err != nil {
  306. assert.Equals(t, err.Type, tt.want.Type)
  307. assert.Equals(t, err.Detail, tt.want.Detail)
  308. assert.Equals(t, err.Status, tt.want.Status)
  309. assert.Equals(t, err.Err.Error(), tt.want.Err.Error())
  310. assert.Equals(t, err.Detail, tt.want.Detail)
  311. }
  312. })
  313. }
  314. }
  315. func Test_reason(t *testing.T) {
  316. tests := []struct {
  317. name string
  318. reasonCode int
  319. want string
  320. }{
  321. {
  322. name: "unspecified reason",
  323. reasonCode: ocsp.Unspecified,
  324. want: "unspecified reason",
  325. },
  326. {
  327. name: "key compromised",
  328. reasonCode: ocsp.KeyCompromise,
  329. want: "key compromised",
  330. },
  331. {
  332. name: "ca compromised",
  333. reasonCode: ocsp.CACompromise,
  334. want: "ca compromised",
  335. },
  336. {
  337. name: "affiliation changed",
  338. reasonCode: ocsp.AffiliationChanged,
  339. want: "affiliation changed",
  340. },
  341. {
  342. name: "superseded",
  343. reasonCode: ocsp.Superseded,
  344. want: "superseded",
  345. },
  346. {
  347. name: "cessation of operation",
  348. reasonCode: ocsp.CessationOfOperation,
  349. want: "cessation of operation",
  350. },
  351. {
  352. name: "certificate hold",
  353. reasonCode: ocsp.CertificateHold,
  354. want: "certificate hold",
  355. },
  356. {
  357. name: "remove from crl",
  358. reasonCode: ocsp.RemoveFromCRL,
  359. want: "remove from crl",
  360. },
  361. {
  362. name: "privilege withdrawn",
  363. reasonCode: ocsp.PrivilegeWithdrawn,
  364. want: "privilege withdrawn",
  365. },
  366. {
  367. name: "aa compromised",
  368. reasonCode: ocsp.AACompromise,
  369. want: "aa compromised",
  370. },
  371. {
  372. name: "default",
  373. reasonCode: -1,
  374. want: "unspecified reason",
  375. },
  376. }
  377. for _, tt := range tests {
  378. t.Run(tt.name, func(t *testing.T) {
  379. if got := reason(tt.reasonCode); got != tt.want {
  380. t.Errorf("reason() = %v, want %v", got, tt.want)
  381. }
  382. })
  383. }
  384. }
  385. func Test_revokeOptions(t *testing.T) {
  386. cert, _, err := generateCertKeyPair()
  387. assert.FatalError(t, err)
  388. type args struct {
  389. serial string
  390. certToBeRevoked *x509.Certificate
  391. reasonCode *int
  392. }
  393. tests := []struct {
  394. name string
  395. args args
  396. want *authority.RevokeOptions
  397. }{
  398. {
  399. name: "ok/no-reasoncode",
  400. args: args{
  401. serial: "1234",
  402. certToBeRevoked: cert,
  403. },
  404. want: &authority.RevokeOptions{
  405. Serial: "1234",
  406. Crt: cert,
  407. ACME: true,
  408. },
  409. },
  410. {
  411. name: "ok/including-reasoncode",
  412. args: args{
  413. serial: "1234",
  414. certToBeRevoked: cert,
  415. reasonCode: v(ocsp.KeyCompromise),
  416. },
  417. want: &authority.RevokeOptions{
  418. Serial: "1234",
  419. Crt: cert,
  420. ACME: true,
  421. ReasonCode: 1,
  422. Reason: "key compromised",
  423. },
  424. },
  425. }
  426. for _, tt := range tests {
  427. t.Run(tt.name, func(t *testing.T) {
  428. if got := revokeOptions(tt.args.serial, tt.args.certToBeRevoked, tt.args.reasonCode); !cmp.Equal(got, tt.want) {
  429. t.Errorf("revokeOptions() diff =\n%s", cmp.Diff(got, tt.want))
  430. }
  431. })
  432. }
  433. }
  434. func TestHandler_RevokeCert(t *testing.T) {
  435. prov := &provisioner.ACME{
  436. Type: "ACME",
  437. Name: "testprov",
  438. }
  439. escProvName := url.PathEscape(prov.GetName())
  440. baseURL := &url.URL{Scheme: "https", Host: "test.ca.smallstep.com"}
  441. chiCtx := chi.NewRouteContext()
  442. revokeURL := fmt.Sprintf("%s/acme/%s/revoke-cert", baseURL.String(), escProvName)
  443. cert, key, err := generateCertKeyPair()
  444. assert.FatalError(t, err)
  445. rp := &revokePayload{
  446. Certificate: base64.RawURLEncoding.EncodeToString(cert.Raw),
  447. }
  448. payloadBytes, err := json.Marshal(rp)
  449. assert.FatalError(t, err)
  450. jws := &jose.JSONWebSignature{
  451. Signatures: []jose.Signature{
  452. {
  453. Protected: jose.Header{
  454. Algorithm: jose.ES256,
  455. KeyID: "bar",
  456. ExtraHeaders: map[jose.HeaderKey]interface{}{
  457. "url": revokeURL,
  458. },
  459. },
  460. },
  461. },
  462. }
  463. type test struct {
  464. db acme.DB
  465. ca acme.CertificateAuthority
  466. ctx context.Context
  467. statusCode int
  468. err *acme.Error
  469. }
  470. var tests = map[string]func(t *testing.T) test{
  471. "fail/no-jws": func(t *testing.T) test {
  472. ctx := context.Background()
  473. return test{
  474. ctx: ctx,
  475. statusCode: 500,
  476. err: acme.NewErrorISE("jws expected in request context"),
  477. }
  478. },
  479. "fail/nil-jws": func(t *testing.T) test {
  480. ctx := context.WithValue(context.Background(), jwsContextKey, nil)
  481. return test{
  482. ctx: ctx,
  483. statusCode: 500,
  484. err: acme.NewErrorISE("jws expected in request context"),
  485. }
  486. },
  487. "fail/no-provisioner": func(t *testing.T) test {
  488. ctx := context.WithValue(context.Background(), jwsContextKey, jws)
  489. return test{
  490. ctx: ctx,
  491. statusCode: 500,
  492. err: acme.NewErrorISE("provisioner does not exist"),
  493. }
  494. },
  495. "fail/nil-provisioner": func(t *testing.T) test {
  496. ctx := context.WithValue(context.Background(), jwsContextKey, jws)
  497. ctx = context.WithValue(ctx, provisionerContextKey, nil)
  498. return test{
  499. ctx: ctx,
  500. statusCode: 500,
  501. err: acme.NewErrorISE("provisioner does not exist"),
  502. }
  503. },
  504. "fail/no-payload": func(t *testing.T) test {
  505. ctx := context.WithValue(context.Background(), jwsContextKey, jws)
  506. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  507. return test{
  508. ctx: ctx,
  509. statusCode: 500,
  510. err: acme.NewErrorISE("payload does not exist"),
  511. }
  512. },
  513. "fail/nil-payload": func(t *testing.T) test {
  514. ctx := context.WithValue(context.Background(), jwsContextKey, jws)
  515. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  516. ctx = context.WithValue(ctx, payloadContextKey, nil)
  517. return test{
  518. ctx: ctx,
  519. statusCode: 500,
  520. err: acme.NewErrorISE("payload does not exist"),
  521. }
  522. },
  523. "fail/unmarshal-payload": func(t *testing.T) test {
  524. malformedPayload := []byte(`{"payload":malformed?}`)
  525. ctx := context.WithValue(context.Background(), jwsContextKey, jws)
  526. ctx = context.WithValue(ctx, provisionerContextKey, prov)
  527. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: malformedPayload})
  528. return test{
  529. ctx: ctx,
  530. statusCode: 500,
  531. err: acme.NewErrorISE("error unmarshaling payload"),
  532. }
  533. },
  534. "fail/wrong-certificate-encoding": func(t *testing.T) test {
  535. wrongPayload := &revokePayload{
  536. Certificate: base64.StdEncoding.EncodeToString(cert.Raw),
  537. }
  538. wronglyEncodedPayloadBytes, err := json.Marshal(wrongPayload)
  539. assert.FatalError(t, err)
  540. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  541. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: wronglyEncodedPayloadBytes})
  542. ctx = context.WithValue(ctx, jwsContextKey, jws)
  543. return test{
  544. ctx: ctx,
  545. statusCode: 400,
  546. err: &acme.Error{
  547. Type: "urn:ietf:params:acme:error:malformed",
  548. Status: 400,
  549. Detail: "The request message was malformed",
  550. },
  551. }
  552. },
  553. "fail/no-certificate-encoded": func(t *testing.T) test {
  554. emptyPayload := &revokePayload{
  555. Certificate: base64.RawURLEncoding.EncodeToString([]byte{}),
  556. }
  557. emptyPayloadBytes, err := json.Marshal(emptyPayload)
  558. assert.FatalError(t, err)
  559. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  560. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: emptyPayloadBytes})
  561. ctx = context.WithValue(ctx, jwsContextKey, jws)
  562. return test{
  563. ctx: ctx,
  564. statusCode: 400,
  565. err: &acme.Error{
  566. Type: "urn:ietf:params:acme:error:malformed",
  567. Status: 400,
  568. Detail: "The request message was malformed",
  569. },
  570. }
  571. },
  572. "fail/db.GetCertificateBySerial": func(t *testing.T) test {
  573. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  574. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  575. ctx = context.WithValue(ctx, jwsContextKey, jws)
  576. db := &acme.MockDB{
  577. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  578. return nil, errors.New("force")
  579. },
  580. }
  581. return test{
  582. db: db,
  583. ctx: ctx,
  584. statusCode: 500,
  585. err: acme.NewErrorISE("error retrieving certificate by serial"),
  586. }
  587. },
  588. "fail/different-certificate-contents": func(t *testing.T) test {
  589. aDifferentCert, _, err := generateCertKeyPair()
  590. assert.FatalError(t, err)
  591. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  592. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  593. ctx = context.WithValue(ctx, jwsContextKey, jws)
  594. db := &acme.MockDB{
  595. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  596. assert.Equals(t, cert.SerialNumber.String(), serial)
  597. return &acme.Certificate{
  598. Leaf: aDifferentCert,
  599. }, nil
  600. },
  601. }
  602. return test{
  603. db: db,
  604. ctx: ctx,
  605. statusCode: 500,
  606. err: acme.NewErrorISE("certificate raw bytes are not equal"),
  607. }
  608. },
  609. "fail/no-account": func(t *testing.T) test {
  610. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  611. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  612. ctx = context.WithValue(ctx, jwsContextKey, jws)
  613. db := &acme.MockDB{
  614. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  615. assert.Equals(t, cert.SerialNumber.String(), serial)
  616. return &acme.Certificate{
  617. Leaf: cert,
  618. }, nil
  619. },
  620. }
  621. return test{
  622. db: db,
  623. ctx: ctx,
  624. statusCode: 400,
  625. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account not in context"),
  626. }
  627. },
  628. "fail/nil-account": func(t *testing.T) test {
  629. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  630. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  631. ctx = context.WithValue(ctx, jwsContextKey, jws)
  632. ctx = context.WithValue(ctx, accContextKey, nil)
  633. db := &acme.MockDB{
  634. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  635. assert.Equals(t, cert.SerialNumber.String(), serial)
  636. return &acme.Certificate{
  637. Leaf: cert,
  638. }, nil
  639. },
  640. }
  641. return test{
  642. db: db,
  643. ctx: ctx,
  644. statusCode: 400,
  645. err: acme.NewError(acme.ErrorAccountDoesNotExistType, "account not in context"),
  646. }
  647. },
  648. "fail/account-not-valid": func(t *testing.T) test {
  649. acc := &acme.Account{ID: "accountID", Status: acme.StatusInvalid}
  650. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  651. ctx = context.WithValue(ctx, accContextKey, acc)
  652. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  653. ctx = context.WithValue(ctx, jwsContextKey, jws)
  654. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  655. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  656. db := &acme.MockDB{
  657. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  658. assert.Equals(t, cert.SerialNumber.String(), serial)
  659. return &acme.Certificate{
  660. AccountID: "accountID",
  661. Leaf: cert,
  662. }, nil
  663. },
  664. }
  665. ca := &mockCA{}
  666. return test{
  667. db: db,
  668. ca: ca,
  669. ctx: ctx,
  670. statusCode: 403,
  671. err: &acme.Error{
  672. Type: "urn:ietf:params:acme:error:unauthorized",
  673. Detail: "No authorization provided for name 127.0.0.1",
  674. Status: 403,
  675. },
  676. }
  677. },
  678. "fail/account-not-authorized": func(t *testing.T) test {
  679. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  680. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  681. ctx = context.WithValue(ctx, accContextKey, acc)
  682. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  683. ctx = context.WithValue(ctx, jwsContextKey, jws)
  684. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  685. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  686. db := &acme.MockDB{
  687. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  688. assert.Equals(t, cert.SerialNumber.String(), serial)
  689. return &acme.Certificate{
  690. AccountID: "differentAccountID",
  691. Leaf: cert,
  692. }, nil
  693. },
  694. MockGetAuthorizationsByAccountID: func(ctx context.Context, accountID string) ([]*acme.Authorization, error) {
  695. assert.Equals(t, "accountID", accountID)
  696. return []*acme.Authorization{
  697. {
  698. AccountID: "accountID",
  699. Status: acme.StatusValid,
  700. Identifier: acme.Identifier{
  701. Type: acme.IP,
  702. Value: "127.0.1.0",
  703. },
  704. },
  705. }, nil
  706. },
  707. }
  708. ca := &mockCA{}
  709. return test{
  710. db: db,
  711. ca: ca,
  712. ctx: ctx,
  713. statusCode: 403,
  714. err: &acme.Error{
  715. Type: "urn:ietf:params:acme:error:unauthorized",
  716. Detail: "No authorization provided for name 127.0.0.1",
  717. Status: 403,
  718. },
  719. }
  720. },
  721. "fail/unauthorized-certificate-key": func(t *testing.T) test {
  722. _, unauthorizedKey, err := generateCertKeyPair()
  723. assert.FatalError(t, err)
  724. jwsPayload := &revokePayload{
  725. Certificate: base64.RawURLEncoding.EncodeToString(cert.Raw),
  726. ReasonCode: v(2),
  727. }
  728. jwsBytes, err := jwsEncodeJSON(rp, unauthorizedKey, "", "nonce", revokeURL)
  729. assert.FatalError(t, err)
  730. parsedJWS, err := jose.ParseJWS(string(jwsBytes))
  731. assert.FatalError(t, err)
  732. unauthorizedPayloadBytes, err := json.Marshal(jwsPayload)
  733. assert.FatalError(t, err)
  734. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  735. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: unauthorizedPayloadBytes})
  736. ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
  737. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  738. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  739. db := &acme.MockDB{
  740. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  741. assert.Equals(t, cert.SerialNumber.String(), serial)
  742. return &acme.Certificate{
  743. AccountID: "accountID",
  744. Leaf: cert,
  745. }, nil
  746. },
  747. }
  748. ca := &mockCA{}
  749. acmeErr := acme.NewError(acme.ErrorUnauthorizedType, "verification of jws using certificate public key failed")
  750. acmeErr.Detail = "No authorization provided for name 127.0.0.1"
  751. return test{
  752. db: db,
  753. ca: ca,
  754. ctx: ctx,
  755. statusCode: 403,
  756. err: acmeErr,
  757. }
  758. },
  759. "fail/certificate-revoked-check-fails": func(t *testing.T) test {
  760. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  761. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  762. ctx = context.WithValue(ctx, accContextKey, acc)
  763. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  764. ctx = context.WithValue(ctx, jwsContextKey, jws)
  765. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  766. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  767. db := &acme.MockDB{
  768. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  769. assert.Equals(t, cert.SerialNumber.String(), serial)
  770. return &acme.Certificate{
  771. AccountID: "accountID",
  772. Leaf: cert,
  773. }, nil
  774. },
  775. }
  776. ca := &mockCA{
  777. MockIsRevoked: func(sn string) (bool, error) {
  778. return false, errors.New("force")
  779. },
  780. }
  781. return test{
  782. db: db,
  783. ca: ca,
  784. ctx: ctx,
  785. statusCode: 500,
  786. err: &acme.Error{
  787. Type: "urn:ietf:params:acme:error:serverInternal",
  788. Detail: "The server experienced an internal error",
  789. Status: 500,
  790. },
  791. }
  792. },
  793. "fail/certificate-already-revoked": func(t *testing.T) test {
  794. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  795. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  796. ctx = context.WithValue(ctx, accContextKey, acc)
  797. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  798. ctx = context.WithValue(ctx, jwsContextKey, jws)
  799. db := &acme.MockDB{
  800. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  801. assert.Equals(t, cert.SerialNumber.String(), serial)
  802. return &acme.Certificate{
  803. AccountID: "accountID",
  804. Leaf: cert,
  805. }, nil
  806. },
  807. }
  808. ca := &mockCA{
  809. MockIsRevoked: func(sn string) (bool, error) {
  810. return true, nil
  811. },
  812. }
  813. return test{
  814. db: db,
  815. ca: ca,
  816. ctx: ctx,
  817. statusCode: 400,
  818. err: &acme.Error{
  819. Type: "urn:ietf:params:acme:error:alreadyRevoked",
  820. Detail: "Certificate already revoked",
  821. Status: 400,
  822. },
  823. }
  824. },
  825. "fail/invalid-reasoncode": func(t *testing.T) test {
  826. invalidReasonPayload := &revokePayload{
  827. Certificate: base64.RawURLEncoding.EncodeToString(cert.Raw),
  828. ReasonCode: v(7),
  829. }
  830. invalidReasonCodePayloadBytes, err := json.Marshal(invalidReasonPayload)
  831. assert.FatalError(t, err)
  832. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  833. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  834. ctx = context.WithValue(ctx, accContextKey, acc)
  835. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: invalidReasonCodePayloadBytes})
  836. ctx = context.WithValue(ctx, jwsContextKey, jws)
  837. db := &acme.MockDB{
  838. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  839. assert.Equals(t, cert.SerialNumber.String(), serial)
  840. return &acme.Certificate{
  841. AccountID: "accountID",
  842. Leaf: cert,
  843. }, nil
  844. },
  845. }
  846. ca := &mockCA{
  847. MockIsRevoked: func(sn string) (bool, error) {
  848. return false, nil
  849. },
  850. }
  851. return test{
  852. db: db,
  853. ca: ca,
  854. ctx: ctx,
  855. statusCode: 400,
  856. err: &acme.Error{
  857. Type: "urn:ietf:params:acme:error:badRevocationReason",
  858. Detail: "The revocation reason provided is not allowed by the server",
  859. Status: 400,
  860. },
  861. }
  862. },
  863. "fail/prov.AuthorizeRevoke": func(t *testing.T) test {
  864. assert.FatalError(t, err)
  865. mockACMEProv := &acme.MockProvisioner{
  866. MauthorizeRevoke: func(ctx context.Context, token string) error {
  867. return errors.New("force")
  868. },
  869. }
  870. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  871. ctx := context.WithValue(context.Background(), provisionerContextKey, mockACMEProv)
  872. ctx = context.WithValue(ctx, accContextKey, acc)
  873. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  874. ctx = context.WithValue(ctx, jwsContextKey, jws)
  875. db := &acme.MockDB{
  876. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  877. assert.Equals(t, cert.SerialNumber.String(), serial)
  878. return &acme.Certificate{
  879. AccountID: "accountID",
  880. Leaf: cert,
  881. }, nil
  882. },
  883. }
  884. ca := &mockCA{
  885. MockIsRevoked: func(sn string) (bool, error) {
  886. return false, nil
  887. },
  888. }
  889. return test{
  890. db: db,
  891. ca: ca,
  892. ctx: ctx,
  893. statusCode: 500,
  894. err: &acme.Error{
  895. Type: "urn:ietf:params:acme:error:serverInternal",
  896. Detail: "The server experienced an internal error",
  897. Status: 500,
  898. },
  899. }
  900. },
  901. "fail/ca.Revoke": func(t *testing.T) test {
  902. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  903. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  904. ctx = context.WithValue(ctx, accContextKey, acc)
  905. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  906. ctx = context.WithValue(ctx, jwsContextKey, jws)
  907. db := &acme.MockDB{
  908. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  909. assert.Equals(t, cert.SerialNumber.String(), serial)
  910. return &acme.Certificate{
  911. AccountID: "accountID",
  912. Leaf: cert,
  913. }, nil
  914. },
  915. }
  916. ca := &mockCA{
  917. MockRevoke: func(ctx context.Context, opts *authority.RevokeOptions) error {
  918. return errors.New("force")
  919. },
  920. }
  921. return test{
  922. db: db,
  923. ca: ca,
  924. ctx: ctx,
  925. statusCode: 500,
  926. err: &acme.Error{
  927. Type: "urn:ietf:params:acme:error:serverInternal",
  928. Detail: "The server experienced an internal error",
  929. Status: 500,
  930. },
  931. }
  932. },
  933. "fail/ca.Revoke-already-revoked": func(t *testing.T) test {
  934. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  935. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  936. ctx = context.WithValue(ctx, accContextKey, acc)
  937. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  938. ctx = context.WithValue(ctx, jwsContextKey, jws)
  939. db := &acme.MockDB{
  940. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  941. assert.Equals(t, cert.SerialNumber.String(), serial)
  942. return &acme.Certificate{
  943. AccountID: "accountID",
  944. Leaf: cert,
  945. }, nil
  946. },
  947. }
  948. ca := &mockCA{
  949. MockIsRevoked: func(sn string) (bool, error) {
  950. return false, nil
  951. },
  952. MockRevoke: func(ctx context.Context, opts *authority.RevokeOptions) error {
  953. return fmt.Errorf("certificate with serial number '%s' is already revoked", cert.SerialNumber.String())
  954. },
  955. }
  956. return test{
  957. db: db,
  958. ca: ca,
  959. ctx: ctx,
  960. statusCode: 400,
  961. err: acme.NewError(acme.ErrorAlreadyRevokedType, "certificate with serial number '%s' is already revoked", cert.SerialNumber.String()),
  962. }
  963. },
  964. "ok/using-account-key": func(t *testing.T) test {
  965. acc := &acme.Account{ID: "accountID", Status: acme.StatusValid}
  966. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  967. ctx = context.WithValue(ctx, accContextKey, acc)
  968. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  969. ctx = context.WithValue(ctx, jwsContextKey, jws)
  970. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  971. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  972. db := &acme.MockDB{
  973. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  974. assert.Equals(t, cert.SerialNumber.String(), serial)
  975. return &acme.Certificate{
  976. AccountID: "accountID",
  977. Leaf: cert,
  978. }, nil
  979. },
  980. }
  981. ca := &mockCA{}
  982. return test{
  983. db: db,
  984. ca: ca,
  985. ctx: ctx,
  986. statusCode: 200,
  987. }
  988. },
  989. "ok/using-certificate-key": func(t *testing.T) test {
  990. jwsBytes, err := jwsEncodeJSON(rp, key, "", "nonce", revokeURL)
  991. assert.FatalError(t, err)
  992. jws, err := jose.ParseJWS(string(jwsBytes))
  993. assert.FatalError(t, err)
  994. ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
  995. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payloadBytes})
  996. ctx = context.WithValue(ctx, jwsContextKey, jws)
  997. ctx = context.WithValue(ctx, baseURLContextKey, baseURL)
  998. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  999. db := &acme.MockDB{
  1000. MockGetCertificateBySerial: func(ctx context.Context, serial string) (*acme.Certificate, error) {
  1001. assert.Equals(t, cert.SerialNumber.String(), serial)
  1002. return &acme.Certificate{
  1003. AccountID: "someDifferentAccountID",
  1004. Leaf: cert,
  1005. }, nil
  1006. },
  1007. }
  1008. ca := &mockCA{}
  1009. return test{
  1010. db: db,
  1011. ca: ca,
  1012. ctx: ctx,
  1013. statusCode: 200,
  1014. }
  1015. },
  1016. }
  1017. for name, setup := range tests {
  1018. tc := setup(t)
  1019. t.Run(name, func(t *testing.T) {
  1020. h := &Handler{linker: NewLinker("dns", "acme"), db: tc.db, ca: tc.ca}
  1021. req := httptest.NewRequest("POST", revokeURL, nil)
  1022. req = req.WithContext(tc.ctx)
  1023. w := httptest.NewRecorder()
  1024. h.RevokeCert(w, req)
  1025. res := w.Result()
  1026. assert.Equals(t, res.StatusCode, tc.statusCode)
  1027. body, err := io.ReadAll(res.Body)
  1028. res.Body.Close()
  1029. assert.FatalError(t, err)
  1030. if res.StatusCode >= 400 && assert.NotNil(t, tc.err) {
  1031. var ae acme.Error
  1032. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
  1033. assert.Equals(t, ae.Type, tc.err.Type)
  1034. assert.Equals(t, ae.Detail, tc.err.Detail)
  1035. assert.Equals(t, ae.Identifier, tc.err.Identifier)
  1036. assert.Equals(t, ae.Subproblems, tc.err.Subproblems)
  1037. assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
  1038. } else {
  1039. assert.True(t, bytes.Equal(bytes.TrimSpace(body), []byte{}))
  1040. assert.Equals(t, int64(0), req.ContentLength)
  1041. assert.Equals(t, []string{fmt.Sprintf("<%s/acme/%s/directory>;rel=\"index\"", baseURL.String(), escProvName)}, res.Header["Link"])
  1042. }
  1043. })
  1044. }
  1045. }
  1046. func TestHandler_isAccountAuthorized(t *testing.T) {
  1047. type test struct {
  1048. db acme.DB
  1049. ctx context.Context
  1050. existingCert *acme.Certificate
  1051. certToBeRevoked *x509.Certificate
  1052. account *acme.Account
  1053. err *acme.Error
  1054. }
  1055. accountID := "accountID"
  1056. var tests = map[string]func(t *testing.T) test{
  1057. "fail/account-invalid": func(t *testing.T) test {
  1058. account := &acme.Account{
  1059. ID: accountID,
  1060. Status: acme.StatusInvalid,
  1061. }
  1062. certToBeRevoked := &x509.Certificate{
  1063. Subject: pkix.Name{
  1064. CommonName: "127.0.0.1",
  1065. },
  1066. }
  1067. return test{
  1068. ctx: context.TODO(),
  1069. certToBeRevoked: certToBeRevoked,
  1070. account: account,
  1071. err: &acme.Error{
  1072. Type: "urn:ietf:params:acme:error:unauthorized",
  1073. Status: http.StatusForbidden,
  1074. Detail: "No authorization provided for name 127.0.0.1",
  1075. Err: errors.New("account 'accountID' has status 'invalid'"),
  1076. },
  1077. }
  1078. },
  1079. "fail/different-account": func(t *testing.T) test {
  1080. account := &acme.Account{
  1081. ID: accountID,
  1082. Status: acme.StatusValid,
  1083. }
  1084. certToBeRevoked := &x509.Certificate{
  1085. IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
  1086. }
  1087. existingCert := &acme.Certificate{
  1088. AccountID: "differentAccountID",
  1089. }
  1090. return test{
  1091. db: &acme.MockDB{
  1092. MockGetAuthorizationsByAccountID: func(ctx context.Context, accountID string) ([]*acme.Authorization, error) {
  1093. assert.Equals(t, "accountID", accountID)
  1094. return []*acme.Authorization{
  1095. {
  1096. AccountID: accountID,
  1097. Status: acme.StatusValid,
  1098. Identifier: acme.Identifier{
  1099. Type: acme.IP,
  1100. Value: "127.0.0.1",
  1101. },
  1102. },
  1103. }, nil
  1104. },
  1105. },
  1106. ctx: context.TODO(),
  1107. existingCert: existingCert,
  1108. certToBeRevoked: certToBeRevoked,
  1109. account: account,
  1110. err: &acme.Error{
  1111. Type: "urn:ietf:params:acme:error:unauthorized",
  1112. Status: http.StatusForbidden,
  1113. Detail: "No authorization provided",
  1114. Err: errors.New("account 'accountID' is not authorized"),
  1115. },
  1116. }
  1117. },
  1118. "ok": func(t *testing.T) test {
  1119. account := &acme.Account{
  1120. ID: accountID,
  1121. Status: acme.StatusValid,
  1122. }
  1123. certToBeRevoked := &x509.Certificate{
  1124. IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
  1125. }
  1126. existingCert := &acme.Certificate{
  1127. AccountID: "accountID",
  1128. }
  1129. return test{
  1130. db: &acme.MockDB{
  1131. MockGetAuthorizationsByAccountID: func(ctx context.Context, accountID string) ([]*acme.Authorization, error) {
  1132. assert.Equals(t, "accountID", accountID)
  1133. return []*acme.Authorization{
  1134. {
  1135. AccountID: accountID,
  1136. Status: acme.StatusValid,
  1137. Identifier: acme.Identifier{
  1138. Type: acme.IP,
  1139. Value: "127.0.0.1",
  1140. },
  1141. },
  1142. }, nil
  1143. },
  1144. },
  1145. ctx: context.TODO(),
  1146. existingCert: existingCert,
  1147. certToBeRevoked: certToBeRevoked,
  1148. account: account,
  1149. err: nil,
  1150. }
  1151. },
  1152. }
  1153. for name, setup := range tests {
  1154. tc := setup(t)
  1155. t.Run(name, func(t *testing.T) {
  1156. h := &Handler{db: tc.db}
  1157. acmeErr := h.isAccountAuthorized(tc.ctx, tc.existingCert, tc.certToBeRevoked, tc.account)
  1158. expectError := tc.err != nil
  1159. gotError := acmeErr != nil
  1160. if expectError != gotError {
  1161. t.Errorf("expected: %t, got: %t", expectError, gotError)
  1162. return
  1163. }
  1164. if !gotError {
  1165. return // nothing to check; return early
  1166. }
  1167. assert.Equals(t, acmeErr.Err.Error(), tc.err.Err.Error())
  1168. assert.Equals(t, acmeErr.Type, tc.err.Type)
  1169. assert.Equals(t, acmeErr.Status, tc.err.Status)
  1170. assert.Equals(t, acmeErr.Detail, tc.err.Detail)
  1171. assert.Equals(t, acmeErr.Identifier, tc.err.Identifier)
  1172. assert.Equals(t, acmeErr.Subproblems, tc.err.Subproblems)
  1173. })
  1174. }
  1175. }
  1176. func Test_wrapUnauthorizedError(t *testing.T) {
  1177. type test struct {
  1178. cert *x509.Certificate
  1179. unauthorizedIdentifiers []acme.Identifier
  1180. msg string
  1181. err error
  1182. want *acme.Error
  1183. }
  1184. var tests = map[string]func(t *testing.T) test{
  1185. "unauthorizedIdentifiers": func(t *testing.T) test {
  1186. acmeErr := acme.NewError(acme.ErrorUnauthorizedType, "account 'accountID' is not authorized")
  1187. acmeErr.Status = http.StatusForbidden
  1188. acmeErr.Detail = "No authorization provided for name 127.0.0.1"
  1189. return test{
  1190. err: nil,
  1191. cert: nil,
  1192. unauthorizedIdentifiers: []acme.Identifier{
  1193. {
  1194. Type: acme.IP,
  1195. Value: "127.0.0.1",
  1196. },
  1197. },
  1198. msg: "account 'accountID' is not authorized",
  1199. want: acmeErr,
  1200. }
  1201. },
  1202. "subject": func(t *testing.T) test {
  1203. acmeErr := acme.NewError(acme.ErrorUnauthorizedType, "account 'accountID' is not authorized")
  1204. acmeErr.Status = http.StatusForbidden
  1205. acmeErr.Detail = "No authorization provided for name test.example.com"
  1206. cert := &x509.Certificate{
  1207. Subject: pkix.Name{
  1208. CommonName: "test.example.com",
  1209. },
  1210. }
  1211. return test{
  1212. err: nil,
  1213. cert: cert,
  1214. unauthorizedIdentifiers: []acme.Identifier{},
  1215. msg: "account 'accountID' is not authorized",
  1216. want: acmeErr,
  1217. }
  1218. },
  1219. "wrap-subject": func(t *testing.T) test {
  1220. acmeErr := acme.NewError(acme.ErrorUnauthorizedType, "verification of jws using certificate public key failed: square/go-jose: error in cryptographic primitive")
  1221. acmeErr.Status = http.StatusForbidden
  1222. acmeErr.Detail = "No authorization provided for name test.example.com"
  1223. cert := &x509.Certificate{
  1224. Subject: pkix.Name{
  1225. CommonName: "test.example.com",
  1226. },
  1227. }
  1228. return test{
  1229. err: errors.New("square/go-jose: error in cryptographic primitive"),
  1230. cert: cert,
  1231. unauthorizedIdentifiers: []acme.Identifier{},
  1232. msg: "verification of jws using certificate public key failed",
  1233. want: acmeErr,
  1234. }
  1235. },
  1236. "default": func(t *testing.T) test {
  1237. acmeErr := acme.NewError(acme.ErrorUnauthorizedType, "account 'accountID' is not authorized")
  1238. acmeErr.Status = http.StatusForbidden
  1239. acmeErr.Detail = "No authorization provided"
  1240. cert := &x509.Certificate{
  1241. Subject: pkix.Name{
  1242. CommonName: "",
  1243. },
  1244. }
  1245. return test{
  1246. err: nil,
  1247. cert: cert,
  1248. unauthorizedIdentifiers: []acme.Identifier{},
  1249. msg: "account 'accountID' is not authorized",
  1250. want: acmeErr,
  1251. }
  1252. },
  1253. }
  1254. for name, prep := range tests {
  1255. tc := prep(t)
  1256. t.Run(name, func(t *testing.T) {
  1257. acmeErr := wrapUnauthorizedError(tc.cert, tc.unauthorizedIdentifiers, tc.msg, tc.err)
  1258. assert.Equals(t, acmeErr.Err.Error(), tc.want.Err.Error())
  1259. assert.Equals(t, acmeErr.Type, tc.want.Type)
  1260. assert.Equals(t, acmeErr.Status, tc.want.Status)
  1261. assert.Equals(t, acmeErr.Detail, tc.want.Detail)
  1262. assert.Equals(t, acmeErr.Identifier, tc.want.Identifier)
  1263. assert.Equals(t, acmeErr.Subproblems, tc.want.Subproblems)
  1264. })
  1265. }
  1266. }