Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ module by commit.
| Path | Purpose |
|---|---|
| `gpgkms.go` | `Identity`, `NewEntity` (key derivation and self-signature), `WritePublicKey`, `Sign`, `SignOptions`, `ValidateSignatures`. |
| `kms.go` | `KMSSigner`, a `crypto.Signer` backed by a Cloud KMS CryptoKeyVersion. Checks the KMS algorithm and HSM protection level, only makes PKCS#1 v1.5 signatures of SHA-256 digests, bounds each request with a timeout, and verifies every KMS signature locally before returning it. |
| `kms.go` | `KMSSigner`, a `crypto.Signer` backed by a Cloud KMS CryptoKeyVersion. Checks the KMS algorithm and HSM protection level, only makes PKCS#1 v1.5 signatures of SHA-256 digests, bounds each request with a timeout, retries transient failures with backoff (`retryKMS`), and verifies every KMS signature locally before returning it. |
| `kms_test.go` | Tests `KMSSigner` against a fake Cloud KMS (`httptest` server, `option.WithEndpoint`). Use it for any KMS change; there is no other way to exercise `kms.go` without credentials. |
| `cmd/gpgkms/main.go` | CLI: flag parsing, `-fingerprint` pinning, file I/O. `newSigner` is a package variable swapped in tests. |
| `gpgkms_test.go` | Library tests; `opaqueSigner` hides `*rsa.PrivateKey` so tests use the `crypto.Signer` path like KMS does. |
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ binary one, which the Terraform Registry requires for `SHA256SUMS.sig`.
Credentials come from Application Default Credentials, for example
`google-github-actions/auth` with workload identity federation. The identity
needs `roles/cloudkms.publicKeyViewer` and `roles/cloudkms.signer` on the key.
KMS requests that fail transiently (5xx, 408, 429, network or credential
errors) are retried up to 5 times with exponential backoff; other 4xx errors
fail immediately.

### Minting the public key

Expand Down
111 changes: 98 additions & 13 deletions kms.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@ import (
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"io"
"net/http"
"time"

"google.golang.org/api/cloudkms/v1"
"google.golang.org/api/googleapi"
"google.golang.org/api/option"
)

Expand All @@ -24,6 +27,17 @@ const KMSAlgorithm = "RSA_SIGN_PKCS1_4096_SHA256"
// release job quickly instead of running until the CI job's own timeout.
const kmsRequestTimeout = time.Minute

// kmsAttempts is how many times a Cloud KMS call is tried. Release jobs have
// failed on short outages of Google's credential and KMS endpoints (for
// example a 503 while exchanging the workload identity token), so transient
// errors are retried.
const kmsAttempts = 5

// kmsRetryDelay is the wait before the first retry. It doubles after each
// failed attempt (1s, 2s, 4s, 8s), so a call gives up after about 15 seconds
// of waiting plus the time spent in the attempts themselves.
const kmsRetryDelay = time.Second

