Permissions: a command is judged by what it touches, and fails closed (M1, S1, S13, S18)

The files a command names were read from its spelling. Brace lists, ~name,
variables and a path riding on an option read protected files unasked in
manual mode; in auto mode a command could write a protected path; a very
long line kept the judge busy for seconds; the force-push floor matched the
word "main" anywhere and missed deletions.

- permission/rules.md §5 (spec 3.15.0): words are read with their quoting,
  expanded as far as modelled (braces, ~, $HOME/$PWD, globs); anything else
  is unresolved, and an unresolved word is never allowed by a rule. Option
  values, name=PATH operands, redirections and cd are read.
- A path a line may write (a redirection's target, or named by a program
  that is not a known reader) that is a protected path is refused in every
  mode.
- A line over 32 KiB is asked about in every mode without being analysed;
  prefix() no longer joins every prefix of a command.
- force-push-main is a reader of the push's refspecs (check: git_push).

Conformance: permission.json 39 -> 99 cases, hardline.json 44 -> 69.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-12-02 21:01:22 +00:00
1 parent 99081c4ed4
commit 4a2a97ffc7
12 files changed
+1157 -118

No files matched your search

+23
View File
@@ -6,6 +6,29 @@ All notable changes to LLeMbas CLI. The format follows
## Unreleased
### Security
- **A shell command is judged by what it will touch, not by how it is spelled (harness spec
3.15.0, `permission/rules.md` §5).** In manual mode a command the default rules allow — `cat`,
`head`, `wc`, `grep`, `rg`, `git blame` — could read a file the `read` rules ask about, or one
outside the project, when the file was written through a brace list, another user's `~name`,
a variable, or inside an option. Now the words are read as the shell expands them, a path
riding on an option is a path, and **a word that cannot be resolved makes the command ask**:
it is never "allowed by rules". Ordinary commands are unchanged; one with a variable of your
own in it (`cat "$f"`) now asks.
- **The protected paths hold for commands in every mode.** In auto mode a command could write
under `~/.ssh` or `~/.gnupg`, which the write tools always refused. A redirection into a
protected path, or a command naming one that is not known to only read (`cp`, `tee`, `sed -i`,
through `sudo`, `bash -c` or a `cd` too), is refused in every mode. Reading there is asked as
before.
- **A command longer than 32 KiB is asked about in every mode, auto included**, without being
analysed: a very long line could keep the permission check — and with it the whole program —
busy for many seconds.
- **The force-push floor reads the push.** It refused any forced push with "main" somewhere in
it (`feature/main-menu`) and missed deleting the branch (`git push origin :main`,
`--delete main`), a forced `--all`/`--mirror`, and a bare `git push -f` while on main. The
push is now read by its refspecs.
### Terminal — LLeMbas TTY is now LLeMbas TERM
- **The terminal was renamed, and the names it gives the CLI with it (harness spec 3.15.0,
+18
View File
@@ -96,6 +96,24 @@ page *Harness-parity* in LLeMbas CLI's wiki.
terminal that exports only the new names checks first.
- `connection.json` `products`: `term` — `llembas-term/<version>`, "LLeMbas TERM"; `tty` stays
known for the terminal's releases before the rename.
- **What a command touches is a rule, and it fails closed** (`permission/rules.md` §5;
`permission/hardline.json` `commands`). A command's words are read as the shell will expand
them — brace lists, `~`, `$HOME`/`$PWD`, globs — and a word that cannot be resolved (`~name`,
any other variable, a sequence, a substitution) makes the line *unresolved*: never allowed by
a rule, asked instead. A path riding on an option (`--opt=PATH`, `-fPATH`) or behind `name=`
is a path; a quoted `>` is not a redirection; a `cd` moves where later paths are read.
**Both implementations must change**: before, `cat .en{v,}`, `cat ~name/.ssh/key`,
`wc --files0-from=.env` and `rg -f.env x` were allowed where `cat .env` asks.
- **The protected paths hold for commands** (`rules.md` §5.5; `hardline.json`
`commands.readers`): a redirection into one, or a command naming one whose program is not
known to only read, is refused in every mode — `cp x ~/.ssh/authorized_keys` in auto mode
was allowed.
- **A line over `commands.max_bytes` (32 KiB) is not analysed and is asked about in every
mode** (`rules.md` §5.6): the floor's patterns are quadratic on hostile input.
- **`force-push-main` reads a push by its refspecs** (`hardline.json`: `check: git_push`, no
pattern). No longer refused: a forced push to `feature/main-menu`. Now refused: `:main`,
`--delete main`, `-d`, a forced `--all`/`--mirror`, and a forced push naming no branch when
the current branch is known to be main or master. `conformance/hardline.json` has `branch`.
- Conformance: every case of `conformance/terminal.json` is in the new names; cases of `env`,
`status`, `status_dir` and `prompt` in the old ones; `errors.json` for the product `term`.
+106 -1
View File
@@ -1,5 +1,5 @@
{
"about": "A command line → the id of the hardline rule it trips, or null. Checked raw and in its plain spelling (../permission/hardline.json).",
"about": "A command line → the id of the hardline rule it trips, or null. Checked raw and in its plain spelling (../permission/hardline.json). `branch`: the branch checked out where the command runs, when the implementation knows it (force-push-main reads a push by its refspecs, spec 3.15.0).",
"cases": [
{
"line": "rm -rf /",
@@ -176,6 +176,111 @@
{
"line": "xargs rm -rf / < list",
"expect": "rm-root"
},
{
"line": "git push --force origin feature/main-menu",
"expect": null
},
{
"line": "git push -f origin my-main-fix",
"expect": null
},
{
"line": "git push --force-with-lease=main origin feature",
"expect": null
},
{
"line": "git push origin feature:main",
"expect": null
},
{
"line": "git push origin :main",
"expect": "force-push-main"
},
{
"line": "git push origin :refs/heads/master",
"expect": "force-push-main"
},
{
"line": "git push --delete origin main",
"expect": "force-push-main"
},
{
"line": "git push -d origin master",
"expect": "force-push-main"
},
{
"line": "git push origin --delete feature",
"expect": null
},
{
"line": "git push -f origin feature:main",
"expect": "force-push-main"
},
{
"line": "git push origin +refs/heads/master",
"expect": "force-push-main"
},
{
"line": "git push origin +feature",
"expect": null
},
{
"line": "git push -uf origin main",
"expect": "force-push-main"
},
{
"line": "git push origin main --force",
"expect": "force-push-main"
},
{
"line": "git push --force --all origin",
"expect": "force-push-main"
},
{
"line": "git push --mirror backup",
"expect": "force-push-main"
},
{
"line": "git push --all origin",
"expect": null
},
{
"line": "sudo git -C repo push -f origin main",
"expect": "force-push-main"
},
{
"line": "git push -o ci.skip -f origin main",
"expect": "force-push-main"
},
{
"line": "git push -f",
"expect": null
},
{
"line": "git push -f",
"branch": "main",
"expect": "force-push-main"
},
{
"line": "git push --force-with-lease origin HEAD",
"branch": "master",
"expect": "force-push-main"
},
{
"line": "git push -f",
"branch": "feature",
"expect": null
},
{
"line": "git push",
"branch": "main",
"expect": null
},
{
"line": "git push -f origin feature",
"branch": "main",
"expect": null
}
]
}
+352 -1
View File
@@ -1,5 +1,5 @@
{
"about": "A bash command line in a mode, with the default rules (and any extra rules given) → allow, ask or deny. The project root is /project and nothing named exists on disk.",
"about": "A bash command line in a mode, with the default rules (and any extra rules given) → allow, ask or deny. The project root is /project and nothing named exists on disk. From spec 3.15.0 (permission/rules.md §5): cases with `about` say what they pin — a word the reader cannot resolve asks; a path riding on an option is a path; a command that may write a protected path is refused in every mode. `repeat: [text, n]` appends `text` n times to `line` (a line too long to analyse). `~` is the home directory of whoever runs the cases.",
"cases": [
{
"mode": "manual",
@@ -285,6 +285,357 @@
}
},
"expect": "deny"
},
{
"about": "Brace expansion is the shell's: this reads .env.",
"mode": "manual",
"line": "cat .en{v,}",
"expect": "ask"
},
{
"about": "…and a brace list of ordinary files is still read unasked.",
"mode": "manual",
"line": "cat src/{a,b}.ts",
"expect": "allow"
},
{
"about": "A sequence is not modelled: unresolved, so asked.",
"mode": "manual",
"line": "cat {1..3}.txt",
"expect": "ask"
},
{
"about": "A brace without a comma is text.",
"mode": "manual",
"line": "git show HEAD@{1}",
"expect": "allow"
},
{
"about": "Quoted braces are text.",
"mode": "manual",
"line": "rg 'a{2,3}' src",
"expect": "allow"
},
{
"about": "~name is another home directory: not modelled, asked.",
"mode": "manual",
"line": "cat ~nobody/.ssh/id_ed25519",
"expect": "ask"
},
{
"about": "The same through a redirection.",
"mode": "manual",
"line": "cat < ~nobody/.ssh/id_ed25519",
"expect": "ask"
},
{
"about": "A tilde that does not start the word is text.",
"mode": "manual",
"line": "git diff HEAD~3",
"expect": "allow"
},
{
"about": "A variable that is not one of the known ones: unresolved.",
"mode": "manual",
"line": "cat $XDG_CONFIG_HOME/app/secrets.yaml",
"expect": "ask"
},
{
"mode": "manual",
"line": "head -c9999 $OLDPWD/x",
"expect": "ask"
},
{
"about": "A variable expands inside double quotes too.",
"mode": "manual",
"line": "cat \"$f\"",
"expect": "ask"
},
{
"about": "…and not inside single quotes: a file named $f.",
"mode": "manual",
"line": "cat '$f'",
"expect": "allow"
},
{
"about": "$PWD is known: the working directory.",
"mode": "manual",
"line": "cat $PWD/README.md",
"expect": "allow"
},
{
"about": "$HOME is known, and outside the project.",
"mode": "manual",
"line": "cat $HOME/notes.txt",
"expect": "ask"
},
{
"about": "A $ that begins no expansion is text.",
"mode": "manual",
"line": "grep -n \"foo$\" src/a.ts",
"expect": "allow"
},
{
"about": "An expansion in a search pattern is still not known.",
"mode": "manual",
"line": "grep \"$USER\" src/a.ts",
"expect": "ask"
},
{
"about": "A path riding on a long option.",
"mode": "manual",
"line": "wc --files0-from=.env",
"expect": "ask"
},
{
"mode": "manual",
"line": "wc --files0-from=list.txt",
"expect": "allow"
},
{
"mode": "manual",
"line": "grep --file=.env -r x .",
"expect": "ask"
},
{
"about": "A path glued to a short option.",
"mode": "manual",
"line": "rg -f.env x",
"expect": "ask"
},
{
"mode": "manual",
"line": "rg -fpatterns.txt x",
"expect": "allow"
},
{
"mode": "manual",
"line": "git blame --contents=.env x",
"expect": "ask"
},
{
"about": "Option values that are not paths resolve harmlessly.",
"mode": "manual",
"line": "git log --format=%H -n5",
"expect": "allow"
},
{
"mode": "manual",
"line": "ls -la",
"expect": "allow"
},
{
"mode": "manual",
"line": "tail -n +5 notes.txt",
"expect": "allow"
},
{
"about": "The pattern came by -e, glued: the first operand is a file.",
"mode": "manual",
"line": "grep -efoo .env",
"expect": "ask"
},
{
"about": "A quoted > is not a redirection: .env is read.",
"mode": "manual",
"line": "grep '>' .env",
"expect": "ask"
},
{
"about": "An input redirection glued to its file.",
"mode": "manual",
"line": "cat <.env",
"expect": "ask"
},
{
"mode": "manual",
"line": "ls 2>/dev/null",
"expect": "allow"
},
{
"mode": "manual",
"line": "git status 2>&1",
"expect": "allow"
},
{
"mode": "manual",
"line": "cat -- .env",
"expect": "ask"
},
{
"about": "name=PATH as an operand.",
"mode": "manual",
"line": "dd if=.env",
"expect": "ask"
},
{
"mode": "edit",
"line": "cat .en{v,}",
"expect": "ask"
},
{
"about": "Plan mode refuses a command it cannot allow.",
"mode": "plan",
"line": "cat .en{v,}",
"expect": "deny"
},
{
"about": "Auto mode asks nothing.",
"mode": "auto",
"line": "cat .en{v,}",
"expect": "allow"
},
{
"about": "cd is not among the allowed commands; the files are judged where the line goes.",
"mode": "manual",
"line": "cd src && cat ../README.md",
"expect": "ask"
},
{
"about": "A protected path named by a command that is not known to only read: refused in every mode.",
"mode": "auto",
"line": "cp x ~/.ssh/authorized_keys",
"expect": "deny"
},
{
"about": "A redirection's target is written, whatever the command.",
"mode": "auto",
"line": "echo k >> ~/.ssh/authorized_keys",
"expect": "deny"
},
{
"mode": "auto",
"line": "echo k >~/.gnupg/x",
"expect": "deny"
},
{
"mode": "auto",
"line": "sed -i s/a/b/ ~/.ssh/config",
"expect": "deny"
},
{
"about": "Through a wrapper.",
"mode": "auto",
"line": "sudo tee -a ~/.ssh/authorized_keys",
"expect": "deny"
},
{
"about": "Through a shell's -c.",
"mode": "auto",
"line": "bash -c 'echo k >> ~/.ssh/authorized_keys'",
"expect": "deny"
},
{
"about": "Inside a substitution.",
"mode": "auto",
"line": "echo $(cp x ~/.ssh/a)",
"expect": "deny"
},
{
"about": "Relative to where cd went.",
"mode": "auto",
"line": "cd ~ && cp x .ssh/authorized_keys",
"expect": "deny"
},
{
"mode": "auto",
"line": "(cd ~/.ssh; cp /tmp/x authorized_keys)",
"expect": "deny"
},
{
"about": "Through a brace list.",
"mode": "auto",
"line": "cp x ~/.ss{h,x}/a",
"expect": "deny"
},
{
"mode": "auto",
"line": "dd of=~/.ssh/authorized_keys",
"expect": "deny"
},
{
"mode": "auto",
"line": "cp x $HOME/.ssh/authorized_keys",
"expect": "deny"
},
{
"mode": "manual",
"line": "cp x ~/.ssh/authorized_keys",
"expect": "deny"
},
{
"about": "Reading is not writing: a reader is not refused by the floor (auto mode asks nothing).",
"mode": "auto",
"line": "cat ~/.ssh/id_ed25519.pub",
"expect": "allow"
},
{
"about": "…and outside auto it is asked, as everything outside the project.",
"mode": "manual",
"line": "cat ~/.ssh/id_ed25519.pub",
"expect": "ask"
},
{
"mode": "auto",
"line": "ssh -i ~/.ssh/id_ed25519 example.org",
"expect": "allow"
},
{
"mode": "auto",
"line": "ls ~/.ssh",
"expect": "allow"
},
{
"mode": "auto",
"line": "cp x notes/.sshrc",
"expect": "allow"
},
{
"about": "A line over hardline.json commands.max_bytes is not analysed: asked, in auto mode too.",
"mode": "auto",
"line": "rm",
"repeat": [
" -a",
12000
],
"expect": "ask"
},
{
"mode": "plan",
"line": "ls",
"repeat": [
" -a",
12000
],
"expect": "deny"
},
{
"about": "Just under the limit it is analysed as any line.",
"mode": "auto",
"line": "rm",
"repeat": [
" -a",
10000
],
"expect": "allow"
},
{
"about": "A short option's value is judged from where letters and digits end: nothing here is /a.ts.",
"mode": "manual",
"line": "git log -Lname:src/a.ts",
"expect": "allow"
},
{
"about": "A backslash makes the $ literal inside double quotes.",
"mode": "manual",
"line": "grep -n \"price: \\$5\" notes.txt",
"expect": "allow"
},
{
"about": "A path glued after a cluster of short options.",
"mode": "manual",
"line": "rg -rf/etc/hostname x",
"expect": "ask"
}
]
}
+99 -2
View File
@@ -60,8 +60,36 @@
},
{
"id": "force-push-main",
"description": "force-push to main/master",
"pattern": "(?:^|[\\n\\`;&|(]|\\$\\()\\s*(?:sudo\\s+(?:-\\S+\\s+)*)?(?:env\\s+(?:\\w+=\\S*\\s+)*)?(?:(?:exec|nohup|setsid|time|command)\\s+)*\\s*git\\s+push\\b(?=[^\\n;&|]*(?:\\s--force\\b|\\s-[a-zA-Z]*f[a-zA-Z]*\\b|\\s--force-with-lease\\b|\\s\\+))[^\\n;&|]*\\b(?:main|master)\\b"
"description": "force-push to, or deletion of, main/master",
"check": "git_push",
"branches": [
"main",
"master"
],
"about": "Not a pattern (spec 3.15.0; a pattern refused `feature/main-menu` and missed `:main`): each simple command in its plain spelling that is `git push` is read as git reads it. Options first: `value_options` take the next word; the first other word is the remote, the rest are refspecs. A refspec's destination is what follows its `:`, or the whole of it, without a leading `+` and without `refs/heads/`. The push is forced when an option is one of `force_options` (a long one also with `=value`; a short one anywhere in a cluster: `-uf`) or a refspec begins with `+`, and for those refspecs only when the `+` is all that forces. It deletes when an option is one of `delete_options` (every refspec is then a deletion) or a refspec's source is empty (`:main`). Refused: a deletion whose destination is one of `branches`; a forced push with a refspec whose destination is one of `branches`; a forced push with one of `all_options` (it takes every branch); and a forced push that names no branch (no refspec, or only `HEAD`) when the implementation knows the current branch and it is one of `branches` — where it cannot know, the floor does not speak and the rules and the mode decide.",
"value_options": [
"-o",
"--push-option",
"--receive-pack",
"--exec",
"--repo"
],
"force_options": [
"-f",
"--force",
"--force-with-lease",
"--force-if-includes",
"--mirror"
],
"delete_options": [
"-d",
"--delete"
],
"all_options": [
"--all",
"--branches",
"--mirror"
]
},
{
"id": "find-delete-system",
@@ -84,6 +112,75 @@
"scope": "cli"
}
],
"commands": {
"about": "How a command line is read for the files it touches (rules.md §5, spec 3.15.0). `max_bytes`: a line longer than this (UTF-8) is not analysed at all — it is asked about in every mode, auto included, and refused where nobody can answer. `known_variables`: the only variables a reader expands ($NAME and ${NAME}); any other expansion leaves the word unresolved. `pattern_first`: programs whose first operand is a pattern, not a file, unless an option gives the pattern (`pattern_options`). `readers`: programs that only read the files they name — a command of any other program that names a protected path is taken to write it, and is refused. `brace_max`: the most words one brace expansion may give before the word counts as unresolved; `glob_max` the same for a glob; `cd`: the programs that change the directory later commands of the line work in.",
"max_bytes": 32768,
"known_variables": [
"HOME",
"PWD"
],
"brace_max": 64,
"glob_max": 500,
"cd": [
"cd",
"pushd"
],
"pattern_first": [
"grep",
"egrep",
"fgrep",
"rg",
"ag",
"ack"
],
"pattern_options": [
"-e",
"--regexp",
"-f",
"--file",
"--files"
],
"readers": [
"cat",
"head",
"tail",
"wc",
"grep",
"egrep",
"fgrep",
"rg",
"ag",
"ack",
"ls",
"file",
"tree",
"which",
"stat",
"du",
"less",
"more",
"diff",
"cmp",
"sha256sum",
"sha1sum",
"md5sum",
"od",
"xxd",
"strings",
"basename",
"dirname",
"realpath",
"readlink",
"test",
"[",
"echo",
"printf",
"cd",
"pushd",
"ssh",
"ssh-add"
]
},
"plain": {
"about": "How a simple command is spelled plainly before the rules are checked again: leading keywords and VAR= assignments dropped; wrapper programs and their options taken off (an option listed for a wrapper takes a value); `timeout` also drops its duration; a shell's -c argument read as its own line; git's global options dropped; quotes, escapes and program paths removed; paths normalised (~ for the home directory).",
"wrappers": {
+89 -1
View File
@@ -121,4 +121,92 @@ in place of it: **a command is never typed at a password prompt**, and not into
command runs unless the call says the pane is at a prompt (`kind: ready`) — both after the
person allowed the call, so an allowed command can still be not typed, in words. A command to
be placed has one check more: **only at an empty prompt** (`kind: prompt`) — nothing is ever
added to what the person typed.
added to what the person typed.
## 5. What a command touches (spec 3.15.0)
A command line is text; what runs is what the shell makes of it. A reader that judged a line by
its spelling let `cat .en{v,}`, `cat ~name/.ssh/key`, `cat $DIR/token`, `wc --files0-from=.env`
and `rg -f.env x` read what `cat .env` is asked about. So the reading is a rule, not a list
(`hardline.json` `commands` holds its data; `conformance/permission.json`):
**The rule: a command is known to be safe only when every word of it is known.** Each word
after the program's name resolves to *a definite path*, *a definite non-path*, or it is
**unresolved** — and a line with an unresolved word is never "allowed by rules": where the
rules would allow it, it is asked about (plan mode, which refuses what it cannot allow, refuses
it; auto mode asks nothing and runs it). The reader fails closed: what it does not model is
unresolved, never ignored.
**1. Words.** The line is split into simple commands (`conformance/split.json`), each into
shell words with their quoting kept: a character is *unquoted*, *double-quoted* (a `$` or a
backquote still expands) or *literal* (single-quoted, or after a backslash — inside double
quotes a backslash makes literal only `$`, a backquote, `"` and `\`). A subshell's own
parentheses are not part of a word. What a `$( … )` or backquote substitution runs, what a
shell's `-c` carries and what `env -S` carries are lines too, read the same way (four deep at
most; deeper is unresolved).
**2. Expansion, as far as it is modelled** — in the shell's order:
| In a word | Read as |
|---|---|
| an unquoted `{a,b}` (a comma at its own depth; nesting allowed) | each alternative, up to `brace_max` words — more is unresolved |
| an unquoted `{x..y}` | unresolved |
| any other brace (`HEAD@{1}`, quoted braces) | text |
| a leading unquoted `~` alone or before `/` | the home directory |
| a leading unquoted `~` before anything else (`~name`, `~+`) | unresolved |
| `$NAME` / `${NAME}`, not literal, `NAME` one of `known_variables` | its value: `HOME` the home directory, `PWD` the directory the command runs in |
| `$NAME` / `${NAME}` of any other name; `$(`, `${…}` of another shape, a backquote, `$?` `$$` `$!` `$@` `$*` `$#` `$-` `$0`–`$9`, not literal | unresolved |
| a `$` followed by anything else (`"foo$"`) | text |
| `*`, `?`, `[` — quoted or not | a glob over what exists, dotfiles included; over `glob_max` names is unresolved; no match is the word itself |
An implementation may expand a variable beyond `known_variables` only when it knows the value
the shell will have for certain; the cases use none.
**3. Which words name a path.** Every word after the program's name is a candidate — a word
that is not really a path resolves inside the working directory, harmlessly — with these
readings:
- **A redirection** whose operator is unquoted: `<file` and `N<file` are read; `>file`,
`>>file`, `N>file`, `&>file`, `>|file`, `<>file` are **written**, the file glued to the
operator or the next word. `>&N`, `N>&M`, `>&-` name no file; the word after `<<`/`<<<` is
data.
- **An option** (a word beginning `-`; `-` and `--` alone name nothing): the text after its
first `=` is a candidate (`--files0-from=PATH`), and for a short option every tail of it
that begins after a run of letters and digits from its second character (`-fPATH`, `-rfPATH`:
the tails `PATH`, `fPATH`…; in `-Lname:src/a.ts` nothing after the `:` begins a tail); a
short option longer than 256 characters is unresolved. The option's own name is not a path.
- **An operand with `=`** (`if=PATH`): the whole word and the text after the first `=`.
- **A pattern-first program** (`pattern_first`): its first operand is the pattern, not a file —
unless a `pattern_options` option, or any short option with `e` or `f` in it, gave the
pattern. The pattern is still a word: an unresolved expansion in it is unresolved.
- The devices `/dev/null`, `zero`, `stdin`, `stdout`, `stderr`, `tty`, `random`, `urandom` are
no file.
**4. Where.** A relative path is taken in the directory the command runs in. After a `cd` (the
programs in `cd`) to a resolved directory, later commands of the line are read there — when the
line is a plain sequence (`;`, `&&`, new lines). When it has a subshell, a group, a pipe, `||`
or a background job, the `cd` may not hold for what follows, and later paths are read in
**both** directories. `cd` with no operand goes home; a `cd` whose target is unresolved (`cd -`)
makes the line unresolved.
**5. What each path means.** Every path named, resolved through symbolic links:
- inside the project, is a **read** of it: the `read` rules apply (`*.env` asks);
- outside the project, falls under `external_directory`;
- **and a path the line may write that is a protected path is refused in every mode**, auto
included (`modes.json` `floor`) — as the write tools are. A line *may write* a path when it
is a redirection's target, or when it is named by a command whose program — after its
wrappers (`hardline.json` `plain.wrappers`) — is not one of `readers`: programs that only
read what they name. Reading a protected path is not refused by the floor; it is asked as
everything outside the project is.
**6. Too long to read.** A line longer than `max_bytes` is not analysed: not by the floor, not
by the rules. It is asked about **in every mode, auto included** (plan mode refuses it; with
nobody to answer it is refused), with no "always". The floor's patterns and this reader are
then never run on unbounded input.
**What this does not see**, so that nobody takes it for more: a program that reads files it was
not given (`grep -r x .` reads every file under `.`; the search *tools* leave protected files
out — `filesystem.md`), what a script does once it runs, and in auto mode an unresolved word (a
variable holding a protected path is not known to be one).
+4 -1
View File
@@ -5,7 +5,9 @@ export function prefix(tokens: string[]) {
// Options before the subcommand do not count ("options never count", in the table's rules): `git -C dir
// commit` is `git commit` — and an "always" for `git -C *` would cover every git command.
if (tokens.length > 1 && tokens.slice(1).some((t) => t.startsWith("-")) && ARITY[tokens[0]!] !== undefined && ARITY[tokens[0]!]! > 1 && tokens[1]!.startsWith("-")) return tokens
for (let len = tokens.length; len > 0; len--) {
// No key of the table is longer than LONGEST words: nothing longer is ever joined (a command
// of thirty thousand words was joined thirty thousand times here).
for (let len = Math.min(tokens.length, LONGEST); len > 0; len--) {
const prefix = tokens.slice(0, len).join(" ")
const arity = ARITY[prefix]
if (arity !== undefined) return tokens.slice(0, arity)
@@ -19,3 +21,4 @@ export function prefix(tokens: string[]) {
// the command, options never count, the longest matching prefix wins.
const ARITY: Record<string, number> = SPEC.arity
const LONGEST = Math.max(1, ...Object.keys(ARITY).map((k) => k.split(" ").length))
+59
View File
@@ -144,3 +144,62 @@ export function words(command: string): string[] {
while (out.length > 1 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(out[0]!)) out.shift()
return out
}
/** A shell word with its quoting kept: `mask[i]` says how `text[i]` was written — `u` unquoted,
* `d` inside double quotes (a `$` still expands there), `s` inside single quotes or after a
* backslash (nothing expands). What `words` reads, for a reader that must know whether a `~`,
* `$`, `{` or `>` is the shell's or the text's own. */
export interface Word {
text: string
mask: string
}
/** Every word of a simple command, quoting kept (leading VAR=value assignments included). */
export function shellWords(command: string): Word[] {
const out: Word[] = []
let text = ""
let mask = ""
let quote: string | null = null
let started = false
const end = () => {
if (started) out.push({ text, mask })
text = ""
mask = ""
started = false
}
for (let i = 0; i < command.length; i++) {
const ch = command[i]!
if (quote) {
if (ch === quote) quote = null
// Inside double quotes a backslash makes the next of $ ` " \\ literal, and is text otherwise.
else if (quote === '"' && ch === "\\" && i + 1 < command.length && '$`"\\'.includes(command[i + 1]!)) {
text += command[++i]
mask += "s"
} else {
text += ch
mask += quote === "'" ? "s" : "d"
}
continue
}
if (ch === "'" || ch === '"') {
quote = ch
started = true
continue
}
if (ch === "\\" && i + 1 < command.length) {
text += command[++i]
mask += "s"
started = true
continue
}
if (/\s/.test(ch)) {
end()
continue
}
text += ch
mask += "u"
started = true
}
end()
return out
}
+33 -75
View File
@@ -8,6 +8,7 @@ import { renamePermissionKeys, type Action, type Mode, type PermissionConfig } f
import { prefix } from "./arity.ts"
import { splitCommand, words } from "./bash.ts"
import { hardlineCommand, plainCommands, protectedPath, type HardlineRule } from "./hardline.ts"
import { MAX_COMMAND_BYTES, touched } from "./touch.ts"
import { match } from "./wildcard.ts"
import DEFAULTS from "../../harness/permission/defaults.json"
import ARITY from "../../harness/permission/arity.json"
@@ -157,6 +158,20 @@ export interface Context {
planDir?: string
/** The project directory (.agent): its config, agents, commands and skills are not edits. */
projectDir?: string
/** The branch checked out in a directory, for the floor's reading of a bare forced push
* (default: asked of git). */
branch?: (cwd: string) => string | undefined
}
/** The branch checked out in `cwd`; undefined when there is none or git does not say. */
export function currentBranch(cwd: string): string | undefined {
try {
const r = Bun.spawnSync(["git", "-C", cwd, "symbolic-ref", "--short", "-q", "HEAD"], { stdout: "pipe", stderr: "ignore", stdin: "ignore", timeout: 2000 })
const out = r.exitCode === 0 ? r.stdout.toString().trim() : ""
return out || undefined
} catch {
return undefined
}
}
const inside = (p: string, dir: string) => p === dir || p.startsWith(dir.endsWith("/") ? dir : dir + "/")
@@ -192,79 +207,6 @@ function guardedEdit(p: string, projectDir?: string): boolean {
return rel.endsWith("config.yaml") || /^(agents|commands|skills)(\/|$)/.test(rel)
}
const DEVICES = /^\/dev\/(null|zero|stdin|stdout|stderr|tty|u?random)$/
const PATTERN_FIRST = new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack"])
const MAX_GLOB = 500
/** What a glob names, as the shell would expand it — dotfiles included, to be safe. Undefined
* when it names too many to judge one by one. */
function expandGlob(abs: string): string[] | undefined {
const parts = abs.split("/")
const at = parts.findIndex((x) => /[*?[]/.test(x))
const base = parts.slice(0, at).join("/") || "/"
const out: string[] = []
try {
for (const f of new Bun.Glob(parts.slice(at).join("/")).scanSync({ cwd: base, dot: true, onlyFiles: false, followSymlinks: false })) {
out.push(join(base, f))
if (out.length > MAX_GLOB) return undefined
}
} catch {}
return out.length ? out : [abs]
}
/** The files a command names, absolute: its arguments that are not options (a search tool's
* pattern excepted), what an input redirection reads, and what a glob expands to. A word that is
* not really a path resolves inside the directory, harmlessly. `unsure`: a glob too wide to judge. */
function commandPaths(commands: string[], cwd: string): { paths: string[]; unsure: boolean } {
const out: string[] = []
let unsure = false
const add = (a: string) => {
const home = a === "~" || a.startsWith("~/") ? join(homedir(), a.slice(1)) : a.replace(/^\$\{?HOME\}?(?=\/|$)/, homedir())
const abs = resolve(cwd, home)
if (!/[*?[]/.test(abs)) return void out.push(abs)
const all = expandGlob(abs)
if (all) out.push(...all)
else unsure = true
}
for (const c of commands) {
const w = words(c)
// rg --files lists files: there is no pattern to skip, the first word is a path.
let skipPattern = PATTERN_FIRST.has(basename(w[0] ?? "")) && !w.some((x) => x === "-e" || x.startsWith("--regexp") || x === "-f" || x === "--files")
let afterRedirect = false
let readNext = false
for (const a of w.slice(1)) {
// An input redirection reads a file just as an argument does: `cat < f`, `cat 0<f`.
const input = /^\d*<(?![<>(])(.*)$/.exec(a)
if (input) {
if (input[1]) add(input[1])
else readNext = true
continue
}
if (readNext) {
readNext = false
add(a)
continue
}
if (/^\d*>/.test(a) || a === "&>" || a === "&>>") {
afterRedirect = true
continue
}
if (afterRedirect) {
afterRedirect = false
continue
}
if (!a || a.startsWith("-") || DEVICES.test(a)) continue
if (skipPattern) {
skipPattern = false
continue
}
add(a)
}
}
return { paths: out, unsure }
}
export function evaluate(req: PermissionRequest, ctx: Context): Decision {
if (req.typed !== undefined && req.command !== undefined) return evaluateTyped(req, ctx)
const d = evaluateRules(req, ctx)
@@ -275,6 +217,8 @@ export function evaluate(req: PermissionRequest, ctx: Context): Decision {
/** rules.md §4: a command typed into the person's terminal. */
function evaluateTyped(req: PermissionRequest, ctx: Context): Decision {
const line = req.command!
// A line too long to read is never typed unasked, and never placed (rules.md §5).
if (tooLong(line)) return { action: ctx.mode === "plan" ? "deny" : "ask", reason: TOO_LONG, always: [] }
// 1. As bash would judge it: the hardline, bash's rules, the files it names, plan mode.
const { typed: _typed, placed: _placed, ...rest } = req
const asBash = evaluateRules({ ...rest, permission: "bash" }, ctx)
@@ -291,10 +235,17 @@ function evaluateTyped(req: PermissionRequest, ctx: Context): Decision {
return { action: "ask", reason: req.typed!, always: [] }
}
const TOO_LONG = `the command is longer than ${MAX_COMMAND_BYTES / 1024} KiB: too long to check, so it is asked about in every mode`
const tooLong = (line: string) => Buffer.byteLength(line, "utf8") > MAX_COMMAND_BYTES
function evaluateRules(req: PermissionRequest, ctx: Context): Decision {
// 0. A line too long to read is not read (rules.md §5): neither the floor nor the rules could
// be trusted on it in bounded time, so it is asked about — in auto mode too — and refused
// where a mode refuses what it cannot allow.
if (req.command !== undefined && tooLong(req.command)) return { action: ctx.mode === "plan" ? "deny" : "ask", reason: TOO_LONG, always: [] }
// 1. The floor.
if (req.command) {
const hit = hardlineCommand(req.command, ctx.hardline)
const hit = hardlineCommand(req.command, ctx.hardline, () => ({ branch: ctx.branch ? ctx.branch(req.paths?.[0] ?? ctx.root) : currentBranch(req.paths?.[0] ?? ctx.root) }))
if (hit) return { action: "deny", reason: `refused: ${hit.description} (hardline rule ${hit.id})`, always: [] }
}
// Where each path really is: a symlink is judged by what it points to.
@@ -334,8 +285,15 @@ function evaluateRules(req: PermissionRequest, ctx: Context): Decision {
// outside the project, whatever the allow rule for `cat *` says.
let named: string[] = []
if (req.command !== undefined) {
const c = commandPaths(patterns, real[0] ?? root)
const c = touched(req.command, real[0] ?? root)
// The protected paths hold for a command as for a tool (modes.json `floor`): what a line
// may write there is refused in every mode. Reading is not: that is asked, as outside.
for (const p of c.writes) {
const guarded = protectedPath(p) ?? protectedPath(realPath(p))
if (guarded) return { action: "deny", reason: `refused: ${guarded} is never written by a tool, and this command names it without being one that only reads`, always: [] }
}
named = c.paths.map(realPath)
// A word that could not be read as a definite path or a definite non-path: not known safe.
if (c.unsure && ruled === "allow") ruled = "ask"
}
// Reading a file by another tool (grep, glob, list) or a command follows the read rules too.
+119 -34
View File
@@ -10,14 +10,76 @@ import SPEC from "../../harness/permission/hardline.json"
export interface HardlineRule {
id: string
description: string
re: RegExp
/** A pattern over the raw line and each plain spelling… */
re?: RegExp
/** …or a reader of one plain spelling (the spec's `check`). */
check?: (plain: string, known: HardlineKnown) => boolean
}
/** What the caller knows that a line does not say. */
export interface HardlineKnown {
/** The branch checked out where the command runs, when it is known. */
branch?: string
}
const rule = (id: string, description: string, src: string): HardlineRule => ({ id, description, re: new RegExp(src, SPEC.flags) })
interface PushSpec {
branches: string[]
value_options: string[]
force_options: string[]
delete_options: string[]
all_options: string[]
}
/** The spec's `git_push` check: a push read by its refspecs (hardline.json, force-push-main). */
export function pushRefused(plain: string, spec: PushSpec, known: HardlineKnown = {}): boolean {
const w = words(plain)
if (basename(w[0] ?? "") !== "git" || w[1] !== "push") return false
const has = (a: string, list: string[]) => list.some((o) => (o.startsWith("--") ? a === o || a.startsWith(o + "=") : /^-[A-Za-z]+$/.test(a) && a.includes(o.slice(1))))
let forced = false
let deletes = false
let all = false
const rest: string[] = []
for (let i = 2; i < w.length; i++) {
const a = w[i]!
if (a === "--") {
rest.push(...w.slice(i + 1))
break
}
if (!a.startsWith("-") || a === "-") {
rest.push(a)
continue
}
if (has(a, spec.force_options)) forced = true
if (has(a, spec.delete_options)) deletes = true
if (has(a, spec.all_options)) all = true
if (spec.value_options.includes(a)) i++
}
const refspecs = rest.slice(1)
const guarded = (name: string) => spec.branches.includes(name.replace(/^refs\/heads\//, ""))
let named = false
for (const r of refspecs) {
const plus = r.startsWith("+")
const body = plus ? r.slice(1) : r
const colon = body.indexOf(":")
const src = colon < 0 ? body : body.slice(0, colon)
const dst = colon < 0 ? body : body.slice(colon + 1)
if (dst !== "HEAD" && dst !== "") named = true
if (!guarded(dst)) continue
if (deletes || (colon >= 0 && src === "")) return true
if (forced || plus) return true
}
if (forced && all) return true
if (forced && !named && known.branch !== undefined && spec.branches.includes(known.branch)) return true
return false
}
// The rules themselves are the harness spec's (harness/permission/hardline.json), which LLeMbas
// checks commands against too.
export const BUILTIN_HARDLINE: HardlineRule[] = SPEC.rules.map((r) => rule(r.id, r.description, r.pattern))
export const BUILTIN_HARDLINE: HardlineRule[] = (SPEC.rules as ({ id: string; description: string; pattern?: string; check?: string } & Partial<PushSpec>)[]).map((r) =>
r.check === "git_push" ? { id: r.id, description: r.description, check: (plain, known) => pushRefused(plain, r as unknown as PushSpec, known) } : rule(r.id, r.description, r.pattern!),
)
export interface HardlineOptions {
extra?: string[]
@@ -33,9 +95,17 @@ export function hardlineRules(opts: HardlineOptions = {}): HardlineRule[] {
/** The rule a command line trips, if any. Checked on the raw line, so splitting cannot hide one,
* and on each command in a plain spelling, so writing it differently cannot hide one either. */
export function hardlineCommand(line: string, rules: HardlineRule[]): HardlineRule | undefined {
for (const l of [line, ...plainCommands(line)]) {
const hit = rules.find((r) => r.re.test(l))
export function hardlineCommand(line: string, rules: HardlineRule[], known: HardlineKnown | (() => HardlineKnown) = {}): HardlineRule | undefined {
const plain = plainCommands(line)
for (const l of [line, ...plain]) {
const hit = rules.find((r) => r.re?.test(l))
if (hit) return hit
}
const readers = rules.filter((r) => r.check)
if (!readers.length || !plain.some((l) => /^git push( |$)/.test(l))) return undefined
const k = typeof known === "function" ? known() : known
for (const l of plain) {
const hit = readers.find((r) => r.check!(l, k))
if (hit) return hit
}
return undefined
@@ -59,6 +129,49 @@ function plainPath(a: string): string {
return p
}
/** A command's words without what merely runs it: shell keywords, VAR= assignments and wrapper
* programs with their options (`sudo -u x`, `env A=1`, `timeout 5`…). `inner` is given the
* command line `env -S` carries. */
export function unwrap(words: string[], inner?: (line: string) => void): string[] {
let w = words
for (;;) {
while (w.length && (KEYWORDS.has(w[0]!) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(w[0]!))) w = w.slice(1)
const prog = basename(w[0] ?? "")
const takes = WRAPPERS[prog]
if (!takes) return w
let i = 1
while (i < w.length) {
const a = w[i]!
if (a === "--") {
i++
break
}
if (prog === "env" && /^[A-Za-z_][A-Za-z0-9_]*=/.test(a)) {
i++
continue
}
if (prog === "env" && (a === "-S" || a.startsWith("--split-string"))) {
const line = a.includes("=") ? a.slice(a.indexOf("=") + 1) : w[i + 1]
if (line) inner?.(line)
i = w.length
break
}
if (!a.startsWith("-")) break
i += takes.includes(a) ? 2 : 1
}
// timeout's first word after its options is the duration.
if (prog === "timeout" && i < w.length) i++
w = w.slice(i)
}
}
/** The command line a shell's -c carries, if these words are such a call. */
export function shellInner(w: string[]): string | undefined {
if (!SHELLS.has(basename(w[0] ?? ""))) return undefined
const flag = w.findIndex((a, i) => i > 0 && /^-[a-zA-Z]*c[a-zA-Z]*$/.test(a))
return flag >= 0 ? w[flag + 1] : undefined
}
/** Each simple command of a line, rewritten plainly: no VAR= prefixes, wrappers (sudo -u x, env
* -i, timeout 5, xargs…), quotes, escapes or program paths; paths normalised (`/etc/` is /etc,
* the home directory is ~); `sh -c "…"` read as the line it runs. */
@@ -71,35 +184,7 @@ export function plainCommands(line: string, depth = 0): string[] {
for (const inner of substitutions(line)) out.push(...plainCommands(inner, depth + 1))
for (const c of splitCommand(line).commands) {
let w = words(c).map((x) => x.replace(/^\(+/, "").replace(/\)+$/, "")).filter((x) => x !== "")
for (;;) {
while (w.length && (KEYWORDS.has(w[0]!) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(w[0]!))) w = w.slice(1)
const prog = basename(w[0] ?? "")
const takes = WRAPPERS[prog]
if (!takes) break
let i = 1
while (i < w.length) {
const a = w[i]!
if (a === "--") {
i++
break
}
if (prog === "env" && /^[A-Za-z_][A-Za-z0-9_]*=/.test(a)) {
i++
continue
}
if (prog === "env" && (a === "-S" || a.startsWith("--split-string"))) {
const inner = a.includes("=") ? a.slice(a.indexOf("=") + 1) : w[i + 1]
if (inner) out.push(...plainCommands(inner, depth + 1))
i = w.length
break
}
if (!a.startsWith("-")) break
i += takes.includes(a) ? 2 : 1
}
// timeout's first word after its options is the duration.
if (prog === "timeout" && i < w.length) i++
w = w.slice(i)
}
w = unwrap(w, (inner) => out.push(...plainCommands(inner, depth + 1)))
if (!w.length) continue
const prog = basename(w[0]!)
let args = w.slice(1)
+251
View File
@@ -0,0 +1,251 @@
// What a command line touches (harness permission/rules.md §5): the files its words name, read
// the way the shell and the program will read them — and, where a word cannot be read that way,
// the answer "not sure", which is never "safe".
import { homedir } from "node:os"
import { basename, join, resolve } from "node:path"
import { shellWords, splitCommand, type Word } from "./bash.ts"
import { shellInner, substitutions, unwrap } from "./hardline.ts"
import SPEC from "../../harness/permission/hardline.json"
const C = SPEC.commands
const KNOWN = new Set(C.known_variables)
const READERS = new Set(C.readers)
const PATTERN_FIRST = new Set(C.pattern_first)
const CD = new Set(C.cd)
const DEVICES = /^\/dev\/(null|zero|stdin|stdout|stderr|tty|u?random)$/
const ASSIGN = /^[A-Za-z_][A-Za-z0-9_]*=/
/** The longest command line that is analysed at all (UTF-8 bytes). */
export const MAX_COMMAND_BYTES = C.max_bytes
export interface Touched {
/** Every path the line names, absolute (not yet real). */
paths: string[]
/** Those it may write: a redirection's target, and every path named by a command that is not
* known to only read what it names. */
writes: string[]
/** A word could not be resolved to a definite path or a definite non-path. */
unsure: boolean
}
/** What a glob names, as the shell would expand it — dotfiles included, to be safe. Undefined
* when it names too many to judge one by one. */
function expandGlob(abs: string): string[] | undefined {
const parts = abs.split("/")
const at = parts.findIndex((x) => /[*?[]/.test(x))
const base = parts.slice(0, at).join("/") || "/"
const out: string[] = []
try {
for (const f of new Bun.Glob(parts.slice(at).join("/")).scanSync({ cwd: base, dot: true, onlyFiles: false, followSymlinks: false })) {
out.push(join(base, f))
if (out.length > C.glob_max) return undefined
}
} catch {}
return out.length ? out : [abs]
}
const sub = (w: Word, from: number, to = w.text.length): Word => ({ text: w.text.slice(from, to), mask: w.mask.slice(from, to) })
const cat = (...ws: Word[]): Word => ({ text: ws.map((w) => w.text).join(""), mask: ws.map((w) => w.mask).join("") })
/** Brace expansion, the shell's first step: `a{b,c}d` is `abd acd`. Undefined for what is not
* modelled (a sequence `{1..9}`, or more words than the spec's cap). A brace without an
* unquoted comma is text (`HEAD@{1}`). */
function braces(w: Word, budget = { n: C.brace_max }): Word[] | undefined {
for (let i = 0; i < w.text.length; i++) {
if (w.text[i] !== "{" || w.mask[i] !== "u") continue
// `${` is a parameter expansion, not a brace list.
if (i > 0 && w.text[i - 1] === "$" && w.mask[i - 1] !== "s") continue
let depth = 0
const cuts: number[] = []
let close = -1
for (let j = i; j < w.text.length; j++) {
if (w.mask[j] !== "u") continue
const ch = w.text[j]
if (ch === "{") depth++
else if (ch === "}" && --depth === 0) {
close = j
break
} else if (ch === "," && depth === 1) cuts.push(j)
}
if (close < 0) return [w]
if (!cuts.length) {
if (/^.+\.\..+$/.test(w.text.slice(i + 1, close))) return undefined
continue
}
const out: Word[] = []
const marks = [i, ...cuts, close]
for (let k = 0; k + 1 < marks.length; k++) {
const part = cat(sub(w, 0, i), sub(w, marks[k]! + 1, marks[k + 1]!), sub(w, close + 1))
const more = braces(part, budget)
if (!more) return undefined
out.push(...more)
if ((budget.n -= more.length) < 0) return undefined
}
return out
}
return [w]
}
/** Tilde and parameter expansion of one word. Undefined when the word holds an expansion that is
* not modelled: `~name`, any variable but the known ones, a command substitution, a special
* parameter. What comes out is text (quoted), except that glob characters stay live. */
function expand(w: Word, vars: Record<string, string>): string | undefined {
let out = ""
let i = 0
if (w.text[0] === "~" && w.mask[0] === "u") {
if (w.text.length > 1 && w.text[1] !== "/") return undefined
out = vars.HOME!
i = 1
}
for (; i < w.text.length; i++) {
const ch = w.text[i]!
const live = w.mask[i] !== "s"
if (ch === "`" && live) return undefined
if (ch !== "$" || !live) {
out += ch
continue
}
const rest = w.text.slice(i + 1)
const name = /^(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/.exec(rest)
if (name) {
const v = name[1] ?? name[2]!
if (!KNOWN.has(v) || vars[v] === undefined) return undefined
out += vars[v]
i += name[0].length
continue
}
// `$(`, `${…}` of another shape, `$?`, `$1`, `$@`…: the shell puts something there.
if (/^[({?$!@*#\-0-9]/.test(rest)) return undefined
out += ch
}
return out
}
function unparen(w: Word): Word {
let a = 0
let b = w.text.length
while (a < b && w.text[a] === "(" && w.mask[a] === "u" && w.text[a + 1] !== ")") a++
while (b > a && w.text[b - 1] === ")" && w.mask[b - 1] === "u") b--
// `<(`, `>(`, `$(` keep their parenthesis: they are judged as what they are.
return a === 0 && b === w.text.length ? w : sub(w, a, b)
}
export function touched(line: string, cwd: string): Touched {
const t: Touched = { paths: [], writes: [], unsure: false }
if (Buffer.byteLength(line, "utf8") > MAX_COMMAND_BYTES) return { ...t, unsure: true }
read(line, [resolve(cwd)], t, 0)
t.paths = [...new Set(t.paths)]
t.writes = [...new Set(t.writes)]
return t
}
function read(line: string, start: string[], t: Touched, depth: number): void {
if (depth > 3) return void (t.unsure = true)
// What a substitution runs names files too: `echo $(cat .env)`.
for (const inner of substitutions(line)) read(inner, start, t, depth + 1)
// The directories the line's commands may run in: where it starts, and wherever a `cd` in it
// goes. A relative path is judged in each (a `cd` in a subshell does not move the next
// command, and one outside does).
let dirs = start
const open = shellWords(line)
.map((x) => [...x.text].map((ch, i) => (x.mask[i] === "u" ? ch : "x")).join(""))
.join(" ")
.replace(/&&|>&|&>/g, " ")
const sequence = !/[()|&{}]/.test(open)
for (const c of splitCommand(line).commands) {
// A subshell's parentheses are the shell's, not part of a name: `(cd x; cat y)`.
let w = shellWords(c).map(unparen).filter((x) => x.text !== "")
while (w.length > 1 && ASSIGN.test(w[0]!.text)) w = w.slice(1)
const texts = w.map((x) => x.text)
const plain = unwrap(texts, (inner) => read(inner, dirs, t, depth + 1))
const prog = basename(plain[0] ?? "")
const inner = shellInner(plain)
if (inner !== undefined) read(inner, dirs, t, depth + 1)
const reader = READERS.has(prog)
const vars = (dir: string): Record<string, string> => ({ HOME: homedir(), PWD: dir })
/** One candidate path: expanded, resolved in every directory, recorded. */
const name = (cand: Word, write: boolean): string[] => {
const found: string[] = []
if (!cand.text) return found
const parts = braces(cand)
if (!parts) return (t.unsure = true), found
for (const part of parts)
for (const dir of dirs) {
const text = expand(part, vars(dir))
if (text === undefined) {
t.unsure = true
continue
}
if (DEVICES.test(text)) continue
const abs = resolve(dir, text)
const names = /[*?[]/.test(abs) ? expandGlob(abs) : [abs]
if (!names) {
t.unsure = true
continue
}
found.push(...names)
t.paths.push(...names)
if (write) t.writes.push(...names)
}
return found
}
let skipPattern = PATTERN_FIRST.has(prog) && !texts.some((x) => C.pattern_options.some((o) => x === o || x.startsWith(o + "=")) || /^-[A-Za-z]*[ef]/.test(x))
let pending: "read" | "write" | "skip" | undefined
const moved: string[] = []
for (const a of w.slice(1)) {
if (pending) {
if (pending !== "skip") name(a, pending === "write")
pending = undefined
continue
}
// A redirection, where the operator is the shell's own (not quoted).
const op = /^(\d*|&)(<<<|<<-?|<>|<|>>|>\||>)(&?)/.exec(a.text)
if (op && !a.mask.slice(0, op[0].length).includes("s") && !a.mask.slice(0, op[0].length).includes("d") && !a.text.startsWith("<(") && !a.text.startsWith(">(")) {
const target = sub(a, op[0].length)
const kind = op[2]!.startsWith("<<") ? "skip" : op[2] === "<" ? "read" : "write"
// `2>&1`, `>&-`: a descriptor, not a file.
if (op[3] && /^(\d+|-)$/.test(target.text)) continue
if (!target.text) pending = kind
else if (kind !== "skip") name(target, kind === "write")
continue
}
if (a.text === "-" || a.text === "--") continue
if (a.text.startsWith("-")) {
// A path may ride on an option: `--file=PATH`, `-fPATH`. Every value an option could
// carry is judged as a path; one that is not a path resolves harmlessly.
const eq = a.text.indexOf("=")
if (eq > 0) name(sub(a, eq + 1), !reader)
if (!a.text.startsWith("--")) {
if (a.text.length > 256) t.unsure = true
else for (let i = 2; i < a.text.length && /^[A-Za-z0-9]$/.test(a.text[i - 1]!); i++) name(sub(a, i), !reader)
}
continue
}
if (skipPattern) {
skipPattern = false
// The pattern is the shell's word first: an expansion in it is still not known.
if (braces(a) === undefined || expand(a, vars(dirs[0]!)) === undefined) t.unsure = true
continue
}
const found = name(a, !reader)
// `if=PATH`, `VAR=PATH` as an operand.
const eq = a.text.indexOf("=")
if (eq > 0) name(sub(a, eq + 1), !reader)
if (CD.has(prog) && !moved.length) moved.push(...found)
}
if (CD.has(prog)) {
const to = moved.length ? moved : w.length === 1 ? [homedir()] : []
// `cd -`, `cd "$d"`: somewhere this reader does not know.
if (!to.length) t.unsure = true
// In a plain sequence the next command runs where `cd` went; inside a subshell, a pipe or
// a background job it may not, so both places are judged.
dirs = to.length && sequence ? [...new Set(to)] : [...new Set([...dirs, ...to])]
if (dirs.length > 16) {
dirs = dirs.slice(0, 16)
t.unsure = true
}
}
}
}
+4 -3
View File
@@ -291,7 +291,7 @@ export const AREAS: Record<string, (c: Case) => unknown> = {
const r = judgeCase(c.line as string, c.mode as Mode, c.rules as PermissionConfig | undefined)
return "run" in r ? "run" : { refused: r.refused }
},
hardline: (c) => hardlineCommand(c.line as string, BUILTIN_HARDLINE)?.id ?? null,
hardline: (c) => hardlineCommand(c.line as string, BUILTIN_HARDLINE, { branch: c.branch as string | undefined })?.id ?? null,
split: (c) => splitCommand(c.line as string),
plain: (c) => plainCommands(c.line as string),
arity: (c) => prefix(words(c.command as string)).join(" "),
@@ -303,10 +303,11 @@ export const AREAS: Record<string, (c: Case) => unknown> = {
return alwaysPatterns({ permission: "bash", class: "execute", patterns: [line], command: line }, split.commands.length ? split.commands : [line])
},
permission: (c) => {
const line = c.line as string
const [text, times] = (c.repeat ?? ["", 0]) as [string, number]
const line = (c.line as string) + text.repeat(times)
const req: PermissionRequest = { permission: "bash", class: "execute", patterns: [line], command: line, paths: ["/project"] }
const rules = [...toRules(DEFAULT_RULES, "default"), ...toRules((c.rules ?? {}) as PermissionConfig, "global")]
return evaluate(req, { mode: c.mode as Mode, rules, hardline: BUILTIN_HARDLINE, root: "/project", planDir: "/project/.agent/plans", projectDir: "/project/.agent" }).action
return evaluate(req, { mode: c.mode as Mode, rules, hardline: BUILTIN_HARDLINE, root: "/project", planDir: "/project/.agent/plans", projectDir: "/project/.agent", branch: () => undefined }).action
},
chunk: (c) => split(c.text as string, c.size as number, c.overlap as number),
think: (c) => {