repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/leaks/__tests__/direct-modules.test.ts

Raw
File outline
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { findBuiltinSpans } from "../src/detectors.ts";
import {
	discoverDotenvFiles,
	learnEnvironmentValues,
	learnedValueSpans,
	loadDotenvValues,
	parseDotenv,
} from "../src/dotenv.ts";
import { LeaksEngine } from "../src/engine.ts";
import { PlaceholderStore } from "../src/placeholders.ts";
import {
	isExistingPlaceholder,
	isPlainObject,
	isWeakValue,
	maskDiagnostic,
	sanitizeTag,
} from "../src/safety.ts";
import { selectSecretSpans } from "../src/selector.ts";
import {
	compileCustomRegex,
	customRegexSpans,
	loadLeaksSettings,
} from "../src/settings.ts";
import {
	findAssignmentSpans,
	findCookieSpans,
	findCredentialedUrlSpans,
	findHeaderSpans,
	findJwtSpans,
	findPrivateKeySpans,
	findSensitiveQuerySpans,
	findStructureSpans,
} from "../src/structures.ts";
import type { SecretSpan, SpanLabel } from "../src/types.ts";

const value = "direct-fixture-secret-123456789";

function header(name: string, body: string) {
	return `${name}: ${body}`;
}

function tmp() {
	return mkdtempSync(path.join(tmpdir(), "leaks-direct-"));
}

function tag(name: string, source: SpanLabel["source"] = "builtin"): SpanLabel {
	return { tag: name, priority: 1, source };
}

function secretSpan(
	start: number,
	end: number,
	kind: SecretSpan["kind"],
): SecretSpan {
	return {
		start,
		end,
		value: "abcdef".slice(0, end - start),
		labels: [tag(kind.toUpperCase())],
		kind,
		confidence: 99,
		wholeSpan: kind === "jwt" || kind === "private-key",
	};
}

