ci: backport release workflow changes to release/2.34 (#29793, #32209, #32211) (#32231)

This commit is contained in:
Jon Ayers authored and GitHub committed 2026-11-15 21:47:08 -06:00
1 parent 80715d25b2
commit 479770702b
11 files changed
+1123 -51

No files matched your search

@@ -0,0 +1,70 @@
name: Install rcodesign
description: |
Install the rcodesign (apple-codesign) binary with PKCS#11 support enabled
so darwin binaries can be signed with an Apple Developer certificate whose
private key lives in Google Cloud KMS.
PKCS#11 support is not in a published apple-codesign release (latest is
0.29.0) and is gated behind the optional "pkcs11" cargo feature, so we build
rcodesign from source at a pinned revision and cache the resulting binary.
We also apply pkcs11-single-init.patch (the apple-codesign/src portion of
https://github.com/indygreg/apple-platform-rs/pull/350) because without it
the module is initialized twice per process and signing fails with
CKR_CRYPTOKI_ALREADY_INITIALIZED.
TODO: switch back to a prebuilt release tarball once a release containing
PKCS#11 support and the initialization fix is published with the feature
enabled.
inputs:
rev:
description: Git revision of indygreg/apple-platform-rs to build.
required: false
default: "0ebbd2ef3b96d5adccc30b1cad4deea38cd735c4"
runs:
using: composite
steps:
- name: Cache rcodesign binary
id: cache-rcodesign
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: /tmp/rcodesign-bin
key: rcodesign-pkcs11-${{ runner.os }}-${{ runner.arch }}-${{ inputs.rev }}-${{ hashFiles('.github/actions/install-rcodesign/pkcs11-single-init.patch') }}
- name: Build rcodesign
if: steps.cache-rcodesign.outputs.cache-hit != 'true'
shell: bash
run: |
set -euo pipefail
if command -v rustup >/dev/null 2>&1; then
rustup toolchain install --profile minimal stable
rustup default stable
elif ! command -v cargo >/dev/null 2>&1; then
./.github/scripts/retry.sh -- curl --proto '=https' --tlsv1.2 -sSfL https://sh.rustup.rs -o /tmp/rustup-init.sh
sh /tmp/rustup-init.sh -y --profile minimal
rm /tmp/rustup-init.sh
fi
export PATH="$HOME/.cargo/bin:$PATH"
src=/tmp/apple-platform-rs-src
rm -rf "$src"
git init -q "$src"
./.github/scripts/retry.sh -- git -C "$src" fetch -q --depth 1 https://github.com/indygreg/apple-platform-rs.git "$RCODESIGN_REV"
git -C "$src" checkout -q FETCH_HEAD
git -C "$src" apply "$GITHUB_ACTION_PATH/pkcs11-single-init.patch"
./.github/scripts/retry.sh -- cargo install \
--path "$src/apple-codesign" \
--features pkcs11 \
--bin rcodesign \
--root /tmp/rcodesign-install
mkdir -p /tmp/rcodesign-bin
cp /tmp/rcodesign-install/bin/rcodesign /tmp/rcodesign-bin/rcodesign
env:
RCODESIGN_REV: ${{ inputs.rev }}
- name: Install rcodesign
shell: bash
run: |
set -euo pipefail
sudo install -m 0755 /tmp/rcodesign-bin/rcodesign /usr/bin/rcodesign
rcodesign --version
@@ -0,0 +1,307 @@
Fix PKCS#11 module double-initialization in apple-codesign.
A PKCS#11 module can only be initialized once per process. rcodesign on
upstream main initializes the module both while resolving the certificate
source and again for each signing operation; the second C_Initialize fails
with CKR_CRYPTOKI_ALREADY_INITIALIZED, which breaks signing with the Google
Cloud KMS PKCS#11 library (and any other PKCS#11 module).
This is the apple-codesign/src portion of the upstream fix:
https://github.com/indygreg/apple-platform-rs/pull/350
(head commit 399e5a8e57ba6c35d1c221be7424f6ba3cfddd6b)
Drop this patch once the pull request lands and the pinned revision in
action.yml is bumped past it.
diff --git a/apple-codesign/src/cli/certificate_source.rs b/apple-codesign/src/cli/certificate_source.rs
index b7d30c00a..df6babaec 100644
--- a/apple-codesign/src/cli/certificate_source.rs
+++ b/apple-codesign/src/cli/certificate_source.rs
@@ -29,10 +29,7 @@ use {
};
#[cfg(feature = "pkcs11")]
-use {
- crate::pkcs11::Pkcs11PrivateKey,
- cryptoki::context::{CInitializeArgs, CInitializeFlags, Pkcs11},
-};
+use crate::pkcs11::{initialized_module, Pkcs11PrivateKey};
#[cfg(target_os = "macos")]
use crate::macos::{keychain_find_code_signing_certificates, KeychainDomain};
@@ -768,10 +765,9 @@ impl KeySource for Pkcs11SigningKey {
None => return Ok(Default::default()),
};
- info!("initializing PKCS11 library: {}", library_path.display());
-
- let pkcs11 = Pkcs11::new(library_path.clone())?;
- pkcs11.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK))?;
+ // Shared with the signing operations that follow: the module can only be
+ // initialized once per process.
+ let pkcs11 = initialized_module(&library_path)?;
let slots = pkcs11.get_slots_with_token()?;
if slots.is_empty() {
diff --git a/apple-codesign/src/pkcs11.rs b/apple-codesign/src/pkcs11.rs
index bd0219f1a..c931975b3 100644
--- a/apple-codesign/src/pkcs11.rs
+++ b/apple-codesign/src/pkcs11.rs
@@ -8,6 +8,7 @@ use {
bytes::Bytes,
cryptoki::{
context::{CInitializeArgs, CInitializeFlags, Pkcs11},
+ error::RvError,
mechanism::{Mechanism, MechanismType},
object::{Attribute, AttributeType, ObjectClass, ObjectHandle},
session::UserType,
@@ -15,7 +16,11 @@ use {
},
log::{info, warn},
signature::Signer,
- std::{collections::HashMap, path::PathBuf},
+ std::{
+ collections::HashMap,
+ path::{Path, PathBuf},
+ sync::{LazyLock, Mutex, MutexGuard},
+ },
x509_certificate::{
rfc3447::DigestInfo, CapturedX509Certificate, DigestAlgorithm, KeyAlgorithm, KeyInfoSigner,
Sign, Signature, SignatureAlgorithm, X509CertificateError,
@@ -23,6 +28,114 @@ use {
zeroize::Zeroizing,
};
+/// A PKCS#11 module context plus how it came to be initialized.
+struct ModuleContext {
+ context: Pkcs11,
+
+ /// Whether the `C_Initialize` backing this context was issued by us.
+ ///
+ /// False when the module reported it was already initialized, in which case something
+ /// else owns that initialization and we must not finalize it out from under it.
+ initialized_here: bool,
+}
+
+/// Process-wide registry of initialized PKCS#11 module contexts, keyed by library path.
+///
+/// A PKCS#11 module is initialized once per process: `C_Initialize` on a module that is
+/// already initialized fails with `CKR_CRYPTOKI_ALREADY_INITIALIZED`. Certificate resolution
+/// and every signing operation each need a context, so contexts are created once and shared
+/// rather than created on demand. Dropping a [Pkcs11] does not finalize the module (cryptoki
+/// has no finalize-on-drop), so creating them on demand leaves the module initialized and
+/// makes every subsequent initialization fail.
+static MODULE_CONTEXTS: LazyLock<Mutex<HashMap<PathBuf, ModuleContext>>> =
+ LazyLock::new(|| Mutex::new(HashMap::new()));
+
+/// Key a module by its resolved path so different spellings of the same library share a context.
+fn module_key(library_path: &Path) -> PathBuf {
+ std::fs::canonicalize(library_path).unwrap_or_else(|_| library_path.to_path_buf())
+}
+
+fn module_contexts() -> MutexGuard<'static, HashMap<PathBuf, ModuleContext>> {
+ // The registry has no invariant that a panic could break, so a poisoned lock is usable.
+ MODULE_CONTEXTS.lock().unwrap_or_else(|e| e.into_inner())
+}
+
+/// Obtain an initialized context for a PKCS#11 module, initializing it on first use.
+///
+/// Repeated calls for the same library return the same context.
+pub(crate) fn initialized_module(library_path: &Path) -> Result<Pkcs11, AppleCodesignError> {
+ let key = module_key(library_path);
+ let mut contexts = module_contexts();
+
+ if let Some(existing) = contexts.get(&key) {
+ return Ok(existing.context.clone());
+ }
+
+ let context = Pkcs11::new(library_path)?;
+
+ let initialized_here =
+ match context.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK)) {
+ Ok(()) => {
+ info!("initialized PKCS11 library: {}", library_path.display());
+ true
+ }
+ // Something else in this process already initialized the module. That
+ // initialization is usable as-is, so adopt it instead of failing.
+ Err(cryptoki::error::Error::Pkcs11(RvError::CryptokiAlreadyInitialized, _)) => {
+ warn!(
+ "PKCS11 library {} is already initialized; reusing that initialization",
+ library_path.display()
+ );
+ false
+ }
+ Err(e) => return Err(e.into()),
+ };
+
+ contexts.insert(
+ key,
+ ModuleContext {
+ context: context.clone(),
+ initialized_here,
+ },
+ );
+
+ Ok(context)
+}
+
+/// Finalize a PKCS#11 module and forget its context.
+///
+/// Does nothing when the module is unknown or when its initialization is owned by something
+/// else. A later [initialized_module] call for the same library initializes it again.
+///
+/// There is no use counting: the first caller to finalize a library finalizes it for every
+/// [Pkcs11PrivateKey] sharing it. The CLI resolves at most one private key, and the
+/// re-initialization above makes that recoverable, so this only matters to embedders
+/// driving several keys on one module.
+pub(crate) fn finalize_module(library_path: &Path) -> Result<(), AppleCodesignError> {
+ let key = module_key(library_path);
+ let mut contexts = module_contexts();
+
+ let Some(entry) = contexts.remove(&key) else {
+ return Ok(());
+ };
+
+ if !entry.initialized_here {
+ return Ok(());
+ }
+
+ // finalize() consumes the context; clone so `entry` survives a failure.
+ if let Err(e) = entry.context.clone().finalize() {
+ // The module is most likely still initialized and still ours, so keep the entry
+ // rather than orphaning a module nothing can finalize later.
+ contexts.insert(key, entry);
+ return Err(e.into());
+ }
+
+ info!("finalized PKCS11 library: {}", library_path.display());
+
+ Ok(())
+}
+
pub struct Pkcs11PrivateKey {
library_path: PathBuf,
slot_id: u64,
@@ -112,8 +225,7 @@ impl Pkcs11PrivateKey {
where
F: FnOnce(&cryptoki::session::Session) -> Result<T, AppleCodesignError>,
{
- let pkcs11 = Pkcs11::new(&self.library_path)?;
- pkcs11.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK))?;
+ let pkcs11 = initialized_module(&self.library_path)?;
let slots = pkcs11.get_slots_with_token()?;
let slot = slots
@@ -471,8 +583,13 @@ impl PrivateKey for Pkcs11PrivateKey {
}
fn finish(&self) -> Result<(), AppleCodesignError> {
- // Could implement cleanup logic here if needed
- // For now, PKCS11 sessions are cleaned up automatically
+ // Sessions close on drop. The module context outlives them and is finalized here so
+ // the process pairs its C_Initialize with a C_Finalize. A module that refuses to
+ // finalize is not a reason to fail a signing run that already wrote its output.
+ if let Err(e) = finalize_module(&self.library_path) {
+ warn!("failed to finalize PKCS11 library: {}", e);
+ }
+
Ok(())
}
}
@@ -483,3 +600,95 @@ impl From<cryptoki::error::Error> for AppleCodesignError {
AppleCodesignError::Pkcs11Error(format!("PKCS11 error: {}", err))
}
}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ /// Path to a PKCS#11 module to exercise, if the environment provides one.
+ ///
+ /// Tests below need a real, spec compliant module. Point this at one to run them, e.g.
+ /// `APPLE_CODESIGN_TEST_PKCS11_LIBRARY=/usr/lib/softhsm/libsofthsm2.so`. The module
+ /// does not need an initialized token; only initialization and slot enumeration are
+ /// exercised.
+ ///
+ /// The name deliberately avoids the `RCODESIGN_` prefix, which the CLI consumes as
+ /// configuration and rejects for unknown keys.
+ fn test_library() -> Option<PathBuf> {
+ let path = PathBuf::from(std::env::var_os("APPLE_CODESIGN_TEST_PKCS11_LIBRARY")?);
+
+ if path.exists() {
+ Some(path)
+ } else {
+ panic!(
+ "APPLE_CODESIGN_TEST_PKCS11_LIBRARY does not exist: {}",
+ path.display()
+ );
+ }
+ }
+
+ /// Walks the full module lifecycle in one test because the registry is process global.
+ #[test]
+ fn module_context_is_shared_and_finalized() {
+ let Some(library) = test_library() else {
+ eprintln!("skipping: APPLE_CODESIGN_TEST_PKCS11_LIBRARY is not set");
+ return;
+ };
+
+ // Stand in for a module the loader keeps resident: it is already initialized by
+ // the time we ask for a context. Adopting that initialization is what keeps this
+ // from failing with CKR_CRYPTOKI_ALREADY_INITIALIZED.
+ let foreign = Pkcs11::new(&library).unwrap();
+ foreign
+ .initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK))
+ .unwrap();
+
+ let adopted = initialized_module(&library).expect("adopting an initialized module");
+ adopted
+ .get_slots_with_token()
+ .expect("adopted context works");
+
+ // Every later request reuses that context rather than initializing a second time.
+ let reused = initialized_module(&library).expect("reusing the adopted module");
+ reused.get_slots_with_token().expect("reused context works");
+
+ {
+ let contexts = module_contexts();
+ assert_eq!(contexts.len(), 1, "both requests share one registry entry");
+ assert!(
+ !contexts.values().next().unwrap().initialized_here,
+ "an adopted initialization is not ours to finalize"
+ );
+ }
+
+ // The initialization is not ours, so finalizing must leave it alone.
+ finalize_module(&library).expect("finalize skips a foreign initialization");
+ foreign
+ .get_slots_with_token()
+ .expect("foreign initialization survived");
+ foreign.finalize().unwrap();
+
+ // Nothing holds the module now, so the next context owns its initialization and
+ // finalizing it is what pairs our C_Initialize with a C_Finalize.
+ let owned = initialized_module(&library).expect("initializing a finalized module");
+ owned.get_slots_with_token().expect("owned context works");
+
+ {
+ let contexts = module_contexts();
+ assert!(
+ contexts.values().next().unwrap().initialized_here,
+ "we performed this initialization"
+ );
+ }
+
+ finalize_module(&library).expect("finalizing our own initialization");
+ assert!(module_contexts().is_empty(), "finalize forgets the context");
+
+ // Finalizing forgets the context, so the module can be initialized again.
+ initialized_module(&library).expect("initializing again after finalize");
+ finalize_module(&library).unwrap();
+
+ // Finalizing a module we know nothing about is a no-op.
+ finalize_module(&library).expect("finalize is idempotent");
+ }
+}
+89 -17
View File
@@ -1091,6 +1091,9 @@ jobs:
- changes
if: (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/heads/release/')) && needs.changes.outputs.docs-only == 'false' && !github.event.pull_request.head.repo.fork
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-22.04' }}
# Gates access to the release signing identity: the GCP workload identity
# provider for release-signer only exchanges tokens for this workflow on a
# push to main or release/* with this environment claim.
environment: ci-signing
permissions:
# Necessary to push docker images to ghcr.io.
@@ -1135,25 +1138,41 @@ jobs:
use-cache: false
- name: Install rcodesign
run: |
set -euo pipefail
wget -O /tmp/rcodesign.tar.gz https://github.com/indygreg/apple-platform-rs/releases/download/apple-codesign%2F0.22.0/apple-codesign-0.22.0-x86_64-unknown-linux-musl.tar.gz
sudo tar -xzf /tmp/rcodesign.tar.gz \
-C /usr/bin \
--strip-components=1 \
apple-codesign-0.22.0-x86_64-unknown-linux-musl/rcodesign
rm /tmp/rcodesign.tar.gz
uses: ./.github/actions/install-rcodesign
- name: Setup Apple Developer certificate
run: |
set -euo pipefail
touch /tmp/{apple_cert.p12,apple_cert_password.txt}
chmod 600 /tmp/{apple_cert.p12,apple_cert_password.txt}
echo "$AC_CERTIFICATE_P12_BASE64" | base64 -d > /tmp/apple_cert.p12
echo "$AC_CERTIFICATE_PASSWORD" > /tmp/apple_cert_password.txt
touch /tmp/apple_cert.pem
chmod 600 /tmp/apple_cert.pem
echo "$AC_CERTIFICATE_PEM" > /tmp/apple_cert.pem
env:
AC_CERTIFICATE_P12_BASE64: ${{ secrets.AC_CERTIFICATE_P12_BASE64 }}
AC_CERTIFICATE_PASSWORD: ${{ secrets.AC_CERTIFICATE_PASSWORD }}
AC_CERTIFICATE_PEM: ${{ secrets.AC_CERTIFICATE_PEM }}
# The Apple Developer certificate's private key lives in Google Cloud
# KMS. rcodesign accesses it through the Cloud KMS PKCS#11 library,
# authenticated via the Google Cloud credentials set up below.
- name: Setup Google Cloud KMS PKCS11 library
run: |
set -euo pipefail
./.github/scripts/retry.sh -- wget -O /tmp/libkmsp11.tar.gz https://github.com/GoogleCloudPlatform/kms-integrations/releases/download/pkcs11-v1.9/libkmsp11-1.9-linux-amd64.tar.gz
echo "5397f965073cd5d1e2c43e5148f102f31a7c835902f97eb41c7c9c0f1b876a40 /tmp/libkmsp11.tar.gz" | sha256sum -c
sudo tar -xzf /tmp/libkmsp11.tar.gz \
-C /usr/local/lib \
--strip-components=1 \
libkmsp11-1.9-linux-amd64/libkmsp11.so
rm /tmp/libkmsp11.tar.gz
# The library requires the config file to be owner-writable only.
touch /tmp/kmsp11_config.yaml
chmod 600 /tmp/kmsp11_config.yaml
cat > /tmp/kmsp11_config.yaml <<EOF
---
tokens:
- key_ring: "$AC_KMS_KEY_RING"
EOF
env:
AC_KMS_KEY_RING: ${{ secrets.AC_KMS_KEY_RING }}
# Necessary for signing Windows binaries.
- name: Setup Java
@@ -1187,7 +1206,8 @@ jobs:
env:
EV_SIGNING_CERT: ${{ secrets.EV_SIGNING_CERT }}
# Setup GCloud for signing Windows binaries.
# Setup GCloud for signing Windows binaries (jsign uses the access
# token).
- name: Authenticate to Google Cloud
id: gcloud_auth
uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0
@@ -1196,9 +1216,54 @@ jobs:
service_account: ${{ vars.GCP_CODE_SIGNING_SERVICE_ACCOUNT }}
token_format: "access_token"
# Secrets can't be used in step conditions. The identity provider only
# accepts push events, so create and workflow_dispatch runs skip KMS signing.
- name: Check for GPG KMS signing key
id: gpg_kms
run: |
enabled=false
if [[ -n "$GPG_KMS_KEY" && "$GITHUB_EVENT_NAME" == "push" ]]; then
enabled=true
fi
echo "enabled=$enabled" >> "$GITHUB_OUTPUT"
env:
GPG_KMS_KEY: ${{ secrets.GPG_KMS_KEY }}
# release-signer@ for the KMS GPG key and the darwin signing key. Not
# exported, so the job's default credentials stay on the EV code signing
# account; GPG steps and the darwin PKCS11 library receive this
# credentials file explicitly. Unconditional because darwin signing
# always needs it, even when the optional KMS GPG signing is disabled.
- name: Authenticate to Google Cloud (release signing)
id: gcloud_auth_gpg
uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0
with:
workload_identity_provider: ${{ secrets.GPG_KMS_WORKLOAD_ID_PROVIDER }}
service_account: ${{ secrets.GPG_KMS_SERVICE_ACCOUNT }}
export_environment_variables: false
- name: Setup GCloud SDK
uses: google-github-actions/setup-gcloud@aa5489c8933f4cc7a4f7d45035b3b1440c9c10db # v3.0.1
# The KMS key's OpenPGP form can only be made by CI. Publish it from main
# builds so its fingerprint can be checked and added to release.key.
- name: Print GPG KMS public key
if: github.ref == 'refs/heads/main' && steps.gpg_kms.outputs.enabled == 'true'
run: |
set -euo pipefail
go run ./scripts/gpgkms public-key -key "$GPG_KMS_KEY" > /tmp/gpg-kms-public.key
gpg --show-keys --with-fingerprint /tmp/gpg-kms-public.key
{
echo "### Cloud KMS release signing key"
echo '```'
gpg --show-keys --with-fingerprint /tmp/gpg-kms-public.key
cat /tmp/gpg-kms-public.key
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
env:
GPG_KMS_KEY: ${{ secrets.GPG_KMS_KEY }}
GOOGLE_APPLICATION_CREDENTIALS: ${{ steps.gcloud_auth_gpg.outputs.credentials_file_path }}
- name: Build
run: |
set -euxo pipefail
@@ -1220,9 +1285,16 @@ jobs:
CODER_WINDOWS_RESOURCES: "1"
CODER_SIGN_GPG: "1"
CODER_GPG_RELEASE_KEY_BASE64: ${{ secrets.GPG_RELEASE_KEY_BASE64 }}
CODER_GPG_KMS_KEY: ${{ secrets.GPG_KMS_KEY }}
CODER_GPG_KMS_CREDENTIALS_FILE: ${{ steps.gcloud_auth_gpg.outputs.credentials_file_path }}
CODER_SIGN_DARWIN: "1"
AC_CERTIFICATE_FILE: /tmp/apple_cert.p12
AC_CERTIFICATE_PASSWORD_FILE: /tmp/apple_cert_password.txt
AC_CERTIFICATE_FILE: /tmp/apple_cert.pem
AC_PKCS11_LIBRARY: /usr/local/lib/libkmsp11.so
AC_PKCS11_KEY_LABEL: ${{ secrets.AC_KMS_KEY }}
KMS_PKCS11_CONFIG: /tmp/kmsp11_config.yaml
# Credentials for the Cloud KMS PKCS11 library (darwin signing)
# only; jsign uses the ambient coder-ci credentials.
GOOGLE_APPLICATION_CREDENTIALS: ${{ steps.gcloud_auth_gpg.outputs.credentials_file_path }}
EV_KEY: ${{ secrets.EV_KEY }}
EV_KEYSTORE: ${{ secrets.EV_KEYSTORE }}
EV_TSA_URL: ${{ secrets.EV_TSA_URL }}
+93 -21
View File
@@ -77,6 +77,9 @@ jobs:
name: Build and publish
needs: [check-perms]
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
# Gates access to the release signing identity: the GCP workload identity
# provider for release-signer only exchanges tokens for this workflow when
# dispatched on a v* tag with this environment claim.
environment: release
permissions:
# Required to publish a release
@@ -291,14 +294,7 @@ jobs:
rm /tmp/nfpm.deb
- name: Install rcodesign
run: |
set -euo pipefail
wget -O /tmp/rcodesign.tar.gz https://github.com/indygreg/apple-platform-rs/releases/download/apple-codesign%2F0.22.0/apple-codesign-0.22.0-x86_64-unknown-linux-musl.tar.gz
sudo tar -xzf /tmp/rcodesign.tar.gz \
-C /usr/bin \
--strip-components=1 \
apple-codesign-0.22.0-x86_64-unknown-linux-musl/rcodesign
rm /tmp/rcodesign.tar.gz
uses: ./.github/actions/install-rcodesign
- name: Install cosign
uses: ./.github/actions/install-cosign
@@ -309,16 +305,39 @@ jobs:
- name: Setup Apple Developer certificate and API key
run: |
set -euo pipefail
touch /tmp/{apple_cert.p12,apple_cert_password.txt,apple_apikey.p8}
chmod 600 /tmp/{apple_cert.p12,apple_cert_password.txt,apple_apikey.p8}
echo "$AC_CERTIFICATE_P12_BASE64" | base64 -d > /tmp/apple_cert.p12
echo "$AC_CERTIFICATE_PASSWORD" > /tmp/apple_cert_password.txt
touch /tmp/{apple_cert.pem,apple_apikey.p8}
chmod 600 /tmp/{apple_cert.pem,apple_apikey.p8}
echo "$AC_CERTIFICATE_PEM" > /tmp/apple_cert.pem
echo "$AC_APIKEY_P8_BASE64" | base64 -d > /tmp/apple_apikey.p8
env:
AC_CERTIFICATE_P12_BASE64: ${{ secrets.AC_CERTIFICATE_P12_BASE64 }}
AC_CERTIFICATE_PASSWORD: ${{ secrets.AC_CERTIFICATE_PASSWORD }}
AC_CERTIFICATE_PEM: ${{ secrets.AC_CERTIFICATE_PEM }}
AC_APIKEY_P8_BASE64: ${{ secrets.AC_APIKEY_P8_BASE64 }}
# The Apple Developer certificate's private key lives in Google Cloud
# KMS. rcodesign accesses it through the Cloud KMS PKCS#11 library,
# authenticated via the Google Cloud credentials set up below.
- name: Setup Google Cloud KMS PKCS11 library
run: |
set -euo pipefail
./.github/scripts/retry.sh -- wget -O /tmp/libkmsp11.tar.gz https://github.com/GoogleCloudPlatform/kms-integrations/releases/download/pkcs11-v1.9/libkmsp11-1.9-linux-amd64.tar.gz
echo "5397f965073cd5d1e2c43e5148f102f31a7c835902f97eb41c7c9c0f1b876a40 /tmp/libkmsp11.tar.gz" | sha256sum -c
sudo tar -xzf /tmp/libkmsp11.tar.gz \
-C /usr/local/lib \
--strip-components=1 \
libkmsp11-1.9-linux-amd64/libkmsp11.so
rm /tmp/libkmsp11.tar.gz
# The library requires the config file to be owner-writable only.
touch /tmp/kmsp11_config.yaml
chmod 600 /tmp/kmsp11_config.yaml
cat > /tmp/kmsp11_config.yaml <<EOF
---
tokens:
- key_ring: "$AC_KMS_KEY_RING"
EOF
env:
AC_KMS_KEY_RING: ${{ secrets.AC_KMS_KEY_RING }}
- name: Setup Windows EV Signing Certificate
run: |
set -euo pipefail
@@ -333,7 +352,9 @@ jobs:
run: |
POSTGRES_VERSION=13 make test-migrations
# Setup GCloud for signing Windows binaries.
# Setup GCloud for signing Windows binaries (jsign uses the access
# token) and for the gsutil upload steps below (exported Application
# Default Credentials).
- name: Authenticate to Google Cloud
id: gcloud_auth
uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0
@@ -342,6 +363,32 @@ jobs:
service_account: ${{ vars.GCP_CODE_SIGNING_SERVICE_ACCOUNT }}
token_format: "access_token"
# Secrets can't be used in step conditions. The identity provider only
# accepts release tags, so dry runs from branches skip KMS signing.
- name: Check for GPG KMS signing key
id: gpg_kms
run: |
enabled=false
if [[ -n "$GPG_KMS_KEY" && "$GITHUB_REF" == refs/tags/* ]]; then
enabled=true
fi
echo "enabled=$enabled" >> "$GITHUB_OUTPUT"
env:
GPG_KMS_KEY: ${{ secrets.GPG_KMS_KEY }}
# release-signer@ for the KMS GPG key and the darwin signing key. Not
# exported, so the job's default credentials stay on the EV code signing
# account; GPG steps and the darwin PKCS11 library receive this
# credentials file explicitly. Unconditional because darwin signing
# always needs it, even when the optional KMS GPG signing is disabled.
- name: Authenticate to Google Cloud (release signing)
id: gcloud_auth_gpg
uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0
with:
workload_identity_provider: ${{ secrets.GPG_KMS_WORKLOAD_ID_PROVIDER }}
service_account: ${{ secrets.GPG_KMS_SERVICE_ACCOUNT }}
export_environment_variables: false
- name: Setup GCloud SDK
uses: google-github-actions/setup-gcloud@aa5489c8933f4cc7a4f7d45035b3b1440c9c10db # v3.0.1
@@ -363,9 +410,16 @@ jobs:
CODER_SIGN_DARWIN: "1"
CODER_SIGN_GPG: "1"
CODER_GPG_RELEASE_KEY_BASE64: ${{ secrets.GPG_RELEASE_KEY_BASE64 }}
CODER_GPG_KMS_KEY: ${{ secrets.GPG_KMS_KEY }}
CODER_GPG_KMS_CREDENTIALS_FILE: ${{ steps.gcloud_auth_gpg.outputs.credentials_file_path }}
CODER_WINDOWS_RESOURCES: "1"
AC_CERTIFICATE_FILE: /tmp/apple_cert.p12
AC_CERTIFICATE_PASSWORD_FILE: /tmp/apple_cert_password.txt
AC_CERTIFICATE_FILE: /tmp/apple_cert.pem
AC_PKCS11_LIBRARY: /usr/local/lib/libkmsp11.so
AC_PKCS11_KEY_LABEL: ${{ secrets.AC_KMS_KEY }}
KMS_PKCS11_CONFIG: /tmp/kmsp11_config.yaml
# Credentials for the Cloud KMS PKCS11 library (darwin signing)
# only; jsign and gsutil use the ambient coder-ci credentials.
GOOGLE_APPLICATION_CREDENTIALS: ${{ steps.gcloud_auth_gpg.outputs.credentials_file_path }}
AC_APIKEY_ISSUER_ID: ${{ secrets.AC_APIKEY_ISSUER_ID }}
AC_APIKEY_ID: ${{ secrets.AC_APIKEY_ID }}
AC_APIKEY_FILE: /tmp/apple_apikey.p8
@@ -377,7 +431,7 @@ jobs:
JSIGN_PATH: /tmp/jsign-6.0.jar
- name: Delete Apple Developer certificate and API key
run: rm -f /tmp/{apple_cert.p12,apple_cert_password.txt,apple_apikey.p8}
run: rm -f /tmp/{apple_cert.pem,apple_apikey.p8,kmsp11_config.yaml}
- name: Delete Windows EV Signing Cert
run: rm /tmp/ev_cert.pem
@@ -641,6 +695,10 @@ jobs:
detached_signature="${slim_binary}.asc"
gcloud storage cp "./build/${slim_binary}" "gs://releases.coder.com/coder-cli/${version}/${cli_name}"
gcloud storage cp "./build/${detached_signature}" "gs://releases.coder.com/coder-cli/${version}/${cli_name}.asc"
# Cloud KMS signature, only present when GPG_KMS_KEY is set.
if [[ -f "./build/${slim_binary}.v2.asc" ]]; then
gcloud storage cp "./build/${slim_binary}.v2.asc" "gs://releases.coder.com/coder-cli/${version}/${cli_name}.v2.asc"
fi
done
# Mint a short-lived installation token from the dedicated release
@@ -703,6 +761,8 @@ jobs:
# from creating tags by the tag-create protection ruleset).
GITHUB_TOKEN: ${{ steps.release_app_token.outputs.token }}
CODER_GPG_RELEASE_KEY_BASE64: ${{ secrets.GPG_RELEASE_KEY_BASE64 }}
CODER_GPG_KMS_KEY: ${{ secrets.GPG_KMS_KEY }}
CODER_GPG_KMS_CREDENTIALS_FILE: ${{ steps.gcloud_auth_gpg.outputs.credentials_file_path }}
VERSION: ${{ steps.version.outputs.version }}
CREATED_LATEST_TAG: ${{ steps.build_docker.outputs.created_latest_tag }}
@@ -752,11 +812,23 @@ jobs:
mkdir -p build/helm
cp "build/coder_helm_${version}.tgz" build/helm
cp "build/provisioner_helm_${version}.tgz" build/helm
gsutil cp gs://helm.coder.com/v2/index.yaml build/helm/index.yaml
helm repo index build/helm --url https://helm.coder.com/v2 --merge build/helm/index.yaml
gsutil -h "Cache-Control:no-cache,max-age=0" cp "build/helm/coder_helm_${version}.tgz" gs://helm.coder.com/v2
gsutil -h "Cache-Control:no-cache,max-age=0" cp "build/helm/provisioner_helm_${version}.tgz" gs://helm.coder.com/v2
gsutil -h "Cache-Control:no-cache,max-age=0" cp "build/helm/index.yaml" gs://helm.coder.com/v2
# index.yaml is shared by every release, so two releases publishing
# concurrently would each merge only their own charts and the last
# writer would drop the other's entries. The if-generation-match
# precondition makes the loser fail instead; re-running the job
# merges against the fresh index.
index_url=gs://helm.coder.com/v2/index.yaml
generation="$(gsutil stat "$index_url" | awk '/^ *Generation:/ {print $2}')"
gsutil cp "$index_url" build/helm/index.yaml
helm repo index build/helm --url https://helm.coder.com/v2 --merge build/helm/index.yaml
if ! gsutil -h "Cache-Control:no-cache,max-age=0" -h "x-goog-if-generation-match:${generation}" cp build/helm/index.yaml "$index_url"; then
echo "::error::index.yaml was modified by another release since it was read (generation $generation). Re-run this job to merge against the current index." >&2
exit 1
fi
gsutil -h "Cache-Control:no-cache,max-age=0" cp "helm/artifacthub-repo.yml" gs://helm.coder.com/v2
helm push "build/coder_helm_${version}.tgz" oci://ghcr.io/coder/chart
helm push "build/provisioner_helm_${version}.tgz" oci://ghcr.io/coder/chart
+6
View File
@@ -426,6 +426,12 @@ $(CODER_ALL_BINARIES): go.mod go.sum \
if [[ "$${CODER_SIGN_GPG:-0}" == "1" ]]; then
cp "$@.asc" "./site/out/bin/coder-$$os-$$arch$$dot_ext.asc"
# Cloud KMS signature, only present when CODER_GPG_KMS_KEY is set.
if [[ -f "$@.v2.asc" ]]; then
cp "$@.v2.asc" "./site/out/bin/coder-$$os-$$arch$$dot_ext.v2.asc"
else
rm -f "./site/out/bin/coder-$$os-$$arch$$dot_ext.v2.asc"
fi
fi
fi
+1 -1
View File
@@ -283,7 +283,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 // indirect
github.com/ProtonMail/go-crypto v1.4.1
github.com/agext/levenshtein v1.2.3 // indirect
github.com/agnivade/levenshtein v1.2.1 // indirect
github.com/akutz/memconn v0.1.0 // indirect
+6 -1
View File
@@ -124,7 +124,12 @@ fi
dependencies go
if [[ "$sign_darwin" == 1 ]]; then
dependencies rcodesign
requiredenvs AC_CERTIFICATE_FILE AC_CERTIFICATE_PASSWORD_FILE
# See ./sign_darwin.sh for the two supported signing modes.
if [[ "${AC_PKCS11_LIBRARY:-}" != "" ]]; then
requiredenvs AC_PKCS11_LIBRARY AC_PKCS11_KEY_LABEL AC_CERTIFICATE_FILE KMS_PKCS11_CONFIG
else
requiredenvs AC_CERTIFICATE_FILE AC_CERTIFICATE_PASSWORD_FILE
fi
fi
if [[ "$sign_windows" == 1 ]]; then
dependencies java
+337
View File
@@ -0,0 +1,337 @@
// 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
@@ -0,0 +1,135 @@
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")
}
+44 -11
View File
@@ -17,8 +17,26 @@
# systems, but it may be less accurate:
# rcodesign verify path/to/binary
#
# Depends on the rcodesign utility. Requires the following environment variables
# to be set:
# Depends on the rcodesign utility. The signing key either lives in Google
# Cloud KMS (preferred) or in a local PKCS#12 certificate file.
#
# To sign with a key in Google Cloud KMS via the Cloud KMS PKCS#11 library
# (https://cloud.google.com/kms/docs/reference/pkcs11-library), the following
# environment variables must be set:
# - $AC_PKCS11_LIBRARY: The path to the Cloud KMS PKCS#11 library
# (libkmsp11.so). rcodesign must be built with the "pkcs11" feature.
# - $AC_PKCS11_KEY_LABEL: The name of the Cloud KMS crypto key to sign with.
# The key must use algorithm RSA_SIGN_PKCS1_2048_SHA256.
# - $AC_CERTIFICATE_FILE: The path to the Apple Developer certificate issued
# for the key (public part only, PEM or DER).
# - $KMS_PKCS11_CONFIG: The path to the Cloud KMS PKCS#11 library YAML
# configuration file naming the key ring that contains the key. Read by the
# library itself.
# Additionally, Google Application Default Credentials with permission to sign
# with the key must be available, e.g. via $GOOGLE_APPLICATION_CREDENTIALS.
#
# To sign with a local PKCS#12 certificate file instead, the following
# environment variables must be set:
# - $AC_CERTIFICATE_FILE: The path to the Apple Developer P12 certificate file.
# - $AC_CERTIFICATE_PASSWORD_FILE: The path to the file containing the password
# for the Apple Developer certificate.
@@ -37,13 +55,28 @@ BINARY_IDENTIFIER="$2"
# Check dependencies
dependencies rcodesign
requiredenvs AC_CERTIFICATE_FILE AC_CERTIFICATE_PASSWORD_FILE
# -v is quite verbose, the default output is pretty good on it's own.
rcodesign sign \
--binary-identifier "$BINARY_IDENTIFIER" \
--p12-file "$AC_CERTIFICATE_FILE" \
--p12-password-file "$AC_CERTIFICATE_PASSWORD_FILE" \
--code-signature-flags runtime \
"$BINARY_PATH" \
1>&2
if [[ "${AC_PKCS11_LIBRARY:-}" != "" ]]; then
requiredenvs AC_PKCS11_LIBRARY AC_PKCS11_KEY_LABEL AC_CERTIFICATE_FILE KMS_PKCS11_CONFIG
# -v is quite verbose, the default output is pretty good on it's own.
rcodesign sign \
--binary-identifier "$BINARY_IDENTIFIER" \
--pkcs11-library "$AC_PKCS11_LIBRARY" \
--pkcs11-key-label "$AC_PKCS11_KEY_LABEL" \
--pkcs11-certificate-file "$AC_CERTIFICATE_FILE" \
--code-signature-flags runtime \
"$BINARY_PATH" \
1>&2
else
requiredenvs AC_CERTIFICATE_FILE AC_CERTIFICATE_PASSWORD_FILE
# -v is quite verbose, the default output is pretty good on it's own.
rcodesign sign \
--binary-identifier "$BINARY_IDENTIFIER" \
--p12-file "$AC_CERTIFICATE_FILE" \
--p12-password-file "$AC_CERTIFICATE_PASSWORD_FILE" \
--code-signature-flags runtime \
"$BINARY_PATH" \
1>&2
fi
+35
View File
@@ -9,6 +9,14 @@
#
# Depends on the GPG utility. Requires the following environment variables to be set:
# - $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
# 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.
# - $CODER_GPG_KMS_CREDENTIALS_FILE: Google credentials for the KMS signer.
# Only gpgkms sees them, so they don't replace the job's default credentials.
set -euo pipefail
# shellcheck source=scripts/lib.sh
@@ -30,6 +38,9 @@ fi
old_gnupg_home="${GNUPGHOME:-}"
gnupg_home_temp="$(mktemp -d)"
export GNUPGHOME="$gnupg_home_temp"
# Remove the temporary keyring (which holds the private key) even if a step
# below fails.
trap 'rm -rf "$gnupg_home_temp"' EXIT
# Ensure GPG uses the temporary directory
echo "$CODER_GPG_RELEASE_KEY_BASE64" | base64 -d | gpg --homedir "$gnupg_home_temp" --import 1>&2
@@ -52,6 +63,30 @@ true | gpg --homedir "$gnupg_home_temp" --detach-sign --armor "$FILE_TO_SIGN" 1>
gpg --homedir "$gnupg_home_temp" --verify "${FILE_TO_SIGN}.asc" "$FILE_TO_SIGN" 1>&2
verification_result=$?
# Never leave a .v2.asc from an earlier build next to a newly built file.
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" "$@"
}
kms_signature="$gnupg_home_temp/kms.asc"
gpgkms sign -key "$CODER_GPG_KMS_KEY" -out "$kms_signature" "$FILE_TO_SIGN" 1>&2
# Verify against a keyring holding only the KMS key, so the file must
# contain exactly one signature, made by that key.
kms_gnupg_home="$gnupg_home_temp/kms"
mkdir -m 700 "$kms_gnupg_home"
gpgkms public-key -key "$CODER_GPG_KMS_KEY" | gpg --homedir "$kms_gnupg_home" --import 1>&2
gpg --homedir "$kms_gnupg_home" --verify "$kms_signature" "$FILE_TO_SIGN" 1>&2 || verification_result=$?
if [[ $verification_result -eq 0 ]]; then
mv "$kms_signature" "${FILE_TO_SIGN}.v2.asc"
fi
fi
# Clean up the temporary GPG home
rm -rf "$gnupg_home_temp"
unset GNUPGHOME