feat(backup,cli): add AES-256-GCM .gcoord.enc backup, verify, restore CLI and API

This commit is contained in:
tyuXX 2026-11-27 14:23:22 +00:00
parent 413053182b
commit fbc1eb94e0
7 changed files with 1155 additions and 19 deletions

View file

@ -2,6 +2,11 @@ import fs from 'node:fs';
import path from 'node:path';
import readline from 'node:readline/promises';
import { parseArgs } from 'node:util';
import {
createBackupBundle,
restoreBackupBundle,
verifyBackupSummaryOnly,
} from '../server/security/backup.js';
import { EmergencyRecoveryService } from '../server/security/recovery-store.js';
import { VaultService } from '../server/security/vault.js';
@ -9,17 +14,47 @@ function printUsage(): void {
console.log(`GCoordinator CLI (gcoord)
Commands:
rotate-key Re-encrypt vault.enc atomically with a new 32-byte master key
rotate-key Re-encrypt vault.enc atomically with a new 32-byte master key
--data-dir <path> Data directory (default: GCOORD_DATA_DIR or ./data)
--current-key-file <path> Path to file containing current 32-byte key
--new-key-out <path> Optional output file (0600) for generated key
Phase 5 commands (scheduled):
backup | verify-backup | restore
backup Create an AES-256-GCM .gcoord.enc portable backup bundle
--out <path.gcoord.enc> Output bundle path (required)
--data-dir <path> Data directory (default: GCOORD_DATA_DIR or ./data)
--key-file <path> Path to 32-byte Vault master key (default mode)
--passphrase-file <path> Path to passphrase file (overrides key-file using scrypt)
verify-backup Verify GCM tag, JSON schemas, and Vault envelope without modifying data
<path.gcoord.enc> Backup bundle path (or --bundle <path>)
--key-file <path> Path to 32-byte master key
--passphrase-file <path> Path to backup passphrase file
--vault-key-file <path> Optional Vault master key to also decrypt/verify vault.enc
--json Print verification summary as JSON
restore Atomically restore config/, vault.enc, known_hosts, and alert_silences
<path.gcoord.enc> Backup bundle path (or --bundle <path>)
--data-dir <path> Target data directory (default: GCOORD_DATA_DIR or ./data)
--key-file <path> Path to 32-byte master key
--passphrase-file <path> Path to backup passphrase file
--vault-key-file <path> Optional Vault master key if backup used a passphrase
`);
}
async function readCurrentKey(keyFile?: string): Promise<string> {
async function promptHiddenOrLine(promptText: string): Promise<string> {
const rl = readline.createInterface({
input: process.stdin,
output: process.stderr,
});
try {
const answer = await rl.question(promptText);
return answer.trim();
} finally {
rl.close();
}
}
async function readCurrentKey(keyFile?: string, dataDir?: string): Promise<string> {
if (keyFile) {
return fs.readFileSync(keyFile, 'utf8').trim();
}
@ -29,16 +64,42 @@ async function readCurrentKey(keyFile?: string): Promise<string> {
if (fs.existsSync('/run/secrets/gcoord_master_key')) {
return fs.readFileSync('/run/secrets/gcoord_master_key', 'utf8').trim();
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stderr,
});
try {
const answer = await rl.question('Enter current 32-byte vault master key (hex or base64): ');
return answer.trim();
} finally {
rl.close();
if (dataDir) {
const localKeyFile = path.join(path.resolve(dataDir), 'vault.key');
if (fs.existsSync(localKeyFile)) {
return fs.readFileSync(localKeyFile, 'utf8').trim();
}
}
return promptHiddenOrLine('Enter current 32-byte vault master key (hex or base64): ');
}
function readOptionalKeyNonInteractive(keyFile?: string, dataDir?: string): string | undefined {
if (keyFile) {
return fs.readFileSync(keyFile, 'utf8').trim();
}
if (process.env.GCOORD_MASTER_KEY?.trim()) {
return process.env.GCOORD_MASTER_KEY.trim();
}
if (fs.existsSync('/run/secrets/gcoord_master_key')) {
return fs.readFileSync('/run/secrets/gcoord_master_key', 'utf8').trim();
}
if (dataDir) {
const localKeyFile = path.join(path.resolve(dataDir), 'vault.key');
if (fs.existsSync(localKeyFile)) {
return fs.readFileSync(localKeyFile, 'utf8').trim();
}
}
return undefined;
}
function readOptionalPassphrase(passphraseFile?: string): string | undefined {
if (passphraseFile) {
return fs.readFileSync(passphraseFile, 'utf8').trim();
}
if (process.env.GCOORD_BACKUP_PASSPHRASE?.trim()) {
return process.env.GCOORD_BACKUP_PASSPHRASE.trim();
}
return undefined;
}
async function runRotateKey(args: string[]): Promise<number> {
@ -89,6 +150,147 @@ async function runRotateKey(args: string[]): Promise<number> {
return 0;
}
async function runBackup(args: string[]): Promise<number> {
const parsed = parseArgs({
args,
options: {
out: { type: 'string' },
'data-dir': { type: 'string' },
'key-file': { type: 'string' },
'passphrase-file': { type: 'string' },
},
allowPositionals: true,
});
const outRaw = parsed.values.out ?? parsed.positionals[0];
if (!outRaw) {
console.error('Error: --out <path.gcoord.enc> is required');
return 1;
}
const dataDir = path.resolve(
parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data',
);
const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']);
const masterKey = passphrase
? readOptionalKeyNonInteractive(parsed.values['key-file'], dataDir)
: await readCurrentKey(parsed.values['key-file'], dataDir);
const result = createBackupBundle({
dataDir,
masterKey,
passphrase,
});
const outPath = path.resolve(outRaw);
fs.mkdirSync(path.dirname(outPath), { recursive: true });
const tmpPath = `${outPath}.tmp.${process.pid}.${Date.now()}`;
const fd = fs.openSync(tmpPath, 'w', 0o600);
try {
fs.writeFileSync(fd, result.serialized, 'utf8');
fs.fsyncSync(fd);
} finally {
fs.closeSync(fd);
}
fs.renameSync(tmpPath, outPath);
fs.chmodSync(outPath, 0o600);
console.log(
`Backup created at ${outPath} (kdf=${result.summary.kdf}, configs=${result.summary.configFileCount}, knownHosts=${result.summary.knownHostsCount}, vaultVerified=${result.summary.vaultVerified})`,
);
return 0;
}
async function runVerifyBackup(args: string[]): Promise<number> {
const parsed = parseArgs({
args,
options: {
bundle: { type: 'string' },
'key-file': { type: 'string' },
'passphrase-file': { type: 'string' },
'vault-key-file': { type: 'string' },
json: { type: 'boolean', default: false },
},
allowPositionals: true,
});
const bundleArg = parsed.values.bundle ?? parsed.positionals[0];
if (!bundleArg) {
console.error('Error: backup bundle path is required');
return 1;
}
const rawBuf = fs.readFileSync(path.resolve(bundleArg));
const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']);
let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file']);
if (!passphrase && !masterKey) {
const rawMeta = JSON.parse(rawBuf.toString('utf8')) as { kdf?: string };
if (rawMeta.kdf === 'scrypt') {
throw new Error('Passphrase required for scrypt-encrypted backup (--passphrase-file or GCOORD_BACKUP_PASSPHRASE)');
}
masterKey = await readCurrentKey(undefined);
}
const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file']);
const summary = verifyBackupSummaryOnly(rawBuf, {
masterKey,
passphrase,
vaultMasterKey,
});
if (parsed.values.json) {
console.log(JSON.stringify(summary, null, 2));
} else {
console.log(
`Backup verified cleanly (createdAt=${summary.createdAt}, kdf=${summary.kdf}, configs=${summary.configFileCount}, vault=${summary.hasVault ? (summary.vaultVerified ? `verified(${summary.vaultCredentialCount ?? 0} creds)` : 'unverified') : 'none'}, knownHosts=${summary.knownHostsCount})`,
);
}
return 0;
}
async function runRestore(args: string[]): Promise<number> {
const parsed = parseArgs({
args,
options: {
bundle: { type: 'string' },
'data-dir': { type: 'string' },
'key-file': { type: 'string' },
'passphrase-file': { type: 'string' },
'vault-key-file': { type: 'string' },
},
allowPositionals: true,
});
const bundleArg = parsed.values.bundle ?? parsed.positionals[0];
if (!bundleArg) {
console.error('Error: backup bundle path is required');
return 1;
}
const dataDir = path.resolve(
parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data',
);
const rawBuf = fs.readFileSync(path.resolve(bundleArg));
const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']);
let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file'], dataDir);
if (!passphrase && !masterKey) {
masterKey = await readCurrentKey(undefined, dataDir);
}
const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file'], dataDir);
const { summary } = restoreBackupBundle(rawBuf, {
dataDir,
masterKey,
passphrase,
vaultMasterKey,
});
console.log(
`Restored GCoordinator state to ${dataDir} (configs=${summary.configFileCount}, knownHosts=${summary.knownHostsCount}, silences=${summary.alertSilenceCount})`,
);
return 0;
}
async function main(): Promise<void> {
const [command, ...rest] = process.argv.slice(2);
if (!command || command === '-h' || command === '--help') {
@ -99,10 +301,14 @@ async function main(): Promise<void> {
if (command === 'rotate-key') {
process.exit(await runRotateKey(rest));
}
if (command === 'backup' || command === 'verify-backup' || command === 'restore') {
console.error(`Command "${command}" is scheduled for Phase 5 (.gcoord.enc portable backup).`);
process.exit(2);
if (command === 'backup') {
process.exit(await runBackup(rest));
}
if (command === 'verify-backup') {
process.exit(await runVerifyBackup(rest));
}
if (command === 'restore') {
process.exit(await runRestore(rest));
}
console.error(`Unknown command: ${command}`);