describe("leaks direct module coverage", () => {
	it("hits detector and structure modules directly", () => {
		expect(findBuiltinSpans("ghp_" + "A".repeat(36))).toHaveLength(1);
		expect(findBuiltinSpans("plain text")).toEqual([]);
		const jwt = [
			"eyJhbGciOiJIUzI1NiJ9",
			"eyJzdWIiOiIxMjM0NTY3ODkwIn0",
			"c2lnbmF0dXJl",
		].join(".");
		const keyLabel = "EC PRIVATE KEY";
		const key = `-----BEGIN ${keyLabel}-----\nbody\n-----END ${keyLabel}-----`;
		const basic = Buffer.from("alice:password").toString("base64");
		const text = [
			jwt,
			key,
			`mysql://user:${value}@host/db`,
			`https://host/path?api_key=${value}`,
			header("Authorization", `Basic ${basic}`),
			`Api-Key: ${value}`,
			`Cookie: auth=${value}; theme=dark`,
			`TOKEN=${value}`,
			`<TOKEN>${value}</TOKEN>`,
		].join("\n");
		expect(findStructureSpans(text)).toHaveLength(7);
		expect(findPrivateKeySpans(key)).toHaveLength(1);
		expect(findJwtSpans(jwt)).toHaveLength(1);
		expect(
			findCredentialedUrlSpans(`mysql://user:${value}@host/db`),
		).toHaveLength(1);
		expect(findSensitiveQuerySpans(`?api_key=${value}`)).toHaveLength(1);
		expect(
			findHeaderSpans(
				[
					header("Authorization", `Basic ${basic}`),
					header("Authorization", `Bearer ${value}`),
				].join("\n"),
			),
		).toHaveLength(2);
		expect(findCookieSpans(`Cookie: auth=${value}; flag`)).toHaveLength(1);
		expect(
			findAssignmentSpans(`TOKEN=${value}\n<TOKEN>${value}</TOKEN>`),
		).toEqual([]);
	});

	it("hits dotenv, settings, safety, selector, placeholder, and engine modules directly", () => {
		const cwd = tmp();
		mkdirSync(path.join(cwd, "dir"));
		writeFileSync(path.join(cwd, ".env"), `TOKEN=${value}\n`, "utf8");
		writeFileSync(
			path.join(cwd, ".env.test.local"),
			`API_KEY=${value}2\n`,
			"utf8",
		);
		expect(discoverDotenvFiles(cwd).map((file) => path.basename(file))).toEqual(
			[".env", ".env.test.local"],
		);
		expect(
			parseDotenv("export TOKEN='x' # y\nDOUBLE=\"y\" tail\nBAD\nZ=plain # c"),
		).toEqual([
			{ key: "TOKEN", value: "x" },
			{ key: "Z", value: "plain" },
		]);
		expect(learnEnvironmentValues({ TOKEN: undefined }).values).toEqual([]);
		const learned = loadDotenvValues(cwd).values;
		expect(learnedValueSpans(`${value} ${value}2`, learned)).toHaveLength(3);

		expect(isPlainObject({})).toBe(true);
		expect(isPlainObject(new Date())).toBe(false);
		expect(sanitizeTag("a/b")).toBe("A_B");
		expect(isExistingPlaceholder("__LEAK_A_abcdef123456_2__")).toBe(true);
		expect(isExistingPlaceholder(`__LEAK_V1_${"_".repeat(10_000)}`)).toBe(
			false,
		);
		expect(maskDiagnostic("a\nb")).toBe("text chars=3 lines=2");
		expect(isWeakValue("https://example.test/path")).toBe(true);

		const loaded = loadLeaksSettings({
			leaks: { regex: [{ pattern: "foo([A-Z]+)", label: "FOO" }] },
		});
		const compiled = compileCustomRegex(loaded.settings);
		expect(customRegexSpans("fooABC", compiled.rules)[0].value).toBe("ABC");

		const selected = selectSecretSpans("abcdef", [
			secretSpan(0, 6, "builtin"),
			secretSpan(1, 4, "structure"),
			secretSpan(4, 6, "custom"),
		]);
		expect(selected.map((item) => item.value)).toEqual(["ab", "abc"]);

		const store = new PlaceholderStore({ digest: () => "abc" });
		store.configure([], () => {});
		const placeholder = store.create(value, [tag("DIRECT")]);
		expect(store.restore(placeholder)).toBe(value);
		store.clear();
		expect(store.restore(placeholder)).toBe(placeholder);

		expect(customRegexSpans("x", [])).toEqual([]);

		const engine = new LeaksEngine({ env: { TOKEN: value } });
		const redacted = engine.redactDeep({ value }, "provider");
		expect(JSON.stringify(redacted.value)).not.toContain(value);
		expect(engine.restoreDeep(redacted.value).value.value).toBe(value);
		expect(engine.restoreDeep("clean").changed).toBe(false);
		expect(engine.redactDeep(new Date()).value).toBeInstanceOf(Date);
		expect(engine.redactDeep(["clean"]).changed).toBe(false);
		expect(engine.redactDeep({ clean: "text" }).changed).toBe(false);
		engine.clear();
		expect(engine.stats().mappingCount).toBe(0);
	});

	it("hits remaining defensive branches directly", () => {
		expect(isWeakValue("NO")).toBe(true);
		expect(isWeakValue("42")).toBe(true);

		const selectorTie = selectSecretSpans("abcdef", [
			{ ...secretSpan(0, 3, "builtin"), confidence: 10 },
			{ ...secretSpan(0, 3, "builtin"), confidence: 99 },
			{ ...secretSpan(0, 3, "builtin"), labels: [tag("BUILTIN")] },
		]);
		expect(selectorTie).toHaveLength(1);
		expect(selectorTie[0].labels).toHaveLength(1);

		const warned = learnEnvironmentValues(
			{
				TOKEN_0: "direct-cap-fixture-0-123456789",
				TOKEN_1: "direct-cap-fixture-1-123456789",
				TOKEN_2: "direct-cap-fixture-2-123456789",
			},
			2,
		);
		expect(
			warned.warnings.some((warning) => warning.code === "learned.cap"),
		).toBe(true);

		const capWarnings: Array<{ code: string }> = [];
		const capped = new PlaceholderStore({
			digest: (input) => input,
			onWarning: (warning) => capWarnings.push(warning),
			cap: 2,
		});
		capped.configure([], () => {});
		for (let index = 0; index < 3; index++)
			capped.create(`value-${index}`, [tag("CAP")]);
		expect(
			capWarnings.some((warning) => warning.code === "placeholder.cap"),
		).toBe(true);
	});
});