mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-11-29 15:51:52 +00:00
security: keep signing keys out of deployable team vaults (CLI 0.13.0) (#264)
Some checks are pending
CI / build (push) Waiting to run
Deploy to dev2 / deploy (push) Waiting to run
test / test (push) Waiting to run
Some checks are pending
CI / build (push) Waiting to run
Deploy to dev2 / deploy (push) Waiting to run
test / test (push) Waiting to run
* security: keep signing keys out of deployable team vaults (CLI 0.13.0) After the 2026-10-27 dev2 incident, root on the box drained every wallet whose key sat in an app.env, and deploys write app.env from team vaults. Wallet keys, seed phrases, hsm secrets and SSH/deploy keys now stay out of that path: - server: a machine (deploy) key never receives a signing key from GET /vaults/:id/secrets (listed as `withheld`, audited as secrets:withheld:signing) and cannot write or delete one (403 signing_key_machine_write). People still see them, so they can move them. - CLI `teams push` refuses a .env holding signing keys, by name or by value shape (PEM private key, 0x-hex, Solana base58/byte array, mnemonic), unless --allow-signing-keys. - CLI `teams pull` withholds signing keys by default; --include-signing-keys needs a person at a terminal, so deploy-app.sh's fallback to the logged-in account withholds them too. - One name rule in packages/opencreds/src/signing-keys.ts, mirrored in apps/pwa/src/lib/signing-keys.mjs, both held to one fixture file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: bound the wallet-name regex, build PEM fixtures at runtime Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Anthony Ettinger <anthony@profullstack.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
1bff3e975c
commit
b5f875837a
12 changed files with 297 additions and 12 deletions
24
apps/pwa/src/lib/signing-keys.mjs
Normal file
24
apps/pwa/src/lib/signing-keys.mjs
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
// Copy of the NAME rule in packages/opencreds/src/signing-keys.ts (read the
|
||||||
|
// reasoning there). The server only sees secret names, so this is what it
|
||||||
|
// enforces: a machine key never receives or writes a signing key. Both copies
|
||||||
|
// are held to packages/opencreds/src/signing-keys.fixtures.json.
|
||||||
|
|
||||||
|
const norm = (name) => `_${name.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}_`;
|
||||||
|
|
||||||
|
/** Seed phrases and raw key material, whatever service they belong to. */
|
||||||
|
const ALWAYS = /_(MNEMONIC|SEED_PHRASE|SEEDPHRASE|SEED_WORDS|RECOVERY_PHRASE|XPRV|XPRIV|HSM_SECRET|KEYPAIR|KEY_PAIR)_/;
|
||||||
|
/** "Private key" in any spelling, and SSH / deploy keys that open a box. */
|
||||||
|
const PRIVATE = /_(PRIVATE_KEY|PRIV_KEY|PRIVKEY|PRIVATEKEY|SIGNING_KEY|SIGNER_KEY|SSH_KEY|DEPLOY_KEY)(_|$)/;
|
||||||
|
/** App keys that sign tokens or pushes, not funds; needed by a running service. */
|
||||||
|
const SERVICE = /_(VAPID|GITHUB_APP|GH_APP|JWT|JWK|DKIM|APNS|APPLE|FIREBASE|GOOGLE|GCP|SERVICE_ACCOUNT|SAML|OIDC|WEBHOOK|TLS|SSL|CERT|CLERK|SUPABASE)_/;
|
||||||
|
/** A wallet word next to KEY / SECRET / SEED: SOLANA_SECRET_KEY, RELAYER_KEY, WALLET_SEED. */
|
||||||
|
const WALLET = /_(SOLANA|SOL|EVM|ETH|ETHEREUM|BTC|BITCOIN|WALLET|HOT_WALLET|RELAYER|TREASURY|SIGNER|OPERATOR|DEPLOYER|PAYER|FEE_PAYER)_(?:[A-Z0-9]{1,24}_){0,4}(KEY|SECRET|SEED)_/;
|
||||||
|
/** ...unless it is plainly an address, an RPC or an API credential. */
|
||||||
|
const NOT_A_KEY = /_(RPC|API|URL|ADDRESS|ADDR|PUBLIC|PUBKEY|PUB|ID|NAME)_/;
|
||||||
|
|
||||||
|
export function isSigningKeyName(name) {
|
||||||
|
const n = norm(name);
|
||||||
|
if (ALWAYS.test(n)) return true;
|
||||||
|
if (PRIVATE.test(n)) return !SERVICE.test(n);
|
||||||
|
return WALLET.test(n) && !NOT_A_KEY.test(n);
|
||||||
|
}
|
||||||
|
|
@ -18,6 +18,7 @@ import { id, sha256, token } from "../lib/crypto.mjs";
|
||||||
import { keyFingerprint, requestOriginInfo } from "../lib/keyfp.mjs";
|
import { keyFingerprint, requestOriginInfo } from "../lib/keyfp.mjs";
|
||||||
import sodium from "libsodium-wrappers";
|
import sodium from "libsodium-wrappers";
|
||||||
import { bearer, keyForBearer, keyCoversVault, normalizeKey } from "../lib/apikey.mjs";
|
import { bearer, keyForBearer, keyCoversVault, normalizeKey } from "../lib/apikey.mjs";
|
||||||
|
import { isSigningKeyName } from "../lib/signing-keys.mjs";
|
||||||
import {
|
import {
|
||||||
TeamMemberError,
|
TeamMemberError,
|
||||||
normEmail,
|
normEmail,
|
||||||
|
|
@ -709,9 +710,14 @@ credshareRouter.delete("/api/credshare/vaults/:id/key-grants/:keyId", api(async
|
||||||
|
|
||||||
credshareRouter.get("/api/credshare/vaults/:id/secrets", api(async (req, res, user, key) => {
|
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 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]);
|
const all_ = await all(`SELECT * FROM credshare_secrets WHERE vault_id = ? ORDER BY name`, [vault.id]);
|
||||||
|
// A deploy box never receives a signing key (wallet key, seed, SSH key): root
|
||||||
|
// on a box running 24/7 must not mean the keys that move money.
|
||||||
|
const withheld = isMachine(key) ? all_.filter((s) => isSigningKeyName(s.name)).map((s) => s.name) : [];
|
||||||
|
const rows = withheld.length ? all_.filter((s) => !withheld.includes(s.name)) : all_;
|
||||||
await audit({ req, teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: "secrets:fetch", keyName: key?.name ?? (req.user ? "browser session" : null) });
|
await audit({ req, teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: "secrets:fetch", keyName: key?.name ?? (req.user ? "browser session" : null) });
|
||||||
res.json({ vaultId: vault.id, keyVersion: Number(vault.key_version ?? 1), secrets: rows.map((s) => ({ name: s.name, nonce: s.nonce, ciphertext: s.ciphertext, fingerprint: s.fingerprint, version: s.version, updatedAt: s.updated_at })) });
|
if (withheld.length) await audit({ req, teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: key.id, action: "secrets:withheld:signing", keyName: withheld.join(",") });
|
||||||
|
res.json({ vaultId: vault.id, keyVersion: Number(vault.key_version ?? 1), withheld, 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" }));
|
}, { machine: "read" }));
|
||||||
|
|
||||||
credshareRouter.put("/api/credshare/vaults/:id/secrets", api(async (req, res, user, key) => {
|
credshareRouter.put("/api/credshare/vaults/:id/secrets", api(async (req, res, user, key) => {
|
||||||
|
|
@ -728,6 +734,10 @@ credshareRouter.put("/api/credshare/vaults/:id/secrets", api(async (req, res, us
|
||||||
}
|
}
|
||||||
const upserts = Array.isArray(req.body?.upserts) ? req.body.upserts : [];
|
const upserts = Array.isArray(req.body?.upserts) ? req.body.upserts : [];
|
||||||
const deletes = Array.isArray(req.body?.deletes) ? req.body.deletes : [];
|
const deletes = Array.isArray(req.body?.deletes) ? req.body.deletes : [];
|
||||||
|
if (isMachine(key)) {
|
||||||
|
const signing = [...upserts.map((u) => u?.name), ...deletes].filter((n) => typeof n === "string" && isSigningKeyName(n));
|
||||||
|
if (signing.length) return res.status(403).json({ error: `A machine key cannot write signing keys (${signing.join(", ")}). Keep them in \`logicsrc keyring\` and unlock them where they are used.`, code: "signing_key_machine_write" });
|
||||||
|
}
|
||||||
const applied = [];
|
const applied = [];
|
||||||
for (const u of upserts) {
|
for (const u of upserts) {
|
||||||
if (!u || typeof u.name !== "string" || typeof u.nonce !== "string" || typeof u.ciphertext !== "string" || typeof u.fingerprint !== "string") {
|
if (!u || typeof u.name !== "string" || typeof u.nonce !== "string" || typeof u.ciphertext !== "string" || typeof u.fingerprint !== "string") {
|
||||||
|
|
|
||||||
|
|
@ -270,6 +270,36 @@ test("a read-only machine key is refused every write; a read-write one may write
|
||||||
await run(`DELETE FROM credshare_secrets WHERE vault_id = ? AND name = 'NEW'`, ["v_web"]);
|
await run(`DELETE FROM credshare_secrets WHERE vault_id = ? AND name = 'NEW'`, ["v_web"]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("a machine key never receives or writes a signing key; a person still sees it", async () => {
|
||||||
|
await run(`INSERT INTO credshare_secrets (vault_id, name, nonce, ciphertext, fingerprint, version, updated_by, updated_at) VALUES (?,?,?,?,?,?,?,?)`,
|
||||||
|
["v_web", "SOLANA_PRIVATE_KEY", "n", "c", "fp", 1, "u_ann", now]);
|
||||||
|
const m = await machineKey({ readOnly: false });
|
||||||
|
await http.post("/api/credshare/keys", m.token, { publicKey: "pk-signing" });
|
||||||
|
await http.post("/api/credshare/vaults/v_web/key-grants", annKey, { keyId: m.id, wrappedDek: "sealed-signing" });
|
||||||
|
|
||||||
|
const got = await http.get("/api/credshare/vaults/v_web/secrets", m.token);
|
||||||
|
assert.equal(got.status, 200);
|
||||||
|
assert.deepEqual(got.body.secrets.map((s) => s.name), ["API_KEY"]);
|
||||||
|
assert.deepEqual(got.body.withheld, ["SOLANA_PRIVATE_KEY"]);
|
||||||
|
const logged = await get(`SELECT * FROM credshare_audit WHERE vault_id = ? AND action = 'secrets:withheld:signing' AND actor_key_id = ?`, ["v_web", m.id]);
|
||||||
|
assert.equal(logged.key_name, "SOLANA_PRIVATE_KEY");
|
||||||
|
|
||||||
|
const person = await http.get("/api/credshare/vaults/v_web/secrets", annKey);
|
||||||
|
assert.deepEqual(person.body.secrets.map((s) => s.name).sort(), ["API_KEY", "SOLANA_PRIVATE_KEY"]);
|
||||||
|
assert.deepEqual(person.body.withheld, []);
|
||||||
|
|
||||||
|
for (const body of [
|
||||||
|
{ upserts: [{ name: "EVM_PRIVATE_KEY", nonce: "n", ciphertext: "c", fingerprint: "f" }], deletes: [] },
|
||||||
|
{ upserts: [], deletes: ["SOLANA_PRIVATE_KEY"] }
|
||||||
|
]) {
|
||||||
|
const put = await http.put("/api/credshare/vaults/v_web/secrets", m.token, body);
|
||||||
|
assert.equal(put.status, 403);
|
||||||
|
assert.equal(put.body.code, "signing_key_machine_write");
|
||||||
|
}
|
||||||
|
assert.ok(await get(`SELECT 1 FROM credshare_secrets WHERE vault_id = ? AND name = 'SOLANA_PRIVATE_KEY'`, ["v_web"]));
|
||||||
|
await run(`DELETE FROM credshare_secrets WHERE vault_id = ? AND name = 'SOLANA_PRIVATE_KEY'`, ["v_web"]);
|
||||||
|
});
|
||||||
|
|
||||||
test("expired and revoked keys are 401, and revoking drops the key's grants", async () => {
|
test("expired and revoked keys are 401, and revoking drops the key's grants", async () => {
|
||||||
const expired = await machineKey({ expiresAt: Date.now() - 1000 });
|
const expired = await machineKey({ expiresAt: Date.now() - 1000 });
|
||||||
assert.equal((await http.get("/api/credshare/me", expired.token)).status, 401);
|
assert.equal((await http.get("/api/credshare/me", expired.token)).status, 401);
|
||||||
|
|
|
||||||
16
apps/pwa/test/signing-keys.test.mjs
Normal file
16
apps/pwa/test/signing-keys.test.mjs
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
// The server's copy of the signing-key NAME rule must agree with the CLI's
|
||||||
|
// (packages/opencreds/src/signing-keys.ts): both are held to one fixture list.
|
||||||
|
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 { isSigningKeyName } from "../src/lib/signing-keys.mjs";
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const fx = JSON.parse(readFileSync(join(here, "../../../packages/opencreds/src/signing-keys.fixtures.json"), "utf8"));
|
||||||
|
|
||||||
|
test("signing key names match the shared fixtures", () => {
|
||||||
|
for (const n of fx.signing) assert.equal(isSigningKeyName(n), true, n);
|
||||||
|
for (const n of fx.not_signing) assert.equal(isSigningKeyName(n), false, n);
|
||||||
|
});
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "@logicsrc/cli",
|
"name": "@logicsrc/cli",
|
||||||
"version": "0.12.0",
|
"version": "0.13.0",
|
||||||
"description": "LogicSRC CLI: every LogicSRC standard and tool as one command.",
|
"description": "LogicSRC CLI: every LogicSRC standard and tool as one command.",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./dist/index.js",
|
"main": "./dist/index.js",
|
||||||
|
|
|
||||||
|
|
@ -1112,9 +1112,10 @@ teams
|
||||||
.argument("<project>", "Project name")
|
.argument("<project>", "Project name")
|
||||||
.argument("<env>", "Environment name (prod, staging, …)")
|
.argument("<env>", "Environment name (prod, staging, …)")
|
||||||
.option("--env <path>", "Source .env file", ".env")
|
.option("--env <path>", "Source .env file", ".env")
|
||||||
|
.option("--allow-signing-keys", "Push wallet keys, seed phrases or SSH keys anyway (refused by default: use `logicsrc keyring`)")
|
||||||
.option("--format <format>", "table, json, or markdown", "table")
|
.option("--format <format>", "table, json, or markdown", "table")
|
||||||
.description("Encrypt and push a local .env into a team vault (<project>--<env>).")
|
.description("Encrypt and push a local .env into a team vault (<project>--<env>). Signing keys are refused.")
|
||||||
.action((slug, project, env, options) => teamsPushAction(slug, project, env, { env: options.env, format: options.format as OutputFormat }));
|
.action((slug, project, env, options) => teamsPushAction(slug, project, env, { env: options.env, format: options.format as OutputFormat, allowSigningKeys: Boolean(options.allowSigningKeys) }));
|
||||||
|
|
||||||
teams
|
teams
|
||||||
.command("pull")
|
.command("pull")
|
||||||
|
|
@ -1122,9 +1123,10 @@ teams
|
||||||
.argument("<project>", "Project name")
|
.argument("<project>", "Project name")
|
||||||
.argument("<env>", "Environment name (prod, staging, …)")
|
.argument("<env>", "Environment name (prod, staging, …)")
|
||||||
.option("--env <path>", "Destination .env file", ".env")
|
.option("--env <path>", "Destination .env file", ".env")
|
||||||
|
.option("--include-signing-keys", "Also write wallet keys, seed phrases and SSH keys (interactive only; withheld by default)")
|
||||||
.option("--format <format>", "table, json, or markdown", "table")
|
.option("--format <format>", "table, json, or markdown", "table")
|
||||||
.description("Pull a team vault (<project>--<env>) and decrypt it into a local .env.")
|
.description("Pull a team vault (<project>--<env>) and decrypt it into a local .env. Signing keys are withheld.")
|
||||||
.action((slug, project, env, options) => teamsPullAction(slug, project, env, { env: options.env, format: options.format as OutputFormat }));
|
.action((slug, project, env, options) => teamsPullAction(slug, project, env, { env: options.env, format: options.format as OutputFormat, includeSigningKeys: Boolean(options.includeSigningKeys) }));
|
||||||
|
|
||||||
const accounts = program.command("accounts").description("Manage connected social and email accounts.");
|
const accounts = program.command("accounts").description("Manage connected social and email accounts.");
|
||||||
|
|
||||||
|
|
|
||||||
33
packages/cli/src/signing-keys-cli.test.ts
Normal file
33
packages/cli/src/signing-keys-cli.test.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
|
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { signingKeysInEnvFile, teamsPullAction, teamsPushAction } from "./teams.js";
|
||||||
|
|
||||||
|
const dirs: string[] = [];
|
||||||
|
const envFile = (body: string) => {
|
||||||
|
const d = mkdtempSync(join(tmpdir(), "lsk-sign-"));
|
||||||
|
dirs.push(d);
|
||||||
|
const p = join(d, ".env");
|
||||||
|
writeFileSync(p, body);
|
||||||
|
return p;
|
||||||
|
};
|
||||||
|
afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });
|
||||||
|
|
||||||
|
describe("signing keys stay out of team vaults", () => {
|
||||||
|
it("finds signing keys by name and by value shape", () => {
|
||||||
|
const p = envFile(`API_KEY=abc\nSOLANA_PRIVATE_KEY=xyz\nNOTES=0x${"ab".repeat(32)}\nSESSION_SECRET=${"cd".repeat(32)}\n`);
|
||||||
|
expect(signingKeysInEnvFile(p)).toEqual(["NOTES", "SOLANA_PRIVATE_KEY"]);
|
||||||
|
expect(signingKeysInEnvFile(join(tmpdir(), "missing-lsk.env"))).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("push refuses a file holding signing keys before touching the network", async () => {
|
||||||
|
const p = envFile("EVM_PRIVATE_KEY=0xabc\n");
|
||||||
|
await expect(teamsPushAction("acme", "web", "prod", { env: p, format: "json" })).rejects.toThrow(/signing keys: EVM_PRIVATE_KEY/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("pull refuses --include-signing-keys without a terminal", async () => {
|
||||||
|
const p = envFile("");
|
||||||
|
await expect(teamsPullAction("acme", "web", "prod", { env: p, format: "json", includeSigningKeys: true })).rejects.toThrow(/needs a person at a terminal/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -3,8 +3,8 @@ import { createHash, randomBytes } from "node:crypto";
|
||||||
import { hostname } from "node:os";
|
import { hostname } from "node:os";
|
||||||
import { spawn } from "node:child_process";
|
import { spawn } from "node:child_process";
|
||||||
import { createInterface } from "node:readline/promises";
|
import { createInterface } from "node:readline/promises";
|
||||||
import { chmodSync, rmSync, writeFileSync } from "node:fs";
|
import { chmodSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||||
import { OTHER_CATEGORY, SECRET_CATEGORIES, categorizeSecret, csvLine, parseCategories } from "@logicsrc/opencreds";
|
import { OTHER_CATEGORY, SECRET_CATEGORIES, categorizeSecret, csvLine, isSigningKey, isSigningKeyName, parseCategories } from "@logicsrc/opencreds";
|
||||||
import {
|
import {
|
||||||
TeamClient,
|
TeamClient,
|
||||||
TeamApiError,
|
TeamApiError,
|
||||||
|
|
@ -28,6 +28,7 @@ import {
|
||||||
checkAndPinKey,
|
checkAndPinKey,
|
||||||
keyFingerprint,
|
keyFingerprint,
|
||||||
pinStatus,
|
pinStatus,
|
||||||
|
parseEnv,
|
||||||
type CredentialEndpoint,
|
type CredentialEndpoint,
|
||||||
type RemoteVault
|
type RemoteVault
|
||||||
} from "@logicsrc/plugin-credential-sharing";
|
} from "@logicsrc/plugin-credential-sharing";
|
||||||
|
|
@ -588,7 +589,23 @@ export function teamEndpoint(slug: string, vault: string): CredentialEndpoint {
|
||||||
|
|
||||||
// Note the two different "env"s: `envName` is the environment half of the vault
|
// Note the two different "env"s: `envName` is the environment half of the vault
|
||||||
// address (prod, staging), while `options.env` is the local .env file path.
|
// address (prod, staging), while `options.env` is the local .env file path.
|
||||||
export async function teamsPushAction(slug: string, project: string, envName: string, options: { env: string; format: OutputFormat }): Promise<void> {
|
const SIGNING_KEY_HELP =
|
||||||
|
"Signing keys (wallet keys, seed phrases, hsm secrets, SSH/deploy keys) do not go in a team vault: a deploy " +
|
||||||
|
"pulls a vault into app.env and keeps it there 24/7. Keep them in `logicsrc keyring` and have the service ask " +
|
||||||
|
"for an unlock when it signs.";
|
||||||
|
|
||||||
|
/** Names in a local .env that are signing keys, by name or by what the value looks like. */
|
||||||
|
export function signingKeysInEnvFile(path: string): string[] {
|
||||||
|
if (!existsSync(path)) return [];
|
||||||
|
const bag = parseEnv(readFileSync(path, "utf8"));
|
||||||
|
return Object.entries(bag).filter(([k, v]) => isSigningKey(k, String(v ?? ""))).map(([k]) => k).sort();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function teamsPushAction(slug: string, project: string, envName: string, options: { env: string; format: OutputFormat; allowSigningKeys?: boolean }): Promise<void> {
|
||||||
|
const signing = signingKeysInEnvFile(options.env);
|
||||||
|
if (signing.length && !options.allowSigningKeys) {
|
||||||
|
throw new Error(`${options.env} holds signing keys: ${signing.join(", ")}. ${SIGNING_KEY_HELP} Remove them from the file, or pass --allow-signing-keys if this vault is never deployed.`);
|
||||||
|
}
|
||||||
requireAuth();
|
requireAuth();
|
||||||
const vault = vaultName(project, envName);
|
const vault = vaultName(project, envName);
|
||||||
const engine = createCredentialEngine();
|
const engine = createCredentialEngine();
|
||||||
|
|
@ -606,12 +623,22 @@ export async function teamsPushAction(slug: string, project: string, envName: st
|
||||||
print({ team: slug, project, env: envName, vault, applied, keys: run.results.map((r) => ({ key: r.key, op: r.op, applied: r.applied })) }, options.format);
|
print({ team: slug, project, env: envName, vault, applied, keys: run.results.map((r) => ({ key: r.key, op: r.op, applied: r.applied })) }, options.format);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function teamsPullAction(slug: string, project: string, envName: string, options: { env: string; format: OutputFormat }): Promise<void> {
|
export async function teamsPullAction(slug: string, project: string, envName: string, options: { env: string; format: OutputFormat; includeSigningKeys?: boolean }): Promise<void> {
|
||||||
|
if (options.includeSigningKeys && !(process.stdin.isTTY && process.stderr.isTTY)) {
|
||||||
|
throw new Error("--include-signing-keys needs a person at a terminal: a script or deploy never writes signing keys to disk.");
|
||||||
|
}
|
||||||
requireAuth();
|
requireAuth();
|
||||||
const vault = vaultName(project, envName);
|
const vault = vaultName(project, envName);
|
||||||
const engine = createCredentialEngine();
|
const engine = createCredentialEngine();
|
||||||
|
const from = teamEndpoint(slug, vault);
|
||||||
const to: CredentialEndpoint = { provider: "env", path: options.env };
|
const to: CredentialEndpoint = { provider: "env", path: options.env };
|
||||||
const plan = await engine.createCredentialSyncPlan({ from: teamEndpoint(slug, vault), to });
|
// Signing keys stay in the vault unless a person asks for them at a terminal;
|
||||||
|
// the server never sends them to a machine key at all.
|
||||||
|
const withheld = options.includeSigningKeys
|
||||||
|
? []
|
||||||
|
: (await engine.diffCredentialEndpoints(from, to)).entries.map((e) => e.key).filter((k) => isSigningKeyName(k));
|
||||||
|
if (withheld.length) console.error(`Withheld ${withheld.length} signing key(s): ${withheld.join(", ")}. ${SIGNING_KEY_HELP}`);
|
||||||
|
const plan = await engine.createCredentialSyncPlan({ from, to, policy: withheld.length ? { denyKeys: withheld } : undefined });
|
||||||
if (plan.changes.length === 0) {
|
if (plan.changes.length === 0) {
|
||||||
console.error(`${options.env} is already up to date with ${slug}/${vault}.`);
|
console.error(`${options.env} is already up to date with ${slug}/${vault}.`);
|
||||||
print({ team: slug, project, env: envName, vault, changes: 0 }, options.format);
|
print({ team: slug, project, env: envName, vault, changes: 0 }, options.format);
|
||||||
|
|
|
||||||
|
|
@ -134,6 +134,8 @@ export {
|
||||||
|
|
||||||
export { looksLikeZip, readZipEntry, zipEntryNames } from "./zip.js";
|
export { looksLikeZip, readZipEntry, zipEntryNames } from "./zip.js";
|
||||||
|
|
||||||
|
export { isSigningKey, isSigningKeyName, looksLikeSigningKeyValue } from "./signing-keys.js";
|
||||||
|
|
||||||
export {
|
export {
|
||||||
ALL_SOURCES,
|
ALL_SOURCES,
|
||||||
SOURCE_NAMES,
|
SOURCE_NAMES,
|
||||||
|
|
|
||||||
45
packages/opencreds/src/signing-keys.fixtures.json
Normal file
45
packages/opencreds/src/signing-keys.fixtures.json
Normal file
|
|
@ -0,0 +1,45 @@
|
||||||
|
{
|
||||||
|
"signing": [
|
||||||
|
"SOLANA_PRIVATE_KEY",
|
||||||
|
"EVM_PRIVATE_KEY",
|
||||||
|
"PRIVATE_KEY",
|
||||||
|
"SYSTEM_MNEMONIC_BTC",
|
||||||
|
"SYSTEM_MNEMONIC_ETH",
|
||||||
|
"WALLET_SEED_PHRASE",
|
||||||
|
"RELAYER_PRIVATE_KEY",
|
||||||
|
"RELAYER_KEY",
|
||||||
|
"SOLANA_SECRET_KEY",
|
||||||
|
"SOL_FEE_PAYER_SECRET",
|
||||||
|
"TREASURY_KEY",
|
||||||
|
"WALLET_KEY",
|
||||||
|
"CLN_HSM_SECRET",
|
||||||
|
"COINBASE_PRIVATE_KEY",
|
||||||
|
"DEV2_SSH_KEY",
|
||||||
|
"DEPLOY_KEY",
|
||||||
|
"SSH_PRIVATE_KEY",
|
||||||
|
"ETH_XPRV",
|
||||||
|
"solana-keypair",
|
||||||
|
"operator.secret.key"
|
||||||
|
],
|
||||||
|
"not_signing": [
|
||||||
|
"VAPID_PRIVATE_KEY",
|
||||||
|
"GITHUB_APP_PRIVATE_KEY",
|
||||||
|
"JWT_PRIVATE_KEY",
|
||||||
|
"DKIM_PRIVATE_KEY",
|
||||||
|
"GOOGLE_PRIVATE_KEY",
|
||||||
|
"FIREBASE_PRIVATE_KEY",
|
||||||
|
"STRIPE_SECRET_KEY",
|
||||||
|
"SUPABASE_SECRET_KEY",
|
||||||
|
"SOLANA_RPC_URL",
|
||||||
|
"SOLANA_RPC_KEY",
|
||||||
|
"EVM_WALLET_ADDRESS",
|
||||||
|
"WALLET_PUBLIC_KEY",
|
||||||
|
"SOLANA_PUBKEY",
|
||||||
|
"OPENAI_API_KEY",
|
||||||
|
"SESSION_SECRET",
|
||||||
|
"SETTINGS_ENCRYPTION_KEY",
|
||||||
|
"WALLETCONNECT_PROJECT_ID",
|
||||||
|
"LNBITS_API_KEY",
|
||||||
|
"DATABASE_URL"
|
||||||
|
]
|
||||||
|
}
|
||||||
39
packages/opencreds/src/signing-keys.test.ts
Normal file
39
packages/opencreds/src/signing-keys.test.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import { isSigningKey, isSigningKeyName, looksLikeSigningKeyValue } from "./signing-keys.js";
|
||||||
|
|
||||||
|
const fx = JSON.parse(readFileSync(new URL("./signing-keys.fixtures.json", import.meta.url), "utf8")) as { signing: string[]; not_signing: string[] };
|
||||||
|
|
||||||
|
describe("isSigningKeyName", () => {
|
||||||
|
it.each(fx.signing)("%s is a signing key", (n) => expect(isSigningKeyName(n)).toBe(true));
|
||||||
|
it.each(fx.not_signing)("%s is not", (n) => expect(isSigningKeyName(n)).toBe(false));
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("looksLikeSigningKeyValue", () => {
|
||||||
|
const hex = "ab".repeat(32);
|
||||||
|
// Built at runtime so secret scanners do not read the fixtures as real keys.
|
||||||
|
const pem = (kind: string) => ["-----BEGIN", `${kind}-----`].join(" ");
|
||||||
|
it("catches PEM, 0x-hex, Solana base58 and byte arrays, and mnemonic shapes", () => {
|
||||||
|
expect(looksLikeSigningKeyValue(`${pem("OPENSSH PRIVATE KEY")}\nb3Bl`)).toBe(true);
|
||||||
|
expect(looksLikeSigningKeyValue(pem("EC PRIVATE KEY"))).toBe(true);
|
||||||
|
expect(looksLikeSigningKeyValue(`0x${hex}`)).toBe(true);
|
||||||
|
expect(looksLikeSigningKeyValue(`"0x${hex}"`)).toBe(true);
|
||||||
|
expect(looksLikeSigningKeyValue("4".repeat(44) + "5".repeat(44))).toBe(true);
|
||||||
|
expect(looksLikeSigningKeyValue(`[${Array.from({ length: 64 }, (_, i) => i).join(",")}]`)).toBe(true);
|
||||||
|
expect(looksLikeSigningKeyValue(Array(12).fill("abandon").join(" "))).toBe(true);
|
||||||
|
expect(looksLikeSigningKeyValue(Array(24).fill("zoo").join(" "))).toBe(true);
|
||||||
|
});
|
||||||
|
it("leaves ordinary secrets alone", () => {
|
||||||
|
expect(looksLikeSigningKeyValue(hex)).toBe(false); // bare hex: HMAC/session secrets look like this
|
||||||
|
expect(looksLikeSigningKeyValue("sk_live_51Habc")).toBe(false);
|
||||||
|
expect(looksLikeSigningKeyValue("https://example.com/path")).toBe(false);
|
||||||
|
expect(looksLikeSigningKeyValue(pem("PUBLIC KEY"))).toBe(false);
|
||||||
|
expect(looksLikeSigningKeyValue("hello world this is a normal sentence of eleven words ok")).toBe(false);
|
||||||
|
expect(looksLikeSigningKeyValue(Array(12).fill("Abandon").join(" "))).toBe(false);
|
||||||
|
});
|
||||||
|
it("isSigningKey checks the name, then the value", () => {
|
||||||
|
expect(isSigningKey("NOTES", `0x${hex}`)).toBe(true);
|
||||||
|
expect(isSigningKey("SOLANA_PRIVATE_KEY")).toBe(true);
|
||||||
|
expect(isSigningKey("NOTES", "plain")).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
57
packages/opencreds/src/signing-keys.ts
Normal file
57
packages/opencreds/src/signing-keys.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
/**
|
||||||
|
* Signing keys: secrets that move money or open a box on their own — wallet
|
||||||
|
* private keys, seed phrases, Lightning hsm_secrets, SSH and deploy keys.
|
||||||
|
*
|
||||||
|
* After the 2026-10-27 dev2 incident (root on the box drained every wallet
|
||||||
|
* whose key sat in an app.env or was pulled there from a vault) these never
|
||||||
|
* live in a deployable team vault: `teams push` refuses them, `teams pull`
|
||||||
|
* withholds them, and the server never hands them to a machine key. They
|
||||||
|
* belong in `logicsrc keyring` (passphrase-sealed, never pulled by a deploy),
|
||||||
|
* and a service that signs asks its user to unlock at use time.
|
||||||
|
*
|
||||||
|
* The NAME rule is what the server enforces, because the server only ever
|
||||||
|
* sees names. The VALUE rule is a second net the CLI runs where it holds
|
||||||
|
* plaintext, for keys stored under a name nobody would guess.
|
||||||
|
*
|
||||||
|
* apps/pwa/src/lib/signing-keys.mjs is a copy of the name rule; both are held
|
||||||
|
* to signing-keys.fixtures.json.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const norm = (name: string): string => `_${name.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}_`;
|
||||||
|
|
||||||
|
/** Seed phrases and raw key material, whatever service they belong to. */
|
||||||
|
const ALWAYS = /_(MNEMONIC|SEED_PHRASE|SEEDPHRASE|SEED_WORDS|RECOVERY_PHRASE|XPRV|XPRIV|HSM_SECRET|KEYPAIR|KEY_PAIR)_/;
|
||||||
|
/** "Private key" in any spelling, and SSH / deploy keys that open a box. */
|
||||||
|
const PRIVATE = /_(PRIVATE_KEY|PRIV_KEY|PRIVKEY|PRIVATEKEY|SIGNING_KEY|SIGNER_KEY|SSH_KEY|DEPLOY_KEY)(_|$)/;
|
||||||
|
/** App keys that sign tokens or pushes, not funds; needed by a running service. */
|
||||||
|
const SERVICE = /_(VAPID|GITHUB_APP|GH_APP|JWT|JWK|DKIM|APNS|APPLE|FIREBASE|GOOGLE|GCP|SERVICE_ACCOUNT|SAML|OIDC|WEBHOOK|TLS|SSL|CERT|CLERK|SUPABASE)_/;
|
||||||
|
/** A wallet word next to KEY / SECRET / SEED: SOLANA_SECRET_KEY, RELAYER_KEY, WALLET_SEED. */
|
||||||
|
const WALLET = /_(SOLANA|SOL|EVM|ETH|ETHEREUM|BTC|BITCOIN|WALLET|HOT_WALLET|RELAYER|TREASURY|SIGNER|OPERATOR|DEPLOYER|PAYER|FEE_PAYER)_(?:[A-Z0-9]{1,24}_){0,4}(KEY|SECRET|SEED)_/;
|
||||||
|
/** ...unless it is plainly an address, an RPC or an API credential. */
|
||||||
|
const NOT_A_KEY = /_(RPC|API|URL|ADDRESS|ADDR|PUBLIC|PUBKEY|PUB|ID|NAME)_/;
|
||||||
|
|
||||||
|
export function isSigningKeyName(name: string): boolean {
|
||||||
|
const n = norm(name);
|
||||||
|
if (ALWAYS.test(n)) return true;
|
||||||
|
if (PRIVATE.test(n)) return !SERVICE.test(n);
|
||||||
|
return WALLET.test(n) && !NOT_A_KEY.test(n);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Does the VALUE look like raw key material? Kept narrow: a false hit blocks a push. */
|
||||||
|
export function looksLikeSigningKeyValue(value: string): boolean {
|
||||||
|
const v = value.trim().replace(/^["']|["']$/g, "");
|
||||||
|
if (/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/.test(v)) return true;
|
||||||
|
// EVM private key written the usual way: 0x + 32 bytes. Bare 64-hex is too
|
||||||
|
// common for HMAC and session secrets to call.
|
||||||
|
if (/^0x[0-9a-fA-F]{64}$/.test(v)) return true;
|
||||||
|
// Solana secret key: base58 of 64 bytes (87-88 chars), or the JSON byte array.
|
||||||
|
if (/^[1-9A-HJ-NP-Za-km-z]{86,88}$/.test(v)) return true;
|
||||||
|
if (/^\[\s*(\d{1,3}\s*,\s*){63}\d{1,3}\s*\]$/.test(v)) return true;
|
||||||
|
// BIP39 shape: 12/15/18/21/24 short lowercase words.
|
||||||
|
const words = v.split(/\s+/);
|
||||||
|
return [12, 15, 18, 21, 24].includes(words.length) && words.every((w) => /^[a-z]{3,8}$/.test(w));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isSigningKey(name: string, value?: string): boolean {
|
||||||
|
return isSigningKeyName(name) || (value !== undefined && looksLikeSigningKeyValue(value));
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue