repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/leaks/__tests__/structures.test.ts

Raw
File outline
import { describe, expect, it } from "vitest";
import { __test } from "../index.ts";

const secret = "structure-fixture-secret-123456789";
const jwt = [
	"eyJhbGciOiJIUzI1NiJ9",
	"eyJzdWIiOiIxMjM0NTY3ODkwIn0",
	"c2lnbmF0dXJl",
].join(".");
function header(name: string, value: string) {
	return `${name}: ${value}`;
}

const privateKeyLabel = "OPENSSH PRIVATE KEY";
const privateKey = `-----BEGIN ${privateKeyLabel}-----\nbody\n-----END ${privateKeyLabel}-----`;

describe("leaks structured component parsers", () => {
	it("redacts credentialed URL passwords while preserving safe URL structure", () => {
		const engine = new __test.LeaksEngine();
		const text = `DATABASE_URL=postgres://alice:${secret}@db/app`;
		const result = engine.redactText(text, "provider");

		expect(result.text).toContain("DATABASE_URL=postgres://alice:");
		expect(result.text).toContain("@db/app");
		expect(result.text.includes(secret)).toBe(false);
	});

	it("redacts sensitive query values and preserves names", () => {
		const engine = new __test.LeaksEngine();
		const text = `https://api.example.test/callback?token=${secret}&user=me`;
		const result = engine.redactText(text, "provider");

		expect(result.text).toContain("token=");
		expect(result.text).toContain("&user=me");
		expect(result.text.includes(secret)).toBe(false);
	});

	it("does not redact URLs without credentials even for database keys", () => {
		const engine = new __test.LeaksEngine();
		const text =
			"DATABASE_URL=postgres://db/app REDIS_URL=redis://cache MONGO_URL=mongodb://mongo/app";
		expect(engine.redactText(text, "provider").text).toBe(text);
	});

	it("redacts validated header values only", () => {
		const engine = new __test.LeaksEngine();
		const basic = Buffer.from("alice:password").toString("base64");
		const text = [
			header("Authorization", `Bearer ${secret}`),
			header("Authorization", `Basic ${basic}`),
			header("X-API-Key", secret),
		].join("\n");
		const result = engine.redactText(text, "provider");

		expect(result.text).not.toContain(secret);
		expect(result.text).not.toContain(basic);
		expect(result.count).toBe(3);
	});

	it("redacts sensitive cookie values only", () => {
		const engine = new __test.LeaksEngine();
		const result = engine.redactText(
			`Cookie: session=${secret}; theme=dark`,
			"provider",
		);

		expect(result.text).toContain("Cookie: session=");
		expect(result.text).toContain("; theme=dark");
		expect(result.text.includes(secret)).toBe(false);
	});

	it("redacts only provider-shaped assignment values", () => {
		const engine = new __test.LeaksEngine();
		const shaped = "ghp_" + "A".repeat(36);
		for (const sample of [
			`TOKEN=${shaped}`,
			`token: ${shaped}`,
			`"token": "${shaped}"`,
			`<token>${shaped}</token>`,
		]) {
			expect(engine.redactText(sample, "provider").text).not.toContain(shaped);
		}
		expect(engine.redactText(`TOKEN=${secret}`, "provider").text).toContain(
			secret,
		);
	});

	it("redacts an HCloud token only in exact key context", () => {
		const engine = new __test.LeaksEngine();
		const token = "A1".repeat(32);

		for (const sample of [
			`1: hcloud_token = "${token}" ssh_public_key = "ssh-ed25519 public"`,
			`TF_VAR_HCLOUD_TOKEN=${token}`,
		]) {
			expect(engine.redactText(sample, "provider").text).not.toContain(token);
		}
		expect(
			engine.redactText(`deployment_id = "${token}"`, "provider").text,
		).toContain(token);
		expect(
			engine.redactText(`hcloud_token = "${token.slice(1)}"`, "provider").text,
		).toContain(token.slice(1));
	});

	it("redacts shell header value without redacting whole command", () => {
		const engine = new __test.LeaksEngine();
		const result = engine.redactText(
			`curl -H 'Authorization: Bearer ${secret}' https://example.test`,
			"provider",
		);

		expect(result.text).toContain("curl -H '");
		expect(result.text).toContain("https://example.test");
		expect(result.text.includes(secret)).toBe(false);
	});

	it("requires exactly three decoded JWT object segments", () => {
		const dotted = "agendaFlick.visibleArea.yPosition";
		const shortPayload = [
			Buffer.from(JSON.stringify({ alg: "A" })).toString("base64url"),
			Buffer.from(JSON.stringify({})).toString("base64url"),
			Buffer.from([0]).toString("base64url"),
		].join(".");
		expect(__test.findJwtSpans(dotted)).toEqual([]);
		expect(__test.findJwtSpans(`${jwt}.extra`)).toEqual([]);
		expect(__test.findJwtSpans(shortPayload).map((span) => span.value)).toEqual(
			[shortPayload],
		);
		expect(__test.findJwtSpans(jwt).map((span) => span.value)).toEqual([jwt]);
	});

	it("reports malformed structured candidates without values", () => {
		const dotted = "agendaFlick.visibleArea.yPosition";
		const malformedUrl = "https://[bad/?token=ordinary-value-123456";
		const malformedBasic = "Authorization: Basic ordinary-value-123456";
		expect(
			__test
				.findStructureAmbiguities(
					[dotted, malformedUrl, malformedBasic].join("\n"),
				)
				.map((item) => item.family)
				.toSorted(),
		).toEqual(["URL_QUERY", "BASIC_AUTH"].toSorted());
	});

	it("rejects malformed structured contexts", () => {
		const ordinary = "ordinary-metadata-value-123456";
		expect(
			__test.findSensitiveQuerySpans(`https://[bad/?token=${ordinary}`),
		).toEqual([]);
		expect(__test.findCookieSpans(`Set-Cookie: session=${ordinary}`)).toEqual(
			[],
		);
		expect(__test.findHeaderSpans(`Authorization: Basic ${ordinary}`)).toEqual(
			[],
		);
	});

	it("parses decoded sensitive query names with exact raw spans", () => {
		const raw = "ordinary-query-value-123456";
		const url = `https://example.test/path?session=${raw}&co%6Fkie=${raw}&jwt=${raw}&pass=${raw}#fragment`;
		const spans = __test.findSensitiveQuerySpans(url);
		expect(spans.map((span) => span.value)).toEqual([raw, raw, raw, raw]);
		expect(spans.map((span) => url.slice(span.start, span.end))).toEqual([
			raw,
			raw,
			raw,
			raw,
		]);
		expect(spans.map((span) => span.labels[0].tag)).toEqual([
			"session",
			"cookie",
			"jwt",
			"pass",
		]);
	});

	it("keeps prose punctuation outside URL query spans", () => {
		const value = "ordinary-query-value-123456";
		const url = new URL("/path", "https://example.test");
		url.searchParams.set("token", value);
		const text = `See (${url}).`;
		const spans = __test.findSensitiveQuerySpans(text);
		expect(spans.map((span) => span.value)).toEqual([value]);
		const redacted = new __test.LeaksEngine().redactText(text).text;
		expect(redacted).toMatch(/__LEAK_V1_[A-Z0-9_]+_[a-f0-9]{32}__\)\.$/);
	});

	it("uses complete query and cookie names", () => {
		const ordinary = "ordinary-metadata-value-123456";
		expect(__test.findSensitiveQuerySpans(`?monkey=${ordinary}`)).toEqual([]);
		expect(__test.findCookieSpans(`Cookie: keyboard=${ordinary}`)).toEqual([]);
		expect(
			__test
				.findSensitiveQuerySpans(`?token=${secret}`)
				.map((span) => span.value),
		).toEqual([secret]);
		expect(
			__test
				.findCookieSpans(`Cookie: session=${secret}`)
				.map((span) => span.value),
		).toEqual([secret]);
	});

	it("redacts JWTs and private keys as whole spans", () => {
		const engine = new __test.LeaksEngine();
		const jwtResult = engine.redactText(`jwt=${jwt}`, "provider");
		const keyResult = engine.redactText(privateKey, "provider");

		expect(jwtResult.text).toMatch(/^jwt=__LEAK_V1_JWT_[a-f0-9]{32}__$/);
		expect(keyResult.text).toMatch(
			/^__LEAK_V1_OPENSSH_PRIVATE_KEY_[a-f0-9]{32}__$/,
		);
	});

	it("skips assignment keys that are common programming nouns", () => {
		const longValue = "abcdef1234567890";
		for (const key of [
			"seed",
			"id",
			"name",
			"count",
			"type",
			"value",
			"path",
			"ts",
			"time",
			"date",
			"idx",
			"mode",
			"flag",
			"opts",
			"params",
			"args",
			"options",
			"label",
			"field",
			"tag",
			"node",
			"host",
			"port",
			"version",
		]) {
			const text = `${key}=${longValue}`;
			expect(
				__test.findAssignmentSpans(text),
				`expected ${key}=<value> to produce zero spans`,
			).toEqual([]);
		}
	});

	it("does not redact sensitive-name code references", () => {
		const engine = new __test.LeaksEngine();
		const samples = [
			"const token = loadToken(email);",
			"const key = match[1] as string;",
			"console.log(`  access_token: ${token.access_token ? 'present' : 'missing'}`);",
			"const key = `${redaction.path}: ${redaction.labels.join(', ')}`;",
			"let session: BaseTestSession;",
			"const value: ${account.hasAccessToken = token.access_token;",
		];

		for (const sample of samples) {
			expect(engine.redactText(sample, "provider").text, sample).toBe(sample);
			expect(__test.findAssignmentSpans(sample), sample).toEqual([]);
		}
	});

	it("keeps ambiguous sensitive-name assignments visible", () => {
		const ordinary = "abcdef1234567890";
		expect(__test.findAssignmentSpans(`KEY=${ordinary}`)).toEqual([]);
		expect(__test.findAssignmentSpans(`TOKEN=${ordinary}`)).toEqual([]);
	});

	it("stoplist is case-insensitive for common programming nouns", () => {
		const longValue = "abcdef1234567890";
		for (const key of ["Seed", "SEED", "Id", "ID", "Name", "Type"]) {
			const text = `${key}=${longValue}`;
			expect(
				__test.findAssignmentSpans(text),
				`expected ${key}=<value> to produce zero spans`,
			).toEqual([]);
		}
	});
});