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
19 changes: 19 additions & 0 deletions src/install-gate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,25 @@ describe("parseInstallCommand — bypass resistance (security)", () => {
);
});

it("HIGH-SHELL: leading shell keywords / grouping / eval don't hide the install", () => {
assert.deepEqual(parseInstallCommand("if true; then npm i evil; fi").refs, ["npm:evil"]);
assert.deepEqual(parseInstallCommand("then npm i evil").refs, ["npm:evil"]);
assert.deepEqual(parseInstallCommand("{ npm i evil ; }").refs, ["npm:evil"]);
assert.deepEqual(parseInstallCommand("for x in 1; do pip install evil; done").refs, [
"pip:evil",
]);
assert.deepEqual(parseInstallCommand("eval 'npm i evil'").refs, ["npm:evil"]);
assert.deepEqual(parseInstallCommand('eval "pip install evil"').refs, ["pip:evil"]);
});

it("HIGH-BG: an install after a background `&` / `|&` is still detected", () => {
assert.deepEqual(parseInstallCommand(": & npm i evil".replace(/:/, "echo hi")).refs, [
"npm:evil",
]);
assert.deepEqual(parseInstallCommand("echo hi & npm install evil").refs, ["npm:evil"]);
assert.deepEqual(parseInstallCommand("true |& npm i evil").refs, ["npm:evil"]);
});

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
53 changes: 52 additions & 1 deletion src/install-gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,39 @@ export interface InstallProbe {
}

/** Shell operators that separate independent commands in one Bash string. */
const SEGMENT_SPLIT = /\s*(?:&&|\|\||;|\||\n)\s*/;
// Command separators. Includes single `&` (job-control background) and `|&` so an
// install placed AFTER a background/`&` op is still its own segment — `: & npm i
// evil` and `true |& npm i evil` previously left the install non-leading and unseen.
const SEGMENT_SPLIT = /\s*(?:&&|\|\||;|\||&|\n)\s*/;

// Leading shell keywords / grouping tokens that precede a real command without
// changing it. Stripped like PREFIX_BINS so `then npm i evil` / `{ npm i evil; }` /
// `if true; then npm i …` don't hide the package manager from the head-anchored
// matcher. `eval`/`xargs` are here for the UNQUOTED form; the quoted form is
// recursed into by nestedCommands.
const SHELL_KEYWORDS = new Set([
"if",
"then",
"else",
"elif",
"fi",
"for",
"while",
"until",
"do",
"done",
"case",
"esac",
"select",
"function",
"{",
"}",
"(",
")",
"!",
"eval",
"xargs",
]);

