repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/leaks/__tests__/ux.test.ts

Raw
File outline
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createTestSession, type TestSession } from "../../../test/harness";

function extPath() {
	return path.resolve(import.meta.dirname, "../index.ts");
}

const secret = "sk-or-v1-" + "e".repeat(64);

describe("leaks UX and commands", () => {
	let t: TestSession | undefined;
	afterEach(() => {
		t?.dispose();
		t = undefined;
	});

	it("notifies once for a redacting provider turn and not for clean turns", async () => {
		t = await createTestSession({ extensions: [extPath()] });
		await t.session.extensionRunner.emitBeforeProviderRequest({ text: secret });
		await t.session.extensionRunner.emitBeforeProviderRequest({
			text: "ordinary metadata",
		});

		const notices = t.events
			.uiCallsFor("notify")
			.map((call) => String(call.args[0]));
		expect(
			notices.filter((notice) => notice.includes("leaks redacted")),
		).toHaveLength(1);
	});

	it("does not re-notify the same redacted value across provider turns", async () => {
		t = await createTestSession({ extensions: [extPath()] });
		await t.session.extensionRunner.emitBeforeProviderRequest({ text: secret });
		await t.session.extensionRunner.emitBeforeProviderRequest({ text: secret });
		await t.session.extensionRunner.emitBeforeProviderRequest({ text: secret });

		const notices = t.events
			.uiCallsFor("notify")
			.map((call) => String(call.args[0]));
		expect(
			notices.filter((notice) => notice.includes("leaks redacted")),
		).toHaveLength(1);
	});

	it("re-notifies after /leaks clear and after reload", async () => {
		t = await createTestSession({
			extensions: [extPath()],
			mockUI: { confirm: true },
		});
		const command =
			t.session.extensionRunner.extensions[0].commands.get("leaks");
		const ctx = t.session.extensionRunner.createContext();

		await t.session.extensionRunner.emitBeforeProviderRequest({ text: secret });
		await t.session.extensionRunner.emitBeforeProviderRequest({ text: secret });
		await command.handler("clear", ctx);
		await t.session.extensionRunner.emitBeforeProviderRequest({ text: secret });

		const notices = t.events
			.uiCallsFor("notify")
			.map((call) => String(call.args[0]));
		expect(
			notices.filter((notice) => notice.includes("leaks redacted")),
		).toHaveLength(2);
	});

	it("notice only lists new redactions when an old secret is repeated alongside a new one", async () => {
		const oldSecret = "tdd-old-secret-value-" + "o".repeat(32);
		const newSecret = "tdd-new-secret-value-" + "n".repeat(32);
		t = await createTestSession({
			extensions: [extPath()],
			env: {
				["OLD_" + "SECRET"]: oldSecret,
				["NEW_" + "SECRET"]: newSecret,
			},
		});

		await t.session.extensionRunner.emitBeforeProviderRequest({
			text: `first ${oldSecret}`,
		});
		await t.session.extensionRunner.emitBeforeProviderRequest({
			text: `again ${oldSecret} and now ${newSecret}`,
		});

		const leakNotices = t.events
			.uiCallsFor("notify")
			.map((call) => String(call.args[0]))
			.filter((notice) => notice.includes("leaks redacted"));
		expect(leakNotices).toHaveLength(2);
		expect(leakNotices[1]).toContain("leaks redacted 1 provider value(s)");
		expect(leakNotices[1]).toContain("ENV_KEY");
		expect(leakNotices[1]).not.toContain(oldSecret);
		expect(leakNotices[1]).not.toContain(newSecret);
	});

	it("notification reports every provider redaction path and label", async () => {
		const sensitiveValue = "tdd-secret-value-" + "x".repeat(32);
		t = await createTestSession({
			extensions: [extPath()],
			env: { ["ALPHA_" + "SECRET"]: sensitiveValue },
		});
		await t.session.extensionRunner.emitBeforeProviderRequest({
			messages: [
				{ content: `first ${sensitiveValue}` },
				{ content: `second ${sensitiveValue}` },
			],
		});

		const notice =
			t.events
				.uiCallsFor("notify")
				.map((call) => String(call.args[0]))
				.find((item) => item.includes("leaks redacted")) ?? "";
		expect(notice).toContain("leaks redacted 2 provider value(s)");
		expect(notice).toContain("• ${0}[0]{0} — ENV_KEY");
		expect(notice).toContain("• ${0}[1]{0} — ENV_KEY");
		expect(notice).not.toContain(sensitiveValue);
	});

	it("groups repeated labels by provider path", async () => {
		const sessionSecret = "cookie-session-value-" + "s".repeat(32);
		const authSecret = "cookie-auth-value-" + "a".repeat(32);
		t = await createTestSession({ extensions: [extPath()] });

		await t.session.extensionRunner.emitBeforeProviderRequest({
			input: [
				{
					arguments: `Cookie: session=${sessionSecret}; auth=${authSecret}; theme=dark`,
				},
			],
		});

		const notice =
			t.events
				.uiCallsFor("notify")
				.map((call) => String(call.args[0]))
				.find((item) => item.includes("leaks redacted")) ?? "";
		expect(notice).toContain("leaks redacted 2 provider value(s)");
		expect(notice).toContain("• ${0}[0]{0} — COOKIE ×2");
		expect(notice.split("\n")).toHaveLength(2);
		expect(notice).not.toContain(sessionSecret);
		expect(notice).not.toContain(authSecret);
	});

	it("leaves malformed cookie-like source visible", async () => {
		const secretValue = "malformed-cookie-secret-" + "m".repeat(32);
		t = await createTestSession({ extensions: [extPath()] });

		await t.session.extensionRunner.emitBeforeProviderRequest({
			input: [
				{
					arguments:
						"Cook" +
						"ie: " +
						'\n\n\tpi.on("session_shutdown", async (_event, ctx)' +
						"=" +
						secretValue,
				},
			],
		});

		const notice =
			t.events
				.uiCallsFor("notify")
				.map((call) => String(call.args[0]))
				.find((item) => item.includes("leaks redacted")) ?? "";
		expect(notice).toBe("");
	});

	it("status reports required safe fields", async () => {
		t = await createTestSession({ extensions: [extPath()] });
		await t.session.extensionRunner.emitBeforeProviderRequest({ text: secret });
		const command =
			t.session.extensionRunner.extensions[0].commands.get("leaks");
		await command.handler("status", t.session.extensionRunner.createContext());

		const status =
			t.events
				.uiCallsFor("notify")
				.map((call) => String(call.args[0]))
				.at(-1) ?? "";
		for (const field of [
			"leaks on",
			"built-in rules:",
			"custom regex:",
			"regex warnings:",
			"invalid regex:",
			"learned:",
			"mappings:",
			"last provider redactions:",
			"total provider redactions:",
			"recent labels:",
			"latest tags:",
		])
			expect(status).toContain(field);
		expect(status).not.toContain(secret);
	});

	it("reload test and clear commands are safe", async () => {
		t = await createTestSession({
			extensions: [extPath()],
			mockUI: { confirm: true },
		});
		const command =
			t.session.extensionRunner.extensions[0].commands.get("leaks");
		const ctx = t.session.extensionRunner.createContext();

		await command.handler("test " + secret, ctx);
		await command.handler("reload", ctx);
		await t.session.extensionRunner.emitBeforeProviderRequest({ text: secret });
		await command.handler("clear", ctx);
		await command.handler("status", ctx);

		const notices = t.events
			.uiCallsFor("notify")
			.map((call) => String(call.args[0]));
		expect(notices.join("\n")).not.toContain(secret);
		expect(notices.some((notice) => notice.includes("leaks reloaded"))).toBe(
			true,
		);
		expect(notices.some((notice) => notice.includes("leaks cleared"))).toBe(
			true,
		);
		expect(notices.at(-1)).toContain("mappings: 0");
	});

	it("clear respects cancellation", async () => {
		t = await createTestSession({
			extensions: [extPath()],
			mockUI: { confirm: false },
		});
		await t.session.extensionRunner.emitBeforeProviderRequest({ text: secret });
		const command =
			t.session.extensionRunner.extensions[0].commands.get("leaks");
		await command.handler("clear", t.session.extensionRunner.createContext());
		await command.handler("status", t.session.extensionRunner.createContext());

		const notices = t.events
			.uiCallsFor("notify")
			.map((call) => String(call.args[0]));
		expect(notices.some((notice) => notice.includes("clear cancelled"))).toBe(
			true,
		);
		expect(notices.at(-1)).toContain("mappings: 1");
	});
});