chore: sign with github.com/coder/gpgkms instead of scripts/gpgkms (#32308)

Replaces `scripts/gpgkms` with
[`github.com/coder/gpgkms`](https://github.com/coder/gpgkms) v0.2.0, the
same code extracted into a shared module (terraform-provider-coder
already signs its releases with it). v0.2.0 also rejects keys that
aren't HSM-backed (`gpg-release` is `HSM`, and the check reads
`protectionLevel` from the existing `GetPublicKey` call, so no new IAM
is needed), limits each KMS request to a minute, and writes `-out`
atomically.

- `go.mod`: gpgkms is a `tool` dependency, so the version is pinned in
`go.mod`/`go.sum` and Dependabot keeps it current. This bumps go-crypto
1.4.1 → 1.5.2, google.golang.org/api 0.308.0 → 0.311.0 and circl 1.6.3 →
1.6.5, plus a few indirect dependencies. go-crypto is now only indirect:
nothing else in coder/coder imports it.
- `scripts/gpgkms.sh` (new): runs it with `go tool` (like
`scripts/format_go_file.sh` does for gofumpt and gci), passing the
release key's OpenPGP identity (name, email, creation time, 4-year
lifetime). The library takes these as flags instead of hardcoding them,
so they now live in one place.
- It also pins `-fingerprint 0F685EFE0AE5A8182A473DD86E3A8E5613707520`,
so signing and `public-key` fail if the KMS key or creation time ever
change. That's the fingerprint every current main build prints (e.g. run
44031030839), and I recomputed it from the KMS public key and the
creation time alone, without signing anything. The fingerprint doesn't
cover the user ID or lifetime; the equivalence check below does.
- `scripts/sign_with_gpg.sh` and the "Print GPG KMS public key" step in
`build.yaml` call the wrapper instead of `./scripts/gpgkms`. Signatures
stay armored `.v2.asc` files, as before.
- `scripts/gpgkms/` is deleted.

## Same key, same signatures

The OpenPGP key's fingerprint depends on these exact inputs, so I
checked that nothing changed. With a local RSA-4096 key standing in for
KMS, the deleted `newEntity`/`writePublicKey`/`sign` produce the same
output as the gpgkms CLI with the flags read out of `scripts/gpgkms.sh`:

- The public key is **byte for byte identical**.
- A signature with `-prepend` is armored the same way and has the same
length (only the timestamp differs). Both the prepended signature and
the KMS signature verify in both outputs.
- Changing the lifetime in the wrapper by one hour makes the comparison
fail, so the check is sensitive.

```
$ git -C gpgkms describe --tags
v0.2.0
$ WRAPPER_ARGS_FILE=wrapper-args.txt go test ./cmd/gpgkms -run TestCoderWrapperMatchesOldCoderCode -count=3 -v
=== RUN   TestCoderWrapperMatchesOldCoderCode
    equiv_coder_test.go:40: wrapper args: ["-name" "Coder Release Signing Key" "-email" "security@coder.com" "-created" "2026-11-16T00:00:00Z" "-lifetime" "35040h"]
--- PASS: TestCoderWrapperMatchesOldCoderCode (0.33s)
--- PASS: TestCoderWrapperMatchesOldCoderCode (0.11s)
--- PASS: TestCoderWrapperMatchesOldCoderCode (0.20s)
ok  	github.com/coder/gpgkms/cmd/gpgkms	0.634s

# with -lifetime 35041h
    equiv_coder_test.go:56: public keys differ:
FAIL

# with the wrapper's -fingerprint pin and a random test key
    derived key has fingerprint 9794B34B5E098DE61DD6CE247E0DFD4BF203C917, want 0F685EFE0AE5A8182A473DD86E3A8E5613707520 (wrong -key, -created or KMS key?)
```

(The byte-for-byte comparison runs without `-fingerprint`, since the
test key is random.)

gpgkms also has its own compatibility test against this identity
(`compat_test.go`).

Other checks:

```
$ ./scripts/gpgkms.sh public-key                 # from the repo root (build.yaml)
gpgkms: -key is required
$ cd scripts && ./gpgkms.sh public-key           # from scripts/ (build_go.sh -> execrelative)
gpgkms: -key is required
$ ./gpgkms.sh sign -key x -prepend ../no-such-file -out o.asc ../go.mod   # relative paths resolve from the caller
gpgkms: read prepend signature: open ../no-such-file: no such file or directory
$ shellcheck -x scripts/gpgkms.sh scripts/sign_with_gpg.sh   # clean
$ shfmt -d scripts/gpgkms.sh scripts/sign_with_gpg.sh        # clean
$ actionlint .github/workflows/build.yaml                    # clean
$ go build ./... && go mod tidy -diff                        # clean
```

