ci(release): 서명 비밀 값을 값 없이 진단하는 verifySigningKey를 더한다

v1.0.0 release(run 9)가 :grpc:grpc-contract:signMavenPublication에서
「Could not read PGP secret key」로 멈췄다. 원인 사슬은 BouncyCastle의
「secret key ring doesn't start with secret key tag: tag 0x37」이다.
Gradle은 키 문자열이 망가진 경우와 비밀번호가 틀린 경우를 같은 문장으로
알리고, secret은 로그에서 볼 수 없어 무엇이 틀렸는지 가릴 길이 없었다.

scripts/release/check-signing-key.sh가 값을 출력하지 않고 본다:
- 모양: 글자·줄 수, CR, 「\n」 문자열, 비ASCII, 앞뒤 공백
- armour: 첫 줄 BEGIN, 끝 줄 END, BEGIN 뒤 빈 줄
- base64 본문: 줄 너비, CRC24가 checksum 줄과 맞는지, 첫 패킷이 비밀
  키(tag 5)인지
- gpg가 가져오는지, 가져온 키의 지문(공개 정보)이 릴리스 키인지
- SIGNING_PASSWORD로 서명되는지(성공/실패만)

Gradle 태스크 verifySigningKey가 이 스크립트를 부른다. `release`는 이것에
의존하고(서명 키가 있으면 releaseRehearsal도), 모든 Sign 태스크는 그 뒤에
돈다. release.yml은 그대로 한 줄이다. 태그 없이 돌리는 수동 workflow
signing-check.yml을 더했다. 릴리스 키 지문은 gradle.properties
signingKeyFingerprint다.

