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:
143
src/server/db.ts
143
src/server/db.ts
@@ -10,11 +10,16 @@ db.pragma('journal_mode = WAL');
|
||||
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS vaults (
|
||||
vault_key TEXT PRIMARY KEY,
|
||||
ciphertext BLOB NOT NULL,
|
||||
nonce BLOB NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
updated_by TEXT NOT NULL
|
||||
vault_key TEXT PRIMARY KEY,
|
||||
ciphertext BLOB NOT NULL,
|
||||
nonce BLOB NOT NULL,
|
||||
-- Exactly one previous version, retained as a rollback safety net for
|
||||
-- an accidental bad push — not a full history. NULL if there is no
|
||||
-- previous version, or if the last push explicitly purged it.
|
||||
prev_ciphertext BLOB,
|
||||
prev_nonce BLOB,
|
||||
updated_at INTEGER NOT NULL,
|
||||
updated_by TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS recipients (
|
||||
@@ -29,10 +34,26 @@ db.exec(`
|
||||
vault_key TEXT NOT NULL,
|
||||
recipient_id TEXT NOT NULL,
|
||||
wrapped_key TEXT NOT NULL, -- base64 crypto_box_seal(vault_symmetric_key, recipient_pubkey)
|
||||
-- Read implied write in the original design; resolved to a real
|
||||
-- capability distinction — a recipient that only needs to pull a
|
||||
-- vault (e.g. an automated deploy identity) shouldn't also be able
|
||||
-- to overwrite it. Defaults to 1 so nothing existing changes.
|
||||
can_write INTEGER NOT NULL DEFAULT 1,
|
||||
granted_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (vault_key, recipient_id)
|
||||
);
|
||||
|
||||
-- Mirrors vault_grants, but for the one retained previous version —
|
||||
-- wrapped keys as they were at push time, so a recipient who had
|
||||
-- access to the previous version can still unwrap it via --previous
|
||||
-- even if their current grant has since changed.
|
||||
CREATE TABLE IF NOT EXISTS vault_grants_previous (
|
||||
vault_key TEXT NOT NULL,
|
||||
recipient_id TEXT NOT NULL,
|
||||
wrapped_key TEXT NOT NULL,
|
||||
PRIMARY KEY (vault_key, recipient_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS access_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
vault_key TEXT NOT NULL,
|
||||
@@ -46,6 +67,8 @@ export interface VaultRow {
|
||||
vault_key: string;
|
||||
ciphertext: Buffer;
|
||||
nonce: Buffer;
|
||||
prev_ciphertext: Buffer | null;
|
||||
prev_nonce: Buffer | null;
|
||||
updated_at: number;
|
||||
updated_by: string;
|
||||
}
|
||||
@@ -61,6 +84,7 @@ export interface GrantRow {
|
||||
vault_key: string;
|
||||
recipient_id: string;
|
||||
wrapped_key: string;
|
||||
can_write: number;
|
||||
granted_at: number;
|
||||
}
|
||||
|
||||
@@ -68,14 +92,71 @@ export function getVault(vaultKey: string): VaultRow | undefined {
|
||||
return db.prepare(`SELECT * FROM vaults WHERE vault_key = ?`).get(vaultKey) as VaultRow | undefined;
|
||||
}
|
||||
|
||||
export function upsertVault(vaultKey: string, ciphertext: Buffer, nonce: Buffer, updatedBy: string): void {
|
||||
db.prepare(
|
||||
`INSERT INTO vaults (vault_key, ciphertext, nonce, updated_at, updated_by)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(vault_key) DO UPDATE SET
|
||||
ciphertext = excluded.ciphertext, nonce = excluded.nonce,
|
||||
updated_at = excluded.updated_at, updated_by = excluded.updated_by`,
|
||||
).run(vaultKey, ciphertext, nonce, Math.floor(Date.now() / 1000), updatedBy);
|
||||
// `purge`: skip retaining the outgoing version as "previous" — used for
|
||||
// compromise-driven rotations, where the whole point is that the old
|
||||
// value stops being retrievable by anyone. A purge also clears out
|
||||
// whatever previous version already existed, since it would defeat the
|
||||
// purpose to still leave the version-before-that recoverable.
|
||||
export function pushVault(
|
||||
vaultKey: string,
|
||||
ciphertext: Buffer,
|
||||
nonce: Buffer,
|
||||
updatedBy: string,
|
||||
wrappedByRecipientId: Map<string, { wrappedKey: string; canWrite: boolean }>,
|
||||
purge: boolean,
|
||||
): void {
|
||||
const tx = db.transaction(() => {
|
||||
const existing = getVault(vaultKey);
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
if (purge) {
|
||||
db.prepare(
|
||||
`INSERT INTO vaults (vault_key, ciphertext, nonce, prev_ciphertext, prev_nonce, updated_at, updated_by)
|
||||
VALUES (?, ?, ?, NULL, NULL, ?, ?)
|
||||
ON CONFLICT(vault_key) DO UPDATE SET
|
||||
ciphertext = excluded.ciphertext, nonce = excluded.nonce,
|
||||
prev_ciphertext = NULL, prev_nonce = NULL,
|
||||
updated_at = excluded.updated_at, updated_by = excluded.updated_by`,
|
||||
).run(vaultKey, ciphertext, nonce, now, updatedBy);
|
||||
db.prepare(`DELETE FROM vault_grants_previous WHERE vault_key = ?`).run(vaultKey);
|
||||
} else {
|
||||
db.prepare(
|
||||
`INSERT INTO vaults (vault_key, ciphertext, nonce, prev_ciphertext, prev_nonce, updated_at, updated_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(vault_key) DO UPDATE SET
|
||||
ciphertext = excluded.ciphertext, nonce = excluded.nonce,
|
||||
prev_ciphertext = excluded.prev_ciphertext, prev_nonce = excluded.prev_nonce,
|
||||
updated_at = excluded.updated_at, updated_by = excluded.updated_by`,
|
||||
).run(vaultKey, ciphertext, nonce, existing?.ciphertext ?? null, existing?.nonce ?? null, now, updatedBy);
|
||||
|
||||
// Move the current grants (as they stood before this push) into
|
||||
// vault_grants_previous, so someone who had access to the
|
||||
// outgoing version can still pull it via --previous.
|
||||
db.prepare(`DELETE FROM vault_grants_previous WHERE vault_key = ?`).run(vaultKey);
|
||||
if (existing) {
|
||||
db.prepare(
|
||||
`INSERT INTO vault_grants_previous (vault_key, recipient_id, wrapped_key)
|
||||
SELECT vault_key, recipient_id, wrapped_key FROM vault_grants WHERE vault_key = ?`,
|
||||
).run(vaultKey);
|
||||
}
|
||||
}
|
||||
|
||||
db.prepare(`DELETE FROM vault_grants WHERE vault_key = ?`).run(vaultKey);
|
||||
const insert = db.prepare(
|
||||
`INSERT INTO vault_grants (vault_key, recipient_id, wrapped_key, can_write, granted_at) VALUES (?, ?, ?, ?, ?)`,
|
||||
);
|
||||
for (const [recipientId, { wrappedKey, canWrite }] of wrappedByRecipientId) {
|
||||
insert.run(vaultKey, recipientId, wrappedKey, canWrite ? 1 : 0, now);
|
||||
}
|
||||
});
|
||||
tx();
|
||||
}
|
||||
|
||||
export function getVaultGrantsPrevious(vaultKey: string, recipientId: string): string | undefined {
|
||||
const row = db.prepare(
|
||||
`SELECT wrapped_key FROM vault_grants_previous WHERE vault_key = ? AND recipient_id = ?`,
|
||||
).get(vaultKey, recipientId) as { wrapped_key: string } | undefined;
|
||||
return row?.wrapped_key;
|
||||
}
|
||||
|
||||
export function getRecipient(recipientId: string): RecipientRow | undefined {
|
||||
@@ -96,6 +177,7 @@ export function deleteRecipient(recipientId: string): void {
|
||||
const tx = db.transaction(() => {
|
||||
db.prepare(`DELETE FROM recipients WHERE recipient_id = ?`).run(recipientId);
|
||||
db.prepare(`DELETE FROM vault_grants WHERE recipient_id = ?`).run(recipientId);
|
||||
db.prepare(`DELETE FROM vault_grants_previous WHERE recipient_id = ?`).run(recipientId);
|
||||
});
|
||||
tx();
|
||||
}
|
||||
@@ -107,6 +189,13 @@ export function hasGrant(vaultKey: string, recipientId: string): boolean {
|
||||
return row != null;
|
||||
}
|
||||
|
||||
export function hasWriteGrant(vaultKey: string, recipientId: string): boolean {
|
||||
const row = db.prepare(
|
||||
`SELECT can_write FROM vault_grants WHERE vault_key = ? AND recipient_id = ?`,
|
||||
).get(vaultKey, recipientId) as { can_write: number } | undefined;
|
||||
return row != null && row.can_write === 1;
|
||||
}
|
||||
|
||||
export function getGrant(vaultKey: string, recipientId: string): GrantRow | undefined {
|
||||
return db.prepare(
|
||||
`SELECT * FROM vault_grants WHERE vault_key = ? AND recipient_id = ?`,
|
||||
@@ -117,29 +206,13 @@ export function listGrantsForVault(vaultKey: string): GrantRow[] {
|
||||
return db.prepare(`SELECT * FROM vault_grants WHERE vault_key = ?`).all(vaultKey) as GrantRow[];
|
||||
}
|
||||
|
||||
export function setGrant(vaultKey: string, recipientId: string, wrappedKeyB64: string): void {
|
||||
export function setGrant(vaultKey: string, recipientId: string, wrappedKeyB64: string, canWrite: boolean): void {
|
||||
db.prepare(
|
||||
`INSERT INTO vault_grants (vault_key, recipient_id, wrapped_key, granted_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(vault_key, recipient_id) DO UPDATE SET wrapped_key = excluded.wrapped_key, granted_at = excluded.granted_at`,
|
||||
).run(vaultKey, recipientId, wrappedKeyB64, Math.floor(Date.now() / 1000));
|
||||
}
|
||||
|
||||
// Used by `push` (rotation): replaces every wrapped-key row for a vault
|
||||
// in one transaction, so a concurrent grant/revoke can't interleave with
|
||||
// a partial rewrap and leave the vault in a mixed old/new-key state.
|
||||
export function replaceAllGrantsForVault(vaultKey: string, wrappedByRecipientId: Map<string, string>): void {
|
||||
const tx = db.transaction(() => {
|
||||
db.prepare(`DELETE FROM vault_grants WHERE vault_key = ?`).run(vaultKey);
|
||||
const insert = db.prepare(
|
||||
`INSERT INTO vault_grants (vault_key, recipient_id, wrapped_key, granted_at) VALUES (?, ?, ?, ?)`,
|
||||
);
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
for (const [recipientId, wrappedKeyB64] of wrappedByRecipientId) {
|
||||
insert.run(vaultKey, recipientId, wrappedKeyB64, now);
|
||||
}
|
||||
});
|
||||
tx();
|
||||
`INSERT INTO vault_grants (vault_key, recipient_id, wrapped_key, can_write, granted_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(vault_key, recipient_id) DO UPDATE SET
|
||||
wrapped_key = excluded.wrapped_key, can_write = excluded.can_write, granted_at = excluded.granted_at`,
|
||||
).run(vaultKey, recipientId, wrappedKeyB64, canWrite ? 1 : 0, Math.floor(Date.now() / 1000));
|
||||
}
|
||||
|
||||
export function deleteGrant(vaultKey: string, recipientId: string): void {
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { Router } from 'express';
|
||||
import {
|
||||
getVault,
|
||||
upsertVault,
|
||||
pushVault,
|
||||
hasGrant,
|
||||
hasWriteGrant,
|
||||
getGrant,
|
||||
getVaultGrantsPrevious,
|
||||
listGrantsForVault,
|
||||
setGrant,
|
||||
replaceAllGrantsForVault,
|
||||
logAccess,
|
||||
getAccessLog,
|
||||
listRecipients,
|
||||
@@ -33,7 +34,10 @@ router.get('/vaults/:key/exists', (req, res) => {
|
||||
});
|
||||
|
||||
// Only current grantees of a vault can see who else has access to it —
|
||||
// needed by `keep push` to know who to re-wrap the rotated key for.
|
||||
// needed by `keep push` to know who to re-wrap the rotated key for, and
|
||||
// to preserve each recipient's can_write flag across a rotation (a push
|
||||
// shouldn't silently upgrade a read-only grantee to read-write, or vice
|
||||
// versa).
|
||||
router.get('/vaults/:key/recipients', (req: AuthedRequest, res) => {
|
||||
const vaultKey = req.params.key;
|
||||
if (!hasGrant(vaultKey, req.recipientId!)) {
|
||||
@@ -44,13 +48,34 @@ router.get('/vaults/:key/recipients', (req: AuthedRequest, res) => {
|
||||
const byId = new Map(listRecipients().map(r => [r.recipient_id, r]));
|
||||
res.json(grants.map(g => {
|
||||
const r = byId.get(g.recipient_id);
|
||||
return { recipientId: g.recipient_id, label: r?.label ?? null, publicKey: r?.public_key ?? null };
|
||||
return { recipientId: g.recipient_id, label: r?.label ?? null, publicKey: r?.public_key ?? null, canWrite: g.can_write === 1 };
|
||||
}));
|
||||
});
|
||||
|
||||
router.get('/vaults/:key/pull', (req: AuthedRequest, res) => {
|
||||
const vaultKey = req.params.key;
|
||||
const recipientId = req.recipientId!;
|
||||
const wantPrevious = req.query.previous === '1' || req.query.previous === 'true';
|
||||
|
||||
if (wantPrevious) {
|
||||
const vault = getVault(vaultKey);
|
||||
const wrappedKey = getVaultGrantsPrevious(vaultKey, recipientId);
|
||||
if (!vault || !vault.prev_ciphertext || !vault.prev_nonce || !wrappedKey) {
|
||||
logAccess(vaultKey, recipientId, 'pull');
|
||||
res.status(404).json({ error: 'no previous version, or no access to it' });
|
||||
return;
|
||||
}
|
||||
logAccess(vaultKey, recipientId, 'pull');
|
||||
res.json({
|
||||
ciphertext: vault.prev_ciphertext.toString('base64'),
|
||||
nonce: vault.prev_nonce.toString('base64'),
|
||||
wrappedKey,
|
||||
updatedAt: null,
|
||||
updatedBy: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const grant = getGrant(vaultKey, recipientId);
|
||||
const vault = getVault(vaultKey);
|
||||
|
||||
@@ -74,53 +99,74 @@ router.get('/vaults/:key/pull', (req: AuthedRequest, res) => {
|
||||
// key in one call — the client has already generated a fresh symmetric
|
||||
// key and re-wrapped it for every currently-granted recipient (fetched
|
||||
// via GET /vaults/:key/recipients first). Existing vaults require the
|
||||
// pusher to already be a grantee (read implies write, v1 decision from
|
||||
// IMPLEMENTATION.md); a brand-new vault key may be created by any
|
||||
// registered recipient, who becomes its first grantee.
|
||||
// pusher to hold a *write* grant — read no longer implies write (see
|
||||
// IMPLEMENTATION.md's resolved design decisions). A brand-new vault key
|
||||
// may be created by any registered recipient, who becomes its first
|
||||
// (read-write) grantee.
|
||||
//
|
||||
// `purge: true` skips retaining the outgoing version as "previous" —
|
||||
// for compromise-driven rotations, where the old value should stop
|
||||
// being retrievable by anyone, not survive one more pull as a rollback.
|
||||
router.post('/vaults/:key/push', (req: AuthedRequest, res) => {
|
||||
const vaultKey = req.params.key;
|
||||
const recipientId = req.recipientId!;
|
||||
const existing = getVault(vaultKey);
|
||||
|
||||
if (existing && !hasGrant(vaultKey, recipientId)) {
|
||||
res.status(403).json({ error: 'no access to this vault' });
|
||||
if (existing && !hasWriteGrant(vaultKey, recipientId)) {
|
||||
res.status(403).json({ error: 'no write access to this vault' });
|
||||
return;
|
||||
}
|
||||
|
||||
const body = req.body as { ciphertext?: string; nonce?: string; wrappedKeys?: Record<string, string> };
|
||||
const body = req.body as {
|
||||
ciphertext?: string;
|
||||
nonce?: string;
|
||||
wrappedKeys?: Record<string, { wrappedKey: string; canWrite?: boolean }>;
|
||||
purge?: boolean;
|
||||
};
|
||||
if (!body.ciphertext || !body.nonce || !body.wrappedKeys || Object.keys(body.wrappedKeys).length === 0) {
|
||||
res.status(400).json({ error: 'ciphertext, nonce, and at least one wrapped key are required' });
|
||||
return;
|
||||
}
|
||||
|
||||
upsertVault(vaultKey, Buffer.from(body.ciphertext, 'base64'), Buffer.from(body.nonce, 'base64'), recipientId);
|
||||
replaceAllGrantsForVault(vaultKey, new Map(Object.entries(body.wrappedKeys)));
|
||||
const wrappedByRecipientId = new Map(
|
||||
Object.entries(body.wrappedKeys).map(([rid, w]) => [rid, { wrappedKey: w.wrappedKey, canWrite: w.canWrite !== false }]),
|
||||
);
|
||||
|
||||
pushVault(
|
||||
vaultKey,
|
||||
Buffer.from(body.ciphertext, 'base64'),
|
||||
Buffer.from(body.nonce, 'base64'),
|
||||
recipientId,
|
||||
wrappedByRecipientId,
|
||||
body.purge === true,
|
||||
);
|
||||
|
||||
logAccess(vaultKey, recipientId, 'push');
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
// Adds ONE new recipient to an existing vault using the CURRENT
|
||||
// (unrotated) symmetric key — the granter must already hold a grant
|
||||
// (meaning they can unwrap the current key locally) and supplies a fresh
|
||||
// seal of that same key for the new recipient's public key. Does not
|
||||
// touch the ciphertext or any other recipient's wrapped key.
|
||||
// (unrotated) symmetric key — the granter must already hold a *write*
|
||||
// grant (granting is a mutation of the vault's membership, not merely a
|
||||
// read) and supplies a fresh seal of that same key for the new
|
||||
// recipient's public key. Does not touch the ciphertext or any other
|
||||
// recipient's wrapped key.
|
||||
router.post('/vaults/:key/grant', (req: AuthedRequest, res) => {
|
||||
const vaultKey = req.params.key;
|
||||
const granterId = req.recipientId!;
|
||||
|
||||
if (!hasGrant(vaultKey, granterId)) {
|
||||
res.status(403).json({ error: 'no access to this vault' });
|
||||
if (!hasWriteGrant(vaultKey, granterId)) {
|
||||
res.status(403).json({ error: 'no write access to this vault' });
|
||||
return;
|
||||
}
|
||||
|
||||
const body = req.body as { recipientId?: string; wrappedKey?: string };
|
||||
const body = req.body as { recipientId?: string; wrappedKey?: string; canWrite?: boolean };
|
||||
if (!body.recipientId || !body.wrappedKey) {
|
||||
res.status(400).json({ error: 'recipientId and wrappedKey are required' });
|
||||
return;
|
||||
}
|
||||
|
||||
setGrant(vaultKey, body.recipientId, body.wrappedKey);
|
||||
setGrant(vaultKey, body.recipientId, body.wrappedKey, body.canWrite !== false);
|
||||
logAccess(vaultKey, granterId, 'grant');
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user