Not run here: real signing through Cloud KMS. The first main build after
merging prints the public key in the job summary; it should be identical
to the one printed by current main builds.

---

AI disclosure: this PR was written by an AI coding agent (Xum) at my
direction, and the agent ran the verification above. It stays a draft
until I've reviewed it.
This commit is contained in:
Dean Sheather authored and GitHub committed 2026-11-18 15:36:57 +11:00
1 parent 3664834296
commit d974fefc08
7 files changed
+58 -495

No files matched your search

+1 -1
View File
@@ -125,7 +125,7 @@ jobs:
echo "GPG_KMS_KEY is not set, skipping."
exit 0
fi
go run ./scripts/gpgkms public-key -key "$GPG_KMS_KEY" > "$RUNNER_TEMP/gpg-kms-public.key"
./scripts/gpgkms.sh public-key -key "$GPG_KMS_KEY" > "$RUNNER_TEMP/gpg-kms-public.key"
gpg --show-keys --with-fingerprint "$RUNNER_TEMP/gpg-kms-public.key"
{
echo "### Cloud KMS release signing key"
+8 -6
View File
@@ -300,7 +300,7 @@ require (
golang.org/x/text v0.43.0
golang.org/x/tools v0.52.0
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da
google.golang.org/api v0.308.0
google.golang.org/api v0.311.0
google.golang.org/grpc v1.85.0
google.golang.org/protobuf v1.36.12
gopkg.in/DataDog/dd-trace-go.v1 v1.74.0
@@ -314,7 +314,7 @@ require (
require (
cloud.google.com/go/auth v0.24.1 // indirect
cloud.google.com/go/auth/oauth2adapt v0.3.0 // indirect
cloud.google.com/go/auth/oauth2adapt v0.3.1 // indirect
dario.cat/mergo v1.0.2 // indirect
filippo.io/edwards25519 v1.1.1 // indirect
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
@@ -332,7 +332,7 @@ require (
github.com/DataDog/sketches-go v1.4.8 // indirect
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 // indirect
github.com/ProtonMail/go-crypto v1.4.1
github.com/ProtonMail/go-crypto v1.5.2 // indirect
github.com/agext/levenshtein v1.2.3 // indirect
github.com/agnivade/levenshtein v1.2.1 // indirect
github.com/akutz/memconn v0.1.0 // indirect
@@ -367,7 +367,7 @@ require (
github.com/chromedp/sysutil v1.1.0 // indirect
github.com/cihub/seelog v0.0.0-20170130134532-f561c5e57575 // indirect
github.com/clbanning/mxj/v2 v2.7.0 // indirect
github.com/cloudflare/circl v1.6.3 // indirect
github.com/cloudflare/circl v1.6.5 // indirect
github.com/containerd/continuity v0.4.5 // indirect
github.com/coreos/go-iptables v0.6.0 // indirect
github.com/dlclark/regexp2 v1.12.0 // indirect
@@ -405,7 +405,7 @@ require (
github.com/google/nftables v0.2.0 // indirect
github.com/google/s2a-go v0.1.11 // indirect
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.23 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.24 // indirect
github.com/googleapis/gax-go/v2 v2.27.0 // indirect
github.com/gorilla/css v1.0.1 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.32.0 // indirect
@@ -530,7 +530,7 @@ require (
google.golang.org/appengine v1.6.8 // indirect
google.golang.org/genproto v0.0.0-20261019180522-ce908d29299b // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20261019180522-ce908d29299b // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20261026165753-2ffab32bce7e // indirect
gopkg.in/ini.v1 v1.67.3 // indirect
howett.net/plist v1.0.1 // indirect
kernel.org/pub/linux/libs/security/libcap/psx v1.2.77 // indirect
@@ -599,6 +599,7 @@ require (
)
require (
github.com/coder/gpgkms v0.2.0 // indirect
github.com/go-openapi/swag/pools v0.29.2 // indirect
github.com/pandatix/go-abnf v0.5.1 // indirect
go.opentelemetry.io/otel/log v1.47.0 // indirect
@@ -728,6 +729,7 @@ require (
)
tool (
github.com/coder/gpgkms/cmd/gpgkms
github.com/daixiang0/gci
github.com/swaggo/swag/cmd/swag
go.uber.org/mock/mockgen
+14 -12
View File
@@ -8,8 +8,8 @@ cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE=
cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU=
cloud.google.com/go/auth v0.24.1 h1:NTmd2iJb4DsGIav0KiqFMYI88nMshA2wnFMBatRmoCs=
cloud.google.com/go/auth v0.24.1/go.mod h1:1dmBXa9xfBvBr39ZnDUDkaaA91ccq9CcqENDgJA4d7c=
cloud.google.com/go/auth/oauth2adapt v0.3.0 h1:FY8oSZpCYoUNv6QxVODuMjQz4IlSOVeiQtZ08vLPz88=
cloud.google.com/go/auth/oauth2adapt v0.3.0/go.mod h1:7+2uCm7++XFO+/lN06c2HXpDXb/NMNn2/UwyBPbTnkk=
cloud.google.com/go/auth/oauth2adapt v0.3.1 h1:BKLDdbWS7pafd820dsyFDF6fPEzIGqr7ny6hbTzCCgE=
cloud.google.com/go/auth/oauth2adapt v0.3.1/go.mod h1:B1nM4FJDxoDqAt3PXFG4IflUoQ5kvWAOOM3R+5wAszg=
cloud.google.com/go/compute/metadata v0.10.0 h1:pyKMUQSwchgkIBBJGdILqQbs/BNJXqwSA7Ej6LAvvtY=
cloud.google.com/go/compute/metadata v0.10.0/go.mod h1:rGFHRrIif570kSibjFTMbt6/4/tzgJWFGI/HVol4GIk=
cloud.google.com/go/iam v1.14.0 h1:YRIB1/4xxwJ+NfI6RQr1WaOoHHeV0MizJEj940nBXJA=
@@ -103,8 +103,8 @@ github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERo
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 h1:TngWCqHvy9oXAN6lEVMRuU21PR1EtLVZJmdB18Gu3Rw=
github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5/go.mod h1:lmUJ/7eu/Q8D7ML55dXQrVaamCz2vxCfdQBasLZfHKk=
github.com/ProtonMail/go-crypto v1.4.1 h1:9RfcZHqEQUvP8RzecWEUafnZVtEvrBVL9BiF67IQOfM=
github.com/ProtonMail/go-crypto v1.4.1/go.mod h1:e1OaTyu5SYVrO9gKOEhTc+5UcXtTUa+P3uLudwcgPqo=
github.com/ProtonMail/go-crypto v1.5.2 h1:cucYnvqcY7UOXVD//mSyjeaPY0SSN3v5cDkYPxumINk=
github.com/ProtonMail/go-crypto v1.5.2/go.mod h1:/RaSu30DaKO4RY+XdV/ACcCcZkGr7AhUIduq5sjzzCo=
github.com/SherClockHolmes/webpush-go v1.4.0 h1:ocnzNKWN23T9nvHi6IfyrQjkIc0oJWv1B1pULsf9i3s=
github.com/SherClockHolmes/webpush-go v1.4.0/go.mod h1:XSq8pKX11vNV8MJEMwjrlTkxhAj1zKfxmyhdV7Pd6UA=
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d h1:licZJFw2RwpHMqeKTCYkitsPqHNxTmd4SNR5r94FGM8=
@@ -307,8 +307,8 @@ github.com/clipperhouse/displaywidth v0.10.0 h1:GhBG8WuerxjFQQYeuZAeVTuyxuX+Urai
github.com/clipperhouse/displaywidth v0.10.0/go.mod h1:XqJajYsaiEwkxOj4bowCTMcT1SgvHo9flfF3jQasdbs=
github.com/clipperhouse/uax29/v2 v2.6.0 h1:z0cDbUV+aPASdFb2/ndFnS9ts/WNXgTNNGFoKXuhpos=
github.com/clipperhouse/uax29/v2 v2.6.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8=
github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA=
github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c=
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 h1:aBangftG7EVZoUb69Os8IaYg++6uMOdKK83QtkkvJik=
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=
github.com/coder/acp-go-sdk v0.13.6-0.20261028153106-0da7315c23b5 h1:Y6kuDDPOkgpTPQGbGd+Ww9bdcTbsq6vmNlCb9x7IquM=
@@ -329,6 +329,8 @@ github.com/coder/go-httpstat v0.0.0-20230801153223-321c88088322 h1:m0lPZjlQ7vdVp
github.com/coder/go-httpstat v0.0.0-20230801153223-321c88088322/go.mod h1:rOLFDDVKVFiDqZFXoteXc97YXx7kFi9kYqR+2ETPkLQ=
github.com/coder/go-scim/pkg/v2 v2.0.0-20230221055123-1d63c1222136 h1:0RgB61LcNs24WOxc3PBvygSNTQurm0PYPujJjLLOzs0=
github.com/coder/go-scim/pkg/v2 v2.0.0-20230221055123-1d63c1222136/go.mod h1:VkD1P761nykiq75dz+4iFqIQIZka189tx1BQLOp0Skc=
github.com/coder/gpgkms v0.2.0 h1:K0ZdTbNV31+2pZNqPlbukfS54pXfyA5wuW9Ly8HnpgI=
github.com/coder/gpgkms v0.2.0/go.mod h1:Kx5c1B1xARHMBAOcr3eoTRLWdksEY0S6TGfwqAGlaZs=
github.com/coder/guts v1.7.0 h1:TaZ/PR9wgN8dlbcckaWV1MxkkuEFZRwSRwBBEm8dYXs=
github.com/coder/guts v1.7.0/go.mod h1:30SShdvpmsauNlsNjECRB5AppScjYk08rf2ZVpH3MFg=
github.com/coder/gvisor v0.0.0-20260313164934-7a658db7b714 h1:j7tyq3rv0ZXkbyy/BE5K3lYiIqEsV8sDTiTjpLLxjiw=
@@ -677,8 +679,8 @@ github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaU
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/enterprise-certificate-proxy v0.3.23 h1:J+VGF1wjAM2dU2kKUXZxJdDppRLReWP7KWcclfngQhc=
github.com/googleapis/enterprise-certificate-proxy v0.3.23/go.mod h1:Y8NO/15GNLkrXI3OR5xOFmeU3XLX1sLSdtlXgJ0zmIw=
github.com/googleapis/enterprise-certificate-proxy v0.3.24 h1:G9iCJIY+AYVmUskKdjX8FVy7sG+nbzjOQ41cvlmhcvg=
github.com/googleapis/enterprise-certificate-proxy v0.3.24/go.mod h1:hEjCmnoakQzv5ImLUp6alkY7XgLlNoAxwTXmhHHNIsI=
github.com/googleapis/gax-go/v2 v2.27.0 h1:qe2iQOUzxb3fd6x6ewpIEixPQhJ+0Ihc/RRZhKA/2g0=
github.com/googleapis/gax-go/v2 v2.27.0/go.mod h1:RofiqDw3ehcG4L0H1zO3D2Itpwd3/uS/7wdmbNDF1DE=
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
@@ -1551,8 +1553,8 @@ golang.zx2c4.com/wireguard/windows v0.5.3 h1:On6j2Rpn3OEMXqBq00QEDC7bWSZrPIHKIus
golang.zx2c4.com/wireguard/windows v0.5.3/go.mod h1:9TEe8TJmtwyQebdFwAkEWOPr3prrtqm+REGFifP60hI=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/api v0.308.0 h1:iGb+4qT3nVb3uuIzwor3yP2nyu+rMZr31PvLFiRNJQk=
google.golang.org/api v0.308.0/go.mod h1:4XMH+b/ZEfuTbK7FnrFRY9c4xfFHVflGTKuy/i5wUmE=
google.golang.org/api v0.311.0 h1:t9xGmC/+3kC75YmJldWrlVW2EZqS+PhxL0QMTdytlAY=
google.golang.org/api v0.311.0/go.mod h1:x9+Bc6l3cH1HItpSGqV2mZnbM1bk1VmpLJMwKEtsmgg=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM=
google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds=
@@ -1562,8 +1564,8 @@ google.golang.org/genproto v0.0.0-20261019180522-ce908d29299b h1:+t2qGqt6R8CO622
google.golang.org/genproto v0.0.0-20261019180522-ce908d29299b/go.mod h1:XRIfc1yr5xsbF8xFw5+g7SEmLJX/eQ7MMazTRbnMMvI=
google.golang.org/genproto/googleapis/api v0.0.0-20261019180522-ce908d29299b h1:nB3spRIaSPtxJpxb0k41yljROvm2Jrwfs2pSNdKS5y8=
google.golang.org/genproto/googleapis/api v0.0.0-20261019180522-ce908d29299b/go.mod h1:9N4vtjEwvgQKEdlFVQO0M44ErhecQ9DCSQfGoZ51M6w=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b h1:6WNWHZk91dp4gZ25642OALkuG1UVNZbwENJD19DnB8k=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261026165753-2ffab32bce7e h1:w3fy/G8OrJHYexn+u5y7hFyc8YRRIr7DCevtIOwAcGY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261026165753-2ffab32bce7e/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# Runs github.com/coder/gpgkms (a go.mod tool dependency) with the
# OpenPGP identity of the Cloud KMS release signing key.
#
# Usage: ./scripts/gpgkms.sh public-key|sign [flags...]
#
# The OpenPGP key is derived from the KMS public key and the identity below, so
# none of it may change: the creation time is part of the fingerprint, and the
# user ID and lifetime are covered by the self-signature. -fingerprint makes
# gpgkms fail if the KMS key or creation time ever change; it does not cover the
# user ID or lifetime. Credentials come from Application Default Credentials
# (GOOGLE_APPLICATION_CREDENTIALS).
set -euo pipefail
# shellcheck source=scripts/lib.sh
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
if [[ $# -lt 1 ]]; then
error "Usage: $0 public-key|sign [flags...]"
fi
cmd="$1"
shift
# go tool needs a working directory inside the module; it is not changed here
# so relative paths in the arguments keep working.
exec go tool github.com/coder/gpgkms/cmd/gpgkms "$cmd" \
-name "Coder Release Signing Key" \
-email "security@coder.com" \
-created "2026-11-16T00:00:00Z" \
-lifetime "$((4 * 365 * 24))h" \
-fingerprint "0F685EFE0AE5A8182A473DD86E3A8E5613707520" \
"$@"
-337
View File
@@ -1,337 +0,0 @@
// Command gpgkms creates OpenPGP signatures with an RSA key held in Google
// Cloud KMS, so the release signing private key never leaves KMS.
//
// The OpenPGP key is derived from the KMS public key and keyCreated. The
// creation time is part of the OpenPGP fingerprint, so it is pinned below and
// must stay the same for the lifetime of the key. RSA PKCS#1 v1.5 signatures are
// deterministic, so the exported public key (including its self-signature) is
// identical every time it is generated.
//
// Usage:
//
// gpgkms public-key -key <version>
// gpgkms sign -key <version> [-prepend <sig>] -out <file.asc> <file>
//
// <version> is a CryptoKeyVersion resource name with the algorithm
// RSA_SIGN_PKCS1_4096_SHA256, e.g.
// projects/p/locations/l/keyRings/r/cryptoKeys/k/cryptoKeyVersions/1.
// Credentials come from Application Default Credentials.
//
// -prepend takes an existing binary (unarmored) detached signature, such as
// one made by `gpg --detach-sign`, and writes its signature packets before the
// KMS signature. This lets a release be signed by the old and new keys at
// once, with the old key's signature first.
package main
import (
"bytes"
"context"
"crypto"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"flag"
"fmt"
"io"
"os"
"time"
"github.com/ProtonMail/go-crypto/openpgp"
"github.com/ProtonMail/go-crypto/openpgp/armor"
"github.com/ProtonMail/go-crypto/openpgp/packet"
"golang.org/x/xerrors"
"google.golang.org/api/cloudkms/v1"
"github.com/coder/coder/v2/coderd/util/ptr"
)
const (
userIDName = "Coder Release Signing Key"
userIDEmail = "security@coder.com"
keyLifetime = 4 * 365 * 24 * time.Hour
kmsAlgorithm = "RSA_SIGN_PKCS1_4096_SHA256"
)
// keyCreated is the OpenPGP creation time of the release key (2026-11-16
// 00:00:00 UTC). It is part of the fingerprint: never change it.
var keyCreated = time.Unix(1794787200, 0)
func main() {
if len(os.Args) < 2 {
usage()
os.Exit(2)
}
ctx := context.Background()
var err error
switch os.Args[1] {
case "public-key":
err = runPublicKey(ctx, os.Args[2:])
case "sign":
err = runSign(ctx, os.Args[2:])
default:
usage()
os.Exit(2)
}
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "gpgkms: %v\n", err)
os.Exit(1)
}
}
func usage() {
_, _ = fmt.Fprintln(os.Stderr, "usage: gpgkms public-key -key <version>")
_, _ = fmt.Fprintln(os.Stderr, " gpgkms sign -key <version> [-prepend <sig>] -out <file.asc> <file>")
}
type commonFlags struct {
key string
}
func (c *commonFlags) register(fs *flag.FlagSet) {
fs.StringVar(&c.key, "key", "", "Cloud KMS CryptoKeyVersion resource name")
}
func (c *commonFlags) entity(ctx context.Context) (*openpgp.Entity, error) {
if c.key == "" {
return nil, xerrors.New("-key is required")
}
signer, err := newKMSSigner(ctx, c.key)
if err != nil {
return nil, err
}
return newEntity(signer, keyCreated)
}
func runPublicKey(ctx context.Context, args []string) error {
fs := flag.NewFlagSet("public-key", flag.ExitOnError)
var c commonFlags
c.register(fs)
if err := fs.Parse(args); err != nil {
return xerrors.Errorf("parse flags: %w", err)
}
e, err := c.entity(ctx)
if err != nil {
return err
}
_, _ = fmt.Fprintf(os.Stderr, "fingerprint: %X\n", e.PrimaryKey.Fingerprint)
return writePublicKey(os.Stdout, e)
}
func runSign(ctx context.Context, args []string) error {
fs := flag.NewFlagSet("sign", flag.ExitOnError)
var c commonFlags
c.register(fs)
prependPath := fs.String("prepend", "", "binary detached signature whose packets are written before the KMS signature")
outPath := fs.String("out", "", "path to write the armored detached signature to")
if err := fs.Parse(args); err != nil {
return xerrors.Errorf("parse flags: %w", err)
}
if fs.NArg() != 1 {
return xerrors.New("exactly one file to sign is required")
}
if *outPath == "" {
return xerrors.New("-out is required")
}
var prepend []byte
if *prependPath != "" {
var err error
prepend, err = os.ReadFile(*prependPath)
if err != nil {
return xerrors.Errorf("read prepend signature: %w", err)
}
}
e, err := c.entity(ctx)
if err != nil {
return err
}
message, err := os.Open(fs.Arg(0))
if err != nil {
return xerrors.Errorf("open file to sign: %w", err)
}
defer message.Close()
var out bytes.Buffer
if err := sign(&out, e, message, prepend, time.Now()); err != nil {
return err
}
// #nosec G306 -- detached signatures are public.
if err := os.WriteFile(*outPath, out.Bytes(), 0o644); err != nil {
return xerrors.Errorf("write signature: %w", err)
}
return nil
}
// newEntity builds the OpenPGP key for signer. The result only depends on the
// signer's public key and created, so it is the same on every call.
func newEntity(signer crypto.Signer, created time.Time) (*openpgp.Entity, error) {
rsaPub, ok := signer.Public().(*rsa.PublicKey)
if !ok {
return nil, xerrors.Errorf("unsupported public key type %T, want RSA", signer.Public())
}
// packet.NewSignerPrivateKey only accepts concrete key types, so build the
// private key by hand. go-crypto signs RSA keys through crypto.Signer.
pub := packet.NewRSAPublicKey(created, rsaPub)
priv := &packet.PrivateKey{PublicKey: *pub, PrivateKey: signer}
e := &openpgp.Entity{
PrimaryKey: pub,
PrivateKey: priv,
Identities: map[string]*openpgp.Identity{},
}
err := e.AddUserId(userIDName, "", userIDEmail, &packet.Config{
DefaultHash: crypto.SHA256,
Time: func() time.Time { return created },
KeyLifetimeSecs: uint32(keyLifetime / time.Second),
// go-crypto adds a random salt notation to v4 signatures by default,
// which would change the exported key every time.
NonDeterministicSignaturesViaNotation: ptr.Ref(false),
})
if err != nil {
return nil, xerrors.Errorf("self-sign user ID: %w", err)
}
return e, nil
}
func writePublicKey(w io.Writer, e *openpgp.Entity) error {
aw, err := armor.Encode(w, openpgp.PublicKeyType, nil)
if err != nil {
return err
}
if err := e.Serialize(aw); err != nil {
return xerrors.Errorf("serialize public key: %w", err)
}
if err := aw.Close(); err != nil {
return err
}
_, err = fmt.Fprintln(w)
return err
}
// sign writes an armored detached signature over message. Signature packets in
// prepend come first, followed by the signature from e.
func sign(w io.Writer, e *openpgp.Entity, message io.Reader, prepend []byte, now time.Time) error {
if len(prepend) > 0 {
if err := validateSignatures(prepend); err != nil {
return xerrors.Errorf("prepend signature: %w", err)
}
}
aw, err := armor.Encode(w, openpgp.SignatureType, nil)
if err != nil {
return err
}
if _, err := aw.Write(prepend); err != nil {
return err
}
err = openpgp.DetachSign(aw, e, message, &packet.Config{
DefaultHash: crypto.SHA256,
Time: func() time.Time { return now },
// Keep release signatures to the standard subpackets for older verifiers.
NonDeterministicSignaturesViaNotation: ptr.Ref(false),
})
if err != nil {
return xerrors.Errorf("sign: %w", err)
}
if err := aw.Close(); err != nil {
return err
}
_, err = fmt.Fprintln(w)
return err
}
// validateSignatures checks that b is a binary stream of one or more OpenPGP
// signature packets and nothing else.
func validateSignatures(b []byte) error {
reader := packet.NewReader(bytes.NewReader(b))
count := 0
for {
p, err := reader.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return xerrors.Errorf("parse packet (the signature must be binary, not armored): %w", err)
}
if _, ok := p.(*packet.Signature); !ok {
return xerrors.Errorf("unexpected %T packet, want only signatures", p)
}
count++
}
if count == 0 {
return xerrors.New("no signature packets found")
}
return nil
}
// kmsSigner is a crypto.Signer backed by a Cloud KMS RSA PKCS#1 v1.5 SHA-256
// key.
type kmsSigner struct {
ctx context.Context
svc *cloudkms.ProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsService
name string
pub *rsa.PublicKey
}
func newKMSSigner(ctx context.Context, name string) (*kmsSigner, error) {
svc, err := cloudkms.NewService(ctx)
if err != nil {
return nil, xerrors.Errorf("create Cloud KMS client: %w", err)
}
versions := svc.Projects.Locations.KeyRings.CryptoKeys.CryptoKeyVersions
resp, err := versions.GetPublicKey(name).Context(ctx).Do()
if err != nil {
return nil, xerrors.Errorf("get public key for %q: %w", name, err)
}
if resp.Algorithm != kmsAlgorithm {
return nil, xerrors.Errorf("key %q has algorithm %s, want %s", name, resp.Algorithm, kmsAlgorithm)
}
block, _ := pem.Decode([]byte(resp.Pem))
if block == nil {
return nil, xerrors.Errorf("decode public key PEM for %q", name)
}
parsed, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, xerrors.Errorf("parse public key for %q: %w", name, err)
}
pub, ok := parsed.(*rsa.PublicKey)
if !ok {
return nil, xerrors.Errorf("key %q is %T, want RSA", name, parsed)
}
return &kmsSigner{ctx: ctx, svc: versions, name: name, pub: pub}, nil
}
func (s *kmsSigner) Public() crypto.PublicKey {
return s.pub
}
func (s *kmsSigner) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
if opts.HashFunc() != crypto.SHA256 || len(digest) != sha256.Size {
return nil, xerrors.Errorf("unsupported hash %v: %s only signs SHA-256 digests", opts.HashFunc(), kmsAlgorithm)
}
resp, err := s.svc.AsymmetricSign(s.name, &cloudkms.AsymmetricSignRequest{
Digest: &cloudkms.Digest{Sha256: base64.StdEncoding.EncodeToString(digest)},
}).Context(s.ctx).Do()
if err != nil {
return nil, xerrors.Errorf("Cloud KMS asymmetric sign: %w", err)
}
sig, err := base64.StdEncoding.DecodeString(resp.Signature)
if err != nil {
return nil, xerrors.Errorf("decode Cloud KMS signature: %w", err)
}
// Check the signature locally so a corrupted response fails here rather
// than producing an unverifiable release signature.
if err := rsa.VerifyPKCS1v15(s.pub, crypto.SHA256, digest, sig); err != nil {
return nil, xerrors.Errorf("verify Cloud KMS signature: %w", err)
}
return sig, nil
}
-135
View File
@@ -1,135 +0,0 @@
package main
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"errors"
"io"
"testing"
"time"
"github.com/ProtonMail/go-crypto/openpgp"
"github.com/ProtonMail/go-crypto/openpgp/armor"
"github.com/ProtonMail/go-crypto/openpgp/packet"
"github.com/stretchr/testify/require"
)
const testUserID = "Coder Release Signing Key <security@coder.com>"
// opaqueSigner hides the concrete *rsa.PrivateKey type, like a KMS-backed
// signer does, so the tests exercise the crypto.Signer path.
type opaqueSigner struct {
key *rsa.PrivateKey
}
func (s opaqueSigner) Public() crypto.PublicKey { return &s.key.PublicKey }
func (s opaqueSigner) Sign(r io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
return s.key.Sign(r, digest, opts)
}
func newTestSigner(t *testing.T) crypto.Signer {
t.Helper()
key, err := rsa.GenerateKey(rand.Reader, 2048)
require.NoError(t, err)
return opaqueSigner{key: key}
}
func TestPublicKeyIsDeterministic(t *testing.T) {
t.Parallel()
signer := newTestSigner(t)
created := time.Unix(1794700000, 0)
export := func() []byte {
e, err := newEntity(signer, created)
require.NoError(t, err)
var buf bytes.Buffer
require.NoError(t, writePublicKey(&buf, e))
return buf.Bytes()
}
first := export()
require.Equal(t, first, export())
keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewReader(first))
require.NoError(t, err)
require.Len(t, keyring, 1)
key := keyring[0]
require.Equal(t, created.Unix(), key.PrimaryKey.CreationTime.Unix())
require.Empty(t, key.Subkeys)
require.Contains(t, key.Identities, testUserID)
selfSig := key.Identities[testUserID].SelfSignature
require.NotNil(t, selfSig.KeyLifetimeSecs)
require.Equal(t, uint32(keyLifetime/time.Second), *selfSig.KeyLifetimeSecs)
require.True(t, selfSig.FlagSign)
require.True(t, selfSig.FlagCertify)
}
func TestSignWithPrependedSignature(t *testing.T) {
t.Parallel()
message := []byte("coder_v2.0.0_checksums.txt contents\n")
// The old key is an ordinary software key, like the one gpg signs with.
oldKey, err := openpgp.NewEntity("Old Key", "", "old@example.com", &packet.Config{RSABits: 2048, Algorithm: packet.PubKeyAlgoRSA})
require.NoError(t, err)
var oldSig bytes.Buffer
require.NoError(t, openpgp.DetachSign(&oldSig, oldKey, bytes.NewReader(message), nil))
newKey, err := newEntity(newTestSigner(t), time.Unix(1794700000, 0))
require.NoError(t, err)
var out bytes.Buffer
require.NoError(t, sign(&out, newKey, bytes.NewReader(message), oldSig.Bytes(), time.Now()))
// The output holds both signatures, with the old key's first. The VS Code
// extension verifies the first signature against the old key.
block, err := armor.Decode(bytes.NewReader(out.Bytes()))
require.NoError(t, err)
require.Equal(t, openpgp.SignatureType, block.Type)
reader := packet.NewReader(block.Body)
var issuers []uint64
for {
p, err := reader.Next()
if errors.Is(err, io.EOF) {
break
}
require.NoError(t, err)
sig, ok := p.(*packet.Signature)
require.True(t, ok, "unexpected packet %T", p)
require.NotNil(t, sig.IssuerKeyId)
issuers = append(issuers, *sig.IssuerKeyId)
}
require.Equal(t, []uint64{oldKey.PrimaryKey.KeyId, newKey.PrimaryKey.KeyId}, issuers)
// Each key verifies its own signature in the combined output.
for _, key := range []*openpgp.Entity{oldKey, newKey} {
signer, err := openpgp.CheckArmoredDetachedSignature(openpgp.EntityList{key}, bytes.NewReader(message), bytes.NewReader(out.Bytes()), nil)
require.NoError(t, err)
require.Equal(t, key.PrimaryKey.KeyId, signer.PrimaryKey.KeyId)
}
// A modified message fails verification.
_, err = openpgp.CheckArmoredDetachedSignature(openpgp.EntityList{newKey}, bytes.NewReader([]byte("tampered")), bytes.NewReader(out.Bytes()), nil)
require.Error(t, err)
}
func TestSignRejectsArmoredPrepend(t *testing.T) {
t.Parallel()
newKey, err := newEntity(newTestSigner(t), time.Unix(1794700000, 0))
require.NoError(t, err)
var armored bytes.Buffer
aw, err := armor.Encode(&armored, openpgp.SignatureType, nil)
require.NoError(t, err)
require.NoError(t, openpgp.DetachSign(aw, newKey, bytes.NewReader([]byte("x")), nil))
require.NoError(t, aw.Close())
var out bytes.Buffer
err = sign(&out, newKey, bytes.NewReader([]byte("x")), armored.Bytes(), time.Now())
require.ErrorContains(t, err, "prepend signature")
}
+2 -4
View File
@@ -11,7 +11,7 @@
# - $CODER_GPG_RELEASE_KEY_BASE64: The base64 encoded private key to use.
#
# Optionally, the file is also signed with a release key held in Google Cloud
# KMS (see scripts/gpgkms). That signature goes in a separate .v2.asc file, so
# KMS (see scripts/gpgkms.sh). That signature goes in a separate .v2.asc file, so
# the .asc file and every client that verifies it stay unchanged. Set both of
# these to enable it:
# - $CODER_GPG_KMS_KEY: The Cloud KMS CryptoKeyVersion resource name.
@@ -67,10 +67,8 @@ verification_result=$?
rm -f "${FILE_TO_SIGN}.v2.asc"
if [[ "${CODER_GPG_KMS_KEY:-}" != "" ]]; then
requiredenvs CODER_GPG_KMS_CREDENTIALS_FILE
gpgkms_bin="$gnupg_home_temp/gpgkms"
(cd "$PROJECT_ROOT" && go build -o "$gpgkms_bin" ./scripts/gpgkms)
gpgkms() {
GOOGLE_APPLICATION_CREDENTIALS="$CODER_GPG_KMS_CREDENTIALS_FILE" "$gpgkms_bin" "$@"
GOOGLE_APPLICATION_CREDENTIALS="$CODER_GPG_KMS_CREDENTIALS_FILE" "$PROJECT_ROOT/scripts/gpgkms.sh" "$@"
}
kms_signature="$gnupg_home_temp/kms.asc"