Merge pull request 'fix(release): 서명 비밀 값을 값 없이 진단하고 base64로 감싼 키를 받는다' (#3) from fix/signing-key-check into main
This commit was merged in pull request #3.
This commit is contained in:
@@ -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 }}
|
||||
+8
-2
@@ -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;
|
||||
|
||||
/**
|
||||
@@ -36,7 +37,8 @@ import org.gradle.plugins.signing.SigningExtension;
|
||||
* the versions its own resolution chose ({@code versionMapping}), and the plugin's POM
|
||||
* customization, which would add the BOM imports a consumer never inherits, is off.
|
||||
*
|
||||
* <p>Signing: with {@code SIGNING_KEY} (an ASCII-armoured PGP secret key) and {@code
|
||||
* <p>Signing: with {@code SIGNING_KEY} (an ASCII-armoured PGP secret key, or the base64 of one;
|
||||
* {@link SigningKeys}) and {@code
|
||||
* SIGNING_PASSWORD} in the environment, every published file gets an {@code .asc}. Without them
|
||||
* nothing is signed, and a task that uploads to {@code gitea} fails before it starts: an unsigned
|
||||
* release is not a release.
|
||||
@@ -137,7 +139,8 @@ public final class LibraryPublishingPlugin implements Plugin<Project> {
|
||||
.dir("staging-repository"));
|
||||
});
|
||||
|
||||
String signingKey = project.getProviders().environmentVariable("SIGNING_KEY").getOrElse("");
|
||||
String signingKey =
|
||||
SigningKeys.armoured(project.getProviders().environmentVariable("SIGNING_KEY").getOrElse(""));
|
||||
String signingPassword =
|
||||
project.getProviders().environmentVariable("SIGNING_PASSWORD").getOrElse("");
|
||||
boolean signed = !signingKey.isBlank();
|
||||
@@ -145,6 +148,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
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package dev.caskeleton.buildlogic.publishing;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* The ASCII-armoured key Gradle's in-memory signatory reads, from what a CI secret holds.
|
||||
*
|
||||
* <p>A secret store keeps a multi-line value badly or not at all, so the common practice is to put
|
||||
* the armoured key file in base64 on one line ({@code base64 -w0 signing-key.asc}). Gradle's {@code
|
||||
* useInMemoryPgpKeys} reads only the armoured text and reports the base64 form as "Could not read
|
||||
* PGP secret key" (v1.0.0 release run 9 and the secret put in after it). Both forms are accepted:
|
||||
* a value that decodes to an armoured private key block is unwrapped, anything else is passed on
|
||||
* unchanged, so a wrong value still fails, and {@code verifySigningKey} says why.
|
||||
*/
|
||||
public final class SigningKeys {
|
||||
private static final String BEGIN = "-----BEGIN PGP PRIVATE KEY BLOCK-----";
|
||||
|
||||
private SigningKeys() {}
|
||||
|
||||
/**
|
||||
* The armoured key: {@code value} itself, or the armoured block it is the base64 of.
|
||||
*
|
||||
* @param value the secret as given (armoured, base64 of the armoured file, or anything else)
|
||||
* @return the armoured key, or {@code value} unchanged when it is neither form
|
||||
*/
|
||||
public static String armoured(String value) {
|
||||
if (value == null || value.isBlank() || value.contains(BEGIN)) {
|
||||
return value;
|
||||
}
|
||||
String compact = value.replaceAll("\\s", "");
|
||||
if (!compact.matches("[A-Za-z0-9+/]+={0,2}")) {
|
||||
return value;
|
||||
}
|
||||
try {
|
||||
String decoded = new String(Base64.getDecoder().decode(compact), StandardCharsets.UTF_8);
|
||||
return decoded.strip().startsWith(BEGIN) ? decoded : value;
|
||||
} catch (IllegalArgumentException notBase64) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package dev.caskeleton.buildlogic.publishing;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SigningKeysTest {
|
||||
private static final String ARMOURED =
|
||||
"-----BEGIN PGP PRIVATE KEY BLOCK-----\n\nlQdGBGrv1SYBEADGgq8C\n=abcd\n"
|
||||
+ "-----END PGP PRIVATE KEY BLOCK-----\n";
|
||||
|
||||
@Test
|
||||
@DisplayName("armour 그대로인 키는 바꾸지 않는다")
|
||||
void anArmouredKeyIsUsedAsItIs() {
|
||||
assertThat(SigningKeys.armoured(ARMOURED)).isEqualTo(ARMOURED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("armour 파일을 base64로 감싼 값은 풀어서 armour로 쓴다")
|
||||
void aBase64WrappedArmouredKeyIsUnwrapped() {
|
||||
String wrapped = Base64.getEncoder().encodeToString(ARMOURED.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
assertThat(SigningKeys.armoured(wrapped)).isEqualTo(ARMOURED);
|
||||
assertThat(SigningKeys.armoured(wrapped.substring(0, 40) + "\n" + wrapped.substring(40)))
|
||||
.isEqualTo(ARMOURED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("지문이나 armour가 아닌 base64는 그대로 두어 서명이 원래 오류로 실패하게 한다")
|
||||
void anythingElseIsLeftAlone() {
|
||||
String fingerprint = "92646CEAFE816CF8B9C249F0A1C936D7F791F8AB";
|
||||
String otherBase64 = Base64.getEncoder().encodeToString("not a key".getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
assertThat(SigningKeys.armoured(fingerprint)).isEqualTo(fingerprint);
|
||||
assertThat(SigningKeys.armoured(otherBase64)).isEqualTo(otherBase64);
|
||||
assertThat(SigningKeys.armoured("")).isEmpty();
|
||||
}
|
||||
}
|
||||
+46
-1
@@ -1,4 +1,5 @@
|
||||
import dev.caskeleton.buildlogic.java.JavaConventionsPlugin
|
||||
import dev.caskeleton.buildlogic.publishing.SigningKeys
|
||||
|
||||
plugins {
|
||||
id 'ca.architecture'
|
||||
@@ -190,7 +191,47 @@ publishing {
|
||||
}
|
||||
}
|
||||
|
||||
def signingKey = providers.environmentVariable('SIGNING_KEY').getOrElse('')
|
||||
// The armoured key, or the base64 of the armoured file (the usual way to keep it in a CI secret).
|
||||
def signingKey = SigningKeys.armoured(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).
|
||||
// gpg reads only a passphrase's first line and Gradle the whole value, so the task then signs a few
|
||||
// bytes with Gradle's own signatory: the verdict is the one the Sign tasks would reach.
|
||||
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 }
|
||||
ignoreExitValue = true
|
||||
commandLine 'bash', file('scripts/release/check-signing-key.sh'),
|
||||
providers.gradleProperty('signingKeyFingerprint').getOrElse('')
|
||||
def signed = !signingKey.isBlank()
|
||||
doLast {
|
||||
boolean scriptPassed = executionResult.get().exitValue == 0
|
||||
boolean gradlePassed = !signed
|
||||
String verdict = 'skipped: no SIGNING_KEY'
|
||||
if (signed) {
|
||||
try {
|
||||
signing.signatory.sign(new ByteArrayInputStream('signing check'.bytes), OutputStream.nullOutputStream())
|
||||
gradlePassed = true
|
||||
verdict = 'ok'
|
||||
} catch (Exception failure) {
|
||||
// Exception text only: BouncyCastle names what failed (checksum mismatch, a tag), never the key.
|
||||
def cause = failure.cause ? " (${failure.cause.class.simpleName}: ${failure.cause.message})" : ''
|
||||
verdict = "failed: ${failure.message}${cause}"
|
||||
}
|
||||
}
|
||||
logger.lifecycle("signing as Gradle's Sign tasks do (in-memory key): ${verdict}")
|
||||
if (!scriptPassed || !gradlePassed) {
|
||||
throw new GradleException('verifySigningKey: the signing secrets would not sign; the PROBLEM lines above say why.')
|
||||
}
|
||||
}
|
||||
}
|
||||
tasks.withType(Sign).configureEach {
|
||||
mustRunAfter tasks.named('verifySigningKey')
|
||||
}
|
||||
if (!signingKey.isBlank()) {
|
||||
signing {
|
||||
useInMemoryPgpKeys(signingKey, providers.environmentVariable('SIGNING_PASSWORD').getOrElse(''))
|
||||
@@ -220,6 +261,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 +288,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')
|
||||
|
||||
+15
-3
@@ -21,12 +21,23 @@ main 병합 ──> 소유자가 태그 vX.Y.Z push ──> .gitea/workflows/rel
|
||||
| --- | --- | --- |
|
||||
| `PACKAGE_TOKEN` | Gitea 개인 토큰. 권한은 `package` 읽기·쓰기만(repository·user 권한 없음). Gitea job 토큰(`GITEA_TOKEN`)은 패키지를 올릴 수 없어서 사람 토큰이 필요하다 | Gitea 웹 → 설정 → 애플리케이션에서 새로 만들어 secret을 덮어쓰고 옛 토큰을 지운다 |
|
||||
| `SIGNING_KEY` | 서명용 PGP 비밀 키(ASCII armor 전체). 두 라이브러리(grpc, messaging)가 같은 키를 쓴다 | 새 키 쌍을 만들고 README 「서명」의 공개 키와 지문을 같은 PR에서 바꾼다. 만료(2028-11-07) 전에 한다 |
|
||||
| `SIGNING_PASSWORD` | 그 키의 암호 | 키와 함께 |
|
||||
| `SIGNING_PASSWORD` | 그 키를 만들 때 정한 암호 한 줄. 키 파일이나 그 base64가 아니다 | 키와 함께 |
|
||||
|
||||
- 이름: 설계(design-docs `repo-structure/05-library-repos.md` 7절)는 `PACKAGES_TOKEN`이라고 적었지만, 등록된 이름 `PACKAGE_TOKEN`에 workflow와 빌드를 맞췄다. 소유자에게 다시 등록을 부탁하지 않는다.
|
||||
- 서명 키: RSA 4096, 지문 `92646CEAFE816CF8B9C249F0A1C936D7F791F8AB`, 2028-11-07 만료. 공개 키는 README 「서명」이다.
|
||||
- 첫 태그는 `v1.0.0`이다(3절).
|
||||
|
||||
**`SIGNING_KEY`에 넣는 것**은 키 지문이나 키 ID(16진수 40·16·8글자)가 아니라 비밀 키 파일 전체다. 파일 그대로(여러 줄)나 그 파일을 base64로 한 줄로 만든 값(`base64 -w0 signing-key.asc`) 둘 다 된다. 빌드가 base64를 풀어 쓴다(`SigningKeys`).
|
||||
|
||||
```bash
|
||||
gpg --armor --export-secret-keys 92646CEAFE816CF8B9C249F0A1C936D7F791F8AB > signing-key.asc
|
||||
```
|
||||
|
||||
1. `signing-key.asc`를 열어 첫 줄 `-----BEGIN PGP PRIVATE KEY BLOCK-----`부터 끝 줄 `-----END PGP PRIVATE KEY BLOCK-----`까지 줄바꿈 그대로 복사한다. RSA 4096 키면 100줄 남짓이다.
|
||||
2. Gitea → 그 repo(grpc-library, messaging-library 둘 다) → 설정 → Actions → Secrets → `SIGNING_KEY`를 고쳐 붙여 넣는다.
|
||||
3. Actions → `signing-check` → Run workflow(main). 로그에 `PROBLEM` 줄이 없고 `gpg import: ok, secret key fingerprint 92646CEA…F791F8AB`, `signing with SIGNING_PASSWORD: ok`가 나오면 된다. 이 workflow는 값을 출력하지 않는다(`scripts/release/check-signing-key.sh`).
|
||||
4. `signing-key.asc`를 지운다(`shred -u signing-key.asc`).
|
||||
|
||||
## 2. 버전 규칙
|
||||
|
||||
- SemVer, repo 하나에 버전 하나. 모든 모듈이 같은 버전으로 나간다. 태그는 `vMAJOR.MINOR.PATCH`이고 접미사(`-rc.1` 등)는 없다. 다른 모양의 태그는 `ca.java-conventions`가 빌드 전에 거부한다.
|
||||
@@ -39,7 +50,7 @@ main 병합 ──> 소유자가 태그 vX.Y.Z push ──> .gitea/workflows/rel
|
||||
|
||||
1. main이 초록인지 본다(main.yml 마지막 실행).
|
||||
2. `CHANGELOG.md`에 그 버전 절을 쓰고 PR로 병합한다.
|
||||
3. 올리기 전까지를 desktop에서 미리 돌려 본다(비밀 값 없이, 4절).
|
||||
3. 올리기 전까지를 desktop에서 미리 돌려 본다(비밀 값 없이, 4절). 비밀 값을 넣거나 바꾼 뒤 첫 태그라면 `signing-check` workflow도 한 번 돌린다(1절).
|
||||
4. 태그를 단다.
|
||||
|
||||
```bash
|
||||
@@ -65,7 +76,8 @@ scripts/verify.sh release --on desktop
|
||||
|
||||
| 어디서 | 뜻 | 할 일 |
|
||||
| --- | --- | --- |
|
||||
| 1~4단계 | 아무것도 올라가지 않았다 | 고쳐서 main에 병합하고 같은 태그 이름을 새 커밋에 다시 달지 않는다. 다음 PATCH 태그를 쓴다 |
|
||||
| 1~4단계, 서명 | 아무것도 올라가지 않았다 | 고쳐서 main에 병합한다. 그 버전의 파일이 Packages에 하나도 없으면(`maven-metadata.xml`에 없음) 태그를 지우고 고친 main 커밋에 같은 태그를 다시 단다. 하나라도 올라갔으면 다음 PATCH를 쓴다 |
|
||||
| 서명 직전 `verifySigningKey`, 또는 `Could not read PGP secret key` | 서명 비밀 값이 키로 읽히지 않는다 | `signing-check` workflow의 `PROBLEM` 줄이 원인이다(지문을 넣음, 줄바꿈 잃음, BEGIN·END 줄 빠짐, base64 손상, 다른 키, 암호 칸에 키를 넣음, 틀린 암호). 1절대로 다시 넣는다 |
|
||||
| 5단계 중간 | 일부 모듈만 올라갔을 수 있다 | 그 버전은 버린다(지우지 않는다). 원인을 고치고 다음 PATCH를 낸다. `CHANGELOG.md`에 버린 버전을 적는다 |
|
||||
| 6단계 | 올라갔지만 익명으로 안 읽힌다 | owner 공개 설정을 확인한다. 템플릿 이미지 빌드가 토큰 없이 읽는다는 전제(설계 8.3절 R1)가 깨진 것이다 |
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
Executable
+175
@@ -0,0 +1,175 @@
|
||||
#!/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)"
|
||||
# The passphrase's shape only: a pasted value often carries a line break or spaces the key was not
|
||||
# protected with, and Gradle uses the value as given.
|
||||
python3 - <<'PY' || fail=1
|
||||
import os, sys
|
||||
p = os.environ.get("SIGNING_PASSWORD", "")
|
||||
print(f"password shape: {len(p)} characters, line breaks {p.count(chr(10))}, CR {p.count(chr(13))},"
|
||||
f" leading whitespace {'yes' if p[:1].isspace() else 'no'}, trailing whitespace {'yes' if p[-1:].isspace() else 'no'},"
|
||||
f" non-ASCII characters {sum(1 for c in p if ord(c) > 127)}")
|
||||
if "-----BEGIN PGP" in p or len(p) > 1000:
|
||||
print("PROBLEM: SIGNING_PASSWORD holds a PGP key block (or something as long), not the passphrase."
|
||||
" Put in only the passphrase chosen when the key was made.")
|
||||
sys.exit(1)
|
||||
PY
|
||||
|
||||
home=$(mktemp -d)
|
||||
trap 'rm -rf "$home"' EXIT
|
||||
chmod 700 "$home"
|
||||
KEY_OUT=$home/key.asc EXPECTED_FINGERPRINT=$expected 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'}")
|
||||
|
||||
stripped = key.strip()
|
||||
compact = re.sub(r"\s", "", key)
|
||||
if "-----BEGIN" not in key and re.fullmatch(r"[A-Za-z0-9+/]+={0,2}", compact or "x"):
|
||||
try:
|
||||
unwrapped = base64.b64decode(compact).decode("utf-8")
|
||||
except Exception:
|
||||
unwrapped = ""
|
||||
if unwrapped.strip().startswith("-----BEGIN PGP PRIVATE KEY BLOCK-----"):
|
||||
print("form: base64 of an armoured key file on one value; the build unwraps it (SigningKeys), so the checks below read the unwrapped text")
|
||||
key = unwrapped
|
||||
stripped = key.strip()
|
||||
print(f"unwrapped shape: {len(key)} characters, {key.count(chr(10)) + 1} lines")
|
||||
|
||||
if re.fullmatch(r"(0x)?[0-9A-Fa-f]{8}|(0x)?[0-9A-Fa-f]{16}|[0-9A-Fa-f]{40}", stripped):
|
||||
expected = os.environ.get("EXPECTED_FINGERPRINT", "")
|
||||
same = " (the release key's fingerprint)" if expected and stripped.upper() == expected.upper() else ""
|
||||
print(f"PROBLEM: SIGNING_KEY holds a {len(stripped)}-hex-digit key ID or fingerprint{same}, not the key."
|
||||
" Put in the output of `gpg --armor --export-secret-keys <fingerprint>` instead, BEGIN to END lines.")
|
||||
sys.exit(1)
|
||||
|
||||
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}")
|
||||
with open(os.environ["KEY_OUT"], "w", encoding="utf-8") as out:
|
||||
out.write(key)
|
||||
sys.exit(1 if problems else 0)
|
||||
PY
|
||||
|
||||
if [ -s "$home/key.asc" ] && GNUPGHOME="$home" gpg --batch --quiet --import "$home/key.asc" >/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"
|
||||
# gpg reads only the first line of the file; the shape line above says whether there is more.
|
||||
printf '%s' "${SIGNING_PASSWORD:-}" > "$home/passphrase"
|
||||
if GNUPGHOME="$home" gpg --batch --pinentry-mode loopback --passphrase-file "$home/passphrase" \
|
||||
--status-fd 3 --local-user "${fingerprint:-none}" --detach-sign --output "$home/message.sig" \
|
||||
"$home/message" >/dev/null 2>&1 3>"$home/status"; then
|
||||
echo "signing with SIGNING_PASSWORD: ok"
|
||||
else
|
||||
# gpg's status keywords only (BAD_PASSPHRASE, MISSING_PASSPHRASE, ERROR …): no values.
|
||||
status=$(awk '$1 == "[GNUPG:]" {print $2}' "$home/status" | sort -u | tr '\n' ' ')
|
||||
echo "PROBLEM: SIGNING_PASSWORD does not unlock the key for signing (gpg status: ${status:-none})"
|
||||
fail=1
|
||||
fi
|
||||
else
|
||||
echo "PROBLEM: gpg cannot import SIGNING_KEY"
|
||||
fail=1
|
||||
fi
|
||||
exit "$fail"
|
||||
Reference in New Issue
Block a user