mirror of
https://bitbucket.org/siakitem/my-pi.git
synced 2026-10-26 10:45:22 +00:00
refactor(permission-system): simplify policy and autoreview flow
This commit is contained in:
@@ -1,395 +0,0 @@
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AccessIntent } from "#src/access-intent/access-intent";
|
||||
import { BashProgram } from "#src/access-intent/bash/program";
|
||||
import { describeBashExternalDirectoryGate } from "#src/handlers/gates/bash-external-directory";
|
||||
import type {
|
||||
GateBypass,
|
||||
GateDescriptor,
|
||||
GateResult,
|
||||
} from "#src/handlers/gates/descriptor";
|
||||
import { isGateBypass, isGateDescriptor } from "#src/handlers/gates/descriptor";
|
||||
import type { ToolCallContext } from "#src/handlers/gates/types";
|
||||
import { pathFlavorForPlatform, win32PathFlavor } from "#src/path/path-flavor";
|
||||
import { PathNormalizer } from "#src/path-normalizer";
|
||||
import type { ScopedPermissionResolver } from "#src/permission-resolver";
|
||||
import {
|
||||
allEvidence,
|
||||
findEvidence,
|
||||
type PromptPayload,
|
||||
} from "#src/presentation/prompt-payload";
|
||||
import type { PermissionCheckResult } from "#src/types";
|
||||
import { getNonEmptyString, toRecord } from "#src/value-guards";
|
||||
|
||||
import { makeResolver } from "#test/helpers/gate-fixtures";
|
||||
|
||||
// ── helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Every escaping path the payload lists, in payload order. */
|
||||
function externalPaths(payload: PromptPayload): string[] {
|
||||
return allEvidence(payload, "external path").map((entry) => entry.text);
|
||||
}
|
||||
|
||||
function makeTcc(overrides: Partial<ToolCallContext> = {}): ToolCallContext {
|
||||
return {
|
||||
toolName: "bash",
|
||||
agentName: null,
|
||||
input: { command: "cat /outside/project/file.ts" },
|
||||
toolCallId: "tc-1",
|
||||
cwd: "/test/project",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeCheckResult(
|
||||
state: "allow" | "deny" | "ask",
|
||||
overrides: Partial<PermissionCheckResult> = {},
|
||||
): PermissionCheckResult {
|
||||
return {
|
||||
state,
|
||||
toolName: "external_directory",
|
||||
source: "special",
|
||||
origin: "builtin",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** Extract the policy match values a resolve(intent) call carries. */
|
||||
function intentValues(intent: AccessIntent): readonly string[] {
|
||||
if (intent.kind === "access-path") return intent.path.matchValues();
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirror the handler's parse-once derivation: parse the bash command into a
|
||||
* shared `BashProgram` and inject it, exactly as `permission-gate-handler.ts`
|
||||
* does, so the gate is exercised through the production wiring.
|
||||
*/
|
||||
async function describeGate(
|
||||
tcc: ToolCallContext,
|
||||
resolver: ScopedPermissionResolver,
|
||||
): Promise<GateResult> {
|
||||
const command = getNonEmptyString(toRecord(tcc.input).command);
|
||||
const bashProgram =
|
||||
tcc.toolName === "bash" && command
|
||||
? await BashProgram.parse(
|
||||
command,
|
||||
new PathNormalizer(pathFlavorForPlatform(process.platform), tcc.cwd),
|
||||
)
|
||||
: null;
|
||||
return describeBashExternalDirectoryGate(tcc, bashProgram, resolver);
|
||||
}
|
||||
|
||||
// ── tests ──────────────────────────────────────────────────────────────────
|
||||
|
||||
describe("describeBashExternalDirectoryGate", () => {
|
||||
it("returns null when tool is not bash", async () => {
|
||||
const result = await describeGate(
|
||||
makeTcc({ toolName: "read" }),
|
||||
makeResolver(makeCheckResult("ask")),
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when command has no external paths", async () => {
|
||||
const result = await describeGate(
|
||||
makeTcc({ input: { command: "ls -la" } }),
|
||||
makeResolver(makeCheckResult("ask")),
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
describe("resolved shell expansions (#694)", () => {
|
||||
it("prompts for a $HOME write target that does not exist yet", async () => {
|
||||
const resolver = makeResolver(makeCheckResult("ask"));
|
||||
const result = await describeGate(
|
||||
makeTcc({
|
||||
input: {
|
||||
command: 'touch "$HOME/pi-permission-system-repro-new"',
|
||||
},
|
||||
}),
|
||||
resolver,
|
||||
);
|
||||
expect(isGateDescriptor(result)).toBe(true);
|
||||
expect(externalPaths((result as GateDescriptor).payload)).toEqual([
|
||||
join(homedir(), "pi-permission-system-repro-new"),
|
||||
]);
|
||||
});
|
||||
|
||||
// biome-ignore lint/suspicious/noTemplateCurlyInString: intentional literal — a braced shell expansion, not a template string
|
||||
it("prompts for a braced ${HOME} reference", async () => {
|
||||
const result = await describeGate(
|
||||
// biome-ignore lint/suspicious/noTemplateCurlyInString: intentional literal — a braced shell expansion, not a template string
|
||||
makeTcc({ input: { command: 'ls "${HOME}/somewhere"' } }),
|
||||
makeResolver(makeCheckResult("ask")),
|
||||
);
|
||||
expect(isGateDescriptor(result)).toBe(true);
|
||||
expect(externalPaths((result as GateDescriptor).payload)).toEqual([
|
||||
join(homedir(), "somewhere"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not prompt for a variable it cannot resolve", async () => {
|
||||
const result = await describeGate(
|
||||
makeTcc({ input: { command: 'CURRENT="$HOME"; ls "$CURRENT"' } }),
|
||||
makeResolver(makeCheckResult("ask")),
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves each external path on the external_directory surface via an access-path intent (#418)", async () => {
|
||||
const resolver = makeResolver(makeCheckResult("ask"));
|
||||
await describeGate(
|
||||
makeTcc({ input: { command: "cat /outside/a.ts" } }),
|
||||
resolver,
|
||||
);
|
||||
const intent = resolver.resolve.mock.calls[0][0];
|
||||
expect(intent).toMatchObject({
|
||||
kind: "access-path",
|
||||
surface: "external_directory",
|
||||
agentName: undefined,
|
||||
});
|
||||
expect(intentValues(intent)).toEqual(["/outside/a.ts"]);
|
||||
});
|
||||
|
||||
it("carries the deciding path's access facts on promptDetails (bash external_directory surface)", async () => {
|
||||
const resolver = makeResolver(makeCheckResult("ask"));
|
||||
const result = (await describeGate(
|
||||
makeTcc({ input: { command: "cat /outside/a.ts" } }),
|
||||
resolver,
|
||||
)) as GateDescriptor;
|
||||
const intent = resolver.resolve.mock.calls[0][0];
|
||||
const path = intent.kind === "access-path" ? intent.path : undefined;
|
||||
expect(path).toBeDefined();
|
||||
expect(result.promptDetails.accessIntent).toEqual({
|
||||
surface: "external_directory",
|
||||
matchValues: path?.matchValues(),
|
||||
boundaryValue: path?.boundaryValue(),
|
||||
});
|
||||
});
|
||||
|
||||
it("emits a bash_external_directory payload listing every escaping path", async () => {
|
||||
const resolver = makeResolver(makeCheckResult("ask"));
|
||||
const result = (await describeGate(
|
||||
makeTcc({ input: { command: "cat /outside/a.ts" } }),
|
||||
resolver,
|
||||
)) as GateDescriptor;
|
||||
|
||||
expect(result.payload.kind).toBe("bash_external_directory");
|
||||
// The command is the decision value; the paths it reaches are evidence.
|
||||
expect(result.payload.request.value).toBe("cat /outside/a.ts");
|
||||
expect(result.payload.evidence).toContainEqual({
|
||||
label: "external path",
|
||||
text: "/outside/a.ts",
|
||||
detail: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns GateBypass when all external paths are session-covered", async () => {
|
||||
const resolver = makeResolver(
|
||||
makeCheckResult("allow", { source: "session" }),
|
||||
);
|
||||
const result = await describeGate(makeTcc(), resolver);
|
||||
expect(result).not.toBeNull();
|
||||
expect(isGateBypass(result)).toBe(true);
|
||||
const bypass = result as GateBypass;
|
||||
expect(bypass.action).toBe("allow");
|
||||
expect(bypass.log).toMatchObject({
|
||||
event: "permission_request.session_approved",
|
||||
details: expect.objectContaining({ resolution: "session_approved" }),
|
||||
});
|
||||
expect(bypass.decidedBy).toEqual({
|
||||
kind: "session_approval",
|
||||
surface: "external_directory",
|
||||
pattern: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns GateDescriptor with multi-pattern sessionApproval for uncovered paths", async () => {
|
||||
const result = await describeGate(
|
||||
makeTcc({ input: { command: "diff /outside/a.ts /outside/b.ts" } }),
|
||||
makeResolver(makeCheckResult("ask")),
|
||||
);
|
||||
expect(isGateDescriptor(result)).toBe(true);
|
||||
const desc = result as GateDescriptor;
|
||||
expect(desc.sessionApproval).toBeDefined();
|
||||
if (!desc.sessionApproval) return;
|
||||
expect(desc.sessionApproval.patterns.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("returns GateBypass when all external paths are config-level allowed", async () => {
|
||||
// Config-level allow (source: "special") should suppress the prompt,
|
||||
// not just session-level allow. This was the bug: source !== "session"
|
||||
// kept config-allowed paths in the uncovered set.
|
||||
const resolver = makeResolver();
|
||||
resolver.resolve.mockImplementation((intent) =>
|
||||
intentValues(intent).length > 0
|
||||
? makeCheckResult("allow", { source: "special" })
|
||||
: makeCheckResult("ask"),
|
||||
);
|
||||
const result = await describeGate(makeTcc(), resolver);
|
||||
expect(result).not.toBeNull();
|
||||
expect(isGateBypass(result)).toBe(true);
|
||||
});
|
||||
|
||||
it("uses worst-check state from uncovered paths for preCheck (config deny > catch-all ask)", async () => {
|
||||
// The path-less extCheck used to always return the "*" catch-all (ask),
|
||||
// silently downgrading a config-level deny to ask. After the fix, the
|
||||
// descriptor's preCheck is derived from the actual path check result.
|
||||
const resolver = makeResolver();
|
||||
resolver.resolve.mockImplementation((intent) =>
|
||||
intentValues(intent).length > 0
|
||||
? makeCheckResult("deny", { source: "special" })
|
||||
: makeCheckResult("ask"),
|
||||
);
|
||||
const result = await describeGate(makeTcc(), resolver);
|
||||
expect(isGateDescriptor(result)).toBe(true);
|
||||
const desc = result as GateDescriptor;
|
||||
expect(desc.preCheck?.state).toBe("deny");
|
||||
});
|
||||
|
||||
it("descriptor surface is 'external_directory'", async () => {
|
||||
const result = await describeGate(
|
||||
makeTcc(),
|
||||
makeResolver(makeCheckResult("ask")),
|
||||
);
|
||||
const desc = result as GateDescriptor;
|
||||
expect(desc.surface).toBe("external_directory");
|
||||
});
|
||||
|
||||
it("descriptor decision surface is 'external_directory'", async () => {
|
||||
const result = await describeGate(
|
||||
makeTcc(),
|
||||
makeResolver(makeCheckResult("ask")),
|
||||
);
|
||||
const desc = result as GateDescriptor;
|
||||
expect(desc.decision.surface).toBe("external_directory");
|
||||
});
|
||||
|
||||
it("payload carries the command and the boundary it escaped", async () => {
|
||||
const result = await describeGate(
|
||||
makeTcc({ input: { command: "cat /outside/file.ts" } }),
|
||||
makeResolver(makeCheckResult("ask")),
|
||||
);
|
||||
const { payload } = result as GateDescriptor;
|
||||
expect(payload.kind).toBe("bash_external_directory");
|
||||
expect(payload.request.value).toBe("cat /outside/file.ts");
|
||||
expect(findEvidence(payload, "working directory")?.text).toBe(
|
||||
"/test/project",
|
||||
);
|
||||
});
|
||||
|
||||
it("promptDetails includes command and tool_call source", async () => {
|
||||
const result = await describeGate(
|
||||
makeTcc({ agentName: "agent-1", toolCallId: "tc-5" }),
|
||||
makeResolver(makeCheckResult("ask")),
|
||||
);
|
||||
const desc = result as GateDescriptor;
|
||||
expect(desc.promptDetails).toMatchObject({
|
||||
source: "tool_call",
|
||||
agentName: "agent-1",
|
||||
toolCallId: "tc-5",
|
||||
toolName: "bash",
|
||||
command: "cat /outside/project/file.ts",
|
||||
});
|
||||
});
|
||||
|
||||
it("config-allowed path is excluded; remaining ask path produces a descriptor", async () => {
|
||||
// One path config-allowed, one config-ask → descriptor with only the ask path.
|
||||
const resolver = makeResolver();
|
||||
resolver.resolve.mockImplementation((intent) =>
|
||||
intentValues(intent).includes("/outside/a.ts")
|
||||
? makeCheckResult("allow", { source: "special" })
|
||||
: makeCheckResult("ask"),
|
||||
);
|
||||
const result = await describeGate(
|
||||
makeTcc({ input: { command: "diff /outside/a.ts /outside/b.ts" } }),
|
||||
resolver,
|
||||
);
|
||||
expect(isGateDescriptor(result)).toBe(true);
|
||||
const desc = result as GateDescriptor;
|
||||
expect(desc.sessionApproval).toBeDefined();
|
||||
if (!desc.sessionApproval) return;
|
||||
expect(desc.sessionApproval.patterns.length).toBe(1);
|
||||
expect(desc.preCheck?.state).toBe("ask");
|
||||
});
|
||||
|
||||
it("config-denied path makes worstCheck deny even when another path is ask", async () => {
|
||||
// One path config-denied, one config-ask → descriptor with preCheck.state === "deny".
|
||||
const resolver = makeResolver();
|
||||
resolver.resolve.mockImplementation((intent) =>
|
||||
intentValues(intent).includes("/outside/a.ts")
|
||||
? makeCheckResult("deny", { source: "special" })
|
||||
: makeCheckResult("ask"),
|
||||
);
|
||||
const result = await describeGate(
|
||||
makeTcc({ input: { command: "diff /outside/a.ts /outside/b.ts" } }),
|
||||
resolver,
|
||||
);
|
||||
expect(isGateDescriptor(result)).toBe(true);
|
||||
const desc = result as GateDescriptor;
|
||||
expect(desc.preCheck?.state).toBe("deny");
|
||||
// Both paths are uncovered (neither is allow), so both patterns are included.
|
||||
expect(desc.sessionApproval).toBeDefined();
|
||||
if (!desc.sessionApproval) return;
|
||||
expect(desc.sessionApproval.patterns.length).toBe(2);
|
||||
});
|
||||
|
||||
it("only includes uncovered paths when some are session-covered", async () => {
|
||||
const resolver = makeResolver();
|
||||
resolver.resolve.mockImplementation((intent) =>
|
||||
intentValues(intent).includes("/outside/a.ts")
|
||||
? makeCheckResult("allow", { source: "session" })
|
||||
: makeCheckResult("ask"),
|
||||
);
|
||||
const result = await describeGate(
|
||||
makeTcc({ input: { command: "diff /outside/a.ts /outside/b.ts" } }),
|
||||
resolver,
|
||||
);
|
||||
expect(isGateDescriptor(result)).toBe(true);
|
||||
const desc = result as GateDescriptor;
|
||||
// Should have patterns only for the uncovered path
|
||||
expect(desc.sessionApproval).toBeDefined();
|
||||
if (!desc.sessionApproval) return;
|
||||
expect(desc.sessionApproval.patterns.length).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("describeBashExternalDirectoryGate — Git Bash semantics (win32)", () => {
|
||||
async function describeGateWin32(
|
||||
tcc: ToolCallContext,
|
||||
resolver: ScopedPermissionResolver,
|
||||
): Promise<GateResult> {
|
||||
const command = getNonEmptyString(toRecord(tcc.input).command);
|
||||
const bashProgram =
|
||||
tcc.toolName === "bash" && command
|
||||
? await BashProgram.parse(
|
||||
command,
|
||||
new PathNormalizer(win32PathFlavor, tcc.cwd),
|
||||
)
|
||||
: null;
|
||||
return describeBashExternalDirectoryGate(tcc, bashProgram, resolver);
|
||||
}
|
||||
|
||||
const winTcc = (command: string): ToolCallContext =>
|
||||
makeTcc({ cwd: "C:/projects/app", input: { command } });
|
||||
|
||||
it("does not prompt for a /dev/null redirect target", async () => {
|
||||
const result = await describeGateWin32(
|
||||
winTcc("echo hi > /dev/null"),
|
||||
makeResolver(makeCheckResult("ask")),
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("prompts for a /tmp path displayed as typed, not as C:\\tmp", async () => {
|
||||
const result = await describeGateWin32(
|
||||
winTcc("ls /tmp"),
|
||||
makeResolver(makeCheckResult("ask")),
|
||||
);
|
||||
expect(isGateDescriptor(result)).toBe(true);
|
||||
expect(externalPaths((result as GateDescriptor).payload)).toEqual(["/tmp"]);
|
||||
});
|
||||
});
|
||||
@@ -1,135 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { AccessPath } from "#src/access-intent/access-path";
|
||||
import {
|
||||
resolveExternalDirectoryPolicy,
|
||||
selectUncoveredExternalPaths,
|
||||
} from "#src/handlers/gates/external-directory-policy";
|
||||
import { posixPathFlavor } from "#src/path/path-flavor";
|
||||
import type { PermissionCheckResult } from "#src/types";
|
||||
|
||||
import { makeResolver } from "#test/helpers/gate-fixtures";
|
||||
|
||||
const cwd = "/test/project";
|
||||
|
||||
function makeCheckResult(
|
||||
state: "allow" | "deny" | "ask",
|
||||
overrides: Partial<PermissionCheckResult> = {},
|
||||
): PermissionCheckResult {
|
||||
return {
|
||||
state,
|
||||
toolName: "external_directory",
|
||||
source: "special",
|
||||
origin: "builtin",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("resolveExternalDirectoryPolicy", () => {
|
||||
it("resolves the path's match aliases on the external_directory surface (#418)", () => {
|
||||
const path = AccessPath.forPath("/outside/a.ts", {
|
||||
cwd,
|
||||
flavor: posixPathFlavor,
|
||||
});
|
||||
const resolver = makeResolver(makeCheckResult("ask"));
|
||||
|
||||
const result = resolveExternalDirectoryPolicy(path, resolver, undefined);
|
||||
|
||||
expect(resolver.resolve).toHaveBeenCalledWith({
|
||||
kind: "access-path",
|
||||
surface: "external_directory",
|
||||
path,
|
||||
agentName: undefined,
|
||||
});
|
||||
expect(result).toEqual(makeCheckResult("ask"));
|
||||
});
|
||||
|
||||
it("threads the agent name through to the resolver", () => {
|
||||
const path = AccessPath.forPath("/outside/a.ts", {
|
||||
cwd,
|
||||
flavor: posixPathFlavor,
|
||||
});
|
||||
const resolver = makeResolver(makeCheckResult("allow"));
|
||||
|
||||
resolveExternalDirectoryPolicy(path, resolver, "reviewer");
|
||||
|
||||
expect(resolver.resolve).toHaveBeenCalledWith({
|
||||
kind: "access-path",
|
||||
surface: "external_directory",
|
||||
path,
|
||||
agentName: "reviewer",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("selectUncoveredExternalPaths", () => {
|
||||
it("returns no uncovered paths when every path resolves to allow", () => {
|
||||
const paths = [
|
||||
AccessPath.forPath("/outside/a.ts", { cwd, flavor: posixPathFlavor }),
|
||||
AccessPath.forPath("/outside/b.ts", { cwd, flavor: posixPathFlavor }),
|
||||
];
|
||||
const resolver = makeResolver(makeCheckResult("allow"));
|
||||
|
||||
const { uncovered, worstCheck } = selectUncoveredExternalPaths(
|
||||
paths,
|
||||
resolver,
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(uncovered).toEqual([]);
|
||||
expect(worstCheck).toBeUndefined();
|
||||
});
|
||||
|
||||
it("collects only paths whose resolved state is not allow", () => {
|
||||
const allowed = AccessPath.forPath("/outside/ok.ts", {
|
||||
cwd,
|
||||
flavor: posixPathFlavor,
|
||||
});
|
||||
const asked = AccessPath.forPath("/outside/ask.ts", {
|
||||
cwd,
|
||||
flavor: posixPathFlavor,
|
||||
});
|
||||
const resolver = makeResolver();
|
||||
resolver.resolve.mockImplementation((intent) => {
|
||||
const values =
|
||||
intent.kind === "access-path" ? intent.path.matchValues() : [];
|
||||
return values.includes("/outside/ok.ts")
|
||||
? makeCheckResult("allow")
|
||||
: makeCheckResult("ask");
|
||||
});
|
||||
|
||||
const { uncovered } = selectUncoveredExternalPaths(
|
||||
[allowed, asked],
|
||||
resolver,
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(uncovered.map(({ path }) => path.value())).toEqual([asked.value()]);
|
||||
});
|
||||
|
||||
it("returns the most restrictive uncovered check as worstCheck (deny > ask)", () => {
|
||||
const asked = AccessPath.forPath("/outside/ask.ts", {
|
||||
cwd,
|
||||
flavor: posixPathFlavor,
|
||||
});
|
||||
const denied = AccessPath.forPath("/outside/deny.ts", {
|
||||
cwd,
|
||||
flavor: posixPathFlavor,
|
||||
});
|
||||
const resolver = makeResolver();
|
||||
resolver.resolve.mockImplementation((intent) => {
|
||||
const values =
|
||||
intent.kind === "access-path" ? intent.path.matchValues() : [];
|
||||
return values.includes("/outside/deny.ts")
|
||||
? makeCheckResult("deny")
|
||||
: makeCheckResult("ask");
|
||||
});
|
||||
|
||||
const { worstCheck } = selectUncoveredExternalPaths(
|
||||
[asked, denied],
|
||||
resolver,
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(worstCheck?.state).toBe("deny");
|
||||
});
|
||||
});
|
||||
@@ -1,304 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type {
|
||||
GateBypass,
|
||||
GateDescriptor,
|
||||
} from "#src/handlers/gates/descriptor";
|
||||
import { isGateBypass, isGateDescriptor } from "#src/handlers/gates/descriptor";
|
||||
import { describeExternalDirectoryGate } from "#src/handlers/gates/external-directory";
|
||||
import type { ToolCallContext } from "#src/handlers/gates/types";
|
||||
import { pathFlavorForPlatform } from "#src/path/path-flavor";
|
||||
import { PathNormalizer } from "#src/path-normalizer";
|
||||
import type { ScopedPermissionResolver } from "#src/permission-resolver";
|
||||
import type { ToolAccessExtractorLookup } from "#src/tool-access-extractor-registry";
|
||||
import { makeResolver } from "#test/helpers/gate-fixtures";
|
||||
import { makeCheckResult } from "#test/helpers/handler-fixtures";
|
||||
|
||||
// ── helpers ───────────────────────────��────────────────────────────��───────
|
||||
|
||||
function makeTcc(overrides: Partial<ToolCallContext> = {}): ToolCallContext {
|
||||
return {
|
||||
toolName: "read",
|
||||
agentName: null,
|
||||
input: { path: "/outside/project/file.ts" },
|
||||
toolCallId: "tc-1",
|
||||
cwd: "/test/project",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
// Default resolver for descriptor-shape tests that do not assert the resolved
|
||||
// state: returns `ask` for the external_directory surface so a descriptor is
|
||||
// produced. Tests that assert the typed+resolved matching pass an explicit
|
||||
// resolver to `describeExternalDirectoryGate` directly.
|
||||
function gateUnderTest(
|
||||
tcc: ToolCallContext,
|
||||
infraDirs: string[],
|
||||
extractors?: ToolAccessExtractorLookup,
|
||||
resolver: ScopedPermissionResolver = makeResolver(
|
||||
makeCheckResult({ state: "ask", toolName: "external_directory" }),
|
||||
),
|
||||
) {
|
||||
return describeExternalDirectoryGate(
|
||||
tcc,
|
||||
infraDirs,
|
||||
resolver,
|
||||
new PathNormalizer(pathFlavorForPlatform(process.platform), tcc.cwd),
|
||||
extractors,
|
||||
);
|
||||
}
|
||||
|
||||
// ── tests ────────────────────��────────────────────────────────────��────────
|
||||
|
||||
describe("describeExternalDirectoryGate", () => {
|
||||
it("returns null when tool is not path-bearing", () => {
|
||||
const result = gateUnderTest(
|
||||
makeTcc({ toolName: "bash", input: { command: "ls" } }),
|
||||
["/test/agent"],
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when path is inside CWD", () => {
|
||||
const result = gateUnderTest(
|
||||
makeTcc({ input: { path: "/test/project/src/index.ts" } }),
|
||||
["/test/agent"],
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
// ── Pi infrastructure read bypass ─────────────────���────────────────────
|
||||
|
||||
it("returns GateBypass for read targeting an infra dir", () => {
|
||||
const result = gateUnderTest(
|
||||
makeTcc({
|
||||
toolName: "read",
|
||||
input: { path: "/test/agent/git/some-package/SKILL.md" },
|
||||
}),
|
||||
["/test/agent", "/test/agent/git"],
|
||||
);
|
||||
expect(result).not.toBeNull();
|
||||
expect(isGateBypass(result)).toBe(true);
|
||||
const bypass = result as GateBypass;
|
||||
expect(bypass.action).toBe("allow");
|
||||
expect(bypass.decision).toMatchObject({
|
||||
resolution: "infrastructure_auto_allowed",
|
||||
result: "allow",
|
||||
});
|
||||
expect(bypass.log).toMatchObject({
|
||||
event: "permission_request.infrastructure_auto_allowed",
|
||||
});
|
||||
// Containment allowed this, not a rule the operator wrote.
|
||||
expect(bypass.decidedBy).toEqual({ kind: "infrastructure_read" });
|
||||
});
|
||||
|
||||
it("returns GateBypass respecting custom infraDirs", () => {
|
||||
const result = gateUnderTest(
|
||||
makeTcc({
|
||||
toolName: "read",
|
||||
input: { path: "/custom/infra/SKILL.md" },
|
||||
}),
|
||||
["/custom/infra"],
|
||||
);
|
||||
expect(isGateBypass(result)).toBe(true);
|
||||
});
|
||||
|
||||
it("does NOT bypass for write tools targeting infra dirs", () => {
|
||||
const result = gateUnderTest(
|
||||
makeTcc({
|
||||
toolName: "write",
|
||||
input: { path: "/test/agent/git/some-file.ts", content: "x" },
|
||||
}),
|
||||
["/test/agent", "/test/agent/git"],
|
||||
);
|
||||
// Should be a GateDescriptor (needs permission check), not a bypass
|
||||
expect(result).not.toBeNull();
|
||||
expect(isGateDescriptor(result)).toBe(true);
|
||||
});
|
||||
|
||||
// ── GateDescriptor for external paths ─────────────────────────────────��
|
||||
|
||||
it("returns GateDescriptor with surface 'external_directory'", () => {
|
||||
const result = gateUnderTest(makeTcc(), ["/test/agent"]);
|
||||
expect(isGateDescriptor(result)).toBe(true);
|
||||
const desc = result as GateDescriptor;
|
||||
expect(desc.surface).toBe("external_directory");
|
||||
});
|
||||
|
||||
it("decision value is the external path", () => {
|
||||
const result = gateUnderTest(
|
||||
makeTcc({ input: { path: "/outside/project/file.ts" } }),
|
||||
["/test/agent"],
|
||||
) as GateDescriptor;
|
||||
expect(result.decision.value).toBe("/outside/project/file.ts");
|
||||
expect(result.decision.surface).toBe("external_directory");
|
||||
});
|
||||
|
||||
it("carries the child-fixed access facts on promptDetails (external_directory surface)", () => {
|
||||
const path = "/outside/project/file.ts";
|
||||
const result = gateUnderTest(makeTcc({ input: { path } }), [
|
||||
"/test/agent",
|
||||
]) as GateDescriptor;
|
||||
const accessPath = new PathNormalizer(
|
||||
pathFlavorForPlatform(process.platform),
|
||||
"/test/project",
|
||||
).forPath(path);
|
||||
expect(result.promptDetails.accessIntent).toEqual({
|
||||
surface: "external_directory",
|
||||
matchValues: accessPath.matchValues(),
|
||||
boundaryValue: accessPath.boundaryValue(),
|
||||
});
|
||||
});
|
||||
|
||||
it("emits an external_directory payload carrying the escaped boundary", () => {
|
||||
const result = gateUnderTest(
|
||||
makeTcc({ input: { path: "/outside/project/file.ts" } }),
|
||||
["/test/agent"],
|
||||
) as GateDescriptor;
|
||||
|
||||
expect(result.payload.kind).toBe("external_directory");
|
||||
expect(result.payload.request.value).toBe("/outside/project/file.ts");
|
||||
expect(result.payload.evidence).toContainEqual({
|
||||
label: "working directory",
|
||||
text: "/test/project",
|
||||
detail: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("carries a precomputed preCheck and an empty input (matching is done by the gate)", () => {
|
||||
const result = gateUnderTest(
|
||||
makeTcc({ input: { path: "/outside/project/file.ts" } }),
|
||||
["/test/agent"],
|
||||
) as GateDescriptor;
|
||||
expect(result.input).toEqual({});
|
||||
expect(result.preCheck).toBeDefined();
|
||||
expect(result.preCheck?.state).toBe("ask");
|
||||
});
|
||||
|
||||
it("resolves the typed and symlink-resolved aliases on the external_directory surface (#418)", () => {
|
||||
const resolver = makeResolver(
|
||||
makeCheckResult({ state: "ask", toolName: "external_directory" }),
|
||||
);
|
||||
gateUnderTest(
|
||||
makeTcc({ input: { path: "/outside/project/file.ts" } }),
|
||||
["/test/agent"],
|
||||
undefined,
|
||||
resolver,
|
||||
);
|
||||
expect(resolver.resolve).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: "access-path",
|
||||
surface: "external_directory",
|
||||
agentName: undefined,
|
||||
}),
|
||||
);
|
||||
const intent = resolver.resolve.mock.calls[0][0];
|
||||
expect(intent.kind).toBe("access-path");
|
||||
if (intent.kind === "access-path") {
|
||||
expect(intent.path.matchValues()).toEqual(["/outside/project/file.ts"]);
|
||||
}
|
||||
});
|
||||
|
||||
it("sessionApproval uses deriveApprovalPattern", () => {
|
||||
const result = gateUnderTest(
|
||||
makeTcc({ input: { path: "/outside/project/file.ts" } }),
|
||||
["/test/agent"],
|
||||
) as GateDescriptor;
|
||||
expect(result.sessionApproval).toBeDefined();
|
||||
expect(result.sessionApproval?.surface).toBe("external_directory");
|
||||
expect(result.sessionApproval?.representativePattern).toBeDefined();
|
||||
});
|
||||
|
||||
it("payload contains the external path and the boundary it escaped", () => {
|
||||
const result = gateUnderTest(
|
||||
makeTcc({ input: { path: "/outside/project/file.ts" } }),
|
||||
["/test/agent"],
|
||||
) as GateDescriptor;
|
||||
expect(result.payload.kind).toBe("external_directory");
|
||||
expect(result.payload.request.toolName).toBe("read");
|
||||
expect(result.payload.request.value).toBe("/outside/project/file.ts");
|
||||
expect(result.payload.evidence).toContainEqual({
|
||||
label: "working directory",
|
||||
text: "/test/project",
|
||||
detail: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("promptDetails includes path and tool_call source", () => {
|
||||
const result = gateUnderTest(
|
||||
makeTcc({ toolName: "read", agentName: "agent-1", toolCallId: "tc-5" }),
|
||||
["/test/agent"],
|
||||
) as GateDescriptor;
|
||||
expect(result.promptDetails).toMatchObject({
|
||||
source: "tool_call",
|
||||
agentName: "agent-1",
|
||||
toolCallId: "tc-5",
|
||||
toolName: "read",
|
||||
path: "/outside/project/file.ts",
|
||||
});
|
||||
});
|
||||
|
||||
it("logContext includes the path, and no prompt wording", () => {
|
||||
const result = gateUnderTest(makeTcc(), ["/test/agent"]) as GateDescriptor;
|
||||
expect(result.logContext).toMatchObject({
|
||||
source: "tool_call",
|
||||
path: "/outside/project/file.ts",
|
||||
});
|
||||
// The payload's request facts are stamped by the runner, not the gate.
|
||||
expect(result.logContext).not.toHaveProperty("message");
|
||||
});
|
||||
});
|
||||
|
||||
// Extension and MCP tools are now external-directory gated (#352) ───────────
|
||||
|
||||
describe("describeExternalDirectoryGate — extension and MCP tools (#352)", () => {
|
||||
it("gates an extension tool with an external input.path", () => {
|
||||
const result = gateUnderTest(
|
||||
makeTcc({
|
||||
toolName: "my-ext",
|
||||
input: { path: "/outside/project/file.ts" },
|
||||
}),
|
||||
["/test/agent"],
|
||||
);
|
||||
expect(isGateDescriptor(result)).toBe(true);
|
||||
expect((result as GateDescriptor).surface).toBe("external_directory");
|
||||
});
|
||||
|
||||
it("gates an MCP tool with an external arguments.path", () => {
|
||||
const result = gateUnderTest(
|
||||
makeTcc({
|
||||
toolName: "mcp",
|
||||
input: { arguments: { path: "/outside/project/file.ts" } },
|
||||
}),
|
||||
["/test/agent"],
|
||||
);
|
||||
expect(isGateDescriptor(result)).toBe(true);
|
||||
});
|
||||
|
||||
it("uses a registered extractor's external path for a custom-shaped tool", () => {
|
||||
const extractors = {
|
||||
get: (name: string) =>
|
||||
name === "ffgrep"
|
||||
? (input: Record<string, unknown>) =>
|
||||
typeof input.target === "string" ? input.target : undefined
|
||||
: undefined,
|
||||
};
|
||||
const result = gateUnderTest(
|
||||
makeTcc({ toolName: "ffgrep", input: { target: "/outside/project/x" } }),
|
||||
["/test/agent"],
|
||||
extractors,
|
||||
);
|
||||
expect(isGateDescriptor(result)).toBe(true);
|
||||
});
|
||||
|
||||
it("returns null for an extension tool whose path is inside cwd", () => {
|
||||
const result = gateUnderTest(
|
||||
makeTcc({
|
||||
toolName: "my-ext",
|
||||
input: { path: "/test/project/src/x.ts" },
|
||||
}),
|
||||
["/test/agent"],
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -847,29 +847,6 @@ describe("GateRunner — request identity", () => {
|
||||
expect(decisions[0].requestId).toBe(reviewWrites[0].details.requestId);
|
||||
});
|
||||
|
||||
it("stamps a bypass's log entry and decision event with one id", async () => {
|
||||
const { runner, reviewWrites, decisions } = makeRecordingRunner();
|
||||
const bypass: GateBypass = {
|
||||
action: "allow",
|
||||
decidedBy: { kind: "infrastructure_read" },
|
||||
log: {
|
||||
event: "permission_request.infrastructure_auto_allowed",
|
||||
details: { path: "/x" },
|
||||
},
|
||||
decision: {
|
||||
surface: "read",
|
||||
value: "/x",
|
||||
result: "allow",
|
||||
resolution: "infrastructure_auto_allowed",
|
||||
origin: null,
|
||||
agentName: null,
|
||||
matchedPattern: null,
|
||||
},
|
||||
};
|
||||
await runner.run(bypass, null);
|
||||
expect(decisions[0].requestId).toMatch(/^perm-/);
|
||||
expect(decisions[0].requestId).toBe(reviewWrites[0].details.requestId);
|
||||
});
|
||||
|
||||
it("stamps an allow decision event even when nothing is written to the log", async () => {
|
||||
const { runner, decisions } = makeRecordingRunner();
|
||||
|
||||
@@ -118,17 +118,6 @@ describe("ToolCallGatePipeline", () => {
|
||||
expect(getToolPreviewLimits).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("calls getInfrastructureReadDirs() during evaluate", async () => {
|
||||
const getInfrastructureReadDirs = vi.fn<() => string[]>(() => []);
|
||||
const resolver = makeResolver(makeCheckResult());
|
||||
const inputs = makeGateInputs({ getInfrastructureReadDirs });
|
||||
const { runner } = makeGateRunner();
|
||||
const pipeline = new ToolCallGatePipeline(resolver, inputs);
|
||||
|
||||
await pipeline.evaluate(makeTcc({ toolName: "read", input: {} }), runner);
|
||||
|
||||
expect(getInfrastructureReadDirs).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("calls getActiveSkillEntries() during evaluate", async () => {
|
||||
const getActiveSkillEntries = vi.fn<() => []>(() => []);
|
||||
|
||||
Reference in New Issue
Block a user