fix: bound source retries and distinguish explicit key revocation

This commit is contained in:
2026-10-14 18:22:16 +08:00
parent 00858ac409
commit 6945095222
15 changed files with 1258 additions and 81 deletions
+26 -14
View File
@@ -9,7 +9,7 @@ export const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
export const digest = data => createHash('sha256').update(data).digest('hex');
import { escapeHTML, commandsFor, renderCommands, renderPage } from '../cf-worker/src/view.js';
export { escapeHTML, commandsFor, renderCommands };
import { validateFallbackSources, parsePublicKeys, validateKeySource, validateSignedReleaseConfig } from '../cf-worker/src/key-source.js';
import { validateFallbackSources, parsePublicKeys, validateKeySource, validateSignedReleaseConfig, isExplicitEmptyKeyFile } from '../cf-worker/src/key-source.js';
import {withoutKeyComments, parsePublishedSignedRelease, SIGNATURE_SEPARATOR} from '../cf-worker/src/signed-release.js';
import {checkSigningCertificate, validatePublicCertificate} from './signature-tools.mjs';
@@ -83,34 +83,46 @@ export function makeKeysText(keys, revision, allowEmpty) {
export async function build({directory = root, outDirectory = join(directory,'cf-worker'), testFixture = false, revision, publishedAt} = {}) {
const config = validateConfig(JSON.parse(await readFile(join(directory,'deployment.json'),'utf8')));
const input = config.keySource?.type === 'gist' && !testFixture ? '' : await readFile(join(directory,testFixture ? 'tests/fixtures/keys.pub' : 'keys/authorized_keys'),'utf8').catch(error => {if (error.code === 'ENOENT' && !testFixture) return ''; throw error;});
const optional = async path => { try { return await readFile(join(directory, path), 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } };
let input = testFixture ? await readFile(join(directory, 'tests/fixtures/keys.pub'), 'utf8') : config.keySource?.type === 'gist' ? null : await optional('keys/authorized_keys');
let keys = [];
revision ||= process.env.GITHUB_SHA || execFileSync('git',['rev-parse','HEAD'],{cwd:directory,encoding:'utf8'}).trim();
if (!/^[0-9a-f]{40}$/.test(revision)) throw Error('Release revision must be a 40-character Git commit SHA.');
publishedAt ||= new Date().toISOString();
const fallbackSources = validateFallbackSources(config.fallbackSources ?? []);
const keySource = validateKeySource(config.keySource), signedRelease = validateSignedReleaseConfig(config.signedRelease);
const optional = async path => { try { return await readFile(join(directory, path), 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } };
let signed = null, publicCertificate = null;
let signed = null, publicCertificate = null, primaryFile = null;
if (keySource.type === 'git' && !testFixture) {
const documentFile = await optional('keys/ssh.keys'), bundleFile = await optional('keys/release.bundle');
if (documentFile !== null && bundleFile !== null) throw Error('Use keys/ssh.keys plus its optional signature OR keys/release.bundle, not both.');
if (documentFile !== null || bundleFile !== null) {
const separator = bundleFile?.indexOf(SIGNATURE_SEPARATOR) ?? -1;
if (bundleFile !== null && separator < 0) throw Error('release.bundle lacks its detached-signature separator.');
const document = documentFile ?? bundleFile.slice(0, separator);
const signature = documentFile !== null ? await optional('keys/ssh.keys.sig') : bundleFile.slice(separator + SIGNATURE_SEPARATOR.length);
signed = await parsePublishedSignedRelease(document, signature, {listId: signedRelease?.listId, checkFreshness: false});
keys = signed.keys;
}
// Do not let a leftover signed artifact silently override an explicitly cleared raw file.
if (isExplicitEmptyKeyFile(input)) throw Error('Ambiguous Git revocation: empty keys/authorized_keys conflicts with a signed publishing file. Keep only the intended publishing form.');
const rawHasContent = input !== null && input.split(/\r?\n/).some(line => {const text = line.replace(/^[ \t]+|[ \t]+$/g, ''); return text !== '' && !text.startsWith('#');});
if (isExplicitEmptyKeyFile(documentFile ?? bundleFile) && rawHasContent) throw Error('Ambiguous Git revocation: empty signed publishing file conflicts with nonempty keys/authorized_keys. Keep only the intended publishing form.');
primaryFile = documentFile !== null ? 'keys/ssh.keys' : 'keys/release.bundle';
input = documentFile ?? bundleFile;
if (!isExplicitEmptyKeyFile(input)) {
const separator = bundleFile?.indexOf(SIGNATURE_SEPARATOR) ?? -1;
if (bundleFile !== null && separator < 0) throw Error('release.bundle lacks its detached-signature separator.');
const document = documentFile ?? bundleFile.slice(0, separator);
const signature = documentFile !== null ? await optional('keys/ssh.keys.sig') : bundleFile.slice(separator + SIGNATURE_SEPARATOR.length);
signed = await parsePublishedSignedRelease(document, signature, {listId: signedRelease?.listId, checkFreshness: false});
keys = signed.keys;
}
} else primaryFile = 'keys/authorized_keys';
if (input === null) throw Error(`No server public keys configured: ${primaryFile} is missing. Keep an existing empty file for an explicit revocation.`);
}
if (!signed) keys = withoutKeyComments(await parseKeys(input));
// A blank file may use lone CR line endings; retain its byte count for parser limits.
if (!signed) keys = withoutKeyComments(await parseKeys(isExplicitEmptyKeyFile(input) ? input.replace(/\r/g, '\n') : input ?? ''));
const explicitEmpty = !testFixture && keySource.type === 'git' && isExplicitEmptyKeyFile(input);
if (!testFixture && keySource.type === 'git' && !signed && !keys.length && !explicitEmpty) throw Error('No server public keys configured: a comments-only placeholder is not an explicit empty revocation.');
if (signedRelease?.publicKeyFile) {
publicCertificate = validatePublicCertificate(await readFile(join(directory, signedRelease.publicKeyFile), 'utf8'));
if (signed && !signed.bundle) throw Error('Configured build signature verification requires a valid detached signature.');
await checkSigningCertificate(publicCertificate, signedRelease.fingerprint, signed?.bundle);
}
const allowEmpty = signed ? signed.metadata.revoke : config.allowEmpty;
const allowEmpty = signed ? signed.metadata.revoke : explicitEmpty || config.allowEmpty;
const needsFallback = keySource.type === 'git' && keys.length === 0 && !allowEmpty && fallbackSources.length > 0;
const needsSource = keySource.type === 'gist' || needsFallback;
if (keySource.type === 'gist') keys = [];
@@ -130,7 +142,7 @@ export async function build({directory = root, outDirectory = join(directory,'cf
if (/@@[A-Z_]+@@/.test(script)) throw Error('Unresolved script template token.');
if (!script.includes('# conf-sshd-script-v2')) throw Error('Missing script format marker.');
execFileSync('sh',['-n'],{input:script,stdio:['pipe','pipe','pipe']});
const release = {schema:1,revision,publishedAt,keyCount:keys.length,allowEmpty,sha256:bundle.sha256,keyRevision:signed?.metadata.documentSha256 ?? bundle.sha256,testFixture,baseUrl:config.baseUrl,repositoryUrl:config.repositoryUrl,fallbackSources,keySource,signedRelease,clientDefaults,publicCertificate,signedDocument:signed?.document ?? null,signature:signed?.signature ?? null,signatureAvailable:Boolean(signed?.signature),publicCertificateAvailable:Boolean(publicCertificate),signedBundle:signed?.bundle ?? null,signedMetadata:signed?.metadata ?? null,needsFallback,needsSource,keys,commands:commandsFor(config)};
const release = {schema:1,revision,publishedAt,keyCount:keys.length,allowEmpty,sha256:bundle.sha256,keyRevision:signed?.metadata.documentSha256 ?? bundle.sha256,testFixture,baseUrl:config.baseUrl,repositoryUrl:config.repositoryUrl,fallbackSources,keySource,primaryFile,explicitEmpty,signedRelease,clientDefaults,publicCertificate,signedDocument:signed?.document ?? null,signature:signed?.signature ?? null,signatureAvailable:Boolean(signed?.signature),publicCertificateAvailable:Boolean(publicCertificate),signedBundle:signed?.bundle ?? null,signedMetadata:signed?.metadata ?? null,needsFallback,needsSource,keys,commands:commandsFor(config)};
let html = await readFile(join(directory,'site/index.html'),'utf8');
const publicDir = join(outDirectory,'public'), generatedDir = join(outDirectory,'generated');
await rm(publicDir,{recursive:true,force:true});
+35 -7
View File
@@ -2,12 +2,31 @@ import {readFile} from 'node:fs/promises';
import {resolve} from 'node:path';
import {fileURLToPath} from 'node:url';
import {createHash} from 'node:crypto';
import {parsePublicKeys} from '../cf-worker/src/key-source.js';
import {parsePublicKeys, resolveKeys, validateKeySource} from '../cf-worker/src/key-source.js';
import {parseSignedDocument, SIGNATURE_SEPARATOR, SIGNED_RELEASE_LIMITS, withoutKeyComments, validateSignature} from '../cf-worker/src/signed-release.js';
import {checkSigningCertificate} from './signature-tools.mjs';
const hash = text => createHash('sha256').update(text).digest('hex');
const root = new URL('../', import.meta.url);
/** Deployment checks the primary itself; a healthy fallback cannot hide an unconfigured primary. */
export async function verifyProduction(release, fetchImpl = fetch, {now, timeoutMs} = {}) {
if (!release || release.testFixture) throw Error('Refusing to deploy a test-fixture or missing build. Run the production build with real server public keys.');
if (!/^[0-9a-f]{40}$/.test(release.revision)) throw Error('Production release revision is invalid.');
const keySource = validateKeySource(release.keySource);
if (keySource.type === 'git' && !['keys/authorized_keys', 'keys/ssh.keys', 'keys/release.bundle'].includes(release.primaryFile)) throw Error('Production Git release has no configured primary file. Rebuild with an existing key file.');
if (keySource.type === 'git' && !release.signedDocument && !release.signedBundle && !release.keys?.length && release.explicitEmpty !== true) throw Error('Production Git revocation lacks an explicitly empty primary file. Rebuild with an existing empty key file.');
const requireSigned = release.clientDefaults?.gpgVerification === 'on';
const snapshot = await resolveKeys(release, fetchImpl, {requirePrimary: true, requireSigned, ...(now === undefined ? {} : {now}), ...(timeoutMs === undefined ? {} : {timeoutMs})});
if (requireSigned && snapshot.signedMetadata?.listId !== release.clientDefaults.listId) throw Error('Client default list ID differs from the primary signed document.');
if (requireSigned && release.signedRelease?.fingerprint && release.clientDefaults.pinMode === 'primary' && release.clientDefaults.fingerprint !== release.signedRelease.fingerprint) throw Error('Client primary fingerprint differs from the configured signing certificate.');
if (snapshot.signedDocument && release.signedRelease?.publicKeyFile) {
if (!snapshot.signedBundle) throw Error('Configured build signature verification requires a valid detached signature.');
await checkSigningCertificate(release.publicCertificate, release.signedRelease.fingerprint, snapshot.signedBundle);
}
const cryptoNote = snapshot.signedDocument && !release.signedRelease?.publicKeyFile ? ' OpenPGP not checked: no build verification certificate configured.' : '';
return `Production primary checked: ${release.revision}; ${snapshot.keyCount} key(s) from ${snapshot.source.type}.${cryptoNote}`;
}
async function remoteText(url, maxBytes, {allowMissing = false, fetchImpl = fetch} = {}) {
const signal = AbortSignal.timeout(20000);
const response = await fetchImpl(url, {cache: 'no-store', redirect: 'error', signal});
@@ -29,7 +48,7 @@ async function remoteText(url, maxBytes, {allowMissing = false, fetchImpl = fetc
} finally { await reader.cancel().catch(() => {}); reader.releaseLock(); }
}
export async function verifyRemote(manifest, fetchImpl = fetch) {
export async function verifyRemote(manifest, fetchImpl = fetch, {now} = {}) {
const read = (path, maxBytes, allowMissing = false) => remoteText(manifest.baseUrl + path, maxBytes, {allowMissing, fetchImpl});
const metadata = JSON.parse(await read('/release.json', 64 * 1024));
if (metadata.revision !== manifest.revision || metadata.testFixture) throw Error('Remote release does not match this build.');
@@ -59,6 +78,7 @@ export async function verifyRemote(manifest, fetchImpl = fetch) {
if (signature !== null) validateSignature(signature);
cryptoNote = ' OpenPGP not checked: no build verification certificate configured.';
}
if (manifest.clientDefaults?.gpgVerification === 'on') await parseSignedDocument(document, {listId: manifest.clientDefaults.listId, ...(now === undefined ? {} : {now})});
} else {
const match = /^# conf-sshd-v1\n# revision ([0-9a-f]{40})\n# key-count (0|[1-9][0-9]*)\n# allow-empty (yes|no)\n# sha256 ([0-9a-f]{64})\n# end-metadata\n([\s\S]*)$/.exec(document);
if (!match || match[1] !== manifest.revision) throw Error('Remote key manifest invalid.');
@@ -66,7 +86,9 @@ export async function verifyRemote(manifest, fetchImpl = fetch) {
if (hash(payload) !== digest) throw Error('Remote key body does not match its response digest.');
const keys = await parsePublicKeys(payload);
count = keys.length; payloadHash = digest;
if (keys.length !== Number(countText) || (!keys.length && (!manifest.allowEmpty || empty !== 'yes')) || withoutKeyComments(keys).map(key => key.text + '\n').join('') !== payload) throw Error('Remote key count/empty/canonical policy invalid.');
// A pinned Gist may be intentionally cleared after this code build, without changing allowEmpty.
const gistRevocation = manifest.keySource?.type === 'gist' && metadata.source?.type === 'gist' && metadata.allowEmpty === true && metadata.keyCount === 0;
if (keys.length !== Number(countText) || (!keys.length && ((!manifest.allowEmpty && !gistRevocation) || empty !== 'yes')) || withoutKeyComments(keys).map(key => key.text + '\n').join('') !== payload) throw Error('Remote key count/empty/canonical policy invalid.');
if (manifest.clientDefaults?.gpgVerification === 'on') throw Error('Verification-enabled clients require a signed-format document.');
}
if (!dynamic && payloadHash !== manifest.sha256) throw Error('Remote repository payload differs from this build.');
@@ -75,8 +97,14 @@ export async function verifyRemote(manifest, fetchImpl = fetch) {
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const manifest = JSON.parse(await readFile(new URL('cf-worker/generated/manifest.json', root), 'utf8'));
if (manifest.testFixture) throw Error('Refusing to deploy a test-fixture build. Run the production build with real server public keys.');
if (!process.argv.includes('--remote')) console.log(`Production release checked: ${manifest.revision}`);
else console.log(await verifyRemote(manifest));
const args = process.argv.slice(2);
if (args.some(arg => arg !== '--remote') || args.length > 1) throw Error('Usage: node scripts/verify-release.mjs [--remote]');
if (args.includes('--remote')) {
const manifest = JSON.parse(await readFile(new URL('cf-worker/generated/manifest.json', root), 'utf8'));
if (manifest.testFixture) throw Error('Refusing to verify a test-fixture deployment.');
console.log(await verifyRemote(manifest));
} else {
const {default: release} = await import(new URL('cf-worker/generated/release.js', root));
console.log(await verifyProduction(release));
}
}