repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/leaks/__tests__/unit.test.ts

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

const fixtureSecret = "shell-fixture-secret-value-123456";

describe("leaks engine shell", () => {
	it("creates active engine with empty volatile state", () => {
		const engine = new __test.LeaksEngine();

		expect(engine.stats()).toMatchObject({
			active: true,
			customRegexCount: 0,
			learnedCount: 0,
			mappingCount: 0,
			lastProviderRedactionCount: 0,
			totalProviderRedactionCount: 0,
		});
		expect(engine.redactDeep(1, "provider")).toEqual({
			value: 1,
			changed: false,
			count: 0,
			redactions: [],
			ambiguities: [],
		});
		expect(engine.redactDeep(null, "provider")).toEqual({
			value: null,
			changed: false,
			count: 0,
			redactions: [],
			ambiguities: [],
		});
		const image = { type: "image", data: fixtureSecret };
		expect(engine.redactDeep(image, "provider").value).toEqual(image);
	});

	it("does not implement rejected compatibility settings", () => {
		expect(__test.RUNTIME_SETTING_KEYS).toEqual(["regex"]);
		for (const key of ["enabled", "keywords", "exclude", "secretFiles"]) {
			expect(__test.RUNTIME_SETTING_KEYS).not.toContain(key);
		}
	});

	it("reports provider redaction paths and labels without secret bytes", () => {
		const sensitiveValue = "alpha-secret";
		const engine = new __test.LeaksEngine({
			detectors: [
				(text) => {
					const start = text.indexOf(sensitiveValue);
					if (start === -1) return [];
					return [
						{
							start,
							end: start + sensitiveValue.length,
							value: sensitiveValue,
							labels: [
								{
									tag: "ALPHA_SECRET",
									priority: 99,
									source: "custom",
								},
							],
							kind: "custom",
							confidence: 99,
							wholeSpan: false,
						},
					];
				},
			],
		});

		const result = engine.redactDeep(
			{ messages: [{ content: `send ${sensitiveValue}` }] },
			"provider",
		);

		expect(JSON.stringify(result.value)).not.toContain(sensitiveValue);
		expect(result.redactions).toEqual([
			{
				path: "${0}[0]{0}",
				labels: ["ALPHA_SECRET"],
				placeholders: [
					expect.stringMatching(/^__LEAK_V1_ALPHA_SECRET_[a-f0-9]{32}__$/),
				],
			},
		]);
		expect(JSON.stringify(result.redactions)).not.toContain(sensitiveValue);
	});

	it("restores every provider redaction back to original text", () => {
		const engine = new __test.LeaksEngine();
		const secret = "ghp_" + "R".repeat(36);
		const original = {
			message: `send ${secret}`,
			nested: [{ text: `again ${secret}` }],
		};

		const redacted = engine.redactDeep(original, "provider");
		expect(JSON.stringify(redacted.value)).not.toContain(secret);
		expect(redacted.count).toBe(2);

		const restored = engine.restoreDeep(redacted.value);
		expect(restored.value).toEqual(original);
		expect(restored.count).toBe(2);
	});

	it("bounds status tag history", () => {
		const engine = new __test.LeaksEngine();
		const values = Array.from(
			{ length: 20 },
			(_, index) => `ghp_${String(index).padStart(2, "0")}${"A".repeat(34)}`,
		);
		engine.redactText(values.join(" "));
		expect(engine.stats().latestTags).toHaveLength(12);
	});

	it("reports property-name redactions", () => {
		const sensitiveKey = "property-name-secret-123456";
		const engine = new __test.LeaksEngine({
			detectors: [
				(text) =>
					text === sensitiveKey
						? [
								{
									start: 0,
									end: text.length,
									value: text,
									labels: [{ tag: "PROPERTY", priority: 1, source: "custom" }],
									kind: "custom",
									confidence: 100,
									wholeSpan: false,
								},
							]
						: [],
			],
		});
		const result = engine.redactDeep({ [sensitiveKey]: "value" });
		expect(result.count).toBe(1);
		expect(result.redactions[0]).toMatchObject({
			path: "${0}.key",
			labels: ["PROPERTY"],
		});
	});

	it("fails open when a detector throws", () => {
		const engine = new __test.LeaksEngine({
			detectors: [
				() => {
					throw new Error("detector broke");
				},
			],
		});

		const result = engine.redactText(`send ${fixtureSecret}`, "provider");

		expect(result).toMatchObject({
			text: `send ${fixtureSecret}`,
			count: 0,
			labels: [],
			placeholders: [],
		});
		expect(engine.stats().warningCount).toBe(1);
	});

	it("keeps warning text secret-free", () => {
		const engine = new __test.LeaksEngine({
			detectors: [
				() => {
					throw new Error(`detector saw ${fixtureSecret}`);
				},
			],
		});

		engine.redactText(`send ${fixtureSecret}`, "provider");

		const warnings = engine.stats().warnings.map((warning) => warning.message);
		expect(warnings.join("\n")).not.toContain(fixtureSecret);
		expect(warnings).toEqual([
			"detector failure; redaction pass left unchanged",
		]);
	});
});