Expand description
Shell command lexing and the registered shell-allowlist gate.
The lexical layer (lexer, heredocs, tokenizer, compound and case constructs,
PowerShell statements) and the security mode live here in the Engine. The
allowlist POLICY (enforcement, approval, self-reconfiguration and side-door
checks) lives above the Engine in crates/lean-ctx-shell-policy (lib
lean_ctx_shell_policy): an edit there re-checks that crate, not the Engine.
The Engine’s own callers reach the policy through register_gate, which the
policy crate installs; without a registration every check fails closed.
Structs§
- Shell
Gate - The shell-allowlist policy as the Engine sees it.
Enums§
- Dialect
- The shell that actually executes the checked line. The check cannot read
this from the process:
ctx_executealways runsbash -con Unix and the hook for the Bash tool hands the line to bash, whatever shell this process resolves, while the PowerShell tool runs PowerShell. - Separator
- The operator that ends a command segment.
- Shell
Security - Active shell-security posture. Order is least → most permissive only for readability; do not rely on ordinal values.
Constants§
- EVALUATED_
SPECIAL_ VARS - Variables bash keeps integer-attributed: assigning one evaluates the value
arithmetically (
a[$(cmd)]runscmd) without any-i. No assignment to them is stepped over, whatever the value, because arithmetic resolves names recursively. The list comes from a fullcompgen -vsweep (plus a further set of well-known special variables) of bash, trying each name asNAME='a[$(cmd)]'; only these runcmd. - MAX_
VALIDATED_ COMMAND_ BYTES - Longest command the gate validates; a longer one is refused in
enforcemode. Every check re-scans the line, and a hook that runs out of time fails open.
Functions§
- assigns_
evaluated_ special - Whether
token(NAME=…,NAME+=…) assigns one ofEVALUATED_SPECIAL_VARS. - check_
registered - Check
commandagainst the registered policy. Fails closed (refuses) when no policy is registered, so a binary that forgot the registration can never run unchecked commands. - contains_
double_ semicolon - Quote-aware scan for a
;;terminator (thecasearm separator). - detect_
function_ def - #1488: detect whether a segment is a shell function definition.
Pattern:
NAME() {,function NAME {orfunction NAME() {; GH #2131 addsNAME(){, a body on the next line and a( … )subshell body. Returns the function name if it is a definition,Noneotherwise. - exec_
name - The program a command word runs, for the gate’s name checks (
env,git, interpreters, wrappers, unconditionally blocked programs): its last path component — on macOS and Windows, whose file systems ignore case by default, lower-cased (and without.exeon Windows), so/usr/bin/ENVisenvthere. A Windows executable name (sh.exe,C:\Tools\BASH.EXE) is its stem on every host (windows_executable_stem). - exec_
name_ for - expand_
to_ leaf_ segments - Expand a (possibly compound) command into the list of simple-command leaves
that must each satisfy the allowlist. This is what makes
for … do CMD; done,if COND; then CMD; fi,while …; do CMD; doneand balanced( CMD )subshells usable in restricted mode without weakening deny-by-default: every leaf is still validated, headers/terminators contribute nothing, and any form this conservative walker cannot prove safe (case/esac,;;, a subshell with trailing content, deep nesting) is rejected — it over-blocks, never under-blocks. - extract_
all_ commands - Extract ALL command segments from a compound shell command. Splits on: &&, ||, ;, | (pipe), and handles subshell grouping.
- extract_
all_ commands_ pub - Public accessor for extracting all command segments.
- extract_
base_ command - extract_
base_ from_ segment - Extract the base command name from a single segment (no operators).
- extract_
command_ tokens_ from_ segment - Extract normalized command tokens from a single segment (no operators):
skip env assignments, skip a PowerShell assignment, return empty for a
PowerShell value expression, skip a leading
{brace-group token (#939 — lean-ctx’s own agent wrapper emits this form), and take the basename of the first token. Shared byextract_base_from_segment(which returns just the first token) and the subcommand-scoped allowlist matcher (which needs the rest of the tokens too), so the two normalizations cannot drift (GH #1419 follow-up). - find_
shell_ word - Return the first standalone unquoted shell word
wordat or afterstart. - function_
body - #1488: the commands of a function definition segment, between the outer
{and}(or(and)) —greet() { echo hi; echo bye; }givesecho hi; echo bye;. The allowlist expands it like a top-level command line, so control flow in a body (for … do … done,if … then … fi) is not mistaken for commands (GH #2002). - gate_
registered - Whether a policy gate is installed.
- heredoc_
delims - The delimiters of the heredoc operators in
line, in source order (only quoted ones withquoted_only). A<<inside quotes,${…}or arithmetic is no operator; a<<<here-string has no body. - host_
dialect - The shell that runs the checked line: the one
ctx_shelland the shell aliases execute with, unless the caller named the executor throughwith_dialect. - quote_
aware_ token_ end - Returns the byte length of the first shell token in
input, respecting quotes and(...)nesting. Used byskip_env_assignmentsto advance past env assignments with quoted values likeFOO="bar baz"— and, critically, past assignments whose value is a command substitution likeFOO=$(cmd a b)(#855): without paren-depth tracking, whitespace inside the unclosed$(...)looked like the end of the token, splittings=$(gh pr view …)into a bogus tokens=$(ghplus a leftoverprthat got misread as the base command. - read_
heredoc_ delim - Parse a heredoc delimiter token starting at
start, returning its bare name (quotes/escapes removed), whether any part was quoted, and the index just past the token.Nonewhen no delimiter is present. - refused_
builtin_ operand - The operand or assignment of a leading
export/unset/… prefix that the gate does not step over, if any.skip_env_assignmentsfails closed on it; this names it for the refusal message. - register_
gate - Install the policy gate. The first registration wins and is never replaced:
returns
falsewhen a gate was already registered, so the caller can refuse to start instead of running under a gate it did not install. - rewrite_
case_ constructs - Replace each
caseconstruct with all of its arm bodies. Pattern labels select which body runs, but they are not commands and must not enter the allowlist walk. Including every body preserves deny-by-default validation: every command that could execute for any pattern must be allowlisted. - segments_
with_ separators - Every segment together with the separator that ends it; the last segment
has none. Same scanner as
split_on_operators, so the two never disagree about where a command ends. - sequence_
statements - The top-level statements of a command line: the original text between
;/newline separators, each still holding its&&,||,|and&verbatim. Same scanner assegments_with_separators. - shell_
tokenize - Tokenize a shell command segment respecting single/double quotes and backslash escapes.
Returns tokens with outer quotes stripped, matching how the shell would parse them.
E.g.
git -C "Program Files" status→["git", "-C", "Program Files", "status"] - skip_
env_ assignments - Skip leading KEY=VALUE environment variable assignments.
Uses quote-aware scanning so
FOO="bar baz" git statuscorrectly skips the entireFOO="bar baz"token. A refused operand of an env-setting builtin, or an assignment to an evaluated special variable, makes the whole segment unmatchable instead: bash never runs an operand as a program, so it must not become a leaf an allowlisted name can unlock. - skip_
powershell_ assignment - Skip a local PowerShell assignment (
$result = Get-Content …) so the wrapped cmdlet is validated. Environment/scoped variables contain:and intentionally remain unrecognized, preventing$env:PATH = …bypasses. - split_
on_ operators - Split command string on shell operators: ;, &&, ||, |
Respects single/double quotes, parentheses nesting, and backslash escapes
outside single quotes (GL #1160):
rg split\.label\|quantityLabelis ONE command — the escaped pipe is regex data, not an operator. The old scanner split there and blocked the pattern fragment as an unknown command; same forfind … -exec rm {} \;. - strip_
all_ heredoc_ bodies - Like
strip_quoted_heredoc_bodiesbut strips bodies for all heredocs (quoted and unquoted delimiters). Use for checks that must never interpret heredoc body content as commands or redirects (#931). - strip_
for_ analysis commandwithout heredoc bodies (only quoted ones withquoted_only) and, withcomments, without comments — in one lexer pass over the raw text, so neither strip can misread what the other one removed.- warn_
only_ reason_ registered - The warn-only reason through the registered policy (the message itself when none is registered).
- windows_
executable_ stem - The program a Windows executable name (
sh.exe,BASH.EXE,C:\Tools\git.exe,/mnt/c/…/python3.exe) runs: its last path component (/or\) without the suffix, lower-cased, since Windows file names ignore case. This holds on every host: Windows findssh.exeforsh, and WSL starts a Windows executable from a Linux shell by its full name. Windows drops trailing dots and spaces from a file name, sosh.exe.,sh.exeandsh.name the same file assh.exeandsh.Nonefor any other word. - with_
dialect - Runs
fwith the allowlist reading the line for the shell that will execute it, instead of the one this process resolves.