revoke_test.go 40 KB

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