Skip to content

Commit fc58fbe

Browse files
committed
fix(pi): close remaining external input permission gaps
Signed-off-by: yashrajbasav <[email protected]>
1 parent 5667438 commit fc58fbe

5 files changed

Lines changed: 138 additions & 26 deletions

File tree

‎docs/PI_EXTENSION.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,14 @@ Equivalent CLI:
4848
- `yaraRulesDir`: optional directory of extra YARA rules.
4949
- `verbose`: optional detailed progress.
5050

51+
Inputs inside the session's working directory run without a prompt. Remote targets
52+
and external paths require confirmation; redirected aliases show their resolved
53+
destination too. Print and JSON sessions reject these requests because they cannot
54+
show a dialog. Use TUI or RPC mode, move the skill into the working directory, or
55+
run the CLI directly. Local targets retain the CLI's refusal of symlinked paths.
56+
Missing rule directories fail before scanning, and YARA `include` directives are
57+
disabled: put self-contained rule files in the selected directory.
58+
5159
## LLM-backed analysis
5260

5361
Static scan is default. To use semantic LLM analysis, configure provider credentials in your shell before launching Pi, then call the tool with `noLlm=false` and a provider.

‎extensions/skillspector.ts‎

Lines changed: 46 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,25 @@ async function approveScanInputs(
6666
ctx: ExtensionContext,
6767
signal?: AbortSignal,
6868
): Promise<SkillSpectorScanParams> {
69+
signal?.throwIfAborted();
6970
const workspace = realpathSync(ctx.cwd);
7071
const prepared = { ...params };
71-
const localPaths: Array<{ input: string; resolved: string }> = [];
72+
const localPaths: Array<{ field: "target" | "yaraRulesDir"; input: string; resolved?: string }> = [];
7273
const requests: string[] = [];
74+
const readRequest = (field: string, path: string) =>
75+
`Read external ${field === "target" ? "scan target" : "YARA rules"}: ${JSON.stringify(path)}`;
76+
async function approve(requests: string[]): Promise<void> {
77+
if (!requests.length) return;
78+
signal?.throwIfAborted();
79+
if (!ctx.hasUI) throw new Error("External scan inputs require user confirmation in an interactive or RPC session.");
80+
const approved = await ctx.ui.confirm(
81+
"Allow SkillSpector external access?",
82+
`${requests.join("\n")}\n\nScanned content and matching rule text can appear in the agent conversation.`,
83+
{ signal },
84+
);
85+
signal?.throwIfAborted();
86+
if (!approved) throw new Error("SkillSpector external access was not approved.");
87+
}
7388
for (const field of ["target", "yaraRulesDir"] as const) {
7489
const value = params[field]?.trim();
7590
if (field === "yaraRulesDir" && !value) {
@@ -85,26 +100,40 @@ async function approveScanInputs(
85100
requests.push(`Fetch remote scan target: ${JSON.stringify(value)}`);
86101
} else {
87102
const input = resolve(ctx.cwd, value);
88-
const resolved = realpathSync(input);
89-
prepared[field] = resolved;
90-
localPaths.push({ input, resolved });
91-
if (!isWithin(workspace, resolved)) {
92-
requests.push(`Read external ${field === "target" ? "scan target" : "YARA rules"}: ${JSON.stringify(resolved)}`);
103+
// Ask before resolving external paths, which can probe the host or access
104+
// a Windows network share even when the file is never opened.
105+
if (!isWithin(resolve(ctx.cwd), input)) {
106+
localPaths.push({ field, input });
107+
requests.push(readRequest(field, input));
108+
} else {
109+
let resolved: string;
110+
try {
111+
resolved = realpathSync(input);
112+
} catch {
113+
throw new Error(`Could not resolve ${field === "target" ? "scan target" : "YARA rules directory"}. Check that it exists and is accessible.`);
114+
}
115+
localPaths.push({ field, input, resolved });
116+
if (!isWithin(workspace, resolved)) requests.push(readRequest(field, resolved));
93117
}
94118
}
95119
}
96-
signal?.throwIfAborted();
97-
if (requests.length) {
98-
if (!ctx.hasUI) throw new Error("External scan inputs require user confirmation in an interactive or RPC session.");
99-
const approved = await ctx.ui.confirm(
100-
"Allow SkillSpector external access?",
101-
`${requests.join("\n")}\n\nScanned content and matching rule text can appear in the agent conversation.`,
102-
);
103-
if (!approved) throw new Error("SkillSpector external access was not approved.");
120+
await approve(requests);
121+
const aliasRequests: string[] = [];
122+
for (const path of localPaths) {
123+
try {
124+
path.resolved ??= realpathSync(path.input);
125+
} catch {
126+
throw new Error(`Could not resolve ${path.field === "target" ? "scan target" : "YARA rules directory"}. Check that it exists and is accessible.`);
127+
}
128+
if (!isWithin(resolve(ctx.cwd), path.input) && !isWithin(workspace, path.resolved) && path.resolved !== path.input) {
129+
aliasRequests.push(readRequest(path.field, path.resolved));
130+
}
131+
// Keep the original target path so the CLI can enforce its no-symlink
132+
// input policy. YARA directories are canonicalised by the CLI too.
133+
prepared[path.field] = path.field === "target" ? path.input : path.resolved;
104134
}
135+
await approve(aliasRequests);
105136
signal?.throwIfAborted();
106-
// The dialog can wait indefinitely. Recheck aliases before launching, and
107-
// pass canonical paths to the CLI, whose file reads use no-follow handles.
108137
if (realpathSync(ctx.cwd) !== workspace || localPaths.some(({ input, resolved }) => realpathSync(input) !== resolved)) {
109138
throw new Error("Scan input path changed while awaiting confirmation.");
110139
}
@@ -170,8 +199,8 @@ export default function (pi: ExtensionAPI) {
170199
parameters: scanSchema,
171200
async execute(_toolCallId, params, signal, onUpdate, ctx) {
172201
const bin = findSkillSpectorBin();
173-
const prepared = await approveScanInputs(params, ctx, signal);
174202
const outputPath = reportOutputPath(ctx.cwd, params.output);
203+
const prepared = await approveScanInputs(params, ctx, signal);
175204
const reportDir = outputPath ? mkdtempSync(join(tmpdir(), "skillspector-report-")) : undefined;
176205
const reportPath = reportDir ? join(reportDir, "report") : undefined;
177206
try {

‎src/skillspector/nodes/analyzers/static_yara.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -522,7 +522,7 @@ def _compile_rules(
522522
"""
523523
_enforce_rule_load_deadline()
524524
try:
525-
compiled = yara.compile(sources=sources)
525+
compiled = yara.compile(sources=sources, includes=False)
526526
_enforce_rule_load_deadline()
527527
return compiled, 0
528528
except yara.SyntaxError:
@@ -534,7 +534,7 @@ def _compile_rules(
534534
for ns, source in sources.items():
535535
_enforce_rule_load_deadline()
536536
try:
537-
yara.compile(source=source)
537+
yara.compile(source=source, includes=False)
538538
good[ns] = source
539539
except (yara.SyntaxError, yara.Error) as exc:
540540
skipped += 1
@@ -548,7 +548,7 @@ def _compile_rules(
548548
)
549549

550550
_enforce_rule_load_deadline()
551-
compiled = yara.compile(sources=good) if good else None
551+
compiled = yara.compile(sources=good, includes=False) if good else None
552552
_enforce_rule_load_deadline()
553553
return compiled, skipped
554554

‎tests/nodes/analyzers/test_static_yara.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2409,6 +2409,35 @@ def test_build_namespace_map_skips_malformed_encoded_rules(self, tmp_path):
24092409
assert "invalid" not in ns_map
24102410
assert skipped == 1
24112411

2412+
@pytest.mark.parametrize("relative", [False, True])
2413+
def test_external_includes_are_rejected_without_dropping_valid_rules(
2414+
self, tmp_path, monkeypatch, relative
2415+
):
2416+
rules_dir = tmp_path / "rules"
2417+
rules_dir.mkdir()
2418+
outside = tmp_path / "private.yar"
2419+
outside.write_text("rule external_private_rule { condition: true }")
2420+
include = "../private.yar" if relative else str(outside)
2421+
(rules_dir / "include.yar").write_text(f'include "{include}"')
2422+
(rules_dir / "good.yar").write_text("rule approved_local_rule { condition: true }")
2423+
monkeypatch.chdir(rules_dir)
2424+
monkeypatch.setattr(static_yara, "_rule_cache", None)
2425+
monkeypatch.setattr(static_yara, "_BUILTIN_RULES_DIR", tmp_path / "empty_builtin")
2426+
result = static_yara.node(
2427+
{
2428+
"components": ["SKILL.md"],
2429+
"file_cache": {"SKILL.md": "Local sample skill."},
2430+
"yara_rules_dir": str(rules_dir),
2431+
}
2432+
)
2433+
assert any("approved_local_rule" in f.message for f in result["findings"])
2434+
assert not any("external_private_rule" in f.message for f in result["findings"])
2435+
assert result["analyzer_status_events"][0]["status"] != "completed"
2436+
assert any(
2437+
event.get("reason_code") == LedgerReason.READ_ERROR
2438+
for event in result["inspection_ledger"]
2439+
)
2440+
24122441
def test_malformed_rule_is_reported_not_silently_dropped(self, tmp_path, monkeypatch):
24132442
"""A custom rule that can't compile must not report a clean, SAFE scan (#554).
24142443

‎tests/unit/test_pi_extension.mjs‎

Lines changed: 52 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,16 @@ async function setup(t, exec, confirm = async () => false) {
6767
scan: (params = {}, context = {}, signal) => tool.execute("scan", { target: "./SKILL.md", ...params }, signal, undefined, {
6868
cwd: workspace,
6969
hasUI: true,
70-
ui: { async confirm(title, message) { prompts.push({ title, message }); return confirm({ root, workspace }); } },
70+
ui: { async confirm(title, message, options) {
71+
prompts.push({ title, message });
72+
return new Promise((resolve, reject) => {
73+
const signal = options?.signal;
74+
const abort = () => reject(signal.reason);
75+
if (signal?.aborted) return abort();
76+
signal?.addEventListener("abort", abort, { once: true });
77+
Promise.resolve(confirm({ root, workspace })).then(resolve, reject).finally(() => signal?.removeEventListener("abort", abort));
78+
});
79+
} },
7180
...context,
7281
}),
7382
};
@@ -187,7 +196,7 @@ test("requires approval before exposing external targets or YARA rules to the CL
187196
assert.ok(ctx.prompts[5].message.includes(JSON.stringify(rules)));
188197
});
189198

190-
test("approves the complete external read scope and passes only canonical paths", async (t) => {
199+
test("approves canonical external scope and preserves the CLI target symlink policy", async (t) => {
191200
const ctx = await setup(t, undefined, async () => true);
192201
writeFileSync(join(ctx.root, "private.md"), "synthetic private content");
193202
mkdirSync(join(ctx.root, "rules"));
@@ -196,7 +205,7 @@ test("approves the complete external read scope and passes only canonical paths"
196205
assert.equal(ctx.prompts.length, 1);
197206
assert.match(ctx.prompts[0].message, /Read external scan target:/);
198207
assert.match(ctx.prompts[0].message, /Read external YARA rules:/);
199-
assert.equal(ctx.calls[0].args[1], join(ctx.root, "private.md"));
208+
assert.equal(ctx.calls[0].args[1], join(ctx.workspace, "external/private.md"));
200209
assert.equal(ctx.calls[0].args.at(-1), join(ctx.root, "rules"));
201210
});
202211

@@ -217,14 +226,12 @@ test("treats local git@ paths as canonical local reads", async (t) => {
217226
});
218227

219228
test("does not launch until approval arrives or after a canceled dialog", async (t) => {
220-
let approve;
221-
const ctx = await setup(t, undefined, () => new Promise((resolve) => { approve = resolve; }));
229+
const ctx = await setup(t, undefined, () => new Promise(() => {}));
222230
const controller = new AbortController();
223231
const scan = ctx.scan({ target: "https://example.test/skill.zip" }, {}, controller.signal);
224232
await new Promise((resolve) => setImmediate(resolve));
225233
assert.equal(ctx.calls.length, 0);
226234
controller.abort();
227-
approve(true);
228235
await assert.rejects(scan, /abort/i);
229236
assert.equal(ctx.calls.length, 0);
230237
});
@@ -384,3 +391,42 @@ test("cleans staged reports after operational failure, cancellation, and missing
384391
});
385392
}
386393
});
394+
395+
396+
test("rejects external headless paths uniformly before checking their existence", async (t) => {
397+
const ctx = await setup(t);
398+
writeFileSync(join(ctx.root, "existing.md"), "private");
399+
for (const target of ["../existing.md", "../missing.md"]) {
400+
await assert.rejects(ctx.scan({ target }, { hasUI: false }), /require user confirmation/);
401+
}
402+
assert.equal(ctx.calls.length, 0);
403+
});
404+
405+
test("rejects invalid output and pre-canceled calls before showing a dialog", async (t) => {
406+
const ctx = await setup(t);
407+
await assert.rejects(ctx.scan({ target: "https://example.test/skill", output: "../report.json" }), /within the current workspace/);
408+
const controller = new AbortController();
409+
controller.abort();
410+
await assert.rejects(ctx.scan({ target: "https://example.test/skill" }, {}, controller.signal), /abort/i);
411+
assert.equal(ctx.prompts.length, 0);
412+
assert.equal(ctx.calls.length, 0);
413+
});
414+
415+
test("rejects a workspace swapped while a remote target awaits approval", async (t) => {
416+
const ctx = await setup(t, undefined, async ({ root, workspace }) => {
417+
renameSync(workspace, join(root, "original-workspace"));
418+
symlinkSync(root, workspace);
419+
return true;
420+
});
421+
await assert.rejects(ctx.scan({ target: "https://example.test/skill" }), /input path changed/);
422+
assert.equal(ctx.calls.length, 0);
423+
});
424+
425+
test("gives a clear error for missing workspace targets or rule directories", async (t) => {
426+
const ctx = await setup(t);
427+
for (const params of [{ target: "missing.md" }, { yaraRulesDir: "missing-rules" }]) {
428+
await assert.rejects(ctx.scan(params), /Could not resolve/);
429+
}
430+
assert.equal(ctx.calls.length, 0);
431+
assert.equal(ctx.prompts.length, 0);
432+
});

0 commit comments

Comments
 (0)