repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/leaks/__fuzz__/lifecycle.fuzz.test.ts

Raw
File outline
import { fc } from "@fast-check/vitest";
import { expect } from "vitest";
import { __test } from "../index.ts";
import type { PersistedEntry } from "../src/placeholders.ts";
import { prop } from "./replay.ts";

const operation = fc.oneof(
	fc.constant({ kind: "clear" } as const),
	fc.record({
		kind: fc.constant("add" as const),
		id: fc.integer({ min: 0, max: 40 }),
	}),
	fc.record({
		kind: fc.constant("fork" as const),
		branch: fc.integer({ min: 0, max: 4 }),
	}),
	fc.record({
		kind: fc.constant("switch" as const),
		branch: fc.integer({ min: 0, max: 4 }),
	}),
);

prop(
	"lifecycle-model",
	{ operations: fc.array(operation, { minLength: 1, maxLength: 100 }) },
	500,
)("reconstructs only the modeled active generation", ({ operations }) => {
	const branches = new Map<number, PersistedEntry[]>([[0, []]]);
	const models = new Map<number, Map<string, string>>([[0, new Map()]]);
	const known = new Map<string, string>();
	let activeBranch = 0;
	let store = new __test.PlaceholderStore();
	const configure = () => {
		const entries = branches.get(activeBranch) as PersistedEntry[];
		store = new __test.PlaceholderStore();
		store.configure(entries, (customType, data) =>
			entries.push({ type: "custom", customType, data }),
		);
	};
	configure();
	for (const item of operations) {
		if (item.kind === "clear") {
			models.set(activeBranch, new Map());
			store.clear();
			continue;
		}
		if (item.kind === "fork") {
			branches.set(
				item.branch,
				structuredClone(branches.get(activeBranch) as PersistedEntry[]),
			);
			models.set(
				item.branch,
				new Map(models.get(activeBranch) as Map<string, string>),
			);
			activeBranch = item.branch;
			configure();
			continue;
		}
		if (item.kind === "switch") {
			if (!branches.has(item.branch)) continue;
			activeBranch = item.branch;
			configure();
			continue;
		}
		const value = `lifecycle-fixture-${item.id}-ordinary`;
		const placeholder = store.create(value, [
			{ tag: "TOKEN", priority: 10, source: "custom" },
		]);
		if (placeholder) {
			models.get(activeBranch)?.set(placeholder, value);
			known.set(placeholder, value);
		}
	}
	configure();
	const active = models.get(activeBranch) as Map<string, string>;
	for (const [placeholder, value] of known) {
		expect(store.restore(placeholder)).toBe(
			active.get(placeholder) ?? placeholder,
		);
		if (active.has(placeholder)) expect(active.get(placeholder)).toBe(value);
	}
});

prop(
	"lifecycle-corruption",
	{
		field: fc.constantFrom("nonce", "authTag", "ciphertext", "placeholder"),
	},
	500,
)("disables creation after generated record corruption", ({ field }) => {
	const entries: PersistedEntry[] = [];
	const store = new __test.PlaceholderStore();
	store.configure(entries, (customType, data) =>
		entries.push({ type: "custom", customType, data }),
	);
	store.create("ordinary-lifecycle-fixture", [
		{ tag: "TOKEN", priority: 10, source: "custom" },
	]);
	const mapping = entries[1].data as Record<string, string>;
	mapping[field] = `${mapping[field]}!`;
	const resumed = new __test.PlaceholderStore();
	resumed.configure(entries, () => {});
	expect(resumed.stats().persistenceEnabled).toBe(false);
	expect(
		resumed.create("another-ordinary-fixture", [
			{ tag: "TOKEN", priority: 10, source: "custom" },
		]),
	).toBeUndefined();
});

prop(
	"lifecycle-failures",
	{ kind: fc.constantFrom("cap", "collision", "append", "unknown-tool") },
	500,
)(
	"models capacity, collision, append, and unknown-tool failures",
	({ kind }) => {
		if (kind === "unknown-tool") {
			const engine = new __test.LeaksEngine();
			expect(
				engine.hydrateToolInput({ value: "__LEAK_TOKEN_abcdef123456__" }).issue,
			).toBeDefined();
			return;
		}
		let appendCalls = 0;
		const store = new __test.PlaceholderStore({
			cap: kind === "cap" ? 1 : 8,
			digest: kind === "collision" ? () => "a".repeat(32) : undefined,
		});
		store.configure([], () => {
			appendCalls++;
			if (kind === "append" && appendCalls > 1) throw new Error("failure");
		});
		const first = store.create("model-fixture-first", [
			{ tag: "TOKEN", priority: 10, source: "custom" },
		]);
		const second = store.create("model-fixture-second", [
			{ tag: "TOKEN", priority: 10, source: "custom" },
		]);
		if (kind === "cap" || kind === "collision") {
			expect(first).toBeDefined();
			expect(second).toBeUndefined();
		} else {
			expect(first).toBeUndefined();
			expect(store.stats().persistenceEnabled).toBe(false);
		}
	},
);

prop(
	"lifecycle-utf16",
	{
		value: fc.string({
			unit: fc
				.integer({ min: 0, max: 0xffff })
				.map((codeUnit) => String.fromCharCode(codeUnit)),
			maxLength: 200,
		}),
	},
	500,
)(
	"round-trips arbitrary UTF-16 code units across reconstruction",
	({ value }) => {
		const entries: PersistedEntry[] = [];
		const store = new __test.PlaceholderStore();
		store.configure(entries, (customType, data) =>
			entries.push({ type: "custom", customType, data }),
		);
		const placeholder = store.create(value, [
			{ tag: "TOKEN", priority: 10, source: "custom" },
		]) as string;
		const resumed = new __test.PlaceholderStore();
		resumed.configure(entries, () => {});
		expect(resumed.restore(placeholder)).toBe(value);
	},
);

prop(
	"lifecycle-hydration",
	{
		value: fc.string({
			unit: fc.constantFrom(..."abcdefghijklmnopqrstuvwxyz"),
			minLength: 8,
			maxLength: 80,
		}),
		path: fc.array(fc.integer({ min: 0, max: 3 }), { maxLength: 20 }),
	},
	500,
)("known placeholders hydrate through generated arrays", ({ value, path }) => {
	const entries: PersistedEntry[] = [];
	const engine = new __test.LeaksEngine({
		detectors: [
			(text) => [
				{
					start: 0,
					end: text.length,
					value: text,
					labels: [{ tag: "TOKEN", priority: 10, source: "custom" }],
					kind: "custom",
					confidence: 100,
					wholeSpan: false,
				},
			],
		],
	});
	engine.configurePersistence(entries, (customType, data) =>
		entries.push({ type: "custom", customType, data }),
	);
	const token = engine.redactText(value).text;
	let nested: unknown = token;
	for (const index of path) {
		const array = Array.from({ length: index + 1 }, () => null as unknown);
		array[index] = nested;
		nested = array;
	}
	const result = engine.hydrateToolInput(nested);
	expect(result.issue).toBeUndefined();
	expect(JSON.stringify(result.value)).toContain(value);
});