Skip to main content

Module shell_allowlist

Module shell_allowlist 

Source
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§

ShellGate
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_execute always runs bash -c on 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.
ShellSecurity
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)] runs cmd) without any -i. No assignment to them is stepped over, whatever the value, because arithmetic resolves names recursively. The list comes from a full compgen -v sweep (plus a further set of well-known special variables) of bash, trying each name as NAME='a[$(cmd)]'; only these run cmd.
MAX_VALIDATED_COMMAND_BYTES
Longest command the gate validates; a longer one is refused in enforce mode. 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 of EVALUATED_SPECIAL_VARS.
check_registered
Check command against 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 (the case arm separator).
detect_function_def
#1488: detect whether a segment is a shell function definition. Pattern: NAME() {, function NAME { or function NAME() {; GH #2131 adds NAME(){, a body on the next line and a ( … ) subshell body. Returns the function name if it is a definition, None otherwise.
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 .exe on Windows), so /usr/bin/ENV is env there. 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; done and 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 by extract_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 word at or after start.
function_body
#1488: the commands of a function definition segment, between the outer { and } (or ( and )) — greet() { echo hi; echo bye; } gives echo 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 with quoted_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_shell and the shell aliases execute with, unless the caller named the executor through with_dialect.
quote_aware_token_end
Returns the byte length of the first shell token in input, respecting quotes and (...) nesting. Used by skip_env_assignments to advance past env assignments with quoted values like FOO="bar baz" — and, critically, past assignments whose value is a command substitution like FOO=$(cmd a b) (#855): without paren-depth tracking, whitespace inside the unclosed $(...) looked like the end of the token, splitting s=$(gh pr view …) into a bogus token s=$(gh plus a leftover pr that 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. None when 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_assignments fails 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 false when 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 case construct 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 as segments_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 status correctly skips the entire FOO="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\|quantityLabel is 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 for find … -exec rm {} \;.
strip_all_heredoc_bodies
Like strip_quoted_heredoc_bodies but 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
command without heredoc bodies (only quoted ones with quoted_only) and, with comments, 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 finds sh.exe for sh, and WSL starts a Windows executable from a Linux shell by its full name. Windows drops trailing dots and spaces from a file name, so sh.exe., sh.exe and sh. name the same file as sh.exe and sh. None for any other word.
with_dialect
Runs f with the allowlist reading the line for the shell that will execute it, instead of the one this process resolves.