Files
ai-agent/runner/extensions/folder-permissions.ts
gabrielvidal aaab115fa2 fix(sidecar): Monitor through the guard, fail-closed, scoped runs ignore project Claude settings; safe git, egress, ship from a copy
Monitor ran shell commands the guard never saw; the owner CLI, docker and ssh
rules fell to ordinary spellings (the CLI now refuses under AIA_GUEST); a guard
exception let the call through; chat-level runs still had the owner's gitea.lab
and gh credential helpers. Scoped lab runs: --setting-sources user,
--strict-mcp-config, hooks under python -I, the project CLAUDE.md appended as
text, scope.noBash. 3d-render uploads carry data: URIs only; a guest's video
URL resolves to public addresses through a vetting proxy; git on a guest repo
runs with fsmonitor, hooks, filters and textconv out of reach; the ship broker
deploys a checked copy; tokens leave argv.
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-15 15:23:05 +01:00

159 lines
7.1 KiB
TypeScript

/**
* folder-permissions — scope-based read/execute/write gating for pi sessions.
*
* pi has no built-in permission system; extensions can block any tool call via
* the `tool_call` event. Policy is derived from the session's worktree path:
*
* PI_PERM_SCOPE the worktree/project root (default: cwd). write/edit are
* allowed ONLY inside it.
* PI_PERM_READ colon-separated extra readable roots (default: $HOME; a
* guest's job: its own folder — the runner's `--read`).
* The scope itself and system prefixes are always readable.
* bash may only reference paths inside the readable roots —
* absolute ones, `~/…` / `$HOME/…`, and relative ones that
* climb with `..` (naive token scan — defense in depth, not
* a sandbox).
*
* PI_ALLOW_CMDS comma-separated programs a lean run may call (sidecar
* launch.py "lean runs"): every command of a bash call must
* start with one of them or a read-only SAFE_CMDS — the
* counterpart of the sidecar's allow_guard.py hook (claude).
*
* A deny-always list protects secrets from write/edit regardless of scope.
* Headless runs have no UI, so every violation is a hard block with a reason
* the model can read and report.
*/
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { realpathSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, resolve } from "node:path";
const SYSTEM_PREFIXES = ["/usr", "/bin", "/sbin", "/etc", "/proc", "/sys", "/opt",
"/var", "/run", "/tmp", "/dev/null", "/dev/stdin", "/dev/stdout", "/dev/stderr"];
const WRITE_DENY = [/\/\.env(\.|$)/, /\.credentials/, /\/\.ssh\//, /\/\.gnupg\//];
// What a lean run may always call, allowlist or not: reading and shaping text.
const SAFE_CMDS = ["cat", "head", "tail", "jq", "ls", "wc", "grep", "echo", "printf", "date",
"sort", "uniq", "cut", "tr", "true", "false", "test", "[", "pwd", "basename", "dirname",
"diff", "stat", "file", "which"];
/** The programs a bash command runs: heredoc bodies and quoted strings
* dropped, split on `&&`, `||`, `;`, `|`, a lone `&`, newlines,
* `$(`/backticks and process substitutions (`<(`, `>(`), then each
* segment's first word past any `VAR=value` — plus, parsed the same
* way, what the shell still runs inside the dropped text: `$(…)` and
* backticks in a double-quoted string or an unquoted heredoc. Naive like the
* path scan — defense in depth, not a sandbox. Same parser as the sidecar's
* allow_guard.py (claude's side). */
export function programs(cmd: string): string[] {
const inner: string[] = [];
const literal = (text: string) => {
for (const m of text.matchAll(/\$\(([^)]*)\)|`([^`]*)`/g)) inner.push(m[1] ?? m[2]);
return "''";
};
const flat = cmd
.replace(/\\\n/g, " ") // a `\`-continued line is the same command
.replace(/<<-?\s*(['"]?)(\w+)\1([^\n]*)\n([\s\S]*?)\n\s*\2\s*(?=\n|$)/g,
(_m, q, _d, rest, body) => rest + (q ? " " : " " + literal(body)))
// one pass: whichever quote opens first wins (an apostrophe inside a
// double-quoted French sentence is just a letter)
.replace(/'[^']*'|"(?:\\.|[^"\\])*"/g, (m) => (m[0] === "'" ? "''" : literal(m)))
// a redirect's `&` is not a separator: `2>&1`, `>&2`, `<&3`, `>&-`, `&>f`
.replace(/\d*[<>]&\s*(\d+|-)?/g, " ")
.replace(/&>>?/g, ">");
const out: string[] = [];
for (const seg of flat.split(/&&|\|\||[;|&\n]|\$\(|`|[<>]\(/)) {
const words = seg.trim().replace(/^[({]\s*/, "").split(/\s+/).filter(Boolean);
while (words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0])) words.shift();
const w = words[0];
if (!w || /^[)}<>]|^\d?>/.test(w) || ["then", "do", "done", "fi", "else", "esac"].includes(w)) continue;
const prog = w.replace(/\)+$/, ""); // `$(date)`, `>(bash)`
out.push(prog.split("/").pop() ?? prog);
}
for (const sub of inner) out.push(...programs(sub));
return out;
}
/** Resolve symlinks on the deepest existing ancestor so `a/../b` and links
* can't escape the scope check. */
function canonical(p: string): string {
let cur = resolve(p);
let suffix = "";
for (;;) {
try {
return resolve(realpathSync(cur), suffix);
} catch {
suffix = suffix ? `${cur.split("/").pop()}/${suffix}` : (cur.split("/").pop() ?? "");
const parent = dirname(cur);
if (parent === cur) return resolve(p);
cur = parent;
}
}
}
export default function (pi: ExtensionAPI) {
const scope = canonical(process.env.PI_PERM_SCOPE || process.cwd());
const readRoots = (process.env.PI_PERM_READ || homedir())
.split(":")
.filter(Boolean)
.map(canonical)
.concat([scope]);
const allowList = (process.env.PI_ALLOW_CMDS || "").split(",").map((p) => p.trim()).filter(Boolean);
// An entry may be a path (`hosts/…/kernel-try.sh`): commands are compared by basename.
const allow = allowList.length
? new Set([...allowList.map((p) => p.split("/").pop() ?? p), ...SAFE_CMDS])
: null;
const inside = (p: string, root: string) => p === root || p.startsWith(root + "/");
const readable = (p: string) =>
readRoots.some((r) => inside(p, r)) || SYSTEM_PREFIXES.some((r) => inside(p, r));
pi.on("tool_call", async (event) => {
const input = event.input as Record<string, unknown>;
const t = event.toolName;
if (t === "write" || t === "edit") {
const p = canonical(String(input.path ?? ""));
if (WRITE_DENY.some((re) => re.test(p)))
return { block: true, reason: `permission denied: ${p} is protected` };
if (!inside(p, scope))
return { block: true, reason: `permission denied: write outside scope ${scope}: ${p}` };
}
if (t === "read" || t === "list" || t === "grep" || t === "glob" || t === "find") {
const raw = String(input.path ?? input.file ?? "");
if (raw && !readable(canonical(raw)))
return { block: true, reason: `permission denied: read outside permitted roots: ${raw}` };
}
if (t === "bash" && allow) {
const refused = programs(String(input.command ?? "")).filter((p) => !allow.has(p));
if (refused.length)
return {
block: true,
reason: `permission denied: this run may only call ${[...allow].filter((p) => !SAFE_CMDS.includes(p)).join(", ")} (and read-only tools) — not ${[...new Set(refused)].join(", ")}`,
};
}
if (t === "bash") {
const cmd = String(input.command ?? "");
const paths = cmd.match(/(?<=^|[\s='"`(])\/(?:[\w.@+~-]+\/)*[\w.@+*~-]+/g) ?? [];
// `~/…`, `$HOME/…` and `../…` too: a guest's job reads only its own
// folder (PI_PERM_READ), and `cat ~/homelab/.env` names no `/…` token.
const home = homedir();
for (const m of cmd.matchAll(/(?<=^|[\s='"`(])(?:~|\$HOME|\$\{HOME\})(?=\/|$|[\s'"`)])(\/[\w.@+*~/-]*)?/g))
paths.push(home + (m[1] ?? ""));
for (const m of cmd.matchAll(/(?<=^|[\s='"`(])[\w.@+*-]+(?:\/[\w.@+*~-]*)*/g))
if (m[0].split("/").includes("..")) paths.push(resolve(process.cwd(), m[0]));
const offending = [...new Set(paths.map(canonical).filter((p) => !readable(p)))];
if (offending.length)
return {
block: true,
reason: `permission denied: command references paths outside the permitted roots: ${offending.join(", ")}`,
};
}
return undefined;
});
}