Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion apps/logicsrc-web/src/lib/page-markup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ const credentialProviders = [
{ name: ".env", detail: "Parse, diff, redact, and write local env files without leaking values into logs." },
{ name: "Doppler", detail: "Sync project/config scoped secrets through provider adapters and auditable key fingerprints." },
{ name: "Railway", detail: "Read and write service variables as a deployment target with explicit approval gates." },
{ name: "GitHub Secrets", detail: "Manage repo, organization, and environment secrets through provider-neutral operations." }
{ name: "GitHub Secrets", detail: "Manage repo, organization, and environment secrets through provider-neutral operations." },
{ name: "sh1pt", detail: "Sync the distribution credential vault — App Store Connect, Play, npm, Docker, and Cloudflare tokens — through the sh1pt CLI." }
];

const credentialSurfaces = [
Expand Down
8 changes: 8 additions & 0 deletions apps/pwa/src/db.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,11 @@ export async function all(sql, args = []) {
const r = await db.execute({ sql, args });
return r.rows;
}

/**
* Run many statements in ONE write transaction — all of them commit, or none
* do. Needed anywhere a partial write would leave unrecoverable state, e.g.
* re-keying a vault, where new grants over old ciphertext locks out every
* member permanently.
*/
export const batch = (statements) => db.batch(statements, "write");
111 changes: 109 additions & 2 deletions apps/pwa/src/routes/credshare.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
// Auth: the acting user comes from a browser session (req.user) OR a
// `Bearer lsk_…` API key (the logicsrc CLI). Mounted at /api/credshare.
import { Router } from "express";
import { get, all, run } from "../db.mjs";
import { get, all, run, batch } from "../db.mjs";
import { id, token, sha256 } from "../lib/crypto.mjs";
import { bearer, userForApiKey } from "../lib/apikey.mjs";
import { config } from "../config.mjs";
Expand Down Expand Up @@ -200,10 +200,117 @@ credshareRouter.get("/api/credshare/vaults/:id/grants", api(async (req, res, use
const granted = new Set((await all(`SELECT user_id FROM credshare_vault_grants WHERE vault_id = ?`, [vault.id])).map((r) => r.user_id));
const members = await all(`SELECT * FROM credshare_members WHERE team_id = ?`, [vault.team_id]);
const grants = [];
for (const m of members) grants.push({ email: m.email, hasPublicKey: m.user_id ? Boolean(await publicKeyFor(m.user_id)) : false, hasAccess: Boolean(m.user_id && granted.has(m.user_id)) });
for (const m of members) {
// The public key is included so a client can re-seal the vault key to every
// member in one pass (see rekey). Public keys are public by construction --
// they exist to be sealed against -- and this route is already member-only.
const publicKey = m.user_id ? await publicKeyFor(m.user_id) : null;
grants.push({
email: m.email,
publicKey,
status: m.status,
hasPublicKey: Boolean(publicKey),
hasAccess: Boolean(m.user_id && granted.has(m.user_id))
});
}
res.json({ grants });
}));

// Re-key a vault: swap in a fresh DEK, re-seal it to the members who keep
// access, and re-encrypt every secret under it. Values do not change, which the
// server enforces by requiring each submitted fingerprint to equal the stored
// one -- it cannot see values, but it can prove they were not swapped.
//
// This is ONE transaction on purpose. The DEK is recoverable only through the
// grants, so a half-applied rotation (new grants over old ciphertext, or the
// reverse) would make the vault permanently unreadable by everyone.
credshareRouter.post("/api/credshare/vaults/:id/rekey", api(async (req, res, user) => {
const vault = await vaultCtx(res, req.params.id, user.id); if (!vault) return;
const iHold = await get(`SELECT 1 FROM credshare_vault_grants WHERE vault_id = ? AND user_id = ?`, [vault.id, user.id]);
if (!iHold) return res.status(403).json({ error: "Only a member with vault access can re-key it." });

const grants = Array.isArray(req.body?.grants) ? req.body.grants : null;
const secrets = Array.isArray(req.body?.secrets) ? req.body.secrets : null;
const revoke = Array.isArray(req.body?.revoke) ? req.body.revoke.map(norm) : [];
if (!grants || !secrets) return res.status(422).json({ error: "Expected { grants, secrets, revoke? }." });
if (grants.length === 0) return res.status(422).json({ error: "A re-key must keep at least one member, or the vault becomes unreadable." });

// The caller must keep their own access; otherwise they lock themselves out
// the moment the transaction commits.
const me = await get(`SELECT email FROM users WHERE id = ?`, [user.id]);
if (!grants.some((g) => norm(g?.email) === norm(me?.email))) {
return res.status(422).json({ error: "A re-key must include your own grant." });
}

// Every secret must be accounted for, with an unchanged fingerprint. This is
// what makes "re-key" distinct from "write": no value may change here.
const stored = await all(`SELECT name, fingerprint FROM credshare_secrets WHERE vault_id = ?`, [vault.id]);
const storedByName = new Map(stored.map((s) => [s.name, s.fingerprint]));
if (secrets.length !== stored.length) {
return res.status(409).json({ error: `Re-key covers ${secrets.length} secret(s) but the vault holds ${stored.length}. Re-read the vault and retry.` });
}
for (const s of secrets) {
if (!s || typeof s.name !== "string" || typeof s.nonce !== "string" || typeof s.ciphertext !== "string" || typeof s.fingerprint !== "string") {
return res.status(422).json({ error: "Each secret needs { name, nonce, ciphertext, fingerprint }." });
}
if (!storedByName.has(s.name)) {
return res.status(409).json({ error: `"${s.name}" is not in this vault. Re-read the vault and retry.` });
}
if (storedByName.get(s.name) !== s.fingerprint) {
return res.status(409).json({ error: `Re-key would change the value of "${s.name}". A re-key re-encrypts; it never changes values.` });
}
}

// Resolve grant targets before writing anything.
const resolved = [];
for (const g of grants) {
const email = norm(g?.email);
if (!email || typeof g?.wrappedDek !== "string" || !g.wrappedDek) {
return res.status(422).json({ error: "Each grant needs { email, wrappedDek }." });
}
const target = await get(`SELECT id FROM users WHERE email = ?`, [email]);
if (!target) return res.status(409).json({ error: `${email} has not logged in yet, so the vault key cannot be sealed to them.` });
resolved.push({ email, userId: target.id, wrappedDek: g.wrappedDek });
}

const revokedUsers = [];
for (const email of revoke) {
const target = await get(`SELECT id FROM users WHERE email = ?`, [email]);
if (target) revokedUsers.push({ email, userId: target.id });
}

const now = Date.now();
const statements = [];
for (const s of secrets) {
statements.push({
sql: `UPDATE credshare_secrets SET nonce = ?, ciphertext = ?, version = version + 1, updated_by = ?, updated_at = ? WHERE vault_id = ? AND name = ?`,
args: [s.nonce, s.ciphertext, user.id, now, vault.id, s.name]
});
}
for (const g of resolved) {
statements.push({
sql: `INSERT INTO credshare_vault_grants (vault_id, user_id, wrapped_dek, granted_by, created_at) VALUES (?,?,?,?,?) ON CONFLICT(vault_id, user_id) DO UPDATE SET wrapped_dek = excluded.wrapped_dek, granted_by = excluded.granted_by, created_at = excluded.created_at`,
args: [vault.id, g.userId, g.wrappedDek, user.id, now]
});
}
for (const r of revokedUsers) {
statements.push({ sql: `DELETE FROM credshare_vault_grants WHERE vault_id = ? AND user_id = ?`, args: [vault.id, r.userId] });
}
statements.push({
sql: `INSERT INTO credshare_audit (id, team_id, vault_id, actor_user_id, action, key_name, fingerprint, created_at) VALUES (?,?,?,?,?,?,?,?)`,
args: [id(), vault.team_id, vault.id, user.id, "vault:rekey", null, null, now]
});
for (const r of revokedUsers) {
statements.push({
sql: `INSERT INTO credshare_audit (id, team_id, vault_id, actor_user_id, action, key_name, fingerprint, created_at) VALUES (?,?,?,?,?,?,?,?)`,
args: [id(), vault.team_id, vault.id, user.id, "vault:revoke", r.email, null, now]
});
}

await batch(statements);
res.json({ ok: true, rekeyed: secrets.length, granted: resolved.map((g) => g.email), revoked: revokedUsers.map((r) => r.email) });
}));

credshareRouter.post("/api/credshare/vaults/:id/grants", api(async (req, res, user) => {
const vault = await vaultCtx(res, req.params.id, user.id); if (!vault) return;
const iHold = await get(`SELECT 1 FROM credshare_vault_grants WHERE vault_id = ? AND user_id = ?`, [vault.id, user.id]);
Expand Down
228 changes: 228 additions & 0 deletions apps/pwa/test/credshare-rekey.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
// Integration tests for POST /api/credshare/vaults/:id/rekey.
//
// The endpoint is the last line of defence on a genuinely unrecoverable
// operation: the vault DEK exists only inside the grants, so a rotation that
// commits half-way, drops a secret, or leaves the caller ungranted destroys the
// vault permanently. These tests pin the guards that stop that.
//
// Runs against an in-memory libSQL database, so DATABASE_URL must be set before
// anything imports db.mjs.
process.env.DATABASE_URL = ":memory:";

import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import express from "express";

const here = dirname(fileURLToPath(import.meta.url));
const { db, run, get, all } = await import("../src/db.mjs");
const { credshareRouter } = await import("../src/routes/credshare.mjs");

/** Apply the schema this router depends on. */
async function migrate() {
for (const file of ["001_auth.sql", "002_credshare.sql"]) {
const sql = readFileSync(join(here, "..", "src", "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) {
await db.execute(statement);
}
}
}

/**
* Mount the router with a fixed acting user, mimicking a browser session.
* Returns a fetch-like helper bound to an ephemeral port.
*/
async function serve(actingUserId) {
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.user = { id: actingUserId };
next();
});
app.use(credshareRouter);
const server = app.listen(0);
await new Promise((resolve) => server.once("listening", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
return {
async post(path, body) {
const res = await fetch(`${base}${path}`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body)
});
return { status: res.status, body: await res.json() };
},
async get(path) {
const res = await fetch(`${base}${path}`);
return { status: res.status, body: await res.json() };
},
close: () => new Promise((resolve) => server.close(resolve)),
};
}

const now = Date.now();

/** A team with one vault, two granted members, and two secrets. */
async function seed() {
await run(`INSERT INTO users (id, email, created_at) VALUES (?,?,?)`, ["u_me", "me@example.com", now]);
await run(`INSERT INTO users (id, email, created_at) VALUES (?,?,?)`, ["u_them", "them@example.com", now]);
await run(`INSERT INTO credshare_keys (user_id, public_key, updated_at) VALUES (?,?,?)`, ["u_me", "pk-me", now]);
await run(`INSERT INTO credshare_keys (user_id, public_key, updated_at) VALUES (?,?,?)`, ["u_them", "pk-them", now]);
await run(`INSERT INTO credshare_teams (id, slug, name, created_by, created_at) VALUES (?,?,?,?,?)`, ["t1", "acme", "Acme", "u_me", now]);
await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, created_at) VALUES (?,?,?,?,?,?,?)`,
["m1", "t1", "u_me", "me@example.com", "owner", "active", now]);
await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, created_at) VALUES (?,?,?,?,?,?,?)`,
["m2", "t1", "u_them", "them@example.com", "member", "active", now]);
await run(`INSERT INTO credshare_vaults (id, team_id, name, created_by, created_at) VALUES (?,?,?,?,?)`, ["v1", "t1", "app--prod", "u_me", now]);
for (const uid of ["u_me", "u_them"]) {
await run(`INSERT INTO credshare_vault_grants (vault_id, user_id, wrapped_dek, granted_by, created_at) VALUES (?,?,?,?,?)`,
["v1", uid, `old-wrapped-${uid}`, "u_me", now]);
}
await run(`INSERT INTO credshare_secrets (vault_id, name, nonce, ciphertext, fingerprint, version, updated_by, updated_at) VALUES (?,?,?,?,?,?,?,?)`,
["v1", "API_KEY", "n1", "c1", "fp-api", 1, "u_me", now]);
await run(`INSERT INTO credshare_secrets (vault_id, name, nonce, ciphertext, fingerprint, version, updated_by, updated_at) VALUES (?,?,?,?,?,?,?,?)`,
["v1", "DB_URL", "n2", "c2", "fp-db", 1, "u_me", now]);
}

/** A well-formed rotation: same names, same fingerprints, fresh ciphertext. */
function validBody(overrides = {}) {
return {
grants: [
{ email: "me@example.com", wrappedDek: "new-wrapped-me" },
{ email: "them@example.com", wrappedDek: "new-wrapped-them" }
],
secrets: [
{ name: "API_KEY", nonce: "n1b", ciphertext: "c1b", fingerprint: "fp-api" },
{ name: "DB_URL", nonce: "n2b", ciphertext: "c2b", fingerprint: "fp-db" }
],
revoke: [],
...overrides
};
}

await migrate();
await seed();

test("re-keys every secret and grant in one commit", async (t) => {
const app = await serve("u_me");
t.after(() => app.close());

const res = await app.post("/api/credshare/vaults/v1/rekey", validBody());
assert.equal(res.status, 200);
assert.equal(res.body.rekeyed, 2);

const secrets = await all(`SELECT name, nonce, ciphertext, fingerprint, version FROM credshare_secrets WHERE vault_id = 'v1' ORDER BY name`);
// New ciphertext, bumped version -- and the fingerprint is untouched, which
// is the machine-checkable statement that no VALUE changed.
assert.deepEqual(secrets.map((s) => s.ciphertext), ["c1b", "c2b"]);
assert.deepEqual(secrets.map((s) => s.version), [2, 2]);
assert.deepEqual(secrets.map((s) => s.fingerprint), ["fp-api", "fp-db"]);

const grants = await all(`SELECT user_id, wrapped_dek FROM credshare_vault_grants WHERE vault_id = 'v1' ORDER BY user_id`);
assert.deepEqual(grants.map((g) => g.wrapped_dek), ["new-wrapped-me", "new-wrapped-them"]);

const audit = await get(`SELECT action FROM credshare_audit WHERE vault_id = 'v1' AND action = 'vault:rekey'`);
assert.equal(audit.action, "vault:rekey");
});

test("refuses a rotation that would change a value", async (t) => {
const app = await serve("u_me");
t.after(() => app.close());

const res = await app.post("/api/credshare/vaults/v1/rekey", validBody({
secrets: [
{ name: "API_KEY", nonce: "x", ciphertext: "x", fingerprint: "fp-DIFFERENT" },
{ name: "DB_URL", nonce: "n2c", ciphertext: "c2c", fingerprint: "fp-db" }
]
}));

assert.equal(res.status, 409);
assert.match(res.body.error, /never changes values/);
// Nothing was written.
const row = await get(`SELECT ciphertext FROM credshare_secrets WHERE vault_id = 'v1' AND name = 'DB_URL'`);
assert.equal(row.ciphertext, "c2b");
});

test("refuses a rotation that drops a secret", async (t) => {
const app = await serve("u_me");
t.after(() => app.close());

const res = await app.post("/api/credshare/vaults/v1/rekey", validBody({
secrets: [{ name: "API_KEY", nonce: "z", ciphertext: "z", fingerprint: "fp-api" }]
}));

assert.equal(res.status, 409);
assert.match(res.body.error, /covers 1 secret\(s\) but the vault holds 2/);
});

test("refuses to let the caller lock themselves out", async (t) => {
const app = await serve("u_me");
t.after(() => app.close());

const res = await app.post("/api/credshare/vaults/v1/rekey", validBody({
grants: [{ email: "them@example.com", wrappedDek: "new-wrapped-them" }]
}));

assert.equal(res.status, 422);
assert.match(res.body.error, /must include your own grant/);
});

test("refuses a rotation that grants nobody", async (t) => {
const app = await serve("u_me");
t.after(() => app.close());

const res = await app.post("/api/credshare/vaults/v1/rekey", validBody({ grants: [] }));

assert.equal(res.status, 422);
assert.match(res.body.error, /at least one member/);
});

test("revoking drops the grant row so access is not merely stale", async (t) => {
const app = await serve("u_me");
t.after(() => app.close());

const res = await app.post("/api/credshare/vaults/v1/rekey", validBody({
grants: [{ email: "me@example.com", wrappedDek: "newer-me" }],
secrets: [
{ name: "API_KEY", nonce: "n1d", ciphertext: "c1d", fingerprint: "fp-api" },
{ name: "DB_URL", nonce: "n2d", ciphertext: "c2d", fingerprint: "fp-db" }
],
revoke: ["them@example.com"]
}));

assert.equal(res.status, 200);
assert.deepEqual(res.body.revoked, ["them@example.com"]);

const theirs = await get(`SELECT 1 AS hit FROM credshare_vault_grants WHERE vault_id = 'v1' AND user_id = 'u_them'`);
assert.equal(theirs, null, "revoked member should have no grant row left");

// And the revocation is on the audit trail by name.
const ev = await get(`SELECT key_name FROM credshare_audit WHERE vault_id = 'v1' AND action = 'vault:revoke'`);
assert.equal(ev.key_name, "them@example.com");
});

test("a member with no vault access cannot re-key it", async (t) => {
// u_them was just revoked above, so they are an active member without a grant.
const app = await serve("u_them");
t.after(() => app.close());

const res = await app.post("/api/credshare/vaults/v1/rekey", validBody());

assert.equal(res.status, 403);
assert.match(res.body.error, /Only a member with vault access/);
});

test("grants expose public keys and status so a client can re-seal in one pass", async (t) => {
const app = await serve("u_me");
t.after(() => app.close());

const res = await app.get("/api/credshare/vaults/v1/grants");

assert.equal(res.status, 200);
const me = res.body.grants.find((g) => g.email === "me@example.com");
assert.equal(me.publicKey, "pk-me");
assert.equal(me.status, "active");
assert.equal(me.hasAccess, true);
});
Loading
Loading