mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-12-01 01:14:47 +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
|
|
@ -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;
|
||||
}
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue