Machine API keys: headless teams pull for deploy boxes and CI

A person's lsk_ key acts as the person, with one identity key per user. Logging
a fresh box in with `login --token` uploaded the box's new keypair as the
person's identity and replaced the real one. Machine keys fix that: a key made
for a box, scoped to one team (and optionally named vaults), read-only unless
--read-write, optionally expiring, with its OWN identity key registered on the
key row. A vault key reaches it as a grant sealed to that public key
(credshare_key_grants), never through the person.

Schema (005_machine_keys, SQLite + Postgres): api_keys gains kind, team_id,
vault_scope, read_only (default 0, so existing person keys keep writing),
expires_at, public_key; new credshare_key_grants; credshare_audit.actor_key_id.

Server: each credshare route declares what a machine key may do (read / write /
register); the rest are people-only. Machine keys see only their team and
scoped vaults, read their grant from credshare_key_grants (audited as
vault:read with the key id), are refused every write when read-only, and cannot
mint/list/revoke keys, read /api/me or touch the personal vault. Expired and
revoked keys are 401. New GET|POST /api/keys, DELETE /api/keys/:id, and
GET|POST|DELETE /api/credshare/vaults/:id/key-grants. A re-key re-seals the
machine grants it is given and drops the rest.

CLI 0.8.0: `logicsrc keys create|list|revoke` (--team, --vault, --read-only /
--read-write, --expires, --out 0600); LOGICSRC_API_KEY and
`login --api-key` with a per-key identity in keys/<prefix>.json (0600),
generated and registered on first use; `login --token` with a machine key takes
that path instead of replacing the person's key; `teams grant … --key <name>`;
`credentials rotate` re-seals machine keys.

PWA: settings creates machine keys (team, vaults, read-only, expiry); a vault
page grants or revokes a machine key in the browser after unlock.

MCP: list_api_keys / create_api_key / revoke_api_key over /api/keys with a
Bearer LOGICSRC_API_KEY.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-10-06 06:02:26 +00:00
parent 4df342a064
commit 77075ea1e2
35 changed files with 2220 additions and 106 deletions

View file

@ -38,3 +38,12 @@ Postgres (it drops and recreates the `public` schema of that database).
The CLI connects with `LOGICSRC_API=<origin> logicsrc login` (browser OAuth-PKCE
loopback → an `lsk_` key). See `docs/credential-sharing.md` in the repo root.
Deploy boxes and CI use a **machine key** instead (`logicsrc keys create`, or
Settings ▸ API keys): one team, optional vault list, read-only by default,
optional expiry, and its own identity public key on the `api_keys` row. Vault
keys reach it through `credshare_key_grants`. Routes: `GET|POST /api/keys`,
`DELETE /api/keys/:id` (session or a person's key only) and
`GET|POST /api/credshare/vaults/:id/key-grants`,
`DELETE /api/credshare/vaults/:id/key-grants/:keyId`. Migration
`005_machine_keys.sql`; tests in `test/machine-keys.test.mjs`.

View file

@ -16,6 +16,8 @@
var STORE = "logicsrc.identityKey";
var status = card.querySelector("[data-role=status]");
var values = null; // name -> plaintext, once unlocked
var vaultDek = null; // the vault key (bytes), once unlocked -- only ever used to seal it to a machine key
var keysCard = document.getElementById("machine-keys");
function say(msg) { if (status) status.textContent = msg || ""; }
@ -90,7 +92,7 @@
out[s.name] = na.to_string(na.crypto_secretbox_open_easy(na.from_base64(s.ciphertext, V), na.from_base64(s.nonce, V), dek));
} catch (_) { failed.push(s.name); }
});
return { values: out, failed: failed };
return { values: out, failed: failed, dek: dek };
});
});
});
@ -107,6 +109,13 @@
function render(result) {
values = result.values;
vaultDek = result.dek || null;
if (keysCard && vaultDek) {
Array.prototype.forEach.call(keysCard.querySelectorAll("[data-action=grant-key]"), function (b) {
b.disabled = false;
b.removeAttribute("title");
});
}
var rows = main.querySelectorAll("tr[data-key-name]");
Array.prototype.forEach.call(rows, function (tr) {
var name = tr.getAttribute("data-key-name");
@ -195,6 +204,61 @@
}
}
function csrfHeader() {
var m = document.cookie.match(/(?:^|; )mc_csrf=([^;]+)/);
return m ? decodeURIComponent(m[1]) : "";
}
function keySay(msg, bad) {
var el = keysCard && keysCard.querySelector("[data-role=key-status]");
if (!el) return;
el.textContent = msg || "";
el.style.color = bad ? "var(--danger,#c23a3a)" : "";
}
// Machine keys: seal the vault key to the machine's own public key, here.
if (keysCard) {
keysCard.addEventListener("click", function (e) {
var btn = e.target && e.target.closest ? e.target.closest("[data-action]") : null;
if (!btn) return;
var action = btn.getAttribute("data-action");
var keyId = btn.getAttribute("data-key-id");
var url = "/api/credshare/vaults/" + encodeURIComponent(vaultId) + "/key-grants";
if (action === "grant-key") {
if (!vaultDek) { keySay("Unlock the vault with your key first.", true); return; }
btn.disabled = true;
sodium().then(function (na) {
var V = na.base64_variants.ORIGINAL;
var sealed = na.to_base64(na.crypto_box_seal(vaultDek, na.from_base64(btn.getAttribute("data-key-public"), V)), V);
return fetch(url, {
method: "POST",
credentials: "same-origin",
headers: { "content-type": "application/json", "x-csrf-token": csrfHeader() },
body: JSON.stringify({ keyId: keyId, wrappedDek: sealed })
});
}).then(function (res) {
return res.json().catch(function () { return {}; }).then(function (body) {
if (!res.ok) throw new Error(body.error || ("HTTP " + res.status));
keySay("Granted " + btn.getAttribute("data-key-name") + ". Reload to see it listed.");
btn.textContent = "Granted";
});
}).catch(function (err) { btn.disabled = false; keySay(err.message, true); });
} else if (action === "revoke-key") {
btn.disabled = true;
fetch(url + "/" + encodeURIComponent(keyId), {
method: "DELETE",
credentials: "same-origin",
headers: { "x-csrf-token": csrfHeader() }
}).then(function (res) {
return res.json().catch(function () { return {}; }).then(function (body) {
if (!res.ok) throw new Error(body.error || ("HTTP " + res.status));
location.reload();
});
}).catch(function (err) { btn.disabled = false; keySay(err.message, true); });
}
});
}
// No identity registered yet: make one here and register only its public half.
function generate(btn) {
btn.disabled = true;

View file

@ -1,33 +1,197 @@
// API keys (lsk_…) for the logicsrc CLI to authenticate.
// API keys (lsk_…) for the logicsrc CLI, CI and deploy boxes.
//
// Two kinds share one table:
// user what `logicsrc login` mints. Acts as the person, with the person's
// identity key. Unchanged since before machine keys existed.
// machine made on purpose for a box. Scoped to one team (and optionally a
// list of vault names), read-only unless asked otherwise, may expire,
// and carries its OWN identity public key (api_keys.public_key),
// registered by the machine on first use. Vault keys reach it through
// credshare_key_grants, never through the person's grants.
//
// Only sha256(key) is stored; the plaintext is shown once, at creation.
import { get, all, run } from "../db.mjs";
import { id, token, sha256 } from "./crypto.mjs";
// Returns { plaintext, row } — plaintext shown ONCE.
export async function createApiKey(userId, name = "cli") {
export const KEY_KINDS = ["user", "machine"];
const VAULT_NAME = /^[a-z0-9][a-z0-9-]{0,62}$/;
export class ApiKeyError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
/**
* Mint a key. Returns { plaintext, row } — plaintext is shown ONCE.
*
* `opts` is only meaningful for machine keys: { kind, teamId, vaultScope
* (array of vault names, or null for every vault in the team), readOnly
* (default true), expiresAt (ms epoch, or null) }.
*/
export async function createApiKey(userId, name = "cli", opts = {}) {
const kind = opts.kind === "machine" ? "machine" : "user";
const plaintext = "lsk_" + token(24);
const prefix = plaintext.slice(0, 12);
const row = { id: id(), user_id: userId, name, token_hash: sha256(plaintext), prefix, created_at: Date.now() };
const machine = kind === "machine";
const row = {
id: id(),
user_id: userId,
name,
token_hash: sha256(plaintext),
prefix,
created_at: Date.now(),
kind,
team_id: machine ? opts.teamId ?? null : null,
vault_scope: machine && Array.isArray(opts.vaultScope) && opts.vaultScope.length ? JSON.stringify(opts.vaultScope) : null,
read_only: machine ? (opts.readOnly === false ? 0 : 1) : 0,
expires_at: opts.expiresAt ?? null
};
await run(
`INSERT INTO api_keys (id, user_id, name, token_hash, prefix, created_at) VALUES (?,?,?,?,?,?)`,
[row.id, row.user_id, row.name, row.token_hash, row.prefix, row.created_at]
`INSERT INTO api_keys (id, user_id, name, token_hash, prefix, created_at, kind, team_id, vault_scope, read_only, expires_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)`,
[row.id, row.user_id, row.name, row.token_hash, row.prefix, row.created_at, row.kind, row.team_id, row.vault_scope, row.read_only, row.expires_at]
);
return { plaintext, row };
}
// Resolve a Bearer token to its owning user (or null). Updates last_used_at.
export async function userForApiKey(bearer) {
if (!bearer) return null;
const key = await get(`SELECT * FROM api_keys WHERE token_hash = ?`, [sha256(bearer)]);
if (!key) return null;
await run(`UPDATE api_keys SET last_used_at = ? WHERE id = ?`, [Date.now(), key.id]);
return get(`SELECT * FROM users WHERE id = ?`, [key.user_id]);
/** A key row is usable when it exists and has not expired. Revoked keys are deleted rows. */
export function keyIsLive(key, now = Date.now()) {
if (!key) return false;
const exp = key.expires_at == null ? null : Number(key.expires_at);
return exp == null || exp > now;
}
export const listApiKeys = (userId) =>
all(`SELECT id, name, prefix, created_at, last_used_at FROM api_keys WHERE user_id = ? ORDER BY created_at DESC`, [userId]);
/**
* Resolve a Bearer token to { key, user } (or null). Expired keys resolve to
* null, which every caller answers with a 401. Updates last_used_at.
*/
export async function keyForBearer(bearerToken) {
if (!bearerToken || !bearerToken.startsWith("lsk_")) return null;
const key = await get(`SELECT * FROM api_keys WHERE token_hash = ?`, [sha256(bearerToken)]);
if (!keyIsLive(key)) return null;
const user = await get(`SELECT * FROM users WHERE id = ?`, [key.user_id]);
if (!user) return null;
await run(`UPDATE api_keys SET last_used_at = ? WHERE id = ?`, [Date.now(), key.id]);
return { key: normalizeKey(key), user };
}
export const revokeApiKey = (userId, keyId) =>
run(`DELETE FROM api_keys WHERE id = ? AND user_id = ?`, [keyId, userId]);
/**
* Resolve a Bearer token to its owning user, for routes that act AS the person
* (the personal vault, /api/me). Machine keys are refused here: a deploy box
* reads the team vaults it was granted and nothing of the person's own.
*/
export async function userForApiKey(bearerToken) {
const found = await keyForBearer(bearerToken);
if (!found || found.key.kind === "machine") return null;
return found.user;
}
/** Parse the stored columns into the shape the routes use. */
export function normalizeKey(key) {
let scope = null;
if (key.vault_scope) {
try {
const parsed = JSON.parse(key.vault_scope);
if (Array.isArray(parsed)) scope = parsed.filter((v) => typeof v === "string");
} catch { scope = null; }
}
return {
...key,
kind: key.kind === "machine" ? "machine" : "user",
vaultScope: scope,
readOnly: Number(key.read_only) === 1,
expiresAt: key.expires_at == null ? null : Number(key.expires_at)
};
}
/** Is `vaultName` inside this key's scope? User keys and unscoped machine keys see every vault. */
export function keyCoversVault(key, vaultName) {
if (!key || key.kind !== "machine") return true;
return !key.vaultScope || key.vaultScope.includes(vaultName);
}
export const listApiKeys = async (userId) =>
(await all(
`SELECT k.id, k.name, k.prefix, k.created_at, k.last_used_at, k.kind, k.team_id, k.vault_scope, k.read_only, k.expires_at, k.public_key, t.slug AS team_slug
FROM api_keys k LEFT JOIN credshare_teams t ON t.id = k.team_id
WHERE k.user_id = ? ORDER BY k.created_at DESC`,
[userId]
)).map(normalizeKey);
/** Public view of a key row (never the hash). */
export function keyJson(k) {
return {
id: k.id,
name: k.name,
prefix: k.prefix,
kind: k.kind,
team: k.team_slug ?? null,
vaults: k.vaultScope ?? null,
readOnly: k.kind === "machine" ? k.readOnly : false,
expiresAt: k.expiresAt ?? null,
expired: !keyIsLive(k),
publicKey: k.public_key ?? null,
createdAt: Number(k.created_at),
lastUsedAt: k.last_used_at == null ? null : Number(k.last_used_at)
};
}
/** Revoke = delete. The key's vault grants go with it (explicitly; SQLite FKs are off by default). */
export async function revokeApiKey(userId, keyId) {
const owned = await get(`SELECT id FROM api_keys WHERE id = ? AND user_id = ?`, [keyId, userId]);
if (!owned) return false;
await run(`DELETE FROM credshare_key_grants WHERE api_key_id = ?`, [keyId]);
await run(`DELETE FROM api_keys WHERE id = ? AND user_id = ?`, [keyId, userId]);
return true;
}
/**
* Validate a machine-key request from the API or the settings form and turn it
* into createApiKey options. Throws ApiKeyError with a status to answer with.
*
* `expires` accepts a ms epoch, an ISO date, or a duration like 30d / 12h / 90m.
*/
export async function machineKeyOptions(userId, { team, vaults, readOnly, expires }) {
const slug = String(team || "").trim().toLowerCase();
if (!slug) throw new ApiKeyError(422, "A machine key needs a team.");
const teamRow = await get(`SELECT * FROM credshare_teams WHERE slug = ?`, [slug]);
if (!teamRow) throw new ApiKeyError(404, `Unknown team: ${slug}`);
const member = await get(`SELECT * FROM credshare_members WHERE team_id = ? AND user_id = ? AND status = 'active'`, [teamRow.id, userId]);
if (!member) throw new ApiKeyError(403, "You are not a member of this team.");
const list = (Array.isArray(vaults) ? vaults : typeof vaults === "string" ? vaults.split(/[\s,]+/) : [])
.map((v) => String(v).trim().toLowerCase())
.filter(Boolean);
for (const v of list) {
if (!VAULT_NAME.test(v)) throw new ApiKeyError(422, `"${v}" is not a vault name (lowercase letters, numbers, dashes; e.g. web--prod).`);
}
const expiresAt = parseExpiry(expires);
if (expiresAt !== null && expiresAt <= Date.now()) throw new ApiKeyError(422, "That expiry is already in the past.");
return {
kind: "machine",
teamId: teamRow.id,
vaultScope: [...new Set(list)],
readOnly: readOnly === false || readOnly === "false" || readOnly === 0 || readOnly === "0" ? false : true,
expiresAt
};
}
export function parseExpiry(value, now = Date.now()) {
if (value === undefined || value === null || value === "" || value === "never") return null;
if (typeof value === "number" && Number.isFinite(value)) return value;
const s = String(value).trim();
const dur = /^(\d+)\s*(m|h|d|w|y)$/i.exec(s);
if (dur) {
const unit = { m: 60e3, h: 3600e3, d: 86400e3, w: 7 * 86400e3, y: 365 * 86400e3 }[dur[2].toLowerCase()];
return now + Number(dur[1]) * unit;
}
if (/^\d{12,}$/.test(s)) return Number(s);
const t = Date.parse(s);
if (Number.isNaN(t)) throw new ApiKeyError(422, `Cannot read expiry "${s}". Use 30d, 12h, or a date like 2027-01-01.`);
return t;
}
// Pull the Bearer token off a request.
export function bearer(req) {

View file

@ -74,7 +74,31 @@ function keyCard({ publicKey, hasGrant, grantCommand }) {
* The page body below the app bar. `secrets` are rows of credshare_secrets
* (name, version, updated_at only — ciphertext is fetched by vault.js).
*/
export function vaultPageBody({ team, vault, secrets, hasGrant, publicKey, email }) {
/**
* The caller's machine keys for this vault's team. Granting one seals the
* vault key to the machine's own public key, in the browser, after unlock --
* the same crypto_box_seal the CLI's `teams grant --key` does.
*/
function machineKeysCard({ machineKeys, team, parts }) {
if (!machineKeys || machineKeys.length === 0) return "";
const grantCmd = (name) => `logicsrc teams grant ${team.slug} ${parts ? `${parts.project} ${parts.env}` : "<project> <env>"} --key ${name}`;
const rows = machineKeys.map((k) => {
const state = k.granted
? `<span class="pill on">granted</span> <button class="btn compact danger" type="button" data-action="revoke-key" data-key-id="${esc(k.id)}">Revoke</button>`
: k.publicKey
? `<button class="btn compact" type="button" data-action="grant-key" data-key-id="${esc(k.id)}" data-key-public="${esc(k.publicKey)}" data-key-name="${esc(k.name)}" disabled title="Unlock with your key first">Grant</button>`
: `<span class="pill warn">not used yet</span> <span class="faint" style="font-size:.74rem">run one command with the key on the box first</span>`;
return `<tr><td><code>${esc(k.name)}</code> <span class="faint">${esc(k.prefix)}…</span></td><td>${k.readOnly ? "read-only" : "read-write"}</td><td><div class="member-actions">${state}</div></td></tr>`;
}).join("");
return `<div class="card" id="machine-keys" style="margin-bottom:18px"><div class="card-head"><span class="h">Machine keys</span></div>
<div class="card-body">
<p class="dim" style="margin-top:0;font-size:.85rem">Your machine API keys scoped to this vault. Unlock above, then grant: the vault key is sealed to the machine's own key in this browser. Or from a terminal: <code>${esc(grantCmd(machineKeys[0].name))}</code></p>
<div class="table-scroll"><table><thead><tr><th>Key</th><th>Access</th><th></th></tr></thead><tbody>${rows}</tbody></table></div>
<p data-role="key-status" class="mono" style="font-size:.8rem;margin-bottom:0"></p>
</div></div>`;
}
export function vaultPageBody({ team, vault, secrets, hasGrant, publicKey, email, machineKeys = [] }) {
const parts = splitVaultName(vault.name);
const grantCommand = `logicsrc teams grant ${team.slug} ${parts ? `${parts.project} ${parts.env}` : "<project> <env>"} ${email || "<your email>"}`;
const rows = secrets.map((s) => `<tr data-key-name="${esc(s.name)}">
@ -89,6 +113,7 @@ export function vaultPageBody({ team, vault, secrets, hasGrant, publicKey, email
<p class="faint mono" style="font-size:.8rem;margin:0 0 6px"><a href="/dashboard">teams</a> / ${esc(team.slug)} / vaults</p>
<div class="section-title"><h1 style="font-size:1.5rem"><code>${esc(vault.name)}</code></h1><span class="count">${secrets.length}</span></div>
${keyCard({ publicKey, hasGrant, grantCommand })}
${machineKeysCard({ machineKeys, team, parts })}
<div class="card"><div class="card-body">
${secrets.length
? `<div class="table-scroll"><table><thead><tr><th>Name</th><th>Value</th><th>v</th><th>Updated (UTC)</th></tr></thead><tbody>${rows}</tbody></table></div>`

View file

@ -0,0 +1,29 @@
-- Machine API keys: headless credentials for deploy boxes and CI.
--
-- A 'user' key is what `logicsrc login` mints: it acts as the person, with the
-- person's identity key. A 'machine' key is created on purpose, is scoped to
-- one team (and optionally a list of vault names), is read-only unless asked
-- otherwise, may expire, and carries its OWN identity public key, registered by
-- the machine on first use. Vault keys are sealed to that public key in
-- credshare_key_grants, so a machine never holds a person's secret key and a
-- revoked machine key reads nothing.
--
-- read_only defaults to 0 so every existing (person) key keeps writing; the
-- app sets it to 1 for a machine key unless --read-write is asked for.
ALTER TABLE api_keys ADD COLUMN kind TEXT NOT NULL DEFAULT 'user';
ALTER TABLE api_keys ADD COLUMN team_id TEXT;
ALTER TABLE api_keys ADD COLUMN vault_scope TEXT;
ALTER TABLE api_keys ADD COLUMN read_only bigint NOT NULL DEFAULT 0;
ALTER TABLE api_keys ADD COLUMN expires_at bigint;
ALTER TABLE api_keys ADD COLUMN public_key TEXT;
ALTER TABLE credshare_audit ADD COLUMN actor_key_id TEXT;
CREATE TABLE IF NOT EXISTS credshare_key_grants (
vault_id TEXT NOT NULL REFERENCES credshare_vaults(id) ON DELETE CASCADE,
api_key_id TEXT NOT NULL REFERENCES api_keys(id) ON DELETE CASCADE,
wrapped_dek TEXT NOT NULL,
granted_by TEXT NOT NULL REFERENCES users(id),
created_at bigint NOT NULL,
PRIMARY KEY (vault_id, api_key_id)
);
CREATE INDEX IF NOT EXISTS idx_key_grants_key ON credshare_key_grants(api_key_id);

View file

@ -0,0 +1,29 @@
-- Machine API keys: headless credentials for deploy boxes and CI.
--
-- A 'user' key is what `logicsrc login` mints: it acts as the person, with the
-- person's identity key. A 'machine' key is created on purpose, is scoped to
-- one team (and optionally a list of vault names), is read-only unless asked
-- otherwise, may expire, and carries its OWN identity public key, registered by
-- the machine on first use. Vault keys are sealed to that public key in
-- credshare_key_grants, so a machine never holds a person's secret key and a
-- revoked machine key reads nothing.
--
-- read_only defaults to 0 so every existing (person) key keeps writing; the
-- app sets it to 1 for a machine key unless --read-write is asked for.
ALTER TABLE api_keys ADD COLUMN kind TEXT NOT NULL DEFAULT 'user';
ALTER TABLE api_keys ADD COLUMN team_id TEXT;
ALTER TABLE api_keys ADD COLUMN vault_scope TEXT;
ALTER TABLE api_keys ADD COLUMN read_only INTEGER NOT NULL DEFAULT 0;
ALTER TABLE api_keys ADD COLUMN expires_at INTEGER;
ALTER TABLE api_keys ADD COLUMN public_key TEXT;
ALTER TABLE credshare_audit ADD COLUMN actor_key_id TEXT;
CREATE TABLE IF NOT EXISTS credshare_key_grants (
vault_id TEXT NOT NULL REFERENCES credshare_vaults(id) ON DELETE CASCADE,
api_key_id TEXT NOT NULL REFERENCES api_keys(id) ON DELETE CASCADE,
wrapped_dek TEXT NOT NULL,
granted_by TEXT NOT NULL REFERENCES users(id),
created_at INTEGER NOT NULL,
PRIMARY KEY (vault_id, api_key_id)
);
CREATE INDEX IF NOT EXISTS idx_key_grants_key ON credshare_key_grants(api_key_id);

View file

@ -0,0 +1,69 @@
// API keys as an API: list, mint and revoke the caller's own lsk_ keys.
//
// GET /api/keys the caller's keys (never a hash, never a secret)
// POST /api/keys mint one; the plaintext is in this response only
// DELETE /api/keys/:id revoke (delete) one, with its vault grants
//
// Auth: a browser session or a person's (`user`) key. A machine key cannot
// mint keys, list them or revoke them: a deploy box that could make itself a
// broader credential would make the scoping pointless.
import { Router } from "express";
import {
ApiKeyError,
bearer,
createApiKey,
keyForBearer,
keyJson,
listApiKeys,
machineKeyOptions,
revokeApiKey
} from "../lib/apikey.mjs";
export const apiKeysRouter = Router();
function personOnly(handler) {
return async (req, res) => {
let user = req.user;
let key = null;
if (!user) {
const found = await keyForBearer(bearer(req));
if (!found) return res.status(401).json({ error: "Not authenticated, or the API key is revoked or expired. Run: logicsrc login" });
({ user, key } = found);
}
if (key?.kind === "machine") {
return res.status(403).json({ error: "A machine API key cannot manage API keys.", code: "machine_key_forbidden" });
}
try {
await handler(req, res, user);
} catch (e) {
if (e instanceof ApiKeyError) return res.status(e.status).json({ error: e.message });
console.error("apikeys:", e);
res.status(500).json({ error: e.message || String(e) });
}
};
}
apiKeysRouter.get("/api/keys", personOnly(async (_req, res, user) => {
res.json({ keys: (await listApiKeys(user.id)).map(keyJson) });
}));
apiKeysRouter.post("/api/keys", personOnly(async (req, res, user) => {
const body = req.body || {};
const name = String(body.name || "").trim().slice(0, 40);
if (!name) return res.status(422).json({ error: "Give the key a name (e.g. dev2-deploy)." });
const kind = body.kind === undefined ? "user" : String(body.kind);
if (kind !== "user" && kind !== "machine") return res.status(422).json({ error: 'kind must be "user" or "machine".' });
const opts = kind === "machine"
? await machineKeyOptions(user.id, { team: body.team, vaults: body.vaults, readOnly: body.readOnly, expires: body.expiresAt ?? body.expires })
: {};
const { plaintext, row } = await createApiKey(user.id, name, opts);
const listed = (await listApiKeys(user.id)).find((k) => k.id === row.id);
res.status(201).json({ key: keyJson(listed), secret: plaintext });
}));
apiKeysRouter.delete("/api/keys/:id", personOnly(async (req, res, user) => {
const ok = await revokeApiKey(user.id, req.params.id);
if (!ok) return res.status(404).json({ error: "No such API key on your account." });
res.json({ ok: true, revoked: req.params.id });
}));

View file

@ -16,7 +16,7 @@ import { get, run } from "../db.mjs";
import { token, sha256 } from "../lib/crypto.mjs";
import { page, footer, appBar, esc } from "../lib/html.mjs";
import { requireAuth, csrfInput } from "../lib/session.mjs";
import { createApiKey, bearer, userForApiKey } from "../lib/apikey.mjs";
import { createApiKey, bearer, keyForBearer } from "../lib/apikey.mjs";
import { requestOrigin } from "../lib/origin.mjs";
import { config } from "../config.mjs";
@ -226,7 +226,11 @@ cliRouter.post("/cli/device/token", async (req, res) => {
});
cliRouter.get("/api/me", async (req, res) => {
const user = await userForApiKey(bearer(req));
if (!user) return res.status(401).json({ error: "invalid or missing API key" });
const found = await keyForBearer(bearer(req));
if (!found) return res.status(401).json({ error: "invalid, revoked, expired or missing API key" });
// /api/me answers "which person is this" -- a machine key is not one. It asks
// /api/credshare/me, which describes the key and its scope instead.
if (found.key.kind === "machine") return res.status(403).json({ error: "A machine API key has no person to describe. Use /api/credshare/me.", code: "machine_key_forbidden" });
const { user } = found;
res.json({ id: user.id, email: user.email || null, name: user.display_name });
});

View file

@ -5,10 +5,17 @@
//
// Auth: the acting user comes from a browser session (req.user) OR a
// `Bearer lsk_…` API key (the logicsrc CLI). Mounted at /api/credshare.
//
// A MACHINE key (api_keys.kind = 'machine') is narrower than its owner: it sees
// one team, optionally only some of its vaults, holds its own identity key, and
// opens vaults only through credshare_key_grants. Each route says whether a
// machine key may call it at all (`machine: "read" | "write" | "register"`);
// anything unmarked is people-only. A read-only machine key gets a 403 on every
// write except registering its own public key.
import { Router } from "express";
import { get, all, run, batch } from "../db.mjs";
import { id, sha256 } from "../lib/crypto.mjs";
import { bearer, userForApiKey } from "../lib/apikey.mjs";
import { bearer, keyForBearer, keyCoversVault, normalizeKey } from "../lib/apikey.mjs";
import {
TeamMemberError,
normEmail,
@ -25,17 +32,37 @@ const slugify = (s) => {
return /^[a-z0-9][a-z0-9-]{0,62}$/.test(v) ? v : null;
};
// Resolve the acting user from session or API key.
const isMachine = (key) => key?.kind === "machine";
// Resolve the acting user (and the API key, when there is one) from session or Bearer.
async function actor(req) {
if (req.user) return req.user;
return userForApiKey(bearer(req));
if (req.user) return { user: req.user, key: null };
return keyForBearer(bearer(req));
}
function api(handler) {
/**
* Wrap a route. `machine` says what a machine key may do here:
* false (default) people only — a machine key gets a 403
* "read" allowed, GET only
* "write" allowed unless the key is read-only
* "register" allowed even for a read-only key (its own public key)
*/
function api(handler, { machine = false } = {}) {
return async (req, res) => {
const user = await actor(req);
if (!user) return res.status(401).json({ error: "Not authenticated. Run: logicsrc login" });
const found = await actor(req);
if (!found) return res.status(401).json({ error: "Not authenticated, or the API key is revoked or expired. Run: logicsrc login" });
const { user, key } = found;
req.apiKey = key;
if (isMachine(key)) {
if (!machine) {
return res.status(403).json({ error: "A machine API key cannot do this. Use a person's login (logicsrc login).", code: "machine_key_forbidden" });
}
if (key.readOnly && machine !== "register" && req.method !== "GET") {
return res.status(403).json({ error: "This machine API key is read-only.", code: "read_only_key" });
}
}
try {
await handler(req, res, user);
await handler(req, res, user, key);
} catch (e) {
console.error("credshare:", e);
res.status(500).json({ error: e.message || String(e) });
@ -43,9 +70,10 @@ function api(handler) {
};
}
async function requireMember(res, slug, userId) {
async function requireMember(res, slug, userId, key = null) {
const team = await get(`SELECT * FROM credshare_teams WHERE slug = ?`, [slug]);
if (!team) { res.status(404).json({ error: `Unknown team: ${slug}` }); return null; }
if (isMachine(key) && key.team_id !== team.id) { res.status(403).json({ error: "This API key is scoped to another team." }); return null; }
const member = await get(`SELECT * FROM credshare_members WHERE team_id = ? AND user_id = ?`, [team.id, userId]);
if (!member || member.status !== "active") { res.status(403).json({ error: "You are not a member of this team." }); return null; }
return { team, member };
@ -57,23 +85,59 @@ async function publicKeyFor(userId) {
}
async function audit(ev) {
await run(`INSERT INTO credshare_audit (id, team_id, vault_id, actor_user_id, action, key_name, fingerprint, created_at) VALUES (?,?,?,?,?,?,?,?)`,
[id(), ev.teamId ?? null, ev.vaultId ?? null, ev.actorUserId, ev.action, ev.keyName ?? null, ev.fingerprint ?? null, Date.now()]);
await run(`INSERT INTO credshare_audit (id, team_id, vault_id, actor_user_id, action, key_name, fingerprint, created_at, actor_key_id) VALUES (?,?,?,?,?,?,?,?,?)`,
[id(), ev.teamId ?? null, ev.vaultId ?? null, ev.actorUserId, ev.action, ev.keyName ?? null, ev.fingerprint ?? null, Date.now(), ev.actorKeyId ?? null]);
}
/** The key facts a client needs about its own credential (null for a browser session). */
function keyInfo(key, teamSlug = null) {
if (!key) return null;
return {
id: key.id,
name: key.name,
prefix: key.prefix,
kind: key.kind,
team: isMachine(key) ? teamSlug : null,
vaults: isMachine(key) ? key.vaultScope : null,
readOnly: isMachine(key) ? key.readOnly : false,
expiresAt: key.expiresAt ?? null
};
}
// ---- identity key + lookup ----
credshareRouter.post("/api/credshare/keys", api(async (req, res, user) => {
credshareRouter.post("/api/credshare/keys", api(async (req, res, user, key) => {
const publicKey = req.body?.publicKey;
if (typeof publicKey !== "string" || !publicKey) return res.status(422).json({ error: "Expected { publicKey }." });
if (isMachine(key)) {
// A machine key registers ITS OWN identity, on its own row. It never
// touches the person's credshare_keys entry. Replacing a different key
// drops this key's grants: they were sealed to the old key and cannot be
// opened with the new one, so keeping them would only hide the breakage.
let dropped = 0;
if (key.public_key && key.public_key !== publicKey) {
dropped = Number((await get(`SELECT COUNT(*) AS n FROM credshare_key_grants WHERE api_key_id = ?`, [key.id]))?.n || 0);
await run(`DELETE FROM credshare_key_grants WHERE api_key_id = ?`, [key.id]);
}
if (key.public_key !== publicKey) {
await run(`UPDATE api_keys SET public_key = ? WHERE id = ?`, [publicKey, key.id]);
await audit({ teamId: key.team_id, actorUserId: user.id, actorKeyId: key.id, action: "key:register", keyName: key.name });
}
return res.json({ email: user.email, publicKey, keyId: key.id, droppedGrants: dropped });
}
await run(`INSERT INTO credshare_keys (user_id, public_key, updated_at) VALUES (?,?,?) ON CONFLICT(user_id) DO UPDATE SET public_key = excluded.public_key, updated_at = excluded.updated_at`,
[user.id, publicKey, Date.now()]);
res.json({ email: user.email, publicKey });
}));
}, { machine: "register" }));
credshareRouter.get("/api/credshare/me", api(async (_req, res, user) => {
credshareRouter.get("/api/credshare/me", api(async (_req, res, user, key) => {
if (isMachine(key)) {
const teams = await all(`SELECT t.id, t.slug, t.name FROM credshare_teams t JOIN credshare_members m ON m.team_id = t.id WHERE m.user_id = ? AND m.status = 'active' AND t.id = ?`, [user.id, key.team_id]);
const team = await get(`SELECT slug FROM credshare_teams WHERE id = ?`, [key.team_id]);
return res.json({ user: { id: user.id, email: user.email, publicKey: key.public_key ?? null }, teams, key: keyInfo(key, team?.slug ?? null) });
}
const teams = await all(`SELECT t.id, t.slug, t.name FROM credshare_teams t JOIN credshare_members m ON m.team_id = t.id WHERE m.user_id = ? AND m.status = 'active'`, [user.id]);
res.json({ user: { id: user.id, email: user.email, publicKey: await publicKeyFor(user.id) }, teams });
}));
res.json({ user: { id: user.id, email: user.email, publicKey: await publicKeyFor(user.id) }, teams, key: keyInfo(key) });
}, { machine: "read" }));
credshareRouter.get("/api/credshare/users", api(async (req, res) => {
const email = norm(req.query.email);
@ -91,14 +155,16 @@ credshareRouter.post("/api/credshare/teams", api(async (req, res, user) => {
await run(`INSERT INTO credshare_teams (id, slug, name, created_by, created_at) VALUES (?,?,?,?,?)`, [team.id, team.slug, team.name, team.createdBy, team.createdAt]);
await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, joined_at, created_at) VALUES (?,?,?,?,?,?,?,?)`,
[id(), team.id, user.id, norm(user.email) || user.id, "owner", "active", Date.now(), Date.now()]);
await audit({ teamId: team.id, actorUserId: user.id, action: "team:create" });
await audit({ teamId: team.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "team:create" });
res.status(201).json({ team: { id: team.id, slug: team.slug, name: team.name } });
}));
credshareRouter.get("/api/credshare/teams", api(async (_req, res, user) => {
const teams = await all(`SELECT t.id, t.slug, t.name FROM credshare_teams t JOIN credshare_members m ON m.team_id = t.id WHERE m.user_id = ? AND m.status = 'active' ORDER BY t.created_at`, [user.id]);
credshareRouter.get("/api/credshare/teams", api(async (_req, res, user, key) => {
const teams = isMachine(key)
? await all(`SELECT t.id, t.slug, t.name FROM credshare_teams t JOIN credshare_members m ON m.team_id = t.id WHERE m.user_id = ? AND m.status = 'active' AND t.id = ? ORDER BY t.created_at`, [user.id, key.team_id])
: await all(`SELECT t.id, t.slug, t.name FROM credshare_teams t JOIN credshare_members m ON m.team_id = t.id WHERE m.user_id = ? AND m.status = 'active' ORDER BY t.created_at`, [user.id]);
res.json({ teams });
}));
}, { machine: "read" }));
credshareRouter.get("/api/credshare/teams/:slug/members", api(async (req, res, user) => {
const ctx = await requireMember(res, req.params.slug, user.id); if (!ctx) return;
@ -171,14 +237,35 @@ credshareRouter.post("/api/credshare/invites/accept", api(async (req, res, user)
if (norm(invite.email) !== norm(user.email)) return res.status(403).json({ error: `This invite is for ${invite.email}, not ${user.email}.` });
await run(`UPDATE credshare_members SET user_id = ?, status = 'active', joined_at = ? WHERE team_id = ? AND email = ?`, [user.id, Date.now(), invite.team_id, norm(invite.email)]);
await run(`UPDATE credshare_invites SET accepted_at = ? WHERE id = ?`, [Date.now(), invite.id]);
await audit({ teamId: invite.team_id, actorUserId: user.id, action: "team:join" });
await audit({ teamId: invite.team_id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "team:join" });
const team = await get(`SELECT id, slug, name FROM credshare_teams WHERE id = ?`, [invite.team_id]);
res.json({ ok: true, team });
}));
// ---- vaults ----
credshareRouter.get("/api/credshare/teams/:slug/vaults", api(async (req, res, user) => {
const ctx = await requireMember(res, req.params.slug, user.id); if (!ctx) return;
credshareRouter.get("/api/credshare/teams/:slug/vaults", api(async (req, res, user, key) => {
const ctx = await requireMember(res, req.params.slug, user.id, key); if (!ctx) return;
if (isMachine(key)) {
// A machine key sees the vaults in its scope, and "access" means a grant
// sealed to ITS key, not to the person who made it.
const rows = await all(
`SELECT v.id,
v.name,
(SELECT COUNT(*) FROM credshare_secrets s
WHERE s.vault_id = v.id) AS secret_count,
EXISTS(SELECT 1 FROM credshare_key_grants g
WHERE g.vault_id = v.id AND g.api_key_id = ?) AS has_access
FROM credshare_vaults v
WHERE v.team_id = ?
ORDER BY v.name`,
[key.id, ctx.team.id]
);
return res.json({
vaults: rows
.filter((v) => keyCoversVault(key, v.name))
.map((v) => ({ id: v.id, name: v.name, hasAccess: Boolean(v.has_access), secretCount: Number(v.secret_count || 0) }))
});
}
// One statement, not one per vault. libSQL is remote, so every execute() is a
// network round trip: the previous loop cost 2N+1 of them, and a team with 176
// vaults spent ~10s here -- doubled by `teams pull`, which resolves the vault
@ -206,7 +293,7 @@ credshareRouter.get("/api/credshare/teams/:slug/vaults", api(async (req, res, us
secretCount: Number(v.secret_count || 0)
}))
});
}));
}, { machine: "read" }));
credshareRouter.post("/api/credshare/teams/:slug/vaults", api(async (req, res, user) => {
const ctx = await requireMember(res, req.params.slug, user.id); if (!ctx) return;
@ -216,25 +303,35 @@ credshareRouter.post("/api/credshare/teams/:slug/vaults", api(async (req, res, u
if (existing) return res.json({ vault: { id: existing.id, name: existing.name } });
const vault = { id: id(), name };
await run(`INSERT INTO credshare_vaults (id, team_id, name, created_by, created_at) VALUES (?,?,?,?,?)`, [vault.id, ctx.team.id, name, user.id, Date.now()]);
await audit({ teamId: ctx.team.id, vaultId: vault.id, actorUserId: user.id, action: "vault:create" });
await audit({ teamId: ctx.team.id, vaultId: vault.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "vault:create" });
res.status(201).json({ vault });
}));
// ---- vault grants / secrets / audit (by vault id) ----
async function vaultCtx(res, vaultId, userId) {
async function vaultCtx(res, vaultId, userId, key = null) {
const vault = await get(`SELECT * FROM credshare_vaults WHERE id = ?`, [vaultId]);
if (!vault) { res.status(404).json({ error: "Unknown vault." }); return null; }
if (isMachine(key) && (vault.team_id !== key.team_id || !keyCoversVault(key, vault.name))) {
res.status(403).json({ error: "This API key is not scoped to this vault." }); return null;
}
const member = await get(`SELECT * FROM credshare_members WHERE team_id = ? AND user_id = ?`, [vault.team_id, userId]);
if (!member || member.status !== "active") { res.status(403).json({ error: "You are not a member of this vault's team." }); return null; }
return vault;
}
credshareRouter.get("/api/credshare/vaults/:id/grant", api(async (req, res, user) => {
const vault = await vaultCtx(res, req.params.id, user.id); if (!vault) return;
credshareRouter.get("/api/credshare/vaults/:id/grant", api(async (req, res, user, key) => {
const vault = await vaultCtx(res, req.params.id, user.id, key); if (!vault) return;
if (isMachine(key)) {
const kg = await get(`SELECT wrapped_dek FROM credshare_key_grants WHERE vault_id = ? AND api_key_id = ?`, [vault.id, key.id]);
if (!kg) return res.status(403).json({ error: `This machine key (${key.name}) has not been granted this vault yet. A member runs: logicsrc teams grant <team> <project> <env> --key ${key.name}`, code: "no_key_grant" });
// The one moment a machine can decrypt: worth a line in the vault's audit trail.
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: key.id, action: "vault:read", keyName: key.name });
return res.json({ wrappedDek: kg.wrapped_dek });
}
const grant = await get(`SELECT wrapped_dek FROM credshare_vault_grants WHERE vault_id = ? AND user_id = ?`, [vault.id, user.id]);
if (!grant) return res.status(403).json({ error: "You do not have access to this vault yet. Ask a member to grant you." });
res.json({ wrappedDek: grant.wrapped_dek });
}));
}, { machine: "read" }));
credshareRouter.get("/api/credshare/vaults/:id/grants", api(async (req, res, user) => {
const vault = await vaultCtx(res, req.params.id, user.id); if (!vault) return;
@ -314,6 +411,28 @@ credshareRouter.post("/api/credshare/vaults/:id/rekey", api(async (req, res, use
resolved.push({ email, userId: target.id, wrappedDek: g.wrappedDek });
}
// Machine keys hold the DEK through credshare_key_grants. A re-key makes every
// one of those dead, so each is either re-sealed in this same transaction
// (keyGrants: [{ keyId, wrappedDek }]) or dropped -- never left stale.
const keyGrantsIn = Array.isArray(req.body?.keyGrants) ? req.body.keyGrants : [];
const currentKeyGrants = await all(
`SELECT g.api_key_id, k.name FROM credshare_key_grants g JOIN api_keys k ON k.id = g.api_key_id WHERE g.vault_id = ?`,
[vault.id]
);
const currentKeyIds = new Map(currentKeyGrants.map((g) => [g.api_key_id, g.name]));
const resealed = [];
for (const g of keyGrantsIn) {
if (!g || typeof g.keyId !== "string" || typeof g.wrappedDek !== "string" || !g.wrappedDek) {
return res.status(422).json({ error: "Each key grant needs { keyId, wrappedDek }." });
}
if (!currentKeyIds.has(g.keyId)) {
return res.status(409).json({ error: `Key ${g.keyId} holds no grant on this vault; grant it after the re-key instead.` });
}
resealed.push(g);
}
const resealedIds = new Set(resealed.map((g) => g.keyId));
const droppedKeys = currentKeyGrants.filter((g) => !resealedIds.has(g.api_key_id)).map((g) => g.name);
const revokedUsers = [];
for (const email of revoke) {
const target = await get(`SELECT id FROM users WHERE email = ?`, [email]);
@ -337,6 +456,13 @@ credshareRouter.post("/api/credshare/vaults/:id/rekey", api(async (req, res, use
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: `DELETE FROM credshare_key_grants WHERE vault_id = ?`, args: [vault.id] });
for (const g of resealed) {
statements.push({
sql: `INSERT INTO credshare_key_grants (vault_id, api_key_id, wrapped_dek, granted_by, created_at) VALUES (?,?,?,?,?)`,
args: [vault.id, g.keyId, g.wrappedDek, user.id, now]
});
}
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]
@ -349,7 +475,14 @@ credshareRouter.post("/api/credshare/vaults/:id/rekey", api(async (req, res, use
}
await batch(statements);
res.json({ ok: true, rekeyed: secrets.length, granted: resolved.map((g) => g.email), revoked: revokedUsers.map((r) => r.email) });
res.json({
ok: true,
rekeyed: secrets.length,
granted: resolved.map((g) => g.email),
revoked: revokedUsers.map((r) => r.email),
keysResealed: resealed.map((g) => currentKeyIds.get(g.keyId)),
keysDropped: droppedKeys
});
}));
credshareRouter.post("/api/credshare/vaults/:id/grants", api(async (req, res, user) => {
@ -364,18 +497,93 @@ credshareRouter.post("/api/credshare/vaults/:id/grants", api(async (req, res, us
if (!(await publicKeyFor(target.id))) return res.status(409).json({ error: "Target user has not uploaded a public key yet." });
await run(`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`,
[vault.id, target.id, wrappedDek, user.id, Date.now()]);
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: "vault:grant", keyName: email });
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "vault:grant", keyName: email });
res.status(201).json({ ok: true });
}));
credshareRouter.get("/api/credshare/vaults/:id/secrets", api(async (req, res, user) => {
// ---- machine-key grants: the vault key sealed to a machine key's own public key ----
/** Machine keys holding this vault, with their public keys (so a re-key can re-seal to them). */
credshareRouter.get("/api/credshare/vaults/:id/key-grants", api(async (req, res, user) => {
const vault = await vaultCtx(res, req.params.id, user.id); if (!vault) return;
const rows = await all(`SELECT * FROM credshare_secrets WHERE vault_id = ? ORDER BY name`, [vault.id]);
res.json({ vaultId: vault.id, secrets: rows.map((s) => ({ name: s.name, nonce: s.nonce, ciphertext: s.ciphertext, fingerprint: s.fingerprint, version: s.version, updatedAt: s.updated_at })) });
const rows = await all(
`SELECT g.api_key_id, g.created_at, k.name, k.prefix, k.public_key, k.read_only, k.expires_at, u.email AS owner
FROM credshare_key_grants g
JOIN api_keys k ON k.id = g.api_key_id
LEFT JOIN users u ON u.id = k.user_id
WHERE g.vault_id = ?
ORDER BY k.name`,
[vault.id]
);
res.json({
keyGrants: rows.map((r) => ({
keyId: r.api_key_id,
name: r.name,
prefix: r.prefix,
owner: r.owner ?? null,
publicKey: r.public_key ?? null,
readOnly: Number(r.read_only) === 1,
expiresAt: r.expires_at == null ? null : Number(r.expires_at),
grantedAt: Number(r.created_at)
}))
});
}));
credshareRouter.put("/api/credshare/vaults/:id/secrets", api(async (req, res, user) => {
/**
* Seal this vault's key to one of YOUR machine keys. The client unwraps the DEK
* with the person's identity and re-seals it to the key's public key, exactly
* as a member grant does; the server only checks who may and stores the box.
*/
credshareRouter.post("/api/credshare/vaults/:id/key-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]);
if (!iHold) return res.status(403).json({ error: "Only a member with vault access can grant a key." });
const keyId = req.body?.keyId, wrappedDek = req.body?.wrappedDek;
if (typeof keyId !== "string" || !keyId || typeof wrappedDek !== "string" || !wrappedDek) {
return res.status(422).json({ error: "Expected { keyId, wrappedDek }." });
}
const raw = await get(`SELECT * FROM api_keys WHERE id = ? AND user_id = ?`, [keyId, user.id]);
if (!raw) return res.status(404).json({ error: "No such API key on your account." });
const target = normalizeKey(raw);
if (target.kind !== "machine") return res.status(422).json({ error: "Only a machine key can be granted a vault. A person's key reads through the person's own grant." });
if (target.expiresAt !== null && target.expiresAt <= Date.now()) return res.status(409).json({ error: "That key has expired." });
if (target.team_id !== vault.team_id) return res.status(409).json({ error: "That key is scoped to another team." });
if (!keyCoversVault(target, vault.name)) return res.status(409).json({ error: `That key is not scoped to ${vault.name}. Its vaults: ${(target.vaultScope || []).join(", ")}.` });
if (!target.public_key) {
return res.status(409).json({ error: "That key has not registered its public key yet. Run any logicsrc command with the key once first (LOGICSRC_API_KEY=… logicsrc whoami).", code: "no_public_key" });
}
await run(`INSERT INTO credshare_key_grants (vault_id, api_key_id, wrapped_dek, granted_by, created_at) VALUES (?,?,?,?,?) ON CONFLICT(vault_id, api_key_id) DO UPDATE SET wrapped_dek = excluded.wrapped_dek, granted_by = excluded.granted_by, created_at = excluded.created_at`,
[vault.id, target.id, wrappedDek, user.id, Date.now()]);
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "vault:grant:key", keyName: target.name });
res.status(201).json({ ok: true, keyId: target.id, name: target.name });
}));
credshareRouter.delete("/api/credshare/vaults/:id/key-grants/:keyId", api(async (req, res, user) => {
const vault = await vaultCtx(res, req.params.id, user.id); if (!vault) return;
const row = await get(
`SELECT k.id, k.name, k.user_id FROM credshare_key_grants g JOIN api_keys k ON k.id = g.api_key_id WHERE g.vault_id = ? AND g.api_key_id = ?`,
[vault.id, req.params.keyId]
);
if (!row) return res.status(404).json({ error: "That key holds no grant on this vault." });
const iHold = await get(`SELECT 1 FROM credshare_vault_grants WHERE vault_id = ? AND user_id = ?`, [vault.id, user.id]);
if (!iHold && row.user_id !== user.id) return res.status(403).json({ error: "Only the key's owner or a member with vault access can revoke it." });
await run(`DELETE FROM credshare_key_grants WHERE vault_id = ? AND api_key_id = ?`, [vault.id, row.id]);
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "vault:revoke:key", keyName: row.name });
res.json({ ok: true, revoked: row.name });
}));
credshareRouter.get("/api/credshare/vaults/:id/secrets", api(async (req, res, user, key) => {
const vault = await vaultCtx(res, req.params.id, user.id, key); if (!vault) return;
const rows = await all(`SELECT * FROM credshare_secrets WHERE vault_id = ? ORDER BY name`, [vault.id]);
res.json({ vaultId: vault.id, secrets: rows.map((s) => ({ name: s.name, nonce: s.nonce, ciphertext: s.ciphertext, fingerprint: s.fingerprint, version: s.version, updatedAt: s.updated_at })) });
}, { machine: "read" }));
credshareRouter.put("/api/credshare/vaults/:id/secrets", api(async (req, res, user, key) => {
const vault = await vaultCtx(res, req.params.id, user.id, key); if (!vault) return;
if (isMachine(key) && !(await get(`SELECT 1 FROM credshare_key_grants WHERE vault_id = ? AND api_key_id = ?`, [vault.id, key.id]))) {
return res.status(403).json({ error: "A machine key can only write a vault it has been granted.", code: "no_key_grant" });
}
const actorKeyId = key?.id ?? null;
const upserts = Array.isArray(req.body?.upserts) ? req.body.upserts : [];
const deletes = Array.isArray(req.body?.deletes) ? req.body.deletes : [];
const applied = [];
@ -387,21 +595,21 @@ credshareRouter.put("/api/credshare/vaults/:id/secrets", api(async (req, res, us
const version = (prev?.version ?? 0) + 1;
await run(`INSERT INTO credshare_secrets (vault_id, name, nonce, ciphertext, fingerprint, version, updated_by, updated_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(vault_id, name) DO UPDATE SET nonce = excluded.nonce, ciphertext = excluded.ciphertext, fingerprint = excluded.fingerprint, version = excluded.version, updated_by = excluded.updated_by, updated_at = excluded.updated_at`,
[vault.id, u.name, u.nonce, u.ciphertext, u.fingerprint, version, user.id, Date.now()]);
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: prev ? "secret:update" : "secret:add", keyName: u.name, fingerprint: u.fingerprint });
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: prev ? "secret:update" : "secret:add", keyName: u.name, fingerprint: u.fingerprint, actorKeyId });
applied.push(u.name);
}
for (const raw of deletes) {
const name = typeof raw === "string" ? raw : null;
if (!name) continue;
await run(`DELETE FROM credshare_secrets WHERE vault_id = ? AND name = ?`, [vault.id, name]);
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: "secret:remove", keyName: name });
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: "secret:remove", keyName: name, actorKeyId });
applied.push(name);
}
res.json({ ok: true, applied });
}));
}, { machine: "write" }));
credshareRouter.get("/api/credshare/vaults/:id/audit", api(async (req, res, user) => {
const vault = await vaultCtx(res, req.params.id, user.id); if (!vault) return;
credshareRouter.get("/api/credshare/vaults/:id/audit", api(async (req, res, user, key) => {
const vault = await vaultCtx(res, req.params.id, user.id, key); if (!vault) return;
const auditRows = await all(`SELECT * FROM credshare_audit WHERE vault_id = ? ORDER BY created_at DESC`, [vault.id]);
res.json({ audit: auditRows });
}));
}, { machine: "read" }));

View file

@ -13,7 +13,7 @@
// Auth: browser session or `Bearer lsk_…` (the logicsrc CLI). Mounted at /api/opencreds.
import { Router } from "express";
import { get, all, run } from "../db.mjs";
import { bearer, userForApiKey } from "../lib/apikey.mjs";
import { bearer, keyForBearer } from "../lib/apikey.mjs";
export const opencredsRouter = Router();
@ -22,8 +22,14 @@ export const MAX_ITEMS_PER_PUSH = 500;
function api(handler) {
return async (req, res) => {
const user = req.user || (await userForApiKey(bearer(req)));
if (!user) return res.status(401).json({ error: "Not authenticated. Run: logicsrc login" });
let user = req.user;
if (!user) {
const found = await keyForBearer(bearer(req));
if (!found) return res.status(401).json({ error: "Not authenticated. Run: logicsrc login" });
// The personal vault is the person's alone; a machine key never reaches it.
if (found.key.kind === "machine") return res.status(403).json({ error: "A machine API key cannot read the personal vault.", code: "machine_key_forbidden" });
user = found.user;
}
try {
await handler(req, res, user);
} catch (e) {

View file

@ -7,7 +7,7 @@ import { get, all, run } from "../db.mjs";
import { id, sha256 } from "../lib/crypto.mjs";
import { page, footer, appBar, esc } from "../lib/html.mjs";
import { requireAuth, csrfInput } from "../lib/session.mjs";
import { createApiKey, listApiKeys, revokeApiKey } from "../lib/apikey.mjs";
import { ApiKeyError, createApiKey, keyCoversVault, listApiKeys, machineKeyOptions, revokeApiKey } from "../lib/apikey.mjs";
import { requestOrigin } from "../lib/origin.mjs";
import { CLI_HINT } from "../lib/cli-hint.mjs";
import { vaultPageBody } from "../lib/vault-page.mjs";
@ -117,7 +117,14 @@ pagesRouter.get("/teams/:slug/vaults/:vaultId", requireAuth, async (req, res, ne
const secrets = await all(`SELECT name, version, updated_at FROM credshare_secrets WHERE vault_id = ? ORDER BY name`, [vault.id]);
const grant = await get(`SELECT 1 FROM credshare_vault_grants WHERE vault_id = ? AND user_id = ?`, [vault.id, req.user.id]);
const key = await get(`SELECT public_key FROM credshare_keys WHERE user_id = ?`, [req.user.id]);
// The caller's own machine keys that could hold this vault, and which already do.
const granted = new Set((await all(`SELECT api_key_id FROM credshare_key_grants WHERE vault_id = ?`, [vault.id])).map((r) => r.api_key_id));
const machineKeys = (await listApiKeys(req.user.id))
.filter((k) => k.kind === "machine" && k.team_id === vault.team_id && keyCoversVault(k, vault.name))
.filter((k) => k.expiresAt === null || k.expiresAt > Date.now())
.map((k) => ({ id: k.id, name: k.name, prefix: k.prefix, publicKey: k.public_key || "", readOnly: k.readOnly, granted: granted.has(k.id) }));
const body = `${appBar(req)}${vaultPageBody({
machineKeys,
team: ctx.team,
vault,
secrets,
@ -238,32 +245,87 @@ pagesRouter.post("/teams/accept", requireAuth, async (req, res) => {
res.redirect("/dashboard");
});
// ---- settings: CLI API keys ----
// ---- settings: API keys (person keys for the CLI, machine keys for boxes) ----
const KEY_ERRORS = {
"no-name": "Give the key a name.",
};
function keyRow(req, k) {
const when = (ms) => (ms ? new Date(Number(ms)).toISOString().slice(0, 10) : "never");
const facts = k.kind === "machine"
? [
`<span class="pill">machine</span>`,
`<span class="pill">${esc(k.team_slug || "?")}</span>`,
`<span class="pill ${k.readOnly ? "" : "warn"}">${k.readOnly ? "read-only" : "read-write"}</span>`,
k.vaultScope ? `<span class="faint">vaults: ${k.vaultScope.map(esc).join(", ")}</span>` : `<span class="faint">every vault in the team</span>`,
`<span class="faint">expires ${esc(when(k.expiresAt))}${k.expiresAt && k.expiresAt <= Date.now() ? " (expired)" : ""}</span>`,
k.public_key ? `<span class="pill on">identity registered</span>` : `<span class="pill warn">not used yet</span>`
].join(" ")
: `<span class="pill">person</span> <span class="faint">acts as you</span>`;
return `
<div style="display:flex;gap:12px;align-items:center;padding:10px 0;border-bottom:1px solid var(--line)" class="mono">
<div style="flex:1;min-width:0"><div>${esc(k.name)} <span class="faint">${esc(k.prefix)}…</span></div>
<div style="font-size:.74rem;margin-top:4px;display:flex;gap:6px;flex-wrap:wrap;align-items:center">${facts}<span class="faint">last used ${esc(when(k.last_used_at))}</span></div></div>
<form method="post" action="/settings/apikeys/${esc(k.id)}/delete" style="margin:0">${csrfInput(req)}<button class="btn danger" style="padding:5px 10px;font-size:.72rem">revoke</button></form>
</div>`;
}
pagesRouter.get("/settings", requireAuth, async (req, res) => {
const keys = await listApiKeys(req.user.id);
const teams = await all(`SELECT t.slug FROM credshare_teams t JOIN credshare_members m ON m.team_id = t.id WHERE m.user_id = ? AND m.status = 'active' ORDER BY t.slug`, [req.user.id]);
const newKey = req.query.key ? String(req.query.key) : "";
const keysHtml = keys.length ? keys.map((k) => `
<div style="display:flex;gap:12px;align-items:center;padding:10px 0;border-bottom:1px solid var(--line)" class="mono">
<span style="flex:1">${esc(k.name)} <span class="faint">${esc(k.prefix)}…</span></span>
<form method="post" action="/settings/apikeys/${k.id}/delete" style="margin:0">${csrfInput(req)}<button class="btn danger" style="padding:5px 10px;font-size:.72rem">revoke</button></form>
</div>`).join("") : `<div class="faint mono" style="font-size:.78rem;padding:6px 0">no keys yet</div>`;
const err = req.query.err ? String(req.query.err).slice(0, 200) : "";
const keysHtml = keys.length ? keys.map((k) => keyRow(req, k)).join("") : `<div class="faint mono" style="font-size:.78rem;padding:6px 0">no keys yet</div>`;
const body = `${appBar(req)}
<main class="wrap" style="max-width:640px;padding-top:30px">
<main class="wrap" style="max-width:720px;padding-top:30px">
<h1 style="font-size:1.5rem;margin-bottom:20px">Settings</h1>
${newKey ? `<div class="notice ok">New API key (copy it now — shown once):<br><b class="mono" style="word-break:break-all">${esc(newKey)}</b></div>` : ""}
<div class="card"><div class="card-head"><span class="h">API keys · for the logicsrc CLI</span></div>
${err ? `<div class="notice err">${esc(KEY_ERRORS[err] || err)}</div>` : ""}
<div class="card"><div class="card-head"><span class="h">API keys</span></div>
<div class="card-body">
<p class="dim" style="font-size:.85rem;margin-top:0">Usually you don't need these — <code>logicsrc login</code> creates one automatically. Manual keys are for CI.</p>
<p class="dim" style="font-size:.85rem;margin-top:0">A <b>person</b> key acts as you; <code>logicsrc login</code> makes one for you. A <b>machine</b> key is for a deploy box or CI: one team, the vaults you list, read-only unless you say otherwise, its own identity key. After the box runs one command with it, grant it a vault from the vault page or with <code>logicsrc teams grant &lt;team&gt; &lt;project&gt; &lt;env&gt; --key &lt;name&gt;</code>.</p>
${keysHtml}
<form method="post" action="/settings/apikeys" style="margin-top:14px;display:flex;gap:10px">${csrfInput(req)}
<input name="name" placeholder="key name (e.g. ci)" style="flex:1"><button class="btn">Create key</button></form>
<form method="post" action="/settings/apikeys" style="margin-top:16px" data-role="new-key">${csrfInput(req)}
<div style="display:flex;gap:10px;flex-wrap:wrap">
<label class="field" style="flex:2;min-width:160px"><span>Name</span><input name="name" placeholder="e.g. dev2-deploy" required maxlength="40"></label>
<label class="field" style="flex:1;min-width:120px"><span>Kind</span><select name="kind"><option value="user">person</option><option value="machine">machine</option></select></label>
</div>
<fieldset data-role="machine-fields" style="border:1px solid var(--line);border-radius:9px;padding:12px 14px 0;margin:0 0 14px">
<legend class="faint mono" style="font-size:.7rem;padding:0 6px">machine keys only</legend>
<div style="display:flex;gap:10px;flex-wrap:wrap">
<label class="field" style="flex:1;min-width:140px"><span>Team</span><select name="team">${teams.length ? teams.map((t) => `<option value="${esc(t.slug)}">${esc(t.slug)}</option>`).join("") : `<option value="">(no teams)</option>`}</select></label>
<label class="field" style="flex:2;min-width:200px"><span>Vaults (blank = all in the team)</span><input name="vaults" placeholder="web--prod, api--prod"></label>
</div>
<div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center">
<label class="field" style="flex:1;min-width:140px"><span>Expires</span><select name="expires"><option value="">never</option><option value="30d">in 30 days</option><option value="90d" selected>in 90 days</option><option value="365d">in a year</option></select></label>
<label class="dim" style="flex:1;min-width:160px;display:flex;gap:8px;align-items:center;font-size:.85rem;margin-bottom:14px"><input type="checkbox" name="readOnly" value="1" checked style="width:auto"> Read-only (pull, never push)</label>
</div>
</fieldset>
<button class="btn">Create key</button>
</form>
</div></div>
</main>${footer}`;
res.type("html").send(page({ title: "LogicSRC ▸ settings", body }));
});
pagesRouter.post("/settings/apikeys", requireAuth, async (req, res) => {
const { plaintext } = await createApiKey(req.user.id, String(req.body.name || "cli").slice(0, 40));
const name = String(req.body.name || "").trim().slice(0, 40);
if (!name) return res.redirect("/settings?err=no-name");
let opts = {};
if (req.body.kind === "machine") {
try {
opts = await machineKeyOptions(req.user.id, {
team: req.body.team,
vaults: req.body.vaults,
readOnly: req.body.readOnly === "1",
expires: req.body.expires || null
});
} catch (error) {
if (error instanceof ApiKeyError) return res.redirect("/settings?err=" + encodeURIComponent(error.message));
throw error;
}
}
const { plaintext } = await createApiKey(req.user.id, name, opts);
res.redirect("/settings?key=" + encodeURIComponent(plaintext));
});
pagesRouter.post("/settings/apikeys/:id/delete", requireAuth, async (req, res) => {

View file

@ -10,6 +10,7 @@ import { authRouter } from "./routes/auth.mjs";
import { passkeyRouter } from "./routes/passkey.mjs";
import { coinpayRouter } from "./routes/coinpay.mjs";
import { credshareRouter } from "./routes/credshare.mjs";
import { apiKeysRouter } from "./routes/apikeys.mjs";
import { opencredsRouter } from "./routes/opencreds.mjs";
import { cliRouter } from "./routes/cli.mjs";
import { pagesRouter } from "./routes/pages.mjs";
@ -50,6 +51,7 @@ app.use(authRouter); // GET / (+ /auth/login|register|logout)
app.use(passkeyRouter);
app.use(coinpayRouter);
app.use(credshareRouter); // /api/credshare/* (session or lsk_ Bearer)
app.use(apiKeysRouter); // /api/keys (session or a person's lsk_ key; never a machine key)
app.use(opencredsRouter); // /api/opencreds/* — personal vault sync (session or lsk_ Bearer)
app.use(cliRouter); // /cli/authorize, /cli/token, /api/me
app.use(pagesRouter); // /dashboard, /teams/*, /settings

View file

@ -28,7 +28,7 @@ async function migrate() {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
for (const file of ["001_auth.sql", "002_credshare.sql"]) {
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) {
await db.execute(statement);

View file

@ -33,7 +33,7 @@ async function migrate() {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
for (const file of ["001_auth.sql", "002_credshare.sql"]) {
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) {
await db.execute(statement);

View file

@ -0,0 +1,330 @@
// Machine API keys: a credential for a deploy box or CI that is narrower than
// the person who made it.
//
// What these pin: the key is stored hashed and shown once; a machine key sees
// one team and only its scoped vaults; it opens a vault only through a grant
// sealed to ITS OWN public key (never the person's); a read-only key is refused
// every write; it cannot mint keys, read /api/me or the personal vault; expired
// and revoked keys are 401; and a person's key behaves exactly as before.
process.env.DATABASE_URL = process.env.PWA_TEST_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, isPostgres } = await import("../src/db.mjs");
const { credshareRouter } = await import("../src/routes/credshare.mjs");
const { apiKeysRouter } = await import("../src/routes/apikeys.mjs");
const { cliRouter } = await import("../src/routes/cli.mjs");
const { opencredsRouter } = await import("../src/routes/opencreds.mjs");
const { createApiKey, keyForBearer, userForApiKey, parseExpiry } = await import("../src/lib/apikey.mjs");
const { sha256 } = await import("../src/lib/crypto.mjs");
async function migrate() {
if (isPostgres) {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) {
await db.execute(statement);
}
}
}
/** The app as production mounts it, minus sessions: every request is Bearer-authed. */
async function serve() {
const app = express();
app.use(express.json());
app.use(credshareRouter);
app.use(apiKeysRouter);
app.use(opencredsRouter);
app.use(cliRouter);
const server = app.listen(0);
await new Promise((resolve) => server.once("listening", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const call = async (method, path, token, body) => {
const headers = { accept: "application/json" };
if (token) headers.authorization = `Bearer ${token}`;
if (body !== undefined) headers["content-type"] = "application/json";
const res = await fetch(`${base}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
const text = await res.text();
return { status: res.status, body: text ? JSON.parse(text) : null };
};
return {
get: (path, token) => call("GET", path, token),
post: (path, token, body) => call("POST", path, token, body ?? {}),
put: (path, token, body) => call("PUT", path, token, body ?? {}),
del: (path, token) => call("DELETE", path, token),
close: () => new Promise((resolve) => server.close(resolve))
};
}
const now = Date.now();
/** Ann owns team acme (vaults web--prod, api--prod) and is in team other (vault x--prod). */
async function seed() {
await run(`INSERT INTO users (id, email, created_at) VALUES (?,?,?)`, ["u_ann", "ann@example.com", now]);
await run(`INSERT INTO credshare_keys (user_id, public_key, updated_at) VALUES (?,?,?)`, ["u_ann", "pk-ann", now]);
for (const [tid, slug] of [["t_acme", "acme"], ["t_other", "other"]]) {
await run(`INSERT INTO credshare_teams (id, slug, name, created_by, created_at) VALUES (?,?,?,?,?)`, [tid, slug, slug, "u_ann", now]);
await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, created_at) VALUES (?,?,?,?,?,?,?)`,
[`m_${slug}`, tid, "u_ann", "ann@example.com", "owner", "active", now]);
}
for (const [vid, tid, name] of [["v_web", "t_acme", "web--prod"], ["v_api", "t_acme", "api--prod"], ["v_x", "t_other", "x--prod"]]) {
await run(`INSERT INTO credshare_vaults (id, team_id, name, created_by, created_at) VALUES (?,?,?,?,?)`, [vid, tid, name, "u_ann", now]);
await run(`INSERT INTO credshare_vault_grants (vault_id, user_id, wrapped_dek, granted_by, created_at) VALUES (?,?,?,?,?)`, [vid, "u_ann", `dek-ann-${vid}`, "u_ann", now]);
await run(`INSERT INTO credshare_secrets (vault_id, name, nonce, ciphertext, fingerprint, version, updated_by, updated_at) VALUES (?,?,?,?,?,?,?,?)`,
[vid, "API_KEY", "n", "c", "fp", 1, "u_ann", now]);
}
}
await migrate();
await seed();
const http = await serve();
test.after(() => http.close());
// Ann's person key, minted the way `logicsrc login` mints it.
const { plaintext: annKey } = await createApiKey("u_ann", "laptop");
test("a key is stored as sha256 with a display prefix, and the plaintext only resolves while live", async () => {
const { plaintext, row } = await createApiKey("u_ann", "hash-check");
assert.match(plaintext, /^lsk_/);
const stored = await get(`SELECT * FROM api_keys WHERE id = ?`, [row.id]);
assert.equal(stored.token_hash, sha256(plaintext));
assert.notEqual(stored.token_hash, plaintext);
assert.equal(stored.prefix, plaintext.slice(0, 12));
assert.equal(stored.kind, "user");
assert.equal(Number(stored.read_only), 0, "person keys are never read-only");
assert.equal((await keyForBearer(plaintext)).user.id, "u_ann");
assert.equal(await keyForBearer(plaintext + "x"), null);
assert.equal(await keyForBearer("not-a-key"), null);
});
test("expiry durations parse, and a past date is refused", () => {
assert.equal(parseExpiry("30d", 0), 30 * 86400e3);
assert.equal(parseExpiry("12h", 0), 12 * 3600e3);
assert.equal(parseExpiry(null), null);
assert.equal(parseExpiry("2027-01-01T00:00:00Z"), Date.parse("2027-01-01T00:00:00Z"));
assert.throws(() => parseExpiry("soonish"));
});
test("a person mints a machine key over the API; the secret is in that response only", async () => {
const made = await http.post("/api/keys", annKey, { name: "dev2-deploy", kind: "machine", team: "acme", vaults: ["web--prod"], readOnly: true, expiresAt: "90d" });
assert.equal(made.status, 201);
assert.match(made.body.secret, /^lsk_/);
assert.equal(made.body.key.kind, "machine");
assert.equal(made.body.key.team, "acme");
assert.deepEqual(made.body.key.vaults, ["web--prod"]);
assert.equal(made.body.key.readOnly, true);
assert.ok(made.body.key.expiresAt > Date.now());
const listed = await http.get("/api/keys", annKey);
assert.equal(listed.status, 200);
const row = listed.body.keys.find((k) => k.name === "dev2-deploy");
assert.ok(row);
assert.equal(JSON.stringify(listed.body).includes(made.body.secret), false, "the list never carries a secret");
assert.equal("token_hash" in row, false);
});
test("machine key requests are validated: team required, membership required, vault names checked", async () => {
assert.equal((await http.post("/api/keys", annKey, { name: "m", kind: "machine" })).status, 422);
assert.equal((await http.post("/api/keys", annKey, { name: "m", kind: "machine", team: "nope" })).status, 404);
assert.equal((await http.post("/api/keys", annKey, { name: "m", kind: "machine", team: "acme", vaults: ["Bad Name"] })).status, 422);
assert.equal((await http.post("/api/keys", annKey, { name: "m", kind: "machine", team: "acme", expiresAt: "2001-01-01" })).status, 422);
assert.equal((await http.post("/api/keys", null, { name: "m" })).status, 401);
});
async function machineKey(opts = {}) {
const { plaintext, row } = await createApiKey("u_ann", opts.name || `m-${Math.random().toString(36).slice(2, 8)}`, {
kind: "machine",
teamId: "t_acme",
vaultScope: opts.vaults ?? ["web--prod"],
readOnly: opts.readOnly ?? true,
expiresAt: opts.expiresAt ?? null
});
return { token: plaintext, id: row.id, name: row.name };
}
test("a machine key cannot mint, list or revoke keys", async () => {
const m = await machineKey();
assert.equal((await http.post("/api/keys", m.token, { name: "escalate", kind: "user" })).status, 403);
assert.equal((await http.post("/api/keys", m.token, { name: "escalate", kind: "machine", team: "acme" })).status, 403);
assert.equal((await http.get("/api/keys", m.token)).status, 403);
assert.equal((await http.del(`/api/keys/${m.id}`, m.token)).status, 403);
});
test("a machine key cannot read /api/me or the personal vault; a person key still can read /api/me", async () => {
const m = await machineKey();
assert.equal((await http.get("/api/me", m.token)).status, 403);
assert.equal((await http.get("/api/opencreds/vault", m.token)).status, 403);
assert.equal(await userForApiKey(m.token), null);
const me = await http.get("/api/me", annKey);
assert.equal(me.status, 200);
assert.equal(me.body.email, "ann@example.com");
});
test("a machine key registers its OWN public key, leaving the person's untouched", async () => {
const m = await machineKey();
const reg = await http.post("/api/credshare/keys", m.token, { publicKey: "pk-machine-1" });
assert.equal(reg.status, 200, "registering is allowed even for a read-only key");
assert.equal((await get(`SELECT public_key FROM api_keys WHERE id = ?`, [m.id])).public_key, "pk-machine-1");
assert.equal((await get(`SELECT public_key FROM credshare_keys WHERE user_id = ?`, ["u_ann"])).public_key, "pk-ann");
const me = await http.get("/api/credshare/me", m.token);
assert.equal(me.status, 200);
assert.equal(me.body.user.publicKey, "pk-machine-1");
assert.deepEqual(me.body.teams.map((t) => t.slug), ["acme"]);
assert.equal(me.body.key.kind, "machine");
assert.equal(me.body.key.team, "acme");
assert.deepEqual(me.body.key.vaults, ["web--prod"]);
assert.equal(me.body.key.readOnly, true);
});
test("a machine key sees one team and only its scoped vaults", async () => {
const m = await machineKey({ vaults: ["web--prod"] });
const teams = await http.get("/api/credshare/teams", m.token);
assert.deepEqual(teams.body.teams.map((t) => t.slug), ["acme"]);
const vaults = await http.get("/api/credshare/teams/acme/vaults", m.token);
assert.equal(vaults.status, 200);
assert.deepEqual(vaults.body.vaults.map((v) => v.name), ["web--prod"]);
assert.equal(vaults.body.vaults[0].hasAccess, false, "access means a grant to the KEY, not to Ann");
assert.equal((await http.get("/api/credshare/teams/other/vaults", m.token)).status, 403);
assert.equal((await http.get("/api/credshare/vaults/v_api/secrets", m.token)).status, 403);
assert.equal((await http.get("/api/credshare/vaults/v_x/secrets", m.token)).status, 403);
assert.equal((await http.get("/api/credshare/vaults/v_web/secrets", m.token)).status, 200);
// An unscoped machine key sees every vault in its team, and still no other team.
const all = await machineKey({ vaults: [] });
const allVaults = await http.get("/api/credshare/teams/acme/vaults", all.token);
assert.deepEqual(allVaults.body.vaults.map((v) => v.name).sort(), ["api--prod", "web--prod"]);
});
test("the vault key reaches a machine only through a grant sealed to its own key", async () => {
const m = await machineKey({ name: "grant-me" });
// Not registered yet: a grant is refused with the instruction to use the key once.
const early = await http.post("/api/credshare/vaults/v_web/key-grants", annKey, { keyId: m.id, wrappedDek: "sealed-to-machine" });
assert.equal(early.status, 409);
assert.equal(early.body.code, "no_public_key");
await http.post("/api/credshare/keys", m.token, { publicKey: "pk-grant-me" });
const before = await http.get("/api/credshare/vaults/v_web/grant", m.token);
assert.equal(before.status, 403);
assert.equal(before.body.code, "no_key_grant");
// Out-of-scope vault: refused even for the owner.
assert.equal((await http.post("/api/credshare/vaults/v_api/key-grants", annKey, { keyId: m.id, wrappedDek: "x" })).status, 409);
// A machine key cannot grant itself (or anything).
assert.equal((await http.post("/api/credshare/vaults/v_web/key-grants", m.token, { keyId: m.id, wrappedDek: "x" })).status, 403);
const granted = await http.post("/api/credshare/vaults/v_web/key-grants", annKey, { keyId: m.id, wrappedDek: "sealed-to-machine" });
assert.equal(granted.status, 201);
const after = await http.get("/api/credshare/vaults/v_web/grant", m.token);
assert.equal(after.status, 200);
assert.equal(after.body.wrappedDek, "sealed-to-machine", "never Ann's wrapped key");
const listed = await http.get("/api/credshare/teams/acme/vaults", m.token);
assert.equal(listed.body.vaults.find((v) => v.name === "web--prod").hasAccess, true);
// The read is in the vault's audit trail, attributed to the key.
const reads = await all(`SELECT * FROM credshare_audit WHERE vault_id = ? AND action = 'vault:read' AND actor_key_id = ?`, ["v_web", m.id]);
assert.equal(reads.length, 1);
assert.equal(reads[0].actor_user_id, "u_ann");
// Ann's own grant is untouched.
assert.equal((await http.get("/api/credshare/vaults/v_web/grant", annKey)).body.wrappedDek, "dek-ann-v_web");
});
test("a read-only machine key is refused every write; a read-write one may write a granted vault", async () => {
const ro = await machineKey({ readOnly: true });
const upsert = { upserts: [{ name: "NEW", nonce: "n", ciphertext: "c", fingerprint: "f" }], deletes: [] };
const roPut = await http.put("/api/credshare/vaults/v_web/secrets", ro.token, upsert);
assert.equal(roPut.status, 403);
assert.equal(roPut.body.code, "read_only_key");
assert.equal((await http.post("/api/credshare/teams/acme/vaults", ro.token, { name: "new--prod" })).status, 403);
assert.equal((await http.post("/api/credshare/teams", ro.token, { slug: "evil" })).status, 403);
assert.equal((await http.post("/api/credshare/teams/acme/invites", ro.token, { email: "x@example.com" })).status, 403);
assert.equal((await http.post("/api/credshare/vaults/v_web/grants", ro.token, { email: "ann@example.com", wrappedDek: "x" })).status, 403);
assert.equal((await http.get("/api/credshare/users?email=ann@example.com", ro.token)).status, 403);
const rw = await machineKey({ readOnly: false });
await http.post("/api/credshare/keys", rw.token, { publicKey: "pk-rw" });
// Write needs a grant first, so a key cannot plant values in a vault it cannot read.
assert.equal((await http.put("/api/credshare/vaults/v_web/secrets", rw.token, upsert)).status, 403);
await http.post("/api/credshare/vaults/v_web/key-grants", annKey, { keyId: rw.id, wrappedDek: "sealed-rw" });
const ok = await http.put("/api/credshare/vaults/v_web/secrets", rw.token, upsert);
assert.equal(ok.status, 200);
const row = await get(`SELECT * FROM credshare_audit WHERE vault_id = ? AND key_name = 'NEW' AND action = 'secret:add'`, ["v_web"]);
assert.equal(row.actor_key_id, rw.id);
// Team admin stays people-only for a read-write key too.
assert.equal((await http.post("/api/credshare/teams", rw.token, { slug: "evil" })).status, 403);
await run(`DELETE FROM credshare_secrets WHERE vault_id = ? AND name = 'NEW'`, ["v_web"]);
});
test("expired and revoked keys are 401, and revoking drops the key's grants", async () => {
const expired = await machineKey({ expiresAt: Date.now() - 1000 });
assert.equal((await http.get("/api/credshare/me", expired.token)).status, 401);
const m = await machineKey();
await http.post("/api/credshare/keys", m.token, { publicKey: "pk-revoke" });
await http.post("/api/credshare/vaults/v_web/key-grants", annKey, { keyId: m.id, wrappedDek: "sealed" });
assert.equal((await http.get("/api/credshare/vaults/v_web/grant", m.token)).status, 200);
assert.equal((await http.del(`/api/keys/${m.id}`, annKey)).status, 200);
assert.equal((await http.get("/api/credshare/vaults/v_web/grant", m.token)).status, 401);
assert.equal((await all(`SELECT * FROM credshare_key_grants WHERE api_key_id = ?`, [m.id])).length, 0);
assert.equal((await http.del(`/api/keys/${m.id}`, annKey)).status, 404);
});
test("re-registering a different public key drops the grants sealed to the old one", async () => {
const m = await machineKey();
await http.post("/api/credshare/keys", m.token, { publicKey: "pk-old" });
await http.post("/api/credshare/vaults/v_web/key-grants", annKey, { keyId: m.id, wrappedDek: "sealed-old" });
const again = await http.post("/api/credshare/keys", m.token, { publicKey: "pk-new" });
assert.equal(again.body.droppedGrants, 1);
assert.equal((await http.get("/api/credshare/vaults/v_web/grant", m.token)).status, 403);
});
test("a re-key re-seals the machine grants it is given and drops the rest", async () => {
const keep = await machineKey({ name: "keep" });
const drop = await machineKey({ name: "drop" });
for (const k of [keep, drop]) {
await http.post("/api/credshare/keys", k.token, { publicKey: `pk-${k.name}` });
await http.post("/api/credshare/vaults/v_web/key-grants", annKey, { keyId: k.id, wrappedDek: `old-${k.name}` });
}
const listed = await http.get("/api/credshare/vaults/v_web/key-grants", annKey);
assert.deepEqual(listed.body.keyGrants.map((g) => g.name).filter((n) => n === "keep" || n === "drop").sort(), ["drop", "keep"]);
assert.equal(listed.body.keyGrants.find((g) => g.name === "keep").publicKey, "pk-keep");
const secrets = (await all(`SELECT name, fingerprint FROM credshare_secrets WHERE vault_id = ?`, ["v_web"]))
.map((s) => ({ name: s.name, nonce: "n2", ciphertext: "c2", fingerprint: s.fingerprint }));
const rekey = await http.post("/api/credshare/vaults/v_web/rekey", annKey, {
grants: [{ email: "ann@example.com", wrappedDek: "dek-ann-v_web" }],
secrets,
keyGrants: [{ keyId: keep.id, wrappedDek: "new-keep" }]
});
assert.equal(rekey.status, 200, JSON.stringify(rekey.body));
assert.deepEqual(rekey.body.keysResealed, ["keep"]);
assert.ok(rekey.body.keysDropped.includes("drop"));
assert.equal((await http.get("/api/credshare/vaults/v_web/grant", keep.token)).body.wrappedDek, "new-keep");
assert.equal((await http.get("/api/credshare/vaults/v_web/grant", drop.token)).status, 403);
});
test("a person's key still registers the person's identity key, as before", async () => {
const { plaintext } = await createApiKey("u_ann", "ci-person");
const reg = await http.post("/api/credshare/keys", plaintext, { publicKey: "pk-ann" });
assert.equal(reg.status, 200);
assert.equal((await get(`SELECT public_key FROM credshare_keys WHERE user_id = ?`, ["u_ann"])).public_key, "pk-ann");
const me = await http.get("/api/credshare/me", plaintext);
assert.deepEqual(me.body.teams.map((t) => t.slug).sort(), ["acme", "other"]);
assert.equal(me.body.key.kind, "user");
});

View file

@ -21,7 +21,7 @@ if (isPostgres) {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
for (const file of ["001_auth.sql", "002_credshare.sql"]) {
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement);
}

View file

@ -23,7 +23,7 @@ async function migrate() {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
for (const file of ["001_auth.sql", "002_credshare.sql"]) {
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) {
await db.execute(statement);