/** A token is a flag (skip it) — `-g`, `--save-dev`, etc. */
function isFlag(tok: string): boolean {
Expand Down Expand Up @@ -71,6 +103,20 @@ function stripCommandPrefix(tokens: string[]): string[] {
while (i < tokens.length && tokens[i].startsWith("-")) i++; // skip the wrapper's own flags
continue;
}
// Leading shell keyword / grouping token (then/do/{/eval/…) → skip; also handle
// a grouping char glued to the next token (`{npm`, `(npm`).
if (SHELL_KEYWORDS.has(t)) {
i++;
continue;
}
if (/^[{(!]+/.test(t) && !SHELL_KEYWORDS.has(t)) {
// strip a leading run of glued grouping chars, keep the rest as a token
tokens[i] = t.replace(/^[{(!]+/, "");
if (tokens[i] === "") {
i++;
}
continue;
}
break;
}
return tokens.slice(i);
Expand All @@ -88,6 +134,11 @@ function nestedCommands(command: string): string[] {
for (const m of command.matchAll(/\$\(([^()]{1,2000})\)/g)) out.push(m[1]);
for (const m of command.matchAll(/`([^`]{1,2000})`/g)) out.push(m[1]);
for (const m of command.matchAll(/-c\s+(['"])([\s\S]{1,2000}?)\1/g)) out.push(m[2]);
// `eval '…'` / `xargs "…"` — the QUOTED script arg (the unquoted form is handled
// by SHELL_KEYWORDS stripping). Recurse so a quoted install can't hide behind eval.
for (const m of command.matchAll(/\b(?:eval|xargs)\s+(['"])([\s\S]{1,2000}?)\1/g)) {
out.push(m[2]);
}
return out;
}

Expand Down
40 changes: 40 additions & 0 deletions src/update-check.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,46 @@ describe("checkForUpdate", () => {
}
});

it("returns null under CONFIG-declared air-gap (.kit.toml) even without KIT_AIRGAP env", async () => {
const { mkdtempSync, writeFileSync, rmSync } = await import("node:fs");
const { tmpdir } = await import("node:os");
const { join } = await import("node:path");
const saved = {
CI: process.env.CI,
GH: process.env.GITHUB_ACTIONS,
GL: process.env.GITLAB_CI,
NO: process.env.KIT_NO_UPDATE_CHECK,
AG: process.env.KIT_AIRGAP,
};
const cwd0 = process.cwd();
const dir = mkdtempSync(join(tmpdir(), "kit-airgap-cfg-"));
writeFileSync(join(dir, ".kit.toml"), "[air_gap]\nenabled = true\n");
// Clear ALL other suppressors incl. the env air-gap flag, so this proves the
// CONFIG posture alone suppresses the beacon.
delete process.env.CI;
delete process.env.GITHUB_ACTIONS;
delete process.env.GITLAB_CI;
delete process.env.KIT_NO_UPDATE_CHECK;
delete process.env.KIT_AIRGAP;
process.chdir(dir);
try {
assert.equal(await checkForUpdate("0.1.0"), null);
} finally {
process.chdir(cwd0);
rmSync(dir, { recursive: true, force: true });
for (const [k, v] of [
["CI", saved.CI],
["GITHUB_ACTIONS", saved.GH],
["GITLAB_CI", saved.GL],
["KIT_NO_UPDATE_CHECK", saved.NO],
["KIT_AIRGAP", saved.AG],
] as const) {
if (v === undefined) delete process.env[k];
else process.env[k] = v;
}
}
});

it("never throws — handles network errors gracefully", async () => {
const origCI = process.env.CI;
const origNo = process.env.KIT_NO_UPDATE_CHECK;
Expand Down
24 changes: 23 additions & 1 deletion src/update-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,28 @@ export interface UpdateInfo {
* Returns null if already on latest, check fails, or check is suppressed.
* Never throws — all errors are caught silently.
*/
/**
* True when the host is in an air-gap posture by EITHER the KIT_AIRGAP env var OR
* the checked-in `.kit.toml [air_gap] enabled = true` (the authoritative
* resolveAirGap notion). `scanners.isAirGap()` reads ONLY the env var, so a
* config-declared enclave (e.g. `kit setup --mode airgap`) without KIT_AIRGAP
* exported would otherwise let the npm update beacon punch through. Best-effort:
* a missing/invalid config falls back to the env-only signal.
*/
async function isAirGapPosture(): Promise<boolean> {
if (isAirGap()) return true;
try {
const [{ loadConfig }, { resolveAirGap }] = await Promise.all([
import("./config.js"),
import("./airgap/config.js"),
]);
const cfg = await loadConfig(join(process.cwd(), ".kit.toml"));
return resolveAirGap(cfg.air_gap).enabled;
} catch {
return false; // no/invalid config → env-only posture
}
}

export async function checkForUpdate(currentVersion: string): Promise<UpdateInfo | null> {
try {
// Suppression conditions. Air-gap is one of them: the update check is the
Expand All @@ -38,7 +60,7 @@ export async function checkForUpdate(currentVersion: string): Promise<UpdateInfo
process.env.CI === "true" ||
process.env.GITHUB_ACTIONS === "true" ||
process.env.GITLAB_CI === "true" ||
isAirGap()
(await isAirGapPosture())
) {
return null;
}
Expand Down
23 changes: 23 additions & 0 deletions src/utils/redactSecrets.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,29 @@ describe("redactSecrets — connection-string + sk-svcacct (regression)", () =>
});
});

describe("redactSecrets — provider tokens (prefix-exclusion leak fix)", () => {
it("redacts provider tokens previously skipped by the prefix allowlist", () => {
for (const kv of [
"VERCEL_TOKEN=xQ9fL2vN8pR4tW6yA1bC3dE5gH7jK0mP",
"RAILWAY_TOKEN=Zk3mP9qR7sT1vW5xY8aB2cD4eF6gH0jL",
"FLY_API_TOKEN=aB2cD4eF6gH0jLxQ9fL2vN8pR4tW6yA1",
"GITHUB_TOKEN=ghXstuffZk3mP9qR7sT1vW5xY8aB2cD4eF",
"CI_JOB_TOKEN=Zk3mP9qR7sT1vW5xY8aB2cD4eF6gH0jL9",
]) {
const out = redactSecrets(kv);
assert.ok(out.includes("[REDACTED]"), `should redact: ${kv}`);
assert.ok(!out.includes(kv.split("=")[1]), `raw value must be gone: ${kv}`);
}
});

it("still skips exact public CI/runtime metadata (no added noise)", () => {
// exact metadata names + KIT_ flags are not credentials → left intact
const meta =
"GITHUB_SHA=a3f5c8e1b2d4f6a8c0e2b4d6f8a0c2e4a3f5c8e1 KIT_POLICY_HASH=deadbeefcafebabe0011";
assert.equal(redactSecrets(meta), meta);
});
});

describe("redactSecrets", () => {
it("redacts stripe test secret keys", () => {
const out = redactSecrets("test_mode_api_key = 'sk_test_51T2AMtJLRlXeUG4dKBwX2nsve3BLEzy'");
Expand Down
53 changes: 52 additions & 1 deletion src/utils/redactSecrets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,57 @@ interface RedactPattern {
replacement?: string;
}

// EXACT non-credential env var names the `kv-secret` matcher skips (public CI /
// runtime metadata that would otherwise drown real findings). Deliberately NOT
// prefix-based: excluding whole prefixes (`GITHUB_`, `VERCEL_`, `RAILWAY_`, `FLY_`,
// `CI_`) also skipped the real tokens under them (GITHUB_TOKEN, VERCEL_TOKEN,
// RAILWAY_TOKEN, FLY_API_TOKEN, CI_JOB_TOKEN) — a leak. Only `KIT_*` stays a prefix
// (kit's own non-credential flag namespace).
const KV_SECRET_EXCLUDE = [
"CI",
"NEXT_RUNTIME",
"RUNNER_OS",
"RUNNER_ARCH",
"RUNNER_NAME",
"RUNNER_TEMP",
"RUNNER_TOOL_CACHE",
"RUNNER_WORKSPACE",
"GITHUB_RUN_ID",
"GITHUB_RUN_NUMBER",
"GITHUB_RUN_ATTEMPT",
"GITHUB_SHA",
"GITHUB_REF",
"GITHUB_REF_NAME",
"GITHUB_REF_TYPE",
"GITHUB_ACTION",
"GITHUB_ACTOR",
"GITHUB_WORKFLOW",
"GITHUB_JOB",
"GITHUB_REPOSITORY",
"GITHUB_REPOSITORY_OWNER",
"GITHUB_EVENT_NAME",
"GITHUB_BASE_REF",
"GITHUB_HEAD_REF",
"GITHUB_SERVER_URL",
"GITHUB_API_URL",
"GITHUB_GRAPHQL_URL",
"CI_JOB_NAME",
"CI_JOB_STAGE",
"CI_PIPELINE_ID",
"CI_PROJECT_NAME",
"CI_PROJECT_PATH",
"CI_COMMIT_SHA",
"CI_COMMIT_REF_NAME",
"CI_SERVER_URL",
];
// `KEY=high-entropy` — a rotation value echoed back in an error message. Excludes
// only the EXACT metadata names above (+ the KIT_ flag namespace); every other
// uppercase KEY= with a 20+ base64url value is redacted, incl. provider tokens.
const KV_SECRET_RE = new RegExp(
`(?<!_)\\b(?!(?:KIT_[A-Z0-9_]+|${KV_SECRET_EXCLUDE.join("|")})=)([A-Z][A-Z0-9_]{2,})=([A-Za-z0-9_\\-+/]{20,})`,
"g",
);

export const SECRET_PATTERNS: RedactPattern[] = [
// Stripe — sk_test_, sk_live_, pk_test_, pk_live_, rk_test_, rk_live_,
// whsec_, sk_test_..., 24+ random chars
Expand Down Expand Up @@ -71,7 +122,7 @@ export const SECRET_PATTERNS: RedactPattern[] = [
// are credentials.
// GITHUB_RUN_ID / GITHUB_SHA — CI metadata.
{
re: /(?<!_)\b(?!(?:KIT|GITHUB|CI|RUNNER|VERCEL|RAILWAY|FLY|NEXT_RUNTIME)_)([A-Z][A-Z0-9_]{2,})=([A-Za-z0-9_\-+/]{20,})/g,
re: KV_SECRET_RE,
label: "kv-secret",
},
// Terraform — `sensitive = "..."` blocks in HCL leak the literal value
Expand Down
Loading