검증(desktop, 버리는 RSA 4096 키): 정상 키 rc=0(모든 칸 yes, 서명 ok).
base64 줄 하나 뺀 키·한 줄로 붙인 키·틀린 비밀번호·다른 키는 각각 rc=1과
그 원인 줄. 같은 BouncyCastle 1.81로 망가뜨린 모양별 오류를 재현했다.
줄 누락은 tag 0x1·0xc·0xf처럼 임의의 tag를 낸다. 한 줄로 붙이거나 공백·
「\n」이 섞이면 0xffffffff, 비밀번호가 틀리면 checksum mismatch다.
This commit is contained in:
DongHyeonka
2026-11-08 15:05:04 +09:00
parent 7757f1e834
commit 5e0c89dab4
5 changed files with 190 additions and 0 deletions
+29
View File
@@ -0,0 +1,29 @@
# Checks the release signing secrets without cutting a tag (docs/work/release.md 5절). Manual only:
# run it after the owner puts SIGNING_KEY or SIGNING_PASSWORD in, and before tagging. It prints shapes
# and verdicts, never the secrets (scripts/release/check-signing-key.sh).
name: signing-check
on:
workflow_dispatch:
permissions:
contents: read
jobs:
signing-check:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: https://github.com/actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
with:
distribution: temurin
java-version: "21.0.11+10.0.LTS"
- uses: https://github.com/gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6
with:
build-scan-publish: false
cache-read-only: true
- run: ./gradlew verifySigningKey --stacktrace
env:
SIGNING_KEY: ${{ secrets.SIGNING_KEY }}
SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
@@ -13,6 +13,7 @@ import org.gradle.api.publish.PublishingExtension;
import org.gradle.api.publish.maven.MavenPublication;
import org.gradle.api.publish.maven.tasks.PublishToMavenRepository;
import org.gradle.authentication.http.HttpHeaderAuthentication;
import org.gradle.plugins.signing.Sign;
import org.gradle.plugins.signing.SigningExtension;
/**
@@ -145,6 +146,9 @@ public final class LibraryPublishingPlugin implements Plugin<Project> {
SigningExtension signing = project.getExtensions().getByType(SigningExtension.class);
signing.useInMemoryPgpKeys(signingKey, signingPassword);
signing.sign(publication);
// The root's verifySigningKey says what is wrong with a key before Gradle's signing reports
// it only as "Could not read PGP secret key".
project.getTasks().withType(Sign.class).configureEach(task -> task.mustRunAfter(":verifySigningKey"));
}
// Nothing leaves the machine before the release checks have passed, and nothing reaches Gitea
+19
View File
@@ -191,6 +191,21 @@ publishing {
}
def signingKey = providers.environmentVariable('SIGNING_KEY').getOrElse('')
// Before anything is signed: the secret's shape, that gpg imports it as the release key and that
// SIGNING_PASSWORD signs with it, printing no part of either. Gradle's signing reports every one of
// these as "Could not read PGP secret key" (v1.0.0 release run 9); this says which. A key other
// than the release key passes with -PsigningKeyFingerprint=<its fingerprint> (a rehearsal key).
tasks.register('verifySigningKey', Exec) {
group = 'verification'
description = 'Checks SIGNING_KEY and SIGNING_PASSWORD without printing them (scripts/release/check-signing-key.sh).'
outputs.upToDateWhen { false }
commandLine 'bash', file('scripts/release/check-signing-key.sh'),
providers.gradleProperty('signingKeyFingerprint').getOrElse('')
}
tasks.withType(Sign).configureEach {
mustRunAfter tasks.named('verifySigningKey')
}
if (!signingKey.isBlank()) {
signing {
useInMemoryPgpKeys(signingKey, providers.environmentVariable('SIGNING_PASSWORD').getOrElse(''))
@@ -220,6 +235,9 @@ tasks.register('releaseRehearsal') {
group = 'release'
description = 'releaseCheck, then publishes every module and the SBOM to build/staging-repository and checks the files.'
dependsOn tasks.named('releaseCheck')
if (!signingKey.isBlank()) {
dependsOn tasks.named('verifySigningKey')
}
dependsOn tasks.named('publishAllPublicationsToStagingRepository')
dependsOn leafPaths.collect { "${it}:publishAllPublicationsToStagingRepository" }
def staging = layout.buildDirectory.dir('staging-repository')
@@ -244,6 +262,7 @@ tasks.register('release') {
group = 'release'
description = 'releaseCheck, publish to Gitea Packages, then verify the version is readable anonymously.'
dependsOn tasks.named('releaseCheck')
dependsOn tasks.named('verifySigningKey')
dependsOn tasks.named('publishAllPublicationsToGiteaRepository')
dependsOn leafPaths.collect { "${it}:publishAllPublicationsToGiteaRepository" }
def url = providers.gradleProperty('packagesUrl')
+2
View File
@@ -3,6 +3,8 @@
libraryGroup=dev.cakit.grpc
packagesUrl=https://git.learn.hyeonworks.com/api/packages/donghyeon.kang/maven
repositoryUrl=https://git.learn.hyeonworks.com/donghyeon.kang/grpc-library
# The release signing key (public fingerprint). verifySigningKey refuses any other key in SIGNING_KEY.
signingKeyFingerprint=92646CEAFE816CF8B9C249F0A1C936D7F791F8AB
# Build defaults, copied from the backend template's src/gradle.properties.
org.gradle.workers.max=4
+136
View File
@@ -0,0 +1,136 @@
#!/usr/bin/env bash
# Checks the release signing secrets before anything is signed, without printing them.
#
# scripts/release/check-signing-key.sh [expected fingerprint]
#
# Reads SIGNING_KEY (an ASCII-armoured PGP secret key) and SIGNING_PASSWORD from the environment and
# prints only shapes and verdicts: line and character counts, whether the armour lines and the blank
# line after BEGIN are where OpenPGP puts them, whether the base64 body decodes and its CRC24 matches,
# the first packet's tag, whether gpg imports it, the imported key's fingerprint (public), and whether
# SIGNING_PASSWORD signs with it. No value, line or fragment of either secret is ever printed; do not
# add `set -x` here.
#
# Why it exists: Gradle's signing reports any of these problems as one "Could not read PGP secret
# key", and the cause sits in a secret nobody can look at in the job log (v1.0.0 release run 9).
# Exit codes: 0 = the key would sign, 1 = a check failed (the line says which), 2 = usage.
set -euo pipefail
expected=${1:-}
fail=0
if [ -z "${SIGNING_KEY:-}" ]; then
echo "check-signing-key: SIGNING_KEY is empty or not set"
exit 1
fi
[ -n "${SIGNING_PASSWORD:-}" ] || echo "check-signing-key: SIGNING_PASSWORD is empty (only right for a key without a passphrase)"
python3 - <<'PY' || fail=1
import base64, os, re, sys
key = os.environ["SIGNING_KEY"]
BEGIN = "-----BEGIN PGP PRIVATE KEY BLOCK-----"
END = "-----END PGP PRIVATE KEY BLOCK-----"
problems = []
print(f"shape: {len(key)} characters, {key.count(chr(10)) + 1} lines,"
f" CR {'present' if chr(13) in key else 'absent'},"
f" literal backslash-n sequences {key.count(chr(92) + 'n')},"
f" non-ASCII characters {sum(1 for c in key if ord(c) > 127)},"
f" leading whitespace {'yes' if key[:1].isspace() else 'no'},"
f" trailing whitespace {'yes' if key[-1:].isspace() else 'no'}")
lines = key.replace("\r\n", "\n").replace("\r", "\n").split("\n")
while lines and lines[-1].strip() == "":
lines.pop()
if "\n" not in key.replace("\r", "\n"):
problems.append("the value is one line: the newlines were lost (paste the file as is, with its line breaks)")
first = lines[0].strip() if lines else ""
last = lines[-1].strip() if lines else ""
print(f"armour: first line is BEGIN {'yes' if first == BEGIN else 'no'}, last line is END {'yes' if last == END else 'no'}")
if first != BEGIN:
kind = "a PUBLIC key block" if "PUBLIC KEY BLOCK" in first else "something else"
problems.append(f"the value does not start with the BEGIN PGP PRIVATE KEY BLOCK line (it starts with {kind})")
if last != END:
problems.append("the value does not end with the END PGP PRIVATE KEY BLOCK line (cut short?)")
body = lines[1:-1] if first == BEGIN and last == END else lines
headers = []
while body and ":" in body[0] and body[0].strip():
headers.append(body.pop(0))
blank_after = bool(body) and body[0].strip() == ""
print(f"armour headers: {len(headers)}, blank line after them {'yes' if blank_after else 'no'}")
if not blank_after:
problems.append("no blank line between the BEGIN line (and its headers) and the base64 body")
data = [l.strip() for l in body if l.strip()]
checksum = data.pop() if data and data[-1].startswith("=") else None
lengths = [len(l) for l in data]
full = sum(1 for n in lengths[:-1] if n == lengths[0]) if lengths else 0
print(f"body: {len(data)} base64 lines, first {lengths[0] if lengths else 0} characters wide,"
f" {full + (1 if lengths else 0)} of {len(data)} lines that width or the last,"
f" checksum line {'present' if checksum else 'absent'}")
if lengths and any(n != lengths[0] for n in lengths[:-1]):
problems.append("base64 lines of different widths before the last one (lines joined, split or cut)")
joined = "".join(data)
bad = sum(1 for c in joined if not re.match(r"[A-Za-z0-9+/=]", c))
if bad:
problems.append(f"{bad} characters outside the base64 alphabet in the body")
try:
raw = base64.b64decode(joined, validate=False)
except Exception as error:
raw = b""
problems.append(f"the body does not decode as base64 ({type(error).__name__})")
if raw:
def crc24(data):
crc = 0xB704CE
for byte in data:
crc ^= byte << 16
for _ in range(8):
crc <<= 1
if crc & 0x1000000:
crc ^= 0x1864CFB
return crc & 0xFFFFFF
if checksum:
try:
stated = int.from_bytes(base64.b64decode(checksum[1:]), "big")
match = stated == crc24(raw)
except Exception:
match = False
print(f"CRC24 of the decoded body matches the checksum line: {'yes' if match else 'no'}")
if not match:
problems.append("the CRC24 checksum does not match: the base64 body was changed (a line lost, added or edited)")
header = raw[0]
tag = (header & 0x3F) if header & 0x40 else ((header & 0x3C) >> 2)
names = {5: "secret key", 6: "public key", 7: "secret subkey"}
print(f"first packet: tag {tag} ({names.get(tag, 'not a key packet')}), {len(raw)} bytes decoded")
if not header & 0x80 or tag != 5:
problems.append("the first packet is not a secret key packet (tag 5)")
for problem in problems:
print(f"PROBLEM: {problem}")
sys.exit(1 if problems else 0)
PY
home=$(mktemp -d)
trap 'rm -rf "$home"' EXIT
chmod 700 "$home"
if printf '%s\n' "$SIGNING_KEY" | GNUPGHOME="$home" gpg --batch --quiet --import >/dev/null 2>&1; then
fingerprint=$(GNUPGHOME="$home" gpg --batch --with-colons --list-secret-keys 2>/dev/null | awk -F: '/^fpr/{print $10; exit}')
echo "gpg import: ok, secret key fingerprint ${fingerprint:-none}"
if [ -n "$expected" ] && [ "${fingerprint:-}" != "$expected" ]; then
echo "PROBLEM: the imported key is not the release key ${expected}"
fail=1
fi
printf 'signing check\n' > "$home/message"
if printf '%s' "${SIGNING_PASSWORD:-}" | GNUPGHOME="$home" gpg --batch --pinentry-mode loopback \
--passphrase-fd 0 --local-user "${fingerprint:-none}" --detach-sign --output "$home/message.sig" \
"$home/message" >/dev/null 2>&1; then
echo "signing with SIGNING_PASSWORD: ok"
else
echo "PROBLEM: SIGNING_PASSWORD does not unlock the key for signing (wrong passphrase, or the key is not a signing key)"
fail=1
fi
else
echo "PROBLEM: gpg cannot import SIGNING_KEY"
fail=1
fi
exit "$fail"