// hsmProtectionLevels are the Cloud KMS protection levels accepted: the key
// material must stay inside an HSM. SOFTWARE keys and external (EKM) keys are
// rejected.
Expand All @@ -32,10 +46,11 @@ var hsmProtectionLevels = map[string]bool{"HSM": true, "HSM_SINGLE_TENANT": true
// KMSSigner is a crypto.Signer backed by a Cloud KMS CryptoKeyVersion with the
// algorithm KMSAlgorithm.
type KMSSigner struct {
ctx context.Context
svc *cloudkms.ProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsService
name string
pub *rsa.PublicKey
ctx context.Context
svc *cloudkms.ProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsService
name string
pub *rsa.PublicKey
retryDelay time.Duration
}

// NewKMSSigner returns a signer for the CryptoKeyVersion name, e.g.
Expand All @@ -47,16 +62,24 @@ type KMSSigner struct {
//
// ctx is used for every later Sign call too, because crypto.Signer has no
// context parameter; each KMS request is additionally limited to one minute.
// Requests that fail with a transient error are retried a few times with
// exponential backoff.
func NewKMSSigner(ctx context.Context, name string, opts ...option.ClientOption) (*KMSSigner, error) {
return newKMSSigner(ctx, name, kmsRetryDelay, opts...)
}

// newKMSSigner is NewKMSSigner with a configurable first retry delay, so
// tests do not wait for real backoff.
func newKMSSigner(ctx context.Context, name string, retryDelay time.Duration, opts ...option.ClientOption) (*KMSSigner, error) {
svc, err := cloudkms.NewService(ctx, opts...)
if err != nil {
return nil, fmt.Errorf("create Cloud KMS client: %w", err)
}
versions := svc.Projects.Locations.KeyRings.CryptoKeys.CryptoKeyVersions

reqCtx, cancel := context.WithTimeout(ctx, kmsRequestTimeout)
defer cancel()
resp, err := versions.GetPublicKey(name).Context(reqCtx).Do()
resp, err := retryKMS(ctx, retryDelay, func(ctx context.Context) (*cloudkms.PublicKey, error) {
return versions.GetPublicKey(name).Context(ctx).Do()
})
if err != nil {
return nil, fmt.Errorf("get public key for %q: %w", name, err)
}
Expand All @@ -78,7 +101,7 @@ func NewKMSSigner(ctx context.Context, name string, opts ...option.ClientOption)
if !ok {
return nil, fmt.Errorf("key %q is %T, want RSA", name, parsed)
}
return &KMSSigner{ctx: ctx, svc: versions, name: name, pub: pub}, nil
return &KMSSigner{ctx: ctx, svc: versions, name: name, pub: pub, retryDelay: retryDelay}, nil
}

// Public implements crypto.Signer.
Expand All @@ -95,11 +118,13 @@ func (s *KMSSigner) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) ([]
if opts.HashFunc() != crypto.SHA256 || len(digest) != sha256.Size {
return nil, fmt.Errorf("unsupported hash %v: %s only signs SHA-256 digests", opts.HashFunc(), KMSAlgorithm)
}
ctx, cancel := context.WithTimeout(s.ctx, kmsRequestTimeout)
defer cancel()
resp, err := s.svc.AsymmetricSign(s.name, &cloudkms.AsymmetricSignRequest{
Digest: &cloudkms.Digest{Sha256: base64.StdEncoding.EncodeToString(digest)},
}).Context(ctx).Do()
// Retrying is safe: signing the same digest again has no side effects, and
// every returned signature is verified below.
resp, err := retryKMS(s.ctx, s.retryDelay, func(ctx context.Context) (*cloudkms.AsymmetricSignResponse, error) {
return s.svc.AsymmetricSign(s.name, &cloudkms.AsymmetricSignRequest{
Digest: &cloudkms.Digest{Sha256: base64.StdEncoding.EncodeToString(digest)},
}).Context(ctx).Do()
})
if err != nil {
return nil, fmt.Errorf("cloud KMS asymmetric sign: %w", err)
}
Expand All @@ -114,3 +139,63 @@ func (s *KMSSigner) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) ([]
}
return sig, nil
}

// retryKMS calls do, each time with its own kmsRequestTimeout, until it
// succeeds, fails with an error that is not retryable, ctx ends or kmsAttempts
// calls have failed. The wait between attempts starts at delay and doubles.
func retryKMS[T any](ctx context.Context, delay time.Duration, do func(context.Context) (T, error)) (T, error) {
for attempt := 1; ; attempt++ {
reqCtx, cancel := context.WithTimeout(ctx, kmsRequestTimeout)
v, err := do(reqCtx)
cancel()
if err == nil {
return v, nil
}
if ctx.Err() != nil {
return v, canceledError(ctx, err)
}
if attempt == kmsAttempts || !retryable(err) {
return v, attemptsError(attempt, err)
}
select {
case <-ctx.Done():
return v, canceledError(ctx, err)
case <-time.After(delay):
}
delay *= 2
}
}

// canceledError wraps both the context error, so callers can detect
// cancellation with errors.Is, and the last KMS error, so logs show why the
// attempts failed.
func canceledError(ctx context.Context, err error) error {
if errors.Is(err, ctx.Err()) {
return err
}
return fmt.Errorf("%w (last error: %w)", ctx.Err(), err)
}

// attemptsError adds the number of attempts to err when there was more than
// one, so CI logs show that retries happened.
func attemptsError(attempts int, err error) error {
if attempts == 1 {
return err
}
return fmt.Errorf("failed %d attempts: %w", attempts, err)
}

// retryable reports whether a failed Cloud KMS call may succeed if repeated.
// A 4xx response from the KMS API (permission denied, key not found, invalid
// request) is permanent, except 408 and 429. Everything else is retried: 5xx
// responses, network errors, per-request timeouts and failures to fetch
// credentials, which the auth library reports as plain errors.
func retryable(err error) bool {
var apiErr *googleapi.Error
if errors.As(err, &apiErr) {
return apiErr.Code >= http.StatusInternalServerError ||
apiErr.Code == http.StatusRequestTimeout ||
apiErr.Code == http.StatusTooManyRequests
}
return true
}
152 changes: 151 additions & 1 deletion kms_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,19 @@ import (
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"time"

"github.com/ProtonMail/go-crypto/openpgp"
"google.golang.org/api/cloudkms/v1"
"google.golang.org/api/googleapi"
"google.golang.org/api/option"
)

Expand All @@ -33,6 +38,28 @@ type fakeKMS struct {
publicKey cloudkms.PublicKey
// sign makes the signature returned by asymmetricSign.
sign func(r *http.Request, digest []byte) []byte

mu sync.Mutex
// failures are HTTP status codes returned, in order, instead of serving
// the next requests.
failures []int
requests int
}

// fail makes the next requests fail with the given status codes.
func (f *fakeKMS) fail(codes ...int) {
f.mu.Lock()
defer f.mu.Unlock()
f.failures = append(f.failures, codes...)
}

// requestCount returns the number of requests served so far, and resets it.
func (f *fakeKMS) requestCount() int {
f.mu.Lock()
defer f.mu.Unlock()
n := f.requests
f.requests = 0
return n
}

func newFakeKMS(t *testing.T) *fakeKMS {
Expand Down Expand Up @@ -61,6 +88,17 @@ func newFakeKMS(t *testing.T) *fakeKMS {
func (f *fakeKMS) signer(ctx context.Context, t *testing.T) (*KMSSigner, error) {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
f.requests++
code := 0
if len(f.failures) > 0 {
code, f.failures = f.failures[0], f.failures[1:]
}
f.mu.Unlock()
if code != 0 {
http.Error(w, http.StatusText(code), code)
return
}
var resp any
switch {
case r.Method == http.MethodGet && r.URL.Path == "/v1/"+testKeyVersion+"/publicKey":
Expand All @@ -84,7 +122,7 @@ func (f *fakeKMS) signer(ctx context.Context, t *testing.T) (*KMSSigner, error)
_ = json.NewEncoder(w).Encode(resp)
}))
t.Cleanup(srv.Close)
return NewKMSSigner(ctx, testKeyVersion, option.WithEndpoint(srv.URL+"/"), option.WithHTTPClient(srv.Client()))
return newKMSSigner(ctx, testKeyVersion, time.Millisecond, option.WithEndpoint(srv.URL+"/"), option.WithHTTPClient(srv.Client()))
}

func TestKMSSignerSignsVerifiableSignatures(t *testing.T) {
Expand Down Expand Up @@ -201,3 +239,115 @@ func TestKMSSignerStopsWhenContextEnds(t *testing.T) {
t.Fatal("Sign did not return after its context ended")
}
}

func TestKMSSignerRetriesTransientErrors(t *testing.T) {
t.Parallel()
f := newFakeKMS(t)
f.fail(http.StatusServiceUnavailable, http.StatusTooManyRequests)
signer, err := f.signer(context.Background(), t)
must(t, err)
if n := f.requestCount(); n != 3 {
t.Errorf("get public key: %d requests, want 3", n)
}

f.fail(http.StatusInternalServerError, http.StatusBadGateway, http.StatusGatewayTimeout, http.StatusRequestTimeout)
digest := sha256.Sum256([]byte("x"))
if _, err := signer.Sign(rand.Reader, digest[:], crypto.SHA256); err != nil {
t.Fatalf("sign: %v", err)
}
if n := f.requestCount(); n != kmsAttempts {
t.Errorf("sign: %d requests, want %d", n, kmsAttempts)
}
}

