mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-08-13 14:37:26 +00:00
feat(credentials): re-key team vaults, and reach sh1pt's vault as a provider (#117)
Two additions to Credential Sharing. `logicsrc credentials rotate` (alias `logicsrc secrets rotate`) re-keys a team vault: fresh DEK, re-sealed to the members who keep access, every secret re-encrypted under it. Values do not change, so nothing that consumes them breaks; what changes is that every wrapped key issued before the rotation is dead. --active (the default) keeps only active members and revokes the rest -- the "someone left" rotation. --all keeps everyone who holds access, for plain hygiene. Dry run by default, like `sync`. The DEK is recoverable ONLY through the grants, so a half-applied rotation makes a vault permanently unreadable by everyone. The whole next state therefore goes to the server in one request and commits in one transaction (new db.batch helper). The server also requires every submitted fingerprint to equal the stored one: it cannot see values, but it can prove a re-key did not swap any. Rotations that would leave the caller ungranted, grant nobody, or cover the wrong secret count are rejected before anything is written. GET /vaults/:id/grants now returns publicKey and status so a client can re-seal in one pass instead of N+1 user lookups, and revocation finally deletes the grant row rather than leaving one that reports access it no longer confers. The sh1pt adapter is the fifth provider. It is the only one driven through a CLI rather than HTTP, because sh1pt publishes `sh1pt secret set|get|list|rm` as the interface to its vault and documents no REST endpoint. Values go over the child's stdin, never argv -- a secret in argv is readable by any user on the host via ps. Since `sh1pt secret get` needs interactive confirmation it cannot be scripted, so the adapter is write-only for values like github-secrets: a sync target, never a source, no value-restoring rollback. Tests drive a real fake sh1pt binary rather than a mocked execFile, which is how the hang surfaced: with nothing to pipe, stdin was left open and any subcommand that reads it would wait forever. It is now always closed. Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
f9ebf9b342
commit
6f23dbdb0f
15 changed files with 1278 additions and 7 deletions
|
|
@ -50,10 +50,20 @@ export interface RemoteSecret {
|
|||
|
||||
export interface RemoteGrantRow {
|
||||
email: string;
|
||||
/** X25519 public key, so a client can re-seal to every member in one pass. */
|
||||
publicKey: string | null;
|
||||
status: "active" | "invited";
|
||||
hasPublicKey: boolean;
|
||||
hasAccess: boolean;
|
||||
}
|
||||
|
||||
export interface RekeyResult {
|
||||
ok: boolean;
|
||||
rekeyed: number;
|
||||
granted: string[];
|
||||
revoked: string[];
|
||||
}
|
||||
|
||||
export class TeamApiError extends Error {
|
||||
constructor(
|
||||
public readonly status: number,
|
||||
|
|
@ -158,6 +168,21 @@ export class TeamClient {
|
|||
putSecrets(vaultId: string, upserts: Array<{ name: string; nonce: string; ciphertext: string; fingerprint: string }>, deletes: string[]) {
|
||||
return this.request<{ ok: boolean; applied: string[] }>("PUT", `/vaults/${encodeURIComponent(vaultId)}/secrets`, { upserts, deletes });
|
||||
}
|
||||
/**
|
||||
* Swap the vault to a fresh DEK. The whole next state goes over in one call
|
||||
* because the server applies it in a single transaction — see rekey.ts for
|
||||
* why a partial rotation is unrecoverable.
|
||||
*/
|
||||
rekeyVault(
|
||||
vaultId: string,
|
||||
body: {
|
||||
grants: Array<{ email: string; wrappedDek: string }>;
|
||||
secrets: Array<{ name: string; nonce: string; ciphertext: string; fingerprint: string }>;
|
||||
revoke: string[];
|
||||
}
|
||||
) {
|
||||
return this.request<RekeyResult>("POST", `/vaults/${encodeURIComponent(vaultId)}/rekey`, body);
|
||||
}
|
||||
listAudit(vaultId: string) {
|
||||
return this.request<{ audit: Array<Record<string, unknown>> }>("GET", `/vaults/${encodeURIComponent(vaultId)}/audit`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -101,4 +101,11 @@ export {
|
|||
type CredentialStore
|
||||
} from "./store.js";
|
||||
export { fingerprintValue, fingerprintsEqual } from "./fingerprint.js";
|
||||
export {
|
||||
planVaultRekey,
|
||||
type RekeyPlan,
|
||||
type RekeyPlanInput,
|
||||
type RekeyMember,
|
||||
type SealedSecret
|
||||
} from "./rekey.js";
|
||||
export * from "./types.js";
|
||||
|
|
|
|||
|
|
@ -3,9 +3,10 @@ import { envProvider } from "./env.js";
|
|||
import { dopplerProvider } from "./doppler.js";
|
||||
import { railwayProvider } from "./railway.js";
|
||||
import { githubSecretsProvider } from "./github-secrets.js";
|
||||
import { sh1ptProvider } from "./sh1pt.js";
|
||||
import { teamProvider } from "./team.js";
|
||||
|
||||
export const credentialProviders: CredentialProvider[] = [envProvider, dopplerProvider, railwayProvider, githubSecretsProvider, teamProvider];
|
||||
export const credentialProviders: CredentialProvider[] = [envProvider, dopplerProvider, railwayProvider, githubSecretsProvider, sh1ptProvider, teamProvider];
|
||||
|
||||
export const credentialProviderRegistry: Map<string, CredentialProvider> = new Map(
|
||||
credentialProviders.map((provider) => [provider.id, provider])
|
||||
|
|
@ -22,5 +23,5 @@ export function listCredentialProviderManifests(): CredentialProviderManifest[]
|
|||
}));
|
||||
}
|
||||
|
||||
export { envProvider, dopplerProvider, railwayProvider, githubSecretsProvider, teamProvider };
|
||||
export { envProvider, dopplerProvider, railwayProvider, githubSecretsProvider, sh1ptProvider, teamProvider };
|
||||
export { parseEnv, applyEnv } from "./env.js";
|
||||
|
|
|
|||
171
plugins/credential-sharing/src/providers/sh1pt.test.ts
Normal file
171
plugins/credential-sharing/src/providers/sh1pt.test.ts
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync, chmodSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { parseSecretList, sh1ptProvider } from "./sh1pt.js";
|
||||
|
||||
/**
|
||||
* These run against a real fake `sh1pt` binary rather than a mocked execFile,
|
||||
* so the child-process path — argv, stdin, exit codes — is genuinely exercised.
|
||||
* That matters here: the whole point of the adapter is that secret values go
|
||||
* over stdin and never appear in argv.
|
||||
*/
|
||||
let dir: string;
|
||||
let binPath: string;
|
||||
let logPath: string;
|
||||
|
||||
/** Write a stub `sh1pt` that records how it was invoked, then prints `stdout`. */
|
||||
function installFakeSh1pt(body: string): void {
|
||||
writeFileSync(
|
||||
binPath,
|
||||
`#!/usr/bin/env node
|
||||
const fs = require("fs");
|
||||
let stdin = "";
|
||||
process.stdin.on("data", (c) => (stdin += c));
|
||||
process.stdin.on("end", run);
|
||||
if (process.stdin.isTTY) run();
|
||||
function run() {
|
||||
const calls = fs.existsSync(${JSON.stringify(logPath)})
|
||||
? JSON.parse(fs.readFileSync(${JSON.stringify(logPath)}, "utf8"))
|
||||
: [];
|
||||
calls.push({ argv: process.argv.slice(2), stdin });
|
||||
fs.writeFileSync(${JSON.stringify(logPath)}, JSON.stringify(calls));
|
||||
${body}
|
||||
}
|
||||
`,
|
||||
{ mode: 0o755 }
|
||||
);
|
||||
chmodSync(binPath, 0o755);
|
||||
}
|
||||
|
||||
function calls(): Array<{ argv: string[]; stdin: string }> {
|
||||
return existsSync(logPath) ? JSON.parse(readFileSync(logPath, "utf8")) : [];
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), "sh1pt-test-"));
|
||||
binPath = join(dir, "sh1pt");
|
||||
logPath = join(dir, "calls.json");
|
||||
process.env.SH1PT_BIN = binPath;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.SH1PT_BIN;
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("parseSecretList", () => {
|
||||
it("reads plain and decorated key lists, and never invents a key", () => {
|
||||
expect(parseSecretList("NPM_TOKEN\nDOCKER_PAT\n")).toEqual(["NPM_TOKEN", "DOCKER_PAT"]);
|
||||
expect(parseSecretList(" - NPM_TOKEN\n * DOCKER_PAT\n\n")).toEqual(["NPM_TOKEN", "DOCKER_PAT"]);
|
||||
// A value accidentally printed alongside a key has whitespace in it, so it
|
||||
// is dropped rather than treated as a key name.
|
||||
expect(parseSecretList("NPM_TOKEN = npm_abc123\nDOCKER_PAT\n")).toEqual(["DOCKER_PAT"]);
|
||||
expect(parseSecretList("")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sh1ptProvider", () => {
|
||||
it("is declared write-only: sh1pt secret get needs a human, so values cannot be read back", () => {
|
||||
expect(sh1ptProvider.capabilities.readValues).toBe(false);
|
||||
expect(sh1ptProvider.capabilities.rollback).toBe(false);
|
||||
expect(sh1ptProvider.readValues).toBeUndefined();
|
||||
expect(sh1ptProvider.capabilities.write).toBe(true);
|
||||
});
|
||||
|
||||
it("lists key names and reports values as unreadable", async () => {
|
||||
installFakeSh1pt(`process.stdout.write("NPM_TOKEN\\nCLOUDFLARE_TOKEN\\n");`);
|
||||
|
||||
const snapshot = await sh1ptProvider.inspect({ provider: "sh1pt", project: "acme", config: "prod" });
|
||||
|
||||
expect(snapshot.valuesReadable).toBe(false);
|
||||
expect(snapshot.keys.map((k) => k.name)).toEqual(["CLOUDFLARE_TOKEN", "NPM_TOKEN"]);
|
||||
// Names only — a fingerprint would imply we had seen the value.
|
||||
expect(snapshot.keys.every((k) => k.fingerprint === undefined)).toBe(true);
|
||||
expect(calls()[0].argv).toEqual(["secret", "list", "--project", "acme", "--env", "prod"]);
|
||||
});
|
||||
|
||||
it("passes secret values on stdin and NEVER in argv", async () => {
|
||||
installFakeSh1pt("");
|
||||
const value = "npm_supersecret_value";
|
||||
|
||||
const results = await sh1ptProvider.write({
|
||||
endpoint: { provider: "sh1pt" },
|
||||
upserts: { NPM_TOKEN: value },
|
||||
deletes: [],
|
||||
dryRun: false
|
||||
});
|
||||
|
||||
expect(results).toEqual([{ key: "NPM_TOKEN", applied: true }]);
|
||||
const call = calls()[0];
|
||||
expect(call.argv).toEqual(["secret", "set", "NPM_TOKEN"]);
|
||||
// The security property this adapter exists to hold: a value in argv is
|
||||
// readable by any process on the box via `ps`.
|
||||
expect(call.argv.join(" ")).not.toContain(value);
|
||||
expect(call.stdin.trim()).toBe(value);
|
||||
});
|
||||
|
||||
it("deletes through `secret rm`", async () => {
|
||||
installFakeSh1pt("");
|
||||
|
||||
const results = await sh1ptProvider.write({
|
||||
endpoint: { provider: "sh1pt" },
|
||||
upserts: {},
|
||||
deletes: ["OLD_TOKEN"],
|
||||
dryRun: false
|
||||
});
|
||||
|
||||
expect(results).toEqual([{ key: "OLD_TOKEN", applied: true }]);
|
||||
expect(calls()[0].argv).toEqual(["secret", "rm", "OLD_TOKEN"]);
|
||||
});
|
||||
|
||||
it("a dry run touches nothing", async () => {
|
||||
installFakeSh1pt("");
|
||||
|
||||
const results = await sh1ptProvider.write({
|
||||
endpoint: { provider: "sh1pt" },
|
||||
upserts: { A: "1" },
|
||||
deletes: ["B"],
|
||||
dryRun: true
|
||||
});
|
||||
|
||||
expect(results).toEqual([
|
||||
{ key: "A", applied: false },
|
||||
{ key: "B", applied: false }
|
||||
]);
|
||||
expect(calls()).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports a per-key failure instead of aborting the whole run", async () => {
|
||||
installFakeSh1pt(`
|
||||
if (process.argv[4] === "BAD") { process.stderr.write("vault rejected BAD"); process.exit(1); }
|
||||
`);
|
||||
|
||||
const results = await sh1ptProvider.write({
|
||||
endpoint: { provider: "sh1pt" },
|
||||
upserts: { GOOD: "1", BAD: "2" },
|
||||
deletes: [],
|
||||
dryRun: false
|
||||
});
|
||||
|
||||
expect(results.find((r) => r.key === "GOOD")?.applied).toBe(true);
|
||||
const bad = results.find((r) => r.key === "BAD");
|
||||
expect(bad?.applied).toBe(false);
|
||||
expect(bad?.error).toMatch(/vault rejected BAD/);
|
||||
});
|
||||
|
||||
it("rejects a malformed secret name before shelling out", async () => {
|
||||
installFakeSh1pt("");
|
||||
|
||||
await expect(
|
||||
sh1ptProvider.write({ provider: "sh1pt", endpoint: { provider: "sh1pt" }, upserts: { "not a key": "x" }, deletes: [], dryRun: false } as never)
|
||||
).rejects.toThrow(/not a valid sh1pt secret name/);
|
||||
expect(calls()).toEqual([]);
|
||||
});
|
||||
|
||||
it("explains how to fix a missing sh1pt CLI", async () => {
|
||||
process.env.SH1PT_BIN = join(dir, "does-not-exist");
|
||||
|
||||
await expect(sh1ptProvider.inspect({ provider: "sh1pt" })).rejects.toThrow(/sh1pt CLI was not found on PATH/);
|
||||
});
|
||||
});
|
||||
156
plugins/credential-sharing/src/providers/sh1pt.ts
Normal file
156
plugins/credential-sharing/src/providers/sh1pt.ts
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
/**
|
||||
* sh1pt credential provider — the distribution-credential vault.
|
||||
*
|
||||
* Unlike every other adapter here, sh1pt is driven through its CLI rather than
|
||||
* a REST call. That is not a shortcut: sh1pt publishes `sh1pt secret set|get|
|
||||
* list|rm` as the interface to its cloud vault and documents no HTTP API for
|
||||
* it, so the CLI *is* the contract. Auth comes from `sh1pt login`, which writes
|
||||
* ~/.sh1pt/credentials; this adapter never handles a sh1pt token itself.
|
||||
*
|
||||
* The vault holds delivery credentials that Doppler/Railway/GitHub generally do
|
||||
* not — App Store Connect keys, Play service accounts, npm and Docker tokens,
|
||||
* Cloudflare tokens — which is exactly why it is worth syncing into.
|
||||
*
|
||||
* Values are written on STDIN, never as argv. `sh1pt secret set <key>` prompts
|
||||
* for the value when it is omitted, and a secret passed as a command-line
|
||||
* argument is world-readable in `ps` for the life of the process.
|
||||
*/
|
||||
import { execFile } from "node:child_process";
|
||||
import { keysFromNames } from "../fingerprint.js";
|
||||
import type { CredentialEndpoint, CredentialProvider, CredentialWriteResult } from "../types.js";
|
||||
|
||||
/** The binary to invoke. Overridable so CI can point at a pinned build. */
|
||||
function sh1ptBin(): string {
|
||||
return process.env.SH1PT_BIN || "sh1pt";
|
||||
}
|
||||
|
||||
/**
|
||||
* Secret names sh1pt will accept. We validate before shelling out: execFile
|
||||
* does not use a shell, so this is not injection defence, it is a clear error
|
||||
* instead of a confusing CLI usage failure on a malformed key.
|
||||
*/
|
||||
const SECRET_NAME = /^[A-Za-z_][A-Za-z0-9_.-]*$/;
|
||||
|
||||
function assertSecretName(name: string): void {
|
||||
if (!SECRET_NAME.test(name)) {
|
||||
throw new Error(
|
||||
`"${name}" is not a valid sh1pt secret name. Use letters, digits, underscore, dot or dash, starting with a letter or underscore.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
interface RunResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the sh1pt CLI. `stdin` is written to the child when provided, which is
|
||||
* how secret values are handed over without ever appearing in the process
|
||||
* table. Scoping flags come from the endpoint: `project` maps to sh1pt's
|
||||
* project, `config` to its environment.
|
||||
*/
|
||||
function runSh1pt(args: string[], endpoint: CredentialEndpoint, stdin?: string): Promise<RunResult> {
|
||||
const scoped = [...args];
|
||||
if (endpoint.project) scoped.push("--project", endpoint.project);
|
||||
if (endpoint.config) scoped.push("--env", endpoint.config);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = execFile(
|
||||
sh1ptBin(),
|
||||
scoped,
|
||||
{ encoding: "utf8", maxBuffer: 10 * 1024 * 1024 },
|
||||
(error, stdout, stderr) => {
|
||||
if (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code === "ENOENT") {
|
||||
reject(
|
||||
new Error(
|
||||
`The sh1pt CLI was not found on PATH. Install it and run "sh1pt login", or set SH1PT_BIN to its path.`
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
// stderr carries sh1pt's own message (not logged in, unknown project, …).
|
||||
reject(new Error(`sh1pt ${scoped[0]} ${scoped[1] ?? ""} failed: ${(stderr || error.message).trim().slice(0, 300)}`));
|
||||
return;
|
||||
}
|
||||
resolve({ stdout, stderr });
|
||||
}
|
||||
);
|
||||
// Always close stdin, even with nothing to send. Leaving it open hangs any
|
||||
// sh1pt subcommand that waits on input (a confirmation prompt, say) until
|
||||
// the process is killed.
|
||||
child.stdin?.end(stdin ?? "");
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* `sh1pt secret list` prints key names, one per line, and never values. We
|
||||
* tolerate a decorated list (bullets, blank lines) but refuse anything with
|
||||
* whitespace inside it, which would mean the output format changed under us.
|
||||
*/
|
||||
export function parseSecretList(stdout: string): string[] {
|
||||
return stdout
|
||||
.split("\n")
|
||||
.map((line) => line.replace(/^[\s*\-•]+/, "").trim())
|
||||
.filter((line) => line.length > 0 && SECRET_NAME.test(line));
|
||||
}
|
||||
|
||||
export const sh1ptProvider: CredentialProvider = {
|
||||
id: "sh1pt",
|
||||
name: "sh1pt",
|
||||
description: "Distribution credential vault (App Store, Play, npm, Docker, Cloudflare) via the sh1pt CLI.",
|
||||
// readValues is false by design, not by omission: `sh1pt secret get` requires
|
||||
// interactive confirmation, so it cannot be scripted. That also makes this a
|
||||
// write-only target -- no rollback pre-image can be captured, same as
|
||||
// github-secrets.
|
||||
capabilities: { readValues: false, readNames: true, write: true, delete: true, rollback: false, audit: false },
|
||||
authRequirements: ["sh1pt login"],
|
||||
status: "available",
|
||||
|
||||
async inspect(endpoint) {
|
||||
const { stdout } = await runSh1pt(["secret", "list"], endpoint);
|
||||
return {
|
||||
provider: "sh1pt",
|
||||
endpoint,
|
||||
valuesReadable: false,
|
||||
keys: keysFromNames(parseSecretList(stdout)),
|
||||
inspectedAt: new Date().toISOString()
|
||||
};
|
||||
},
|
||||
|
||||
async write({ endpoint, upserts, deletes, dryRun }) {
|
||||
for (const key of [...Object.keys(upserts), ...deletes]) {
|
||||
assertSecretName(key);
|
||||
}
|
||||
|
||||
const results: CredentialWriteResult[] = [];
|
||||
if (dryRun) {
|
||||
return [
|
||||
...Object.keys(upserts).map((key) => ({ key, applied: false })),
|
||||
...deletes.map((key) => ({ key, applied: false }))
|
||||
];
|
||||
}
|
||||
|
||||
// One invocation per key: the CLI has no bulk form, and a partial failure
|
||||
// should report per-key rather than abort the whole run.
|
||||
for (const [key, value] of Object.entries(upserts)) {
|
||||
try {
|
||||
await runSh1pt(["secret", "set", key], endpoint, `${value}\n`);
|
||||
results.push({ key, applied: true });
|
||||
} catch (error) {
|
||||
results.push({ key, applied: false, error: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
}
|
||||
for (const key of deletes) {
|
||||
try {
|
||||
await runSh1pt(["secret", "rm", key], endpoint);
|
||||
results.push({ key, applied: true });
|
||||
} catch (error) {
|
||||
results.push({ key, applied: false, error: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
};
|
||||
170
plugins/credential-sharing/src/rekey.test.ts
Normal file
170
plugins/credential-sharing/src/rekey.test.ts
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
generateIdentityKeyPair,
|
||||
generateVaultKey,
|
||||
encryptValue,
|
||||
decryptValue,
|
||||
wrapVaultKey,
|
||||
unwrapVaultKey,
|
||||
type IdentityKeyPair
|
||||
} from "./crypto.js";
|
||||
import { fingerprintValue } from "./fingerprint.js";
|
||||
import { planVaultRekey, type RekeyMember, type SealedSecret } from "./rekey.js";
|
||||
|
||||
/** Build a vault sealed under a fresh DEK, plus a grant for each holder. */
|
||||
async function makeVault(values: Record<string, string>, holders: IdentityKeyPair[]) {
|
||||
const dek = await generateVaultKey();
|
||||
const secrets: SealedSecret[] = [];
|
||||
for (const [name, value] of Object.entries(values)) {
|
||||
const sealed = await encryptValue(value, dek);
|
||||
secrets.push({ name, nonce: sealed.nonce, ciphertext: sealed.ciphertext, fingerprint: fingerprintValue(value) });
|
||||
}
|
||||
const wrapped = await Promise.all(holders.map((h) => wrapVaultKey(dek, h.publicKey)));
|
||||
return { dek, secrets, wrapped };
|
||||
}
|
||||
|
||||
function member(email: string, keys: IdentityKeyPair | null, over: Partial<RekeyMember> = {}): RekeyMember {
|
||||
return { email, publicKey: keys?.publicKey ?? null, status: "active", hasAccess: true, ...over };
|
||||
}
|
||||
|
||||
describe("planVaultRekey", () => {
|
||||
it("re-encrypts every secret under a new key without changing any value", async () => {
|
||||
const me = await generateIdentityKeyPair();
|
||||
const values = { API_KEY: "sk-live-abc123", DB_URL: "postgres://u:p@h/db" };
|
||||
const { dek: oldDek, secrets, wrapped } = await makeVault(values, [me]);
|
||||
|
||||
const plan = await planVaultRekey({
|
||||
myWrappedDek: wrapped[0],
|
||||
identity: me,
|
||||
secrets,
|
||||
members: [member("me@example.com", me)]
|
||||
});
|
||||
|
||||
// The new grant opens a DEK that is genuinely different...
|
||||
const newDek = await unwrapVaultKey(plan.grants[0].wrappedDek, me);
|
||||
expect(newDek).not.toBe(oldDek);
|
||||
|
||||
// ...and every value survives the trip unchanged.
|
||||
for (const secret of plan.secrets) {
|
||||
const roundTripped = await decryptValue({ nonce: secret.nonce, ciphertext: secret.ciphertext }, newDek);
|
||||
expect(roundTripped).toBe(values[secret.name as keyof typeof values]);
|
||||
}
|
||||
// Fingerprints are the contract the server checks: same value, same print.
|
||||
expect(plan.secrets.map((s) => s.fingerprint).sort()).toEqual(secrets.map((s) => s.fingerprint).sort());
|
||||
});
|
||||
|
||||
it("makes the OLD key useless against the rotated ciphertext", async () => {
|
||||
const me = await generateIdentityKeyPair();
|
||||
const { dek: oldDek, secrets, wrapped } = await makeVault({ TOKEN: "hunter2" }, [me]);
|
||||
|
||||
const plan = await planVaultRekey({ myWrappedDek: wrapped[0], identity: me, secrets, members: [member("me@example.com", me)] });
|
||||
|
||||
// This is the entire point of rotating: a leaked old DEK buys nothing.
|
||||
await expect(
|
||||
decryptValue({ nonce: plan.secrets[0].nonce, ciphertext: plan.secrets[0].ciphertext }, oldDek)
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("drops a departed member, and their old grant no longer opens the vault", async () => {
|
||||
const me = await generateIdentityKeyPair();
|
||||
const leaver = await generateIdentityKeyPair();
|
||||
const { secrets, wrapped } = await makeVault({ TOKEN: "hunter2" }, [me, leaver]);
|
||||
const leaverOldGrant = wrapped[1];
|
||||
|
||||
const plan = await planVaultRekey({
|
||||
myWrappedDek: wrapped[0],
|
||||
identity: me,
|
||||
secrets,
|
||||
// The leaver is still on the vault but is no longer an active member.
|
||||
members: [member("me@example.com", me), member("leaver@example.com", leaver, { status: "invited" })]
|
||||
});
|
||||
|
||||
expect(plan.grants.map((g) => g.email)).toEqual(["me@example.com"]);
|
||||
expect(plan.revoked).toEqual(["leaver@example.com"]);
|
||||
|
||||
// The leaver's old grant still opens the OLD dek — but that dek is now
|
||||
// worthless against the re-encrypted ciphertext.
|
||||
const staleDek = await unwrapVaultKey(leaverOldGrant, leaver);
|
||||
await expect(
|
||||
decryptValue({ nonce: plan.secrets[0].nonce, ciphertext: plan.secrets[0].ciphertext }, staleDek)
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("--all keeps a non-active member who holds access", async () => {
|
||||
const me = await generateIdentityKeyPair();
|
||||
const other = await generateIdentityKeyPair();
|
||||
const { secrets, wrapped } = await makeVault({ TOKEN: "hunter2" }, [me, other]);
|
||||
|
||||
const plan = await planVaultRekey({
|
||||
myWrappedDek: wrapped[0],
|
||||
identity: me,
|
||||
secrets,
|
||||
members: [member("me@example.com", me), member("other@example.com", other, { status: "invited" })],
|
||||
scope: "all"
|
||||
});
|
||||
|
||||
expect(plan.grants.map((g) => g.email).sort()).toEqual(["me@example.com", "other@example.com"]);
|
||||
expect(plan.revoked).toEqual([]);
|
||||
// And the kept member can actually read the rotated vault.
|
||||
const theirDek = await unwrapVaultKey(plan.grants.find((g) => g.email === "other@example.com")!.wrappedDek, other);
|
||||
expect(await decryptValue({ nonce: plan.secrets[0].nonce, ciphertext: plan.secrets[0].ciphertext }, theirDek)).toBe("hunter2");
|
||||
});
|
||||
|
||||
it("never drops a member silently when they have no key to re-seal to", async () => {
|
||||
const me = await generateIdentityKeyPair();
|
||||
const { secrets, wrapped } = await makeVault({ TOKEN: "hunter2" }, [me]);
|
||||
|
||||
const plan = await planVaultRekey({
|
||||
myWrappedDek: wrapped[0],
|
||||
identity: me,
|
||||
secrets,
|
||||
members: [member("me@example.com", me), member("keyless@example.com", null)]
|
||||
});
|
||||
|
||||
expect(plan.skipped).toEqual([{ email: "keyless@example.com", reason: "no public key on file" }]);
|
||||
expect(plan.revoked).toContain("keyless@example.com");
|
||||
});
|
||||
|
||||
it("refuses to rotate a vault into a state nobody can read", async () => {
|
||||
const me = await generateIdentityKeyPair();
|
||||
const { secrets, wrapped } = await makeVault({ TOKEN: "hunter2" }, [me]);
|
||||
|
||||
await expect(
|
||||
planVaultRekey({
|
||||
myWrappedDek: wrapped[0],
|
||||
identity: me,
|
||||
secrets,
|
||||
members: [member("me@example.com", me, { status: "invited" })]
|
||||
})
|
||||
).rejects.toThrow(/no member would keep access/i);
|
||||
});
|
||||
|
||||
it("aborts on a secret that does not decrypt rather than dropping it", async () => {
|
||||
const me = await generateIdentityKeyPair();
|
||||
const { secrets, wrapped } = await makeVault({ GOOD: "value" }, [me]);
|
||||
const corrupted = [...secrets, { name: "BAD", nonce: secrets[0].nonce, ciphertext: secrets[0].ciphertext.replace(/^./, "A"), fingerprint: fingerprintValue("x") }];
|
||||
|
||||
await expect(
|
||||
planVaultRekey({ myWrappedDek: wrapped[0], identity: me, secrets: corrupted, members: [member("me@example.com", me)] })
|
||||
).rejects.toThrow(/did not decrypt|inconsistent/i);
|
||||
});
|
||||
|
||||
it("aborts when a stored fingerprint disagrees with its ciphertext", async () => {
|
||||
const me = await generateIdentityKeyPair();
|
||||
const { secrets, wrapped } = await makeVault({ TOKEN: "hunter2" }, [me]);
|
||||
const tampered = [{ ...secrets[0], fingerprint: fingerprintValue("something-else") }];
|
||||
|
||||
await expect(
|
||||
planVaultRekey({ myWrappedDek: wrapped[0], identity: me, secrets: tampered, members: [member("me@example.com", me)] })
|
||||
).rejects.toThrow(/fingerprint/i);
|
||||
});
|
||||
|
||||
it("rotates an empty vault without inventing secrets", async () => {
|
||||
const me = await generateIdentityKeyPair();
|
||||
const { wrapped } = await makeVault({}, [me]);
|
||||
|
||||
const plan = await planVaultRekey({ myWrappedDek: wrapped[0], identity: me, secrets: [], members: [member("me@example.com", me)] });
|
||||
expect(plan.secrets).toEqual([]);
|
||||
expect(plan.grants).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
155
plugins/credential-sharing/src/rekey.ts
Normal file
155
plugins/credential-sharing/src/rekey.ts
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
/**
|
||||
* Vault re-keying (rotation) for LogicSRC team vaults.
|
||||
*
|
||||
* Re-keying replaces a vault's data-encryption key. Every secret is decrypted
|
||||
* with the old DEK and re-encrypted under a new one, and the new DEK is sealed
|
||||
* afresh to each member who should keep access. Secret VALUES never change --
|
||||
* that is the whole point. Nothing downstream breaks; what changes is that
|
||||
* every previously-issued wrapped DEK becomes useless, so anyone dropped from
|
||||
* the grant list can no longer read the vault even if they kept a copy of their
|
||||
* old grant.
|
||||
*
|
||||
* This module is deliberately pure: it takes the current sealed state plus the
|
||||
* caller's identity and returns the complete next state. All of it runs on the
|
||||
* member's machine -- the server receives ciphertext and sealed keys only, and
|
||||
* never sees either DEK.
|
||||
*
|
||||
* Ordering matters and is NOT this module's problem: a half-applied rotation
|
||||
* (new grants, old ciphertext, or the reverse) locks everyone out permanently,
|
||||
* because the DEK is recoverable only through the grants. The server applies
|
||||
* the result of `planVaultRekey` in a single transaction; see the
|
||||
* /vaults/:id/rekey endpoint.
|
||||
*/
|
||||
import { decryptValue, encryptValue, generateVaultKey, unwrapVaultKey, wrapVaultKey, type IdentityKeyPair } from "./crypto.js";
|
||||
import { fingerprintValue, fingerprintsEqual } from "./fingerprint.js";
|
||||
|
||||
/** A secret as the server stores it. */
|
||||
export interface SealedSecret {
|
||||
name: string;
|
||||
nonce: string;
|
||||
ciphertext: string;
|
||||
fingerprint: string;
|
||||
}
|
||||
|
||||
/** A member who is a candidate to receive the new DEK. */
|
||||
export interface RekeyMember {
|
||||
email: string;
|
||||
/** X25519 public key, or null if they have never uploaded one. */
|
||||
publicKey: string | null;
|
||||
/** Team membership status. Only "active" members are kept by default. */
|
||||
status: "active" | "invited";
|
||||
/** Whether they hold a grant on this vault today. */
|
||||
hasAccess: boolean;
|
||||
}
|
||||
|
||||
export interface RekeyPlanInput {
|
||||
/** The caller's own wrapped DEK, which bootstraps the whole operation. */
|
||||
myWrappedDek: string;
|
||||
/** The caller's identity keypair. */
|
||||
identity: IdentityKeyPair;
|
||||
/** Every secret currently in the vault. */
|
||||
secrets: SealedSecret[];
|
||||
/** Every team member, with their current access. */
|
||||
members: RekeyMember[];
|
||||
/**
|
||||
* Who keeps access.
|
||||
* - "active" (default): only members whose team status is "active" AND who
|
||||
* hold a grant today. This is the "someone left the team" rotation.
|
||||
* - "all": everyone holding a grant today, whatever their status. Pure
|
||||
* crypto hygiene -- re-key without revoking anyone.
|
||||
*/
|
||||
scope?: "active" | "all";
|
||||
}
|
||||
|
||||
export interface RekeyPlan {
|
||||
/** Re-encrypted secrets, ready to write. Values are identical to the input. */
|
||||
secrets: SealedSecret[];
|
||||
/** New sealed DEKs, one per retained member. */
|
||||
grants: Array<{ email: string; wrappedDek: string }>;
|
||||
/** Members whose access this rotation removes. */
|
||||
revoked: string[];
|
||||
/** Members skipped because they have no public key to seal to. */
|
||||
skipped: Array<{ email: string; reason: string }>;
|
||||
}
|
||||
|
||||
/** Members who have no key yet cannot be sealed to, whatever the scope. */
|
||||
function sealable(member: RekeyMember): boolean {
|
||||
return typeof member.publicKey === "string" && member.publicKey.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the complete next state of a vault under a fresh DEK.
|
||||
*
|
||||
* Throws rather than returning a partial plan: a rotation that silently dropped
|
||||
* a secret it could not decrypt would destroy it on write.
|
||||
*/
|
||||
export async function planVaultRekey(input: RekeyPlanInput): Promise<RekeyPlan> {
|
||||
const scope = input.scope ?? "active";
|
||||
|
||||
const oldDek = await unwrapVaultKey(input.myWrappedDek, input.identity);
|
||||
const newDek = await generateVaultKey();
|
||||
|
||||
// Decrypt everything BEFORE encrypting anything. If one secret fails to open
|
||||
// we abort with the vault untouched, rather than writing a half-rotated set.
|
||||
const plaintext = new Map<string, string>();
|
||||
for (const secret of input.secrets) {
|
||||
let value: string;
|
||||
try {
|
||||
value = await decryptValue({ nonce: secret.nonce, ciphertext: secret.ciphertext }, oldDek);
|
||||
} catch {
|
||||
throw new Error(
|
||||
`Cannot rotate: "${secret.name}" did not decrypt with your vault key. The vault may already be mid-rotation, or your grant is stale — re-run after a member with access re-grants you.`
|
||||
);
|
||||
}
|
||||
// The fingerprint is a deterministic hash of the value, so a mismatch here
|
||||
// means the stored row was already inconsistent. Refuse to propagate it.
|
||||
if (!fingerprintsEqual(secret.fingerprint, fingerprintValue(value))) {
|
||||
throw new Error(
|
||||
`Cannot rotate: "${secret.name}" has a fingerprint that does not match its ciphertext. Refusing to re-encrypt a record that is already inconsistent.`
|
||||
);
|
||||
}
|
||||
plaintext.set(secret.name, value);
|
||||
}
|
||||
|
||||
const secrets: SealedSecret[] = [];
|
||||
for (const secret of input.secrets) {
|
||||
const value = plaintext.get(secret.name) as string;
|
||||
const sealed = await encryptValue(value, newDek);
|
||||
secrets.push({
|
||||
name: secret.name,
|
||||
nonce: sealed.nonce,
|
||||
ciphertext: sealed.ciphertext,
|
||||
// Unchanged by construction -- the value did not change. Recomputed
|
||||
// rather than copied so a bug here surfaces as a server-side rejection.
|
||||
fingerprint: fingerprintValue(value)
|
||||
});
|
||||
}
|
||||
|
||||
const grants: Array<{ email: string; wrappedDek: string }> = [];
|
||||
const revoked: string[] = [];
|
||||
const skipped: Array<{ email: string; reason: string }> = [];
|
||||
|
||||
for (const member of input.members) {
|
||||
const keep = member.hasAccess && (scope === "all" || member.status === "active");
|
||||
if (!keep) {
|
||||
if (member.hasAccess) revoked.push(member.email);
|
||||
continue;
|
||||
}
|
||||
if (!sealable(member)) {
|
||||
// Holds access today but has no key to re-seal to. Rotating would cut
|
||||
// them off silently, so surface it instead of burying it.
|
||||
skipped.push({ email: member.email, reason: "no public key on file" });
|
||||
revoked.push(member.email);
|
||||
continue;
|
||||
}
|
||||
grants.push({ email: member.email, wrappedDek: await wrapVaultKey(newDek, member.publicKey as string) });
|
||||
}
|
||||
|
||||
if (grants.length === 0) {
|
||||
throw new Error(
|
||||
"Cannot rotate: no member would keep access, which would make the vault permanently unreadable. Grant at least one active member with a registered key first."
|
||||
);
|
||||
}
|
||||
|
||||
return { secrets, grants, revoked, skipped };
|
||||
}
|
||||
|
|
@ -11,7 +11,7 @@ import type { LogicSrcPrincipal, LogicSrcPolicyDecision } from "@logicsrc/accoun
|
|||
* - Adapters declare read/write capabilities before a plan is generated.
|
||||
*/
|
||||
|
||||
export type CredentialProviderId = "env" | "doppler" | "railway" | "github-secrets" | (string & {});
|
||||
export type CredentialProviderId = "env" | "doppler" | "railway" | "github-secrets" | "sh1pt" | "team" | (string & {});
|
||||
|
||||
export interface CredentialProviderCapabilities {
|
||||
/** Adapter can read raw secret values (enables value-level fingerprint diffs). */
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue