Resolve open design questions: write-scoped grants, rollback, purge
Per-question resolution, per best practice rather than deferral: - Push authorization: closed the least-privilege gap where read implied write. vault_grants gained can_write (default true, so nothing existing changes); enforced on push and grant (granting others is itself a mutation of vault membership, so it needs write too, not just read). 'keep grant --read-only' creates a read-only grant. - Version history: not full history (conflates "undo a typo'd push" with "this leaked, stop retaining it" into one mechanism). Retains exactly one previous version as a rollback safety net (vaults.prev_ciphertext/prev_nonce + a vault_grants_previous mirror table so recipients can unwrap it), plus 'keep push --purge' for compromise-driven rotations that explicitly skips retention and wipes any existing previous version too. - Per-secret-key granularity: resolved by NOT building it — documented the escape hatch (split into more vaults) instead of adding partial- decrypt complexity for a problem the existing primitive solves. One more real bug caught during verification: the CLI's --previous flag initially signed a path including its query string, but the server verifies against req.originalUrl with the query stripped — a mismatch that would have made every --previous request fail signature verification. Fixed by splitting the signed path from the request URL in signedFetch, signing only the former. Verified end-to-end with three independent identities: read-only grant correctly blocked from push and from granting others, write access and read-only status both preserved correctly across a rotation, previous- version pull working for a routine push and correctly unavailable to every recipient after a purge push. Also re-verified against a fresh Docker build. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,7 +11,7 @@ import {
|
||||
enc,
|
||||
} from '../../shared/crypto.js';
|
||||
|
||||
export async function vaultPush(vaultKey: string, file: string): Promise<void> {
|
||||
export async function vaultPush(vaultKey: string, file: string, purge: boolean): Promise<void> {
|
||||
await ready();
|
||||
const { identity, recipientId } = await requireIdentityAndRecipientId();
|
||||
|
||||
@@ -21,8 +21,11 @@ export async function vaultPush(vaultKey: string, file: string): Promise<void> {
|
||||
|
||||
const existsRes = await expectOk(await signedFetch(identity, recipientId, 'GET', `/api/vaults/${encodeURIComponent(vaultKey)}/exists`));
|
||||
|
||||
const wrapFor = new Map<string, string>(); // recipientId -> publicKey
|
||||
wrapFor.set(recipientId, identity.id);
|
||||
// recipientId -> { publicKey, canWrite } — canWrite is preserved across
|
||||
// a rotation, not reset, so pushing an update never silently changes
|
||||
// who else can write vs. only read.
|
||||
const wrapFor = new Map<string, { publicKey: string; canWrite: boolean }>();
|
||||
wrapFor.set(recipientId, { publicKey: identity.id, canWrite: true });
|
||||
|
||||
if (existsRes.exists) {
|
||||
const recipientsRes = await signedFetch(identity, recipientId, 'GET', `/api/vaults/${encodeURIComponent(vaultKey)}/recipients`);
|
||||
@@ -30,32 +33,34 @@ export async function vaultPush(vaultKey: string, file: string): Promise<void> {
|
||||
const body = await recipientsRes.json().catch(() => ({}));
|
||||
throw new Error(body.error ?? `no access to vault '${vaultKey}' — ask an existing grantee to run 'keep grant ${vaultKey} ${recipientId}'`);
|
||||
}
|
||||
const current = await recipientsRes.json() as { recipientId: string; publicKey: string }[];
|
||||
for (const r of current) if (r.publicKey) wrapFor.set(r.recipientId, r.publicKey);
|
||||
const current = await recipientsRes.json() as { recipientId: string; publicKey: string; canWrite: boolean }[];
|
||||
for (const r of current) if (r.publicKey) wrapFor.set(r.recipientId, { publicKey: r.publicKey, canWrite: r.canWrite });
|
||||
}
|
||||
|
||||
const symmetricKey = generateSymmetricKey();
|
||||
const { nonce, ciphertext } = secretboxEncrypt(symmetricKey, payload);
|
||||
|
||||
const wrappedKeys: Record<string, string> = {};
|
||||
for (const [rid, pubHex] of wrapFor) {
|
||||
wrappedKeys[rid] = enc.toBase64(Identity.sealFor(pubHex, symmetricKey));
|
||||
const wrappedKeys: Record<string, { wrappedKey: string; canWrite: boolean }> = {};
|
||||
for (const [rid, { publicKey, canWrite }] of wrapFor) {
|
||||
wrappedKeys[rid] = { wrappedKey: enc.toBase64(Identity.sealFor(publicKey, symmetricKey)), canWrite };
|
||||
}
|
||||
|
||||
await expectOk(await signedFetch(identity, recipientId, 'POST', `/api/vaults/${encodeURIComponent(vaultKey)}/push`, {
|
||||
ciphertext: enc.toBase64(ciphertext),
|
||||
nonce: enc.toBase64(nonce),
|
||||
wrappedKeys,
|
||||
purge,
|
||||
}));
|
||||
|
||||
console.log(`pushed '${vaultKey}' — ${Object.keys(values).length} key${Object.keys(values).length === 1 ? '' : 's'}, wrapped for ${wrapFor.size} recipient${wrapFor.size === 1 ? '' : 's'}.`);
|
||||
console.log(`pushed '${vaultKey}' — ${Object.keys(values).length} key${Object.keys(values).length === 1 ? '' : 's'}, wrapped for ${wrapFor.size} recipient${wrapFor.size === 1 ? '' : 's'}${purge ? ' (purged previous version)' : ''}.`);
|
||||
}
|
||||
|
||||
export async function vaultPull(vaultKey: string, format: 'env' | 'json', outFile?: string): Promise<void> {
|
||||
export async function vaultPull(vaultKey: string, format: 'env' | 'json', outFile: string | undefined, previous: boolean): Promise<void> {
|
||||
await ready();
|
||||
const { identity, recipientId } = await requireIdentityAndRecipientId();
|
||||
|
||||
const data = await expectOk(await signedFetch(identity, recipientId, 'GET', `/api/vaults/${encodeURIComponent(vaultKey)}/pull`));
|
||||
const query = previous ? '?previous=1' : '';
|
||||
const data = await expectOk(await signedFetch(identity, recipientId, 'GET', `/api/vaults/${encodeURIComponent(vaultKey)}/pull${query}`));
|
||||
|
||||
const symmetricKey = identity.openSealed(enc.fromBase64(data.wrappedKey));
|
||||
if (!symmetricKey) throw new Error('failed to unwrap this vault\'s key — wrong identity, or the grant is stale');
|
||||
@@ -66,13 +71,13 @@ export async function vaultPull(vaultKey: string, format: 'env' | 'json', outFil
|
||||
const out = format === 'json' ? JSON.stringify(values, null, 2) : serializeEnv(values);
|
||||
if (outFile) {
|
||||
fs.writeFileSync(outFile, out);
|
||||
console.error(`wrote ${Object.keys(values).length} key(s) to ${outFile}`);
|
||||
console.error(`wrote ${Object.keys(values).length} key(s) to ${outFile}${previous ? ' (previous version)' : ''}`);
|
||||
} else {
|
||||
process.stdout.write(out);
|
||||
}
|
||||
}
|
||||
|
||||
export async function vaultGrant(vaultKey: string, targetRecipientId: string): Promise<void> {
|
||||
export async function vaultGrant(vaultKey: string, targetRecipientId: string, readOnly: boolean): Promise<void> {
|
||||
await ready();
|
||||
const { identity, recipientId } = await requireIdentityAndRecipientId();
|
||||
|
||||
@@ -88,15 +93,16 @@ export async function vaultGrant(vaultKey: string, targetRecipientId: string): P
|
||||
await expectOk(await signedFetch(identity, recipientId, 'POST', `/api/vaults/${encodeURIComponent(vaultKey)}/grant`, {
|
||||
recipientId: targetRecipientId,
|
||||
wrappedKey,
|
||||
canWrite: !readOnly,
|
||||
}));
|
||||
|
||||
console.log(`granted '${vaultKey}' to ${targetRecipientId}.`);
|
||||
console.log(`granted ${readOnly ? 'read-only ' : ''}'${vaultKey}' access to ${targetRecipientId}.`);
|
||||
}
|
||||
|
||||
export async function vaultRevoke(vaultKey: string, targetRecipientId: string): Promise<void> {
|
||||
await expectOk(await adminFetch('DELETE', `/api/admin/vaults/${encodeURIComponent(vaultKey)}/grants/${encodeURIComponent(targetRecipientId)}`));
|
||||
console.log(`revoked ${targetRecipientId}'s access to '${vaultKey}'.`);
|
||||
console.log(`Note: this stops future pulls only. If this was a compromise response, also run 'keep push ${vaultKey}' with rotated values.`);
|
||||
console.log(`Note: this stops future pulls only. If this was a compromise response, also run 'keep push ${vaultKey} --purge' with rotated values.`);
|
||||
}
|
||||
|
||||
export async function vaultLog(vaultKey: string): Promise<void> {
|
||||
|
||||
@@ -8,6 +8,10 @@ function flag(args: string[], name: string, fallback?: string): string | undefin
|
||||
return i !== -1 ? args[i + 1] : fallback;
|
||||
}
|
||||
|
||||
function boolFlag(args: string[], name: string): boolean {
|
||||
return args.includes(`--${name}`);
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const [, , cmd, sub, ...rest] = process.argv;
|
||||
|
||||
@@ -24,9 +28,9 @@ async function main(): Promise<void> {
|
||||
if (sub === 'remove') return await recipientRemove(rest[0]);
|
||||
}
|
||||
|
||||
if (cmd === 'push') return await vaultPush(sub, flag(rest, 'file', '.env')!);
|
||||
if (cmd === 'pull') return await vaultPull(sub, (flag(rest, 'format', 'env') as 'env' | 'json'), flag(rest, 'out'));
|
||||
if (cmd === 'grant') return await vaultGrant(sub, rest[0]);
|
||||
if (cmd === 'push') return await vaultPush(sub, flag(rest, 'file', '.env')!, boolFlag(rest, 'purge'));
|
||||
if (cmd === 'pull') return await vaultPull(sub, (flag(rest, 'format', 'env') as 'env' | 'json'), flag(rest, 'out'), boolFlag(rest, 'previous'));
|
||||
if (cmd === 'grant') return await vaultGrant(sub, rest[0], boolFlag(rest, 'read-only'));
|
||||
if (cmd === 'revoke') return await vaultRevoke(sub, rest[0]);
|
||||
if (cmd === 'log') return await vaultLog(sub);
|
||||
|
||||
@@ -45,9 +49,9 @@ function printUsage(): void {
|
||||
keep identity show
|
||||
keep identity set-id <recipient-id>
|
||||
|
||||
keep push <vault> [--file .env]
|
||||
keep pull <vault> [--format env|json] [--out <path>]
|
||||
keep grant <vault> <recipient-id>
|
||||
keep push <vault> [--file .env] [--purge] (--purge: don't retain the outgoing version as rollback)
|
||||
keep pull <vault> [--format env|json] [--out <path>] [--previous]
|
||||
keep grant <vault> <recipient-id> [--read-only]
|
||||
keep revoke <vault> <recipient-id> (admin — needs KEEP_ADMIN_PASSWORD)
|
||||
keep log <vault>
|
||||
|
||||
|
||||
@@ -4,6 +4,16 @@ export function serverUrl(): string {
|
||||
return process.env.KEEP_SERVER_URL ?? 'http://localhost:3050';
|
||||
}
|
||||
|
||||
function splitQuery(path: string): [string, string] {
|
||||
const i = path.indexOf('?');
|
||||
return i === -1 ? [path, ''] : [path.slice(0, i), path.slice(i)];
|
||||
}
|
||||
|
||||
// `path` must NOT include a query string — the server verifies the
|
||||
// signature against req.originalUrl with the query string stripped
|
||||
// (see server/auth.ts), so signing one here would never match. Pass
|
||||
// query params via `path` only for the actual request URL, kept
|
||||
// separate from what gets signed.
|
||||
export async function signedFetch(
|
||||
identity: Identity,
|
||||
recipientId: string,
|
||||
@@ -11,12 +21,13 @@ export async function signedFetch(
|
||||
path: string,
|
||||
body?: unknown,
|
||||
): Promise<Response> {
|
||||
const [signedPath, query] = splitQuery(path);
|
||||
const bodyBytes = body !== undefined ? enc.fromUtf8(JSON.stringify(body)) : new Uint8Array();
|
||||
const timestamp = Math.floor(Date.now() / 1000);
|
||||
const toSign = signingString(method, path, timestamp, bodyBytes);
|
||||
const toSign = signingString(method, signedPath, timestamp, bodyBytes);
|
||||
const signature = enc.toHex(identity.sign(enc.fromUtf8(toSign)));
|
||||
|
||||
return fetch(`${serverUrl()}${path}`, {
|
||||
return fetch(`${serverUrl()}${signedPath}${query}`, {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
|
||||
Reference in New Issue
Block a user