4
0

revoke_test.go 41 KB

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