func TestKMSSignerGivesUpAfterAttempts(t *testing.T) {
t.Parallel()
f := newFakeKMS(t)
signer, err := f.signer(context.Background(), t)
must(t, err)
f.requestCount()

for range kmsAttempts + 1 {
f.fail(http.StatusServiceUnavailable)
}
digest := sha256.Sum256([]byte("x"))
_, err = signer.Sign(rand.Reader, digest[:], crypto.SHA256)
if err == nil || !strings.Contains(err.Error(), "failed 5 attempts") {
t.Fatalf("err = %v", err)
}
if n := f.requestCount(); n != kmsAttempts {
t.Errorf("%d requests, want %d", n, kmsAttempts)
}
}

func TestKMSSignerDoesNotRetryPermanentErrors(t *testing.T) {
t.Parallel()
for _, code := range []int{http.StatusBadRequest, http.StatusForbidden, http.StatusNotFound} {
f := newFakeKMS(t)
f.fail(code)
if _, err := f.signer(context.Background(), t); err == nil || strings.Contains(err.Error(), "attempts") {
t.Errorf("%d: err = %v, want error without retries", code, err)
}
if n := f.requestCount(); n != 1 {
t.Errorf("%d: %d requests, want 1", code, n)
}
}
}

func TestKMSSignerStopsRetryingWhenContextEnds(t *testing.T) {
t.Parallel()
f := newFakeKMS(t)
f.fail(http.StatusServiceUnavailable)
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, err := f.signer(ctx, t); !errors.Is(err, context.Canceled) {
t.Fatalf("err = %v, want context.Canceled", err)
}
if n := f.requestCount(); n > 1 {
t.Errorf("%d requests after the context ended, want at most 1", n)
}
}

func TestRetryKMSReturnsContextErrorDuringBackoff(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
transient := errors.New("credentials: status code 503")
calls := 0
_, err := retryKMS(ctx, time.Hour, func(context.Context) (struct{}, error) {
calls++
// End the context while retryKMS waits before the next attempt.
time.AfterFunc(10*time.Millisecond, cancel)
return struct{}{}, transient
})
if !errors.Is(err, context.Canceled) || !errors.Is(err, transient) {
t.Fatalf("err = %v, want both context.Canceled and the last KMS error", err)
}
if calls != 1 {
t.Errorf("%d calls, want 1", calls)
}
}

func TestRetryable(t *testing.T) {
t.Parallel()
for name, tc := range map[string]struct {
err error
want bool
}{
"credentials 503": {errors.New(`Get "https://cloudkms.googleapis.com/v1/k/publicKey": credentials: status code 503: upstream connect error`), true},
"network error": {&url.Error{Op: "Post", URL: "https://cloudkms.googleapis.com", Err: errors.New("connection reset by peer")}, true},
"deadline": {context.DeadlineExceeded, true},
"KMS 500": {&googleapi.Error{Code: http.StatusInternalServerError}, true},
"KMS 503": {fmt.Errorf("wrapped: %w", &googleapi.Error{Code: http.StatusServiceUnavailable}), true},
"KMS 408": {&googleapi.Error{Code: http.StatusRequestTimeout}, true},
"KMS 429": {&googleapi.Error{Code: http.StatusTooManyRequests}, true},
"KMS 400": {&googleapi.Error{Code: http.StatusBadRequest}, false},
"KMS 401": {&googleapi.Error{Code: http.StatusUnauthorized}, false},
"KMS 403": {&googleapi.Error{Code: http.StatusForbidden}, false},
"KMS 404": {&googleapi.Error{Code: http.StatusNotFound}, false},
} {
if got := retryable(tc.err); got != tc.want {
t.Errorf("%s: retryable = %v, want %v", name, got, tc.want)
}
}
}
Loading