aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,565 @@
use std::path::PathBuf;
use tree_sitter::Node;
use tree_sitter::Parser;
use tree_sitter::Tree;
use tree_sitter_bash::LANGUAGE as BASH;
use crate::shell_detect::ShellType;
use crate::shell_detect::detect_shell_type;
/// Parse the provided bash source using tree-sitter-bash, returning a Tree on
/// success or None if parsing failed.
pub fn try_parse_shell(shell_lc_arg: &str) -> Option<Tree> {
let lang = BASH.into();
let mut parser = Parser::new();
#[expect(clippy::expect_used)]
parser.set_language(&lang).expect("load bash grammar");
let old_tree: Option<&Tree> = None;
parser.parse(shell_lc_arg, old_tree)
}
/// Parse a script which may contain multiple simple commands joined only by
/// the safe logical/pipe/sequencing operators: `&&`, `||`, `;`, `|`.
///
/// Returns `Some(Vec<command_words>)` if every command is a plain word‑only
/// command and the parse tree does not contain disallowed constructs
/// (parentheses, redirections, substitutions, control flow, etc.). Otherwise
/// returns `None`.
pub fn try_parse_word_only_commands_sequence(tree: &Tree, src: &str) -> Option<Vec<Vec<String>>> {
if tree.root_node().has_error() {
return None;
}
// List of allowed (named) node kinds for a "word only commands sequence".
// If we encounter a named node that is not in this list we reject.
const ALLOWED_KINDS: &[&str] = &[
// top level containers
"program",
"list",
"pipeline",
// commands & words
"command",
"command_name",
"word",
"string",
"string_content",
"raw_string",
"number",
"concatenation",
];
// Allow only safe punctuation / operator tokens; anything else causes reject.
const ALLOWED_PUNCT_TOKENS: &[&str] = &["&&", "||", ";", "|", "\"", "'"];
let root = tree.root_node();
let mut cursor = root.walk();
let mut stack = vec![root];
let mut command_nodes = Vec::new();
while let Some(node) = stack.pop() {
let kind = node.kind();
if node.is_named() {
if !ALLOWED_KINDS.contains(&kind) {
return None;
}
if matches!(kind, "word" | "number") && !is_literal_word_or_number(node, src) {
return None;
}
if kind == "command" {
command_nodes.push(node);
}
} else {
// Reject any punctuation / operator tokens that are not explicitly allowed.
if kind.chars().any(|c| "&;|".contains(c)) && !ALLOWED_PUNCT_TOKENS.contains(&kind) {
return None;
}
if !(ALLOWED_PUNCT_TOKENS.contains(&kind) || kind.trim().is_empty()) {
// If it's a quote token or operator it's allowed above; we also allow whitespace tokens.
// Any other punctuation like parentheses, braces, redirects, backticks, etc are rejected.
return None;
}
}
for child in node.children(&mut cursor) {
stack.push(child);
}
}
// Walk uses a stack (LIFO), so re-sort by position to restore source order.
command_nodes.sort_by_key(Node::start_byte);
let mut commands = Vec::new();
for node in command_nodes {
if let Some(words) = parse_plain_command_from_node(node, src) {
commands.push(words);
} else {
return None;
}
}
Some(commands)
}
/// Parses a shell script consisting only of plain commands joined by safe operators.
pub fn parse_shell_script_into_commands(script: &str) -> Option<Vec<Vec<String>>> {
let tree = try_parse_shell(script)?;
try_parse_word_only_commands_sequence(&tree, script)
}
pub fn extract_bash_command(command: &[String]) -> Option<(&str, &str)> {
let [shell, flag, script] = command else {
return None;
};
if !matches!(flag.as_str(), "-lc" | "-c")
|| !matches!(
detect_shell_type(PathBuf::from(shell)),
Some(ShellType::Zsh) | Some(ShellType::Bash) | Some(ShellType::Sh)
)
{
return None;
}
Some((shell, script))
}
/// Returns the sequence of plain commands within a `bash -lc "..."` or
/// `zsh -lc "..."` invocation when the script only contains word-only commands
/// joined by safe operators.
pub fn parse_shell_lc_plain_commands(command: &[String]) -> Option<Vec<Vec<String>>> {
let (_, script) = extract_bash_command(command)?;
parse_shell_script_into_commands(script)
}
/// Extracts the literal portions of command invocations from a shell script.
///
/// Unlike [`parse_shell_lc_plain_commands`], this accepts complex shell syntax
/// and returns the statically known words from every command node in a valid
/// syntax tree. Dynamic words and redirections are omitted. This is suitable
/// for identifying dangerous literal commands, but must not be used to prove
/// that a command is safe.
pub(crate) fn parse_shell_lc_literal_commands(command: &[String]) -> Option<Vec<Vec<String>>> {
let (_, script) = extract_bash_command(command)?;
let tree = try_parse_shell(script)?;
let root = tree.root_node();
if root.has_error() {
return None;
}
let mut commands = Vec::new();
let mut stack = vec![root];
while let Some(node) = stack.pop() {
if node.kind() == "command"
&& let Some(command) = parse_literal_command_from_node(node, script)
{
commands.push(command);
}
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
stack.push(child);
}
}
Some(commands)
}
fn parse_plain_command_from_node(cmd: tree_sitter::Node, src: &str) -> Option<Vec<String>> {
if cmd.kind() != "command" {
return None;
}
let mut words = Vec::new();
let mut cursor = cmd.walk();
for child in cmd.named_children(&mut cursor) {
match child.kind() {
"command_name" => {
let word_node = child.named_child(0)?;
if word_node.kind() != "word" {
return None;
}
words.push(word_node.utf8_text(src.as_bytes()).ok()?.to_owned());
}
"word" | "number" => {
words.push(child.utf8_text(src.as_bytes()).ok()?.to_owned());
}
"string" => {
let parsed = parse_double_quoted_string(child, src)?;
words.push(parsed);
}
"raw_string" => {
let parsed = parse_raw_string(child, src)?;
words.push(parsed);
}
"concatenation" => {
// Handle concatenated arguments like -g"*.py"
let mut concatenated = String::new();
let mut concat_cursor = child.walk();
for part in child.named_children(&mut concat_cursor) {
match part.kind() {
"word" | "number" => {
concatenated
.push_str(part.utf8_text(src.as_bytes()).ok()?.to_owned().as_str());
}
"string" => {
let parsed = parse_double_quoted_string(part, src)?;
concatenated.push_str(&parsed);
}
"raw_string" => {
let parsed = parse_raw_string(part, src)?;
concatenated.push_str(&parsed);
}
_ => return None,
}
}
if concatenated.is_empty() {
return None;
}
words.push(concatenated);
}
_ => return None,
}
}
Some(words)
}
fn parse_literal_command_from_node(cmd: Node<'_>, src: &str) -> Option<Vec<String>> {
if cmd.kind() != "command" {
return None;
}
let mut words = Vec::new();
let mut found_command_name = false;
let mut cursor = cmd.walk();
for child in cmd.named_children(&mut cursor) {
if child.kind() == "command_name" {
let command_name = parse_literal_shell_word(child.named_child(0)?, src)?;
words.push(command_name);
found_command_name = true;
} else if found_command_name && let Some(word) = parse_literal_shell_word(child, src) {
words.push(word);
}
}
found_command_name.then_some(words)
}
fn parse_literal_shell_word(node: Node<'_>, src: &str) -> Option<String> {
match node.kind() {
"word" | "number" if is_literal_word_or_number(node, src) => {
Some(node.utf8_text(src.as_bytes()).ok()?.to_owned())
}
"string" => parse_double_quoted_string(node, src),
"raw_string" => parse_raw_string(node, src),
"concatenation" => {
let mut concatenated = String::new();
let mut cursor = node.walk();
for part in node.named_children(&mut cursor) {
concatenated.push_str(&parse_literal_shell_word(part, src)?);
}
(!concatenated.is_empty()).then_some(concatenated)
}
_ => None,
}
}
fn is_literal_word_or_number(node: Node<'_>, src: &str) -> bool {
if !matches!(node.kind(), "word" | "number") {
return false;
}
let mut cursor = node.walk();
node.named_children(&mut cursor).next().is_none()
&& node.utf8_text(src.as_bytes()).is_ok_and(|word| {
// A tree-sitter word can still undergo shell expansion or escape
// removal. Do not use its source spelling as proof of runtime argv.
// Include Zsh's equals expansion and extended glob syntax because
// this parser is also used for Zsh commands.
!word.starts_with('=')
&& !word.contains(['{', '}', '*', '?', '[', ']', '\\', '~', '^', '#', '$', '`'])
})
}
fn parse_double_quoted_string(node: Node, src: &str) -> Option<String> {
if node.kind() != "string" {
return None;
}
let mut cursor = node.walk();
for part in node.named_children(&mut cursor) {
if part.kind() != "string_content" {
return None;
}
}
let raw = node.utf8_text(src.as_bytes()).ok()?;
let stripped = raw
.strip_prefix('"')
.and_then(|text| text.strip_suffix('"'))?;
// Double quotes suppress globbing and brace expansion, but not escape
// removal. Only accept contents whose source spelling is already literal.
if stripped
.as_bytes()
.windows(2)
.any(|pair| pair[0] == b'\\' && matches!(pair[1], b'$' | b'`' | b'"' | b'\\' | b'\n'))
{
return None;
}
Some(stripped.to_owned())
}
fn parse_raw_string(node: Node, src: &str) -> Option<String> {
if node.kind() != "raw_string" {
return None;
}
let raw_string = node.utf8_text(src.as_bytes()).ok()?;
let stripped = raw_string
.strip_prefix('\'')
.and_then(|s| s.strip_suffix('\''));
stripped.map(str::to_owned)
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
fn parse_seq(src: &str) -> Option<Vec<Vec<String>>> {
parse_shell_script_into_commands(src)
}
#[test]
fn accepts_single_simple_command() {
let cmds = parse_seq("ls -1").unwrap();
assert_eq!(cmds, vec![vec!["ls".to_string(), "-1".to_string()]]);
}
#[test]
fn accepts_multiple_commands_with_allowed_operators() {
let src = "ls && pwd; echo 'hi there' | wc -l";
let cmds = parse_seq(src).unwrap();
let expected: Vec<Vec<String>> = vec![
vec!["ls".to_string()],
vec!["pwd".to_string()],
vec!["echo".to_string(), "hi there".to_string()],
vec!["wc".to_string(), "-l".to_string()],
];
assert_eq!(cmds, expected);
}
#[test]
fn extracts_double_and_single_quoted_strings() {
let cmds = parse_seq("echo \"hello world\"").unwrap();
assert_eq!(
cmds,
vec![vec!["echo".to_string(), "hello world".to_string()]]
);
let cmds2 = parse_seq("echo 'hi there'").unwrap();
assert_eq!(
cmds2,
vec![vec!["echo".to_string(), "hi there".to_string()]]
);
}
#[test]
fn accepts_double_quoted_strings_with_newlines() {
let cmds = parse_seq("git commit -m \"line1\nline2\"").unwrap();
assert_eq!(
cmds,
vec![vec![
"git".to_string(),
"commit".to_string(),
"-m".to_string(),
"line1\nline2".to_string(),
]]
);
}
#[test]
fn accepts_mixed_quote_concatenation() {
assert_eq!(
parse_seq(r#"echo "/usr"'/'"local"/bin"#).unwrap(),
vec![vec!["echo".to_string(), "/usr/local/bin".to_string()]]
);
assert_eq!(
parse_seq(r#"echo '/usr'"/"'local'/bin"#).unwrap(),
vec![vec!["echo".to_string(), "/usr/local/bin".to_string()]]
);
}
#[test]
fn rejects_double_quoted_strings_with_expansions() {
assert!(parse_seq(r#"echo "hi ${USER}""#).is_none());
assert!(parse_seq(r#"echo "$HOME""#).is_none());
}
#[test]
fn accepts_numbers_as_words() {
let cmds = parse_seq("echo 123 456").unwrap();
assert_eq!(
cmds,
vec![vec![
"echo".to_string(),
"123".to_string(),
"456".to_string()
]]
);
}
#[test]
fn rejects_parentheses_and_subshells() {
assert!(parse_seq("(ls)").is_none());
assert!(parse_seq("ls || (pwd && echo hi)").is_none());
}
#[test]
fn rejects_redirections_and_unsupported_operators() {
assert!(parse_seq("ls > out.txt").is_none());
assert!(parse_seq("echo hi & echo bye").is_none());
}
#[test]
fn rejects_command_and_process_substitutions_and_expansions() {
assert!(parse_seq("echo $(pwd)").is_none());
assert!(parse_seq("echo `pwd`").is_none());
assert!(parse_seq("echo $HOME").is_none());
assert!(parse_seq("echo \"hi $USER\"").is_none());
}
#[test]
fn rejects_runtime_expansion_in_plain_words() {
for script in [
"find . -{delete,print}",
"rg --pre{=,=sh} pattern payload.sh",
"find . -del*",
"find . -delet?",
"find . -delet[e]",
r"find . -de\lete",
"echo ~",
"echo ~HOME",
"echo HEAD~1",
"echo HEAD^",
"echo file~",
"echo =sh",
"echo foo^bar",
"echo foo#bar",
"l* -l",
] {
for shell in ["bash", "zsh"] {
for flag in ["-c", "-lc"] {
let command = [shell, flag, script].map(str::to_owned);
assert_eq!(parse_shell_lc_plain_commands(&command), None, "{command:?}");
}
}
}
}
#[test]
fn preserves_quoted_literals() {
for (script, expected) in [
(r#"rg -g"*.py" pattern"#, vec!["rg", "-g*.py", "pattern"]),
(r#"echo "\n""#, vec!["echo", r"\n"]),
(
r#"echo "~HOME" 'HEAD~1' "HEAD^" 'foo#bar' "=sh" 'file~'"#,
vec![
"echo", "~HOME", "HEAD~1", "HEAD^", "foo#bar", "=sh", "file~",
],
),
(
r#"echo -"{a,b}" '*?[]~^#=\\'"#,
vec!["echo", "-{a,b}", r"*?[]~^#=\\"],
),
] {
let expected = vec![expected.into_iter().map(str::to_owned).collect::<Vec<_>>()];
assert_eq!(
parse_shell_script_into_commands(script),
Some(expected),
"{script:?}"
);
}
}
#[test]
fn rejects_double_quoted_escapes() {
for script in [
r#"echo "\$HOME\`\"\\\n""#,
"find . \"-de\\\nlete\"",
r#"echo "\\""#,
] {
assert_eq!(parse_seq(script), None, "{script:?}");
for shell in ["bash", "zsh"] {
let command = [shell, "-lc", script].map(str::to_owned);
assert_eq!(parse_shell_lc_plain_commands(&command), None, "{command:?}");
}
}
}
#[test]
fn rejects_variable_assignment_prefix() {
assert!(parse_seq("FOO=bar ls").is_none());
}
#[test]
fn rejects_trailing_operator_parse_error() {
assert!(parse_seq("ls &&").is_none());
}
#[test]
fn rejects_empty_command_position_with_leading_operator() {
assert!(parse_seq("&& ls").is_none());
}
#[test]
fn rejects_empty_command_position_with_double_separator() {
assert!(parse_seq("ls ;; pwd").is_none());
}
#[test]
fn rejects_empty_command_position_with_empty_pipeline_segment() {
assert!(parse_seq("ls | | wc").is_none());
}
#[test]
fn parse_zsh_lc_plain_commands() {
let command = vec!["zsh".to_string(), "-lc".to_string(), "ls".to_string()];
let parsed = parse_shell_lc_plain_commands(&command).unwrap();
assert_eq!(parsed, vec![vec!["ls".to_string()]]);
}
#[test]
fn accepts_concatenated_flag_and_value() {
// Test case: -g"*.py" (flag directly concatenated with quoted value)
let cmds = parse_seq("rg -n \"foo\" -g\"*.py\"").unwrap();
assert_eq!(
cmds,
vec![vec![
"rg".to_string(),
"-n".to_string(),
"foo".to_string(),
"-g*.py".to_string(),
]]
);
}
#[test]
fn accepts_concatenated_flag_with_single_quotes() {
let cmds = parse_seq("grep -n 'pattern' -g'*.txt'").unwrap();
assert_eq!(
cmds,
vec![vec![
"grep".to_string(),
"-n".to_string(),
"pattern".to_string(),
"-g*.txt".to_string(),
]]
);
}
#[test]
fn rejects_concatenation_with_variable_substitution() {
// Environment variables in concatenated strings should be rejected
assert!(parse_seq("rg -g\"$VAR\" pattern").is_none());
assert!(parse_seq("rg -g\"${VAR}\" pattern").is_none());
}
#[test]
fn rejects_concatenation_with_command_substitution() {
// Command substitution in concatenated strings should be rejected
assert!(parse_seq("rg -g\"$(pwd)\" pattern").is_none());
assert!(parse_seq("rg -g\"$(echo '*.py')\" pattern").is_none());
}
}

View File

@@ -0,0 +1,70 @@
[
{"name":"echo","script":"echo hi","expected":[["echo","hi"]]},
{"name":"single_quote","script":"Get-Content 'foo bar'","expected":[["Get-Content","foo bar"]]},
{"name":"quoted_comma","script":"Get-Content 'foo,bar'","expected":[["Get-Content","foo,bar"]]},
{"name":"double_quote","script":"Get-Content \"foo bar\"","expected":[["Get-Content","foo bar"]]},
{"name":"doubled_single_quote","script":"Write-Output 'a''b'","expected":[["Write-Output","a'b"]]},
{"name":"escaped_double_quote","script":"Write-Output \"a`\"b\"","expected":[["Write-Output","a\"b"]]},
{"name":"powershell_7_escape_in_double_quote","script":"rg \"--pr`e=helper.exe\" pattern","expected":null},
{"name":"unicode_escape_in_double_quote","script":"rg \"--pre=`u{68}elper.exe\" pattern","expected":null},
{"name":"escaped_space","script":"Get-Content foo` bar","expected":[["Get-Content","foo bar"]]},
{"name":"powershell_7_escape_in_bare_word","script":"rg --pr`e helper.exe pattern","expected":null},
{"name":"command_parameter","script":"Get-ChildItem -Path .","expected":[["Get-ChildItem","-Path","."]]},
{"name":"attached_parameter_argument","script":"Get-Content -Path:1","expected":null},
{"name":"attached_quoted_parameter_argument","script":"Get-Content -Path:'foo bar'","expected":null},
{"name":"pipeline","script":"Write-Output foo | Measure-Object","expected":[["Write-Output","foo"],["Measure-Object"]]},
{"name":"semicolon","script":"Get-Content Cargo.toml; Test-Path Cargo.toml","expected":[["Get-Content","Cargo.toml"],["Test-Path","Cargo.toml"]]},
{"name":"and_chain","script":"pwd && ls","expected":[["pwd"],["ls"]]},
{"name":"or_chain","script":"pwd || ls","expected":[["pwd"],["ls"]]},
{"name":"parenthesized_command","script":"(Get-Content foo.rs -Raw)","expected":null},
{"name":"parenthesized_pipeline","script":"(Get-Content foo | Measure-Object)","expected":null},
{"name":"parenthesized_chain","script":"(pwd && ls)","expected":null},
{"name":"canonical_numeric_argument","script":"Get-Content -TotalCount 100","expected":[["Get-Content","-TotalCount","100"]]},
{"name":"negative_numeric_argument","script":"git log -1 Cargo.toml","expected":[["git","log","-1","Cargo.toml"]]},
{"name":"hexadecimal_numeric_argument","script":"Write-Output 0x10","expected":null},
{"name":"signed_hexadecimal_numeric_argument","script":"Write-Output 0xFFFFFFFF","expected":null},
{"name":"binary_numeric_argument","script":"Write-Output 0b101","expected":null},
{"name":"type_suffixed_numeric_argument","script":"Write-Output 1d","expected":null},
{"name":"powershell_7_type_suffixed_numeric_argument","script":"Write-Output 1u","expected":null},
{"name":"size_suffixed_numeric_argument","script":"Write-Output 1kb","expected":null},
{"name":"leading_zero_numeric_argument","script":"Write-Output 01","expected":null},
{"name":"real_numeric_argument","script":"Write-Output 1.0","expected":null},
{"name":"exponent_numeric_argument","script":"Write-Output 1e3","expected":null},
{"name":"numeric_leading_filename","script":"Get-Content 1.0.0","expected":null},
{"name":"inline_double_dash_parameter","script":"Get-Content --flag=value","expected":[["Get-Content","--flag=value"]]},
{"name":"inline_double_dash_parameter_pipeline","script":"Get-Content --flag=value | Measure-Object","expected":[["Get-Content","--flag=value"],["Measure-Object"]]},
{"name":"git_dir_inline","script":"git --git-dir=.git status","expected":[["git","--git-dir=.git","status"]]},
{"name":"windows_path","script":"Get-Content C:\\tmp\\x","expected":[["Get-Content","C:\\tmp\\x"]]},
{"name":"verbatim_here_string","script":"Write-Output @'\nhello\n'@","expected":null},
{"name":"expandable_here_string_without_expansion","script":"Write-Output @\"\nhello\n\"@","expected":null},
{"name":"expandable_here_string_with_escaped_dollar","script":"Write-Output @\"\n`$foo\n\"@","expected":null},
{"name":"dangerous_literal_url","script":"Start-Process 'https://example.com'","expected":[["Start-Process","https://example.com"]]},
{"name":"dangerous_literal_force","script":"Remove-Item test -Force","expected":[["Remove-Item","test","-Force"]]},
{"name":"unicode_dash_parameter","script":"Remove-Item test –Force","expected":null},
{"name":"trailing_comment","script":"Get-Content Cargo.toml # comment","expected":[["Get-Content","Cargo.toml"]]},
{"name":"hash_inside_token","script":"Get-Content foo#bar","expected":[["Get-Content","foo#bar"]]},
{"name":"embedded_hash_before_separator","script":"git status --short#; Remove-Item victim","expected":null},
{"name":"smart_quote_delimiter","script":"rg “--pre=helper.exe” pattern","expected":null},
{"name":"hash_inside_recovered_command_token","script":"pwd#evil --flag=value","expected":[["pwd#evil","--flag=value"]]},
{"name":"block_comment_before_command","script":"<# note #>\nGet-Content foo","expected":[["Get-Content","foo"]]},
{"name":"stop_parsing","script":"git log --% HEAD --output=codex_poc.txt","expected":null},
{"name":"param_block","script":"param([string]$path = (Get-Location)) Write-Output test","expected":null},
{"name":"named_blocks","script":"begin { Set-Content codex_poc.txt pwned } end { Get-Content Cargo.toml }","expected":null},
{"name":"using_statement","script":"using module ./codex_poc.psm1\nGet-Content Cargo.toml","expected":null},
{"name":"mixed_case_using_statement","script":"Using module ./codex_poc.psm1\nGet-Content Cargo.toml","expected":null},
{"name":"trap_block","script":"trap { Set-Content codex_poc.txt pwned; continue } Get-Content missing -ErrorAction Stop","expected":null},
{"name":"redirection","script":"echo hi > out.txt","expected":null},
{"name":"invocation_operator","script":"& Remove-Item foo","expected":null},
{"name":"nested_command","script":"Write-Output (Set-Content foo6.txt 'abc')","expected":null},
{"name":"subexpression","script":"Write-Output $(Get-Content foo)","expected":null},
{"name":"array_expression","script":"ls @(calc.exe)","expected":null},
{"name":"splat","script":"Get-Content @args","expected":null},
{"name":"empty_word","script":"''","expected":null},
{"name":"dynamic_argument","script":"Get-Content $foo","expected":null},
{"name":"expandable_dynamic","script":"Write-Output \"foo $bar\"","expected":null},
{"name":"comma_form","script":"Get-Content foo,bar","expected":null},
{"name":"single_dash_equals_is_not_recovery","script":"Get-Content -foo=bar","expected":null},
{"name":"uncovered_closing_paren","script":"Get-Content --flag=value )","expected":null},
{"name":"uncovered_invalid_tail","script":"Get-Content --flag=value | if (","expected":null},
{"name":"dangling_escape_after_recovery","script":"Get-Content --flag=value `","expected":null}
]

View File

@@ -0,0 +1,332 @@
use crate::bash::parse_shell_lc_literal_commands;
#[path = "windows_dangerous_commands.rs"]
mod windows_dangerous_commands;
pub use windows_dangerous_commands::powershell_commands_are_independent;
/// The platform whose command semantics should be used for safety checks.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DangerousCommandPlatform {
/// POSIX command and path semantics.
Posix,
/// Windows command and path semantics.
Windows,
}
impl DangerousCommandPlatform {
/// Returns the platform where the classifier is running.
pub fn host() -> Self {
if cfg!(windows) {
Self::Windows
} else {
Self::Posix
}
}
}
/// Identifies the dangerous-command rule matched by a command invocation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DangerousCommandMatch {
/// An `rm` invocation includes the force option.
ForcedRm,
/// Another dangerous-command rule matched.
Other,
}
const MAX_DANGEROUS_COMMAND_WRAPPER_DEPTH: usize = 8;
/// Returns the dangerous-command rule matched by an already-tokenized command.
pub fn dangerous_command_match(command: &[String]) -> Option<DangerousCommandMatch> {
dangerous_command_match_for_platform(command, DangerousCommandPlatform::host())
}
/// Returns the dangerous-command rule matched using the target platform's semantics.
pub fn dangerous_command_match_for_platform(
command: &[String],
platform: DangerousCommandPlatform,
) -> Option<DangerousCommandMatch> {
dangerous_command_match_with_depth(command, /*wrapper_depth*/ 0, platform)
}
fn dangerous_command_match_with_depth(
command: &[String],
wrapper_depth: usize,
platform: DangerousCommandPlatform,
) -> Option<DangerousCommandMatch> {
if wrapper_depth > MAX_DANGEROUS_COMMAND_WRAPPER_DEPTH {
return Some(DangerousCommandMatch::Other);
}
if let Some(dangerous_match) =
dangerous_command_match_for_exec(command, wrapper_depth, platform)
{
return Some(dangerous_match);
}
// Support shell scripts where any literal command might be dangerous,
// including commands nested in control flow or substitutions.
if let Some(dangerous_match) = parse_shell_lc_literal_commands(command).and_then(|commands| {
commands.iter().find_map(|command| {
dangerous_command_match_with_depth(command, wrapper_depth + 1, platform)
})
}) {
return Some(dangerous_match);
}
if platform == DangerousCommandPlatform::Windows
&& windows_dangerous_commands::is_dangerous_command_windows(command)
{
return Some(DangerousCommandMatch::Other);
}
None
}
/// Returns the PowerShell-specific rule matched using the target platform's semantics.
pub fn dangerous_powershell_words_match(
command: &[String],
platform: DangerousCommandPlatform,
) -> Option<DangerousCommandMatch> {
if platform == DangerousCommandPlatform::Windows {
windows_dangerous_commands::is_dangerous_powershell_words(command)
.then_some(DangerousCommandMatch::Other)
} else {
None
}
}
/// Classifies a strictly lowered command from an independent literal PowerShell script.
pub fn dangerous_powershell_literal_words_match(
command: &[String],
) -> Option<DangerousCommandMatch> {
windows_dangerous_commands::is_dangerous_powershell_literal_words(command)
.then_some(DangerousCommandMatch::Other)
}
fn executable_name_lookup_key(raw: &str, platform: DangerousCommandPlatform) -> Option<String> {
match platform {
DangerousCommandPlatform::Posix => raw
.rsplit('/')
.next()
.filter(|name| !name.is_empty())
.map(str::to_owned),
DangerousCommandPlatform::Windows => {
let name = raw
.rsplit(['/', '\\'])
.next()
.filter(|name| !name.is_empty())?;
let name = match name.as_bytes() {
[drive, b':', ..] if drive.is_ascii_alphabetic() => &name[2..],
_ => name,
};
let name = name.to_ascii_lowercase();
for suffix in [".exe", ".cmd", ".bat", ".com"] {
if let Some(stripped) = name.strip_suffix(suffix) {
return Some(stripped.to_string());
}
}
(!name.is_empty()).then_some(name)
}
}
}
fn dangerous_command_match_for_exec(
command: &[String],
wrapper_depth: usize,
platform: DangerousCommandPlatform,
) -> Option<DangerousCommandMatch> {
let cmd0 = command
.first()
.and_then(|command| executable_name_lookup_key(command, platform));
match cmd0.as_deref() {
Some("rm") if rm_args_include_force_option(&command[1..]) => {
Some(DangerousCommandMatch::ForcedRm)
}
// For sudo <cmd>, simply check <cmd>.
Some("sudo") => {
dangerous_command_match_with_depth(&command[1..], wrapper_depth + 1, platform)
}
// Skip environment assignments before checking the command run by env.
Some("env") => dangerous_command_match_for_env(command, wrapper_depth, platform),
// A trap action is shell source stored in the first operand.
Some("trap") => dangerous_command_match_for_trap(command, wrapper_depth, platform),
// ── anything else ─────────────────────────────────────────────────
_ => None,
}
}
fn dangerous_command_match_for_env(
command: &[String],
wrapper_depth: usize,
platform: DangerousCommandPlatform,
) -> Option<DangerousCommandMatch> {
let mut command_index = 1;
while let Some(argument) = command.get(command_index) {
if argument == "--" {
command_index += 1;
break;
}
if matches!(argument.as_str(), "-i" | "--ignore-environment")
|| argument
.split_once('=')
.is_some_and(|(name, _)| !name.is_empty() && !name.starts_with('-'))
{
command_index += 1;
continue;
}
break;
}
dangerous_command_match_with_depth(&command[command_index..], wrapper_depth + 1, platform)
}
fn dangerous_command_match_for_trap(
command: &[String],
wrapper_depth: usize,
platform: DangerousCommandPlatform,
) -> Option<DangerousCommandMatch> {
let mut action_index = 1;
if command
.get(action_index)
.is_some_and(|argument| argument == "--")
{
action_index += 1;
}
let action = command
.get(action_index)
.filter(|action| !action.starts_with('-'))?;
let shell_command = vec!["sh".to_string(), "-c".to_string(), action.clone()];
dangerous_command_match_with_depth(&shell_command, wrapper_depth + 1, platform)
}
fn rm_args_include_force_option(args: &[String]) -> bool {
args.iter()
.take_while(|arg| arg.as_str() != "--")
.any(|arg| {
arg == "--force"
|| arg
.strip_prefix('-')
.is_some_and(|flags| !flags.starts_with('-') && flags.contains('f'))
})
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
fn vec_str(items: &[&str]) -> Vec<String> {
items.iter().map(std::string::ToString::to_string).collect()
}
#[test]
fn rm_rf_is_dangerous() {
assert_eq!(
dangerous_command_match(&vec_str(&["rm", "-rf", "/"])),
Some(DangerousCommandMatch::ForcedRm)
);
}
#[test]
fn rm_f_is_dangerous() {
assert_eq!(
dangerous_command_match(&vec_str(&["rm", "-f", "/"])),
Some(DangerousCommandMatch::ForcedRm)
);
}
#[test]
fn forced_rm_variants_are_dangerous() {
for command in [
vec_str(&["/bin/rm", "-fr", "/tmp/example"]),
vec_str(&["rm", "-r", "-f", "/tmp/example"]),
vec_str(&["rm", "--force", "/tmp/example"]),
vec_str(&["rm", "/tmp/example", "-f"]),
vec_str(&["sudo", "rm", "-rf", "/tmp/example"]),
vec_str(&["env", "TARGET=/tmp/example", "rm", "-rf", "/tmp/example"]),
] {
assert_eq!(
dangerous_command_match(&command),
Some(DangerousCommandMatch::ForcedRm),
"{command:?}"
);
}
}
#[test]
fn deeply_nested_command_wrappers_fail_closed() {
for (depth, expected) in [
(
MAX_DANGEROUS_COMMAND_WRAPPER_DEPTH,
DangerousCommandMatch::ForcedRm,
),
(
MAX_DANGEROUS_COMMAND_WRAPPER_DEPTH + 1,
DangerousCommandMatch::Other,
),
] {
let command = std::iter::repeat_n("env", depth)
.chain(["rm", "-rf", "/tmp/example"])
.map(str::to_owned)
.collect::<Vec<_>>();
assert_eq!(dangerous_command_match(&command), Some(expected));
}
}
#[test]
fn forced_rm_in_complex_shell_syntax_is_dangerous() {
for script in [
"printf x | rm -rf /tmp/example",
"if test -d /tmp/example; then rm --force /tmp/example; fi",
"rm -rf \"$TARGET\" >/dev/null",
"for target in /tmp/a /tmp/b; do rm -r -f \"$target\"; done",
"echo \"$(rm -rf /tmp/example)\"",
"bash -c 'rm -rf /tmp/example'",
"trap 'rm -rf /tmp/example' EXIT",
"for a in '-C5a25KeRr' '--' '--json' '--bogus'; do HOME=$(mktemp -d) MDE_URL=http://127.0.0.1:1 MDE_TOKEN=x node cli/mde.cjs ls \"$a\" >/tmp/mde-review-out 2>/tmp/mde-review-err; code=$?; printf '%s\\t%s\\t%s\\n' \"$a\" \"$code\" \"$(tr '\\n' ' ' </tmp/mde-review-err)\"; rm -rf \"$HOME\"; done",
] {
let command = vec_str(&["bash", "-lc", script]);
assert_eq!(
dangerous_command_match(&command),
Some(DangerousCommandMatch::ForcedRm),
"{script}"
);
}
}
#[test]
fn non_forced_or_non_literal_rm_is_not_dangerous() {
for command in [
vec_str(&["rm", "-r", "/tmp/example"]),
vec_str(&["rm", "--", "-f"]),
vec_str(&["bash", "-lc", "echo 'rm -rf /tmp/example'"]),
vec_str(&["bash", "-lc", "cmd=rm; $cmd -rf /tmp/example"]),
vec_str(&["bash", "-lc", "if then rm -rf /tmp/example"]),
vec_str(&["env", "TARGET=/tmp/example", "rm", "-r", "/tmp/example"]),
vec_str(&["bash", "-lc", "trap 'echo rm -rf /tmp/example' EXIT"]),
] {
assert_eq!(dangerous_command_match(&command), None, "{command:?}");
}
}
#[test]
fn direct_powershell_words_return_other_match_on_windows() {
let command = vec_str(&["Remove-Item", "test", "-Force"]);
if cfg!(windows) {
assert_eq!(
dangerous_powershell_words_match(&command, DangerousCommandPlatform::host()),
Some(DangerousCommandMatch::Other)
);
} else {
assert_eq!(
dangerous_powershell_words_match(&command, DangerousCommandPlatform::host()),
None
);
}
}
}

View File

@@ -0,0 +1,9 @@
// Keep the PowerShell subprocess parser available as a test oracle, but do not
// compile it into production command classification.
#[cfg(test)]
#[allow(dead_code)]
mod powershell_parser;
mod powershell_tree_sitter;
pub mod is_dangerous_command;
pub(crate) use powershell_tree_sitter::try_parse_powershell_commands;

View File

@@ -0,0 +1,281 @@
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
# Long-lived PowerShell AST parser used by the Rust command-safety layer on Windows.
# The caller starts one child process per PowerShell executable variant and then sends
# newline-delimited JSON requests over stdin:
# { "id": <u64>, "payload": "<base64-encoded UTF-16LE script>" }
# We answer with one compact JSON line per request:
# { "id": <same>, "status": "ok", "commands": [["Get-Content", "foo.txt"]] }
# or:
# { "id": <same>, "status": "parse_failed" | "parse_errors" | "unsupported" }
#
# "unsupported" is intentional: it means the script parsed successfully, but the AST
# included constructs that we conservatively refuse to lower into argv-like command words.
# The Rust side treats that the same way as an unsafe command.
# Use BOM-free UTF-8 on the protocol stream so Rust sees clean JSON lines with no
# leading BOM bytes on the first response.
$utf8 = [System.Text.UTF8Encoding]::new($false)
$stdin = [System.IO.StreamReader]::new([Console]::OpenStandardInput(), $utf8, $false)
$stdout = [System.IO.StreamWriter]::new([Console]::OpenStandardOutput(), $utf8)
$stdout.AutoFlush = $true
function Invoke-ParseRequest {
param($RequestId, $Source)
$tokens = $null
$errors = $null
$ast = $null
try {
$ast = [System.Management.Automation.Language.Parser]::ParseInput(
$Source,
[ref]$tokens,
[ref]$errors
)
} catch {
return @{ id = $RequestId; status = 'parse_failed' }
}
if ($errors.Count -gt 0) {
return @{ id = $RequestId; status = 'parse_errors' }
}
# Top-level AST regions and collections outside the end-block statement list
# can execute code that the command lowering below does not inspect.
$cleanBlock = $ast.PSObject.Properties['CleanBlock']
if (
$ast.ParamBlock -ne $null -or
$ast.DynamicParamBlock -ne $null -or
$ast.BeginBlock -ne $null -or
$ast.ProcessBlock -ne $null -or
($cleanBlock -ne $null -and $cleanBlock.Value -ne $null) -or
$ast.UsingStatements.Count -gt 0 -or
$ast.EndBlock.Traps.Count -gt 0
) {
return @{ id = $RequestId; status = 'unsupported' }
}
# PowerShell's stop-parsing marker hands the remaining source text to native
# commands with runtime argument handling that does not match the AST shape we
# flatten below. Keep that form out of the argv-like lowering path entirely.
foreach ($token in $tokens) {
if ($token.Text -eq '--%') {
return @{ id = $RequestId; status = 'unsupported' }
}
}
# Only accept AST shapes we can flatten into a list of argv-like command words.
# Anything more dynamic than that becomes "unsupported" instead of being guessed at.
$commands = [System.Collections.ArrayList]::new()
foreach ($statement in $ast.EndBlock.Statements) {
if (-not (Add-CommandsFromPipelineBase $statement $commands)) {
$commands = $null
break
}
}
if ($commands -ne $null) {
$normalized = [System.Collections.ArrayList]::new()
foreach ($cmd in $commands) {
# Convert every successful parse result to an array-of-arrays shape so the Rust
# side can deserialize one uniform representation.
if ($cmd -is [string]) {
$null = $normalized.Add(@($cmd))
continue
}
if ($cmd -is [System.Array] -or $cmd -is [System.Collections.IEnumerable]) {
$null = $normalized.Add(@($cmd))
continue
}
$normalized = $null
break
}
$commands = $normalized
}
if ($commands -eq $null) {
return @{ id = $RequestId; status = 'unsupported' }
}
return @{ id = $RequestId; status = 'ok'; commands = $commands }
}
function Write-Response {
param($Response)
$stdout.WriteLine(($Response | ConvertTo-Json -Compress -Depth 3))
}
function Convert-CommandElement {
param($element)
# Accept only literal-ish command elements. Variable expansion, subexpressions, splats,
# and other dynamic forms return $null so the whole request becomes unsupported.
if ($element -is [System.Management.Automation.Language.StringConstantExpressionAst]) {
return @($element.Value)
}
if ($element -is [System.Management.Automation.Language.ExpandableStringExpressionAst]) {
if ($element.NestedExpressions.Count -gt 0) {
return $null
}
return @($element.Value)
}
if ($element -is [System.Management.Automation.Language.ConstantExpressionAst]) {
return @($element.Value.ToString())
}
if ($element -is [System.Management.Automation.Language.CommandParameterAst]) {
if ($element.Argument -eq $null) {
return @('-' + $element.ParameterName)
}
if ($element.Argument -is [System.Management.Automation.Language.StringConstantExpressionAst]) {
return @('-' + $element.ParameterName, $element.Argument.Value)
}
if ($element.Argument -is [System.Management.Automation.Language.ConstantExpressionAst]) {
return @('-' + $element.ParameterName, $element.Argument.Value.ToString())
}
return $null
}
return $null
}
function Convert-PipelineElement {
param($element)
if ($element -is [System.Management.Automation.Language.CommandAst]) {
# Redirections and invocation operators make the command harder to classify safely,
# so reject them rather than trying to normalize them.
if ($element.Redirections.Count -gt 0) {
return $null
}
if (
$element.InvocationOperator -ne $null -and
$element.InvocationOperator -ne [System.Management.Automation.Language.TokenKind]::Unknown
) {
return $null
}
$parts = @()
foreach ($commandElement in $element.CommandElements) {
$converted = Convert-CommandElement $commandElement
if ($converted -eq $null) {
return $null
}
$parts += $converted
}
return $parts
}
if ($element -is [System.Management.Automation.Language.CommandExpressionAst]) {
if ($element.Redirections.Count -gt 0) {
return $null
}
# Allow a parenthesized single pipeline element like "(Get-Content foo.rs -Raw)" so
# the caller still sees the inner command words. More complex expressions stay unsupported.
if ($element.Expression -is [System.Management.Automation.Language.ParenExpressionAst]) {
$innerPipeline = $element.Expression.Pipeline
if ($innerPipeline -and $innerPipeline.PipelineElements.Count -eq 1) {
return Convert-PipelineElement $innerPipeline.PipelineElements[0]
}
}
return $null
}
return $null
}
function Add-CommandsFromPipelineAst {
param($pipeline, $commands)
if ($pipeline.PipelineElements.Count -eq 0) {
return $false
}
foreach ($element in $pipeline.PipelineElements) {
$words = Convert-PipelineElement $element
if ($words -eq $null -or $words.Count -eq 0) {
return $false
}
$null = $commands.Add($words)
}
return $true
}
function Add-CommandsFromPipelineChain {
param($chain, $commands)
if (-not (Add-CommandsFromPipelineBase $chain.LhsPipelineChain $commands)) {
return $false
}
if (-not (Add-CommandsFromPipelineAst $chain.RhsPipeline $commands)) {
return $false
}
return $true
}
function Add-CommandsFromPipelineBase {
param($pipeline, $commands)
if ($pipeline -is [System.Management.Automation.Language.PipelineAst]) {
return Add-CommandsFromPipelineAst $pipeline $commands
}
# Windows PowerShell 5.1 does not define PipelineChainAst, so avoid a direct type
# reference here and instead check the runtime type name.
if ($pipeline.GetType().FullName -eq 'System.Management.Automation.Language.PipelineChainAst') {
return Add-CommandsFromPipelineChain $pipeline $commands
}
return $false
}
# This script stays alive so the Rust caller can amortize PowerShell startup across
# many parse requests. Each request and response is one compact JSON line.
while (($requestLine = $stdin.ReadLine()) -ne $null) {
$request = $null
try {
$request = $requestLine | ConvertFrom-Json
} catch {
Write-Response @{ id = $null; status = 'parse_failed' }
continue
}
# We process requests serially, but still echo the id back so the Rust side can
# detect protocol desyncs instead of silently trusting mixed stdout.
$requestId = $request.id
$payload = $request.payload
if ([string]::IsNullOrEmpty($payload)) {
Write-Response @{ id = $requestId; status = 'parse_failed' }
continue
}
try {
$source =
[System.Text.Encoding]::Unicode.GetString(
[System.Convert]::FromBase64String($payload)
)
} catch {
Write-Response @{ id = $requestId; status = 'parse_failed' }
continue
}
Write-Response (Invoke-ParseRequest -RequestId $requestId -Source $source)
}

View File

@@ -0,0 +1,373 @@
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
use std::io::BufRead;
use std::io::BufReader;
use std::io::ErrorKind;
use std::io::Write;
use std::process::Child;
use std::process::ChildStdin;
use std::process::ChildStdout;
use std::process::Command;
use std::process::Stdio;
use std::sync::LazyLock;
use std::sync::Mutex;
use std::sync::PoisonError;
const POWERSHELL_PARSER_SCRIPT: &str = include_str!("powershell_parser.ps1");
/// Cache one long-lived parser process per executable path so repeated safety checks reuse
/// PowerShell startup work while still consulting the real parser every time.
///
/// We keep the cache behind one mutex because each child process speaks a simple
/// request/response protocol over a single stdin/stdout pair, so callers targeting the same
/// executable must serialize access anyway.
pub(super) fn parse_with_powershell_ast(executable: &str, script: &str) -> PowershellParseOutcome {
static PARSER_PROCESSES: LazyLock<Mutex<HashMap<String, PowershellParserProcess>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
let mut parser_processes = PARSER_PROCESSES
.lock()
.unwrap_or_else(PoisonError::into_inner);
parse_with_cached_process(&mut parser_processes, executable, script)
}
pub(crate) fn try_parse_powershell_ast_commands(
executable: &str,
script: &str,
) -> Option<Vec<Vec<String>>> {
match parse_with_powershell_ast(executable, script) {
PowershellParseOutcome::Commands(commands) => Some(commands),
PowershellParseOutcome::Unsupported | PowershellParseOutcome::Failed => None,
}
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum PowershellParseOutcome {
Commands(Vec<Vec<String>>),
Unsupported,
Failed,
}
fn parse_with_cached_process(
parser_processes: &mut HashMap<String, PowershellParserProcess>,
executable: &str,
script: &str,
) -> PowershellParseOutcome {
// `powershell.exe` and `pwsh.exe` do not accept the same language surface, so each
// executable keeps its own parser process and request stream.
let parser_key = executable.to_string();
for attempt in 0..=1 {
if !parser_processes.contains_key(&parser_key) {
match PowershellParserProcess::spawn(executable) {
Ok(process) => {
parser_processes.insert(parser_key.clone(), process);
}
Err(_) => return PowershellParseOutcome::Failed,
}
}
let Some(parser_process) = parser_processes.get_mut(&parser_key) else {
return PowershellParseOutcome::Failed;
};
let parse_result = parser_process.parse(script);
match parse_result {
Ok(outcome) => return outcome,
Err(_) if attempt == 0 => {
// The common failure mode here is that a previously cached child exited or its
// stdio stream became unusable between requests. Drop that process and retry once
// with a fresh child before giving up.
parser_processes.remove(&parser_key);
}
Err(_) => return PowershellParseOutcome::Failed,
}
}
PowershellParseOutcome::Failed
}
fn encode_powershell_base64(script: &str) -> String {
let mut utf16 = Vec::with_capacity(script.len() * 2);
for unit in script.encode_utf16() {
utf16.extend_from_slice(&unit.to_le_bytes());
}
BASE64_STANDARD.encode(utf16)
}
fn encoded_parser_script() -> &'static str {
static ENCODED: LazyLock<String> =
LazyLock::new(|| encode_powershell_base64(POWERSHELL_PARSER_SCRIPT));
&ENCODED
}
struct PowershellParserProcess {
child: Child,
stdin: ChildStdin,
stdout: BufReader<ChildStdout>,
// Request ids are monotonic within one child process so the caller can detect protocol
// desynchronization if stdout is contaminated or the child is unexpectedly replaced.
next_request_id: u64,
}
impl PowershellParserProcess {
fn spawn(executable: &str) -> std::io::Result<Self> {
let mut command = Command::new(executable);
command
.args([
"-NoLogo",
"-NoProfile",
"-NonInteractive",
"-EncodedCommand",
encoded_parser_script(),
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null());
akode_protocol::shell_environment::scrub_non_inheritable_env_vars(&mut command);
let mut child = command.spawn()?;
let stdin = match take_child_stdin(&mut child) {
Ok(stdin) => stdin,
Err(error) => {
kill_child(&mut child);
return Err(error);
}
};
let stdout = match take_child_stdout(&mut child) {
Ok(stdout) => stdout,
Err(error) => {
kill_child(&mut child);
return Err(error);
}
};
Ok(Self {
child,
stdin,
stdout,
next_request_id: 0,
})
}
fn parse(&mut self, script: &str) -> std::io::Result<PowershellParseOutcome> {
let request = PowershellParserRequest {
id: self.next_request_id,
payload: encode_powershell_base64(script),
};
self.next_request_id = self.next_request_id.wrapping_add(1);
let mut request_json = serialize_request(&request)?;
request_json.push('\n');
self.stdin.write_all(request_json.as_bytes())?;
self.stdin.flush()?;
let mut response_line = String::new();
if self.stdout.read_line(&mut response_line)? == 0 {
return Err(std::io::Error::new(
ErrorKind::UnexpectedEof,
"PowerShell parser closed stdout",
));
}
let response = deserialize_response(&response_line)?;
// Requests are serialized today; the id still catches protocol desyncs if stdout is
// contaminated or the child process is unexpectedly replaced mid-request. That turns an
// ambiguous parser result into a hard failure so the caller can discard the cached child.
if response.id != request.id {
return Err(std::io::Error::new(
ErrorKind::InvalidData,
format!(
"PowerShell parser returned response id {} for request {}",
response.id, request.id
),
));
}
Ok(response.into_outcome())
}
}
impl Drop for PowershellParserProcess {
fn drop(&mut self) {
kill_child(&mut self.child);
}
}
fn take_child_stdin(child: &mut Child) -> std::io::Result<ChildStdin> {
child.stdin.take().ok_or_else(|| {
std::io::Error::new(
ErrorKind::BrokenPipe,
"PowerShell parser child did not expose stdin",
)
})
}
fn take_child_stdout(child: &mut Child) -> std::io::Result<BufReader<ChildStdout>> {
child.stdout.take().map(BufReader::new).ok_or_else(|| {
std::io::Error::new(
ErrorKind::BrokenPipe,
"PowerShell parser child did not expose stdout",
)
})
}
fn serialize_request(request: &PowershellParserRequest) -> std::io::Result<String> {
serde_json::to_string(request).map_err(|error| {
std::io::Error::new(
ErrorKind::InvalidData,
format!("failed to serialize PowerShell parser request: {error}"),
)
})
}
fn deserialize_response(response_line: &str) -> std::io::Result<PowershellParserResponse> {
serde_json::from_str(response_line).map_err(|error| {
std::io::Error::new(
ErrorKind::InvalidData,
format!("failed to parse PowerShell parser response: {error}"),
)
})
}
#[derive(Serialize)]
struct PowershellParserRequest {
id: u64,
payload: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PowershellParserResponse {
id: u64,
status: String,
commands: Option<Vec<Vec<String>>>,
}
impl PowershellParserResponse {
fn into_outcome(self) -> PowershellParseOutcome {
match self.status.as_str() {
"ok" => self
.commands
.filter(|commands| {
!commands.is_empty()
&& commands
.iter()
.all(|cmd| !cmd.is_empty() && cmd.iter().all(|word| !word.is_empty()))
})
.map(PowershellParseOutcome::Commands)
.unwrap_or(PowershellParseOutcome::Unsupported),
"unsupported" => PowershellParseOutcome::Unsupported,
_ => PowershellParseOutcome::Failed,
}
}
}
fn kill_child(child: &mut Child) {
let _ = child.kill();
let _ = child.wait();
}
#[cfg(all(test, windows))]
mod tests {
use super::*;
use crate::powershell::try_find_powershell_executable_blocking;
use pretty_assertions::assert_eq;
#[test]
fn parser_process_handles_multiple_requests() {
let Some(powershell) = try_find_powershell_executable_blocking() else {
return;
};
let powershell = powershell.as_path().to_str().unwrap();
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
let first = parser.parse("Get-Content 'foo bar'").unwrap();
assert_eq!(
first,
PowershellParseOutcome::Commands(vec![vec![
"Get-Content".to_string(),
"foo bar".to_string(),
]]),
);
let second = parser.parse("Write-Output foo | Measure-Object").unwrap();
assert_eq!(
second,
PowershellParseOutcome::Commands(vec![
vec!["Write-Output".to_string(), "foo".to_string()],
vec!["Measure-Object".to_string()],
]),
);
}
#[test]
fn parser_process_rejects_stop_parsing_forms() {
let Some(powershell) = try_find_powershell_executable_blocking() else {
return;
};
let powershell = powershell.as_path().to_str().unwrap();
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
let parsed = parser
.parse("git log --% HEAD --output=codex_poc.txt")
.unwrap();
assert_eq!(parsed, PowershellParseOutcome::Unsupported);
}
#[test]
fn parser_process_rejects_param_blocks() {
let Some(powershell) = try_find_powershell_executable_blocking() else {
return;
};
let powershell = powershell.as_path().to_str().unwrap();
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
let parsed = parser
.parse("param([string]$path = (Get-Location)) Write-Output test")
.unwrap();
assert_eq!(parsed, PowershellParseOutcome::Unsupported);
}
#[test]
fn parser_process_rejects_named_blocks() {
let Some(powershell) = try_find_powershell_executable_blocking() else {
return;
};
let powershell = powershell.as_path().to_str().unwrap();
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
let parsed = parser
.parse("begin { Set-Content codex_poc.txt pwned } end { Get-Content Cargo.toml }")
.unwrap();
assert_eq!(parsed, PowershellParseOutcome::Unsupported);
}
#[test]
fn parser_process_rejects_using_statements() {
let Some(powershell) = try_find_powershell_executable_blocking() else {
return;
};
let powershell = powershell.as_path().to_str().unwrap();
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
let parsed = parser
.parse("using module ./codex_poc.psm1\nGet-Content Cargo.toml")
.unwrap();
assert_eq!(parsed, PowershellParseOutcome::Unsupported);
}
#[test]
fn parser_process_rejects_trap_blocks() {
let Some(powershell) = try_find_powershell_executable_blocking() else {
return;
};
let powershell = powershell.as_path().to_str().unwrap();
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
let parsed = parser
.parse(
"trap { Set-Content codex_poc.txt pwned; continue } Get-Content missing -ErrorAction Stop",
)
.unwrap();
assert_eq!(parsed, PowershellParseOutcome::Unsupported);
}
}

View File

@@ -0,0 +1,482 @@
use tree_sitter::Node;
use tree_sitter::Parser;
/// Lowers a literal PowerShell script into argv-like command vectors.
///
/// This module does not decide whether a command is safe or dangerous; callers apply those
/// policies to the lowered words. Its job is only to recognize a deliberately small literal
/// PowerShell subset and fail closed for everything else.
///
/// Unknown syntax, parse recovery, and dynamic expressions fail closed instead of being guessed
/// at. The accepted CST shapes intentionally cover only common literal command forms; rare
/// PowerShell syntax and value-conversion cases stay opaque.
pub(crate) fn try_parse_powershell_commands(script: &str) -> Option<Vec<Vec<String>>> {
lower_with_tree_sitter(script).ok()
}
fn lower_with_tree_sitter(script: &str) -> Result<Vec<Vec<String>>, String> {
// PowerShell treats these Unicode characters as syntax aliases even when tree-sitter leaves
// them inside generic tokens. Keep that whole spelling family opaque rather than guessing at
// whether a quote or dash is structural in a particular position.
if script
.chars()
.any(|ch| matches!(ch, '‘' | '’' | '“' | '”' | '–' | '—' | '―'))
{
return Err("PowerShell Unicode syntax alias".to_string());
}
let mut parser = Parser::new();
parser
.set_language(&tree_sitter_powershell::LANGUAGE.into())
.map_err(|error| format!("load grammar: {error}"))?;
// The grammar rejects native `--flag=value`. Mask only the `=` in conservatively
// recognized bare tokens; the one-byte replacement keeps CST ranges valid for `script`.
let mut parse_source = script.as_bytes().to_vec();
for equals in inline_double_dash_parameter_equals(script) {
parse_source[equals] = b' ';
}
let parse_source = String::from_utf8(parse_source)
.map_err(|_| "masked command source is not UTF-8".to_string())?;
let tree = parser
.parse(&parse_source, None)
.ok_or_else(|| "tree-sitter returned no tree".to_string())?;
let root = tree.root_node();
if root.has_error() {
return Err("tree contains ERROR or missing nodes".to_string());
}
if has_requires_directive(root, script) {
return Err("requires directives can execute before command lowering".to_string());
}
if let Some(kind) = first_unrecognized_named_kind(root) {
return Err(format!("unrecognized named node: {kind}"));
}
let mut command_nodes = Vec::new();
collect_command_nodes(root, &mut command_nodes);
if command_nodes.is_empty() {
return Err("no literal command nodes".to_string());
}
let mut commands = Vec::with_capacity(command_nodes.len());
let mut command_ranges = Vec::with_capacity(command_nodes.len());
for node in command_nodes {
let text = node
.utf8_text(script.as_bytes())
.map_err(|_| "command source is not UTF-8".to_string())?;
command_ranges.push(node.start_byte()..node.end_byte());
commands.push(lower_command_text(text)?);
}
if !source_is_covered_by_commands(script, &command_ranges) {
return Err("source outside literal command nodes".to_string());
}
if commands.iter().any(|command| {
command
.first()
.is_some_and(|word| word.eq_ignore_ascii_case("using"))
}) {
return Err("using declarations require the PowerShell AST oracle".to_string());
}
if commands
.iter()
.any(|command| command.is_empty() || command.iter().any(String::is_empty))
{
return Err("empty lowered command or word".to_string());
}
Ok(commands)
}
fn collect_command_nodes<'tree>(root: Node<'tree>, commands: &mut Vec<Node<'tree>>) {
// Script nesting is model-controlled, so keep CST traversal off the call stack.
let mut stack = vec![root];
while let Some(node) = stack.pop() {
if node.kind() == "command" {
commands.push(node);
continue;
}
for child_index in (0..node.named_child_count()).rev() {
if let Some(child) = node.named_child(child_index) {
stack.push(child);
}
}
}
}
fn has_requires_directive(root: Node<'_>, script: &str) -> bool {
// Tree-sitter exposes #requires as a comment, but PowerShell evaluates it before the
// script body and can load modules or assemblies.
let mut stack = vec![root];
while let Some(node) = stack.pop() {
if node.kind() == "comment"
&& node
.utf8_text(script.as_bytes())
.ok()
.is_some_and(|comment| {
comment
.trim_start()
.to_ascii_lowercase()
.starts_with("#requires")
})
{
return true;
}
let mut cursor = node.walk();
stack.extend(node.named_children(&mut cursor));
}
false
}
// These helpers are the allowlist for PowerShell CST forms we intentionally understand. A new
// named tree-sitter node is rejected until its lowering semantics are reviewed.
fn first_unrecognized_named_kind(root: Node<'_>) -> Option<String> {
let mut stack = vec![root];
while let Some(node) = stack.pop() {
if node.is_named() && !is_allowed_named_kind(node.kind()) {
return Some(node.kind().to_string());
}
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
stack.push(child);
}
}
None
}
fn is_allowed_named_kind(kind: &str) -> bool {
matches!(
kind,
"program"
| "statement_list"
| "pipeline"
| "pipeline_chain"
| "pipeline_chain_tail"
| "command"
| "command_name"
| "command_elements"
| "command_argument_sep"
| "command_parameter"
| "generic_token"
| "array_literal_expression"
| "unary_expression"
| "string_literal"
| "verbatim_string_characters"
| "expandable_string_literal"
| "integer_literal"
| "decimal_integer_literal"
| "comment"
| "empty_statement"
// Negative numeric flags such as git log -1 use this wrapper.
| "expression_with_unary_operator"
)
}
// Find only bare literal `--flag=value` forms whose `=` can be masked before parsing.
fn inline_double_dash_parameter_equals(script: &str) -> Vec<usize> {
let mut equals = Vec::new();
let mut start = 0;
for (index, ch) in script.char_indices() {
if is_inline_parameter_token_separator(ch) {
push_inline_parameter_equals(&mut equals, script, start, index);
start = index + ch.len_utf8();
}
}
push_inline_parameter_equals(&mut equals, script, start, script.len());
equals
}
fn push_inline_parameter_equals(equals: &mut Vec<usize>, script: &str, start: usize, end: usize) {
let token = &script[start..end];
if token.starts_with("--")
&& token
.chars()
.all(|ch| !is_rejected_inline_parameter_character(ch))
&& let Some(relative_equals) = token.find('=')
&& relative_equals > 2
&& relative_equals + 1 < token.len()
{
equals.push(start + relative_equals);
}
}
fn is_inline_parameter_token_separator(ch: char) -> bool {
ch.is_whitespace() || "|&;#><(){}".contains(ch)
}
fn is_rejected_inline_parameter_character(ch: char) -> bool {
ch.is_whitespace() || is_rejected_bare_character(ch) || matches!(ch, '\u{60}' | '#')
}
fn source_is_covered_by_commands(script: &str, command_ranges: &[std::ops::Range<usize>]) -> bool {
// Command nodes alone are not enough: reject any source outside the literal commands and
// separators/comments we explicitly understand.
let mut index = 0;
let mut range_index = 0;
let mut can_chain = false;
let mut needs_command = false;
let mut paren_depth = 0;
while index < script.len() {
if let Some(range) = command_ranges.get(range_index)
&& index == range.start
{
index = range.end;
range_index += 1;
can_chain = true;
needs_command = false;
continue;
}
let Some(ch) = script[index..].chars().next() else {
return false;
};
let next = index + ch.len_utf8();
if ch == '\r' || ch == '\n' {
can_chain = false;
index = next;
continue;
}
if ch.is_whitespace() {
index = next;
continue;
}
if ch == ';' {
if needs_command {
return false;
}
can_chain = false;
index = next;
continue;
}
if ch == '(' && !can_chain {
paren_depth += 1;
index = next;
continue;
}
if ch == ')' && paren_depth > 0 && !needs_command {
paren_depth -= 1;
index = next;
continue;
}
if ch == '|' && can_chain {
can_chain = false;
needs_command = true;
index = if script[next..].starts_with('|') {
next + '|'.len_utf8()
} else {
next
};
continue;
}
if ch == '&' && can_chain && script[next..].starts_with('&') {
can_chain = false;
needs_command = true;
index = next + '&'.len_utf8();
continue;
}
if ch == '#' && !needs_command {
// `#` starts a comment only at a token boundary. Tree-sitter can split an
// embedded `#` out of a bare token, so reject that recovery instead of dropping
// the rest of the line.
if index > 0
&& !script[..index]
.chars()
.next_back()
.is_some_and(|previous| previous.is_whitespace() || previous == ';')
{
return false;
}
index = script[next..]
.find(['\r', '\n'])
.map_or(script.len(), |offset| next + offset);
continue;
}
if script[index..].starts_with("<#")
&& !needs_command
&& (index == 0
|| script[..index]
.chars()
.next_back()
.is_some_and(|previous| previous.is_whitespace() || previous == ';'))
{
let Some(end) = script[next..].find("#>") else {
return false;
};
index = next + end + "#>".len();
continue;
}
return false;
}
range_index == command_ranges.len() && !needs_command && paren_depth == 0
}
fn lower_command_text(command_text: &str) -> Result<Vec<String>, String> {
// This is literal argv lowering, not safe/dangerous classification. Quoting and escapes are
// decoded only for forms whose runtime value is statically known.
let mut words = Vec::new();
let chars: Vec<char> = command_text.trim().chars().collect();
let mut index = 0;
while index < chars.len() {
while index < chars.len() && chars[index].is_whitespace() {
index += 1;
}
if index == chars.len() || chars[index] == '#' {
break;
}
let (word, next, is_bare) = if chars[index] == '\'' {
let (word, next) = parse_single_quoted(&chars, index)?;
(word, next, false)
} else if chars[index] == '"' {
let (word, next) = parse_double_quoted(&chars, index)?;
(word, next, false)
} else {
let (word, next) = parse_bare_word(&chars, index)?;
(word, next, true)
};
index = next;
if index < chars.len() && !chars[index].is_whitespace() && chars[index] != '#' {
return Err("adjacent/concatenated command elements".to_string());
}
if word.is_empty() {
return Err("empty word".to_string());
}
if is_bare {
reject_unsupported_bare_word(&word)?;
}
words.push(word);
}
if words.is_empty() {
return Err("command lowered to no words".to_string());
}
Ok(words)
}
fn parse_single_quoted(chars: &[char], start: usize) -> Result<(String, usize), String> {
let mut value = String::new();
let mut index = start + 1;
while index < chars.len() {
if chars[index] == '\'' {
if chars.get(index + 1) == Some(&'\'') {
value.push('\'');
index += 2;
continue;
}
return Ok((value, index + 1));
}
value.push(chars[index]);
index += 1;
}
Err("unterminated single-quoted string".to_string())
}
fn parse_double_quoted(chars: &[char], start: usize) -> Result<(String, usize), String> {
let mut value = String::new();
let mut index = start + 1;
while index < chars.len() {
match chars[index] {
'"' => return Ok((value, index + 1)),
'$' => return Err("expandable string contains variable syntax".to_string()),
'`' => {
let escaped = *chars
.get(index + 1)
.ok_or_else(|| "trailing PowerShell escape".to_string())?;
// `e is ESC only in PowerShell 6+, so it has no version-neutral value.
if escaped == 'e' {
return Err("PowerShell-version-dependent escape".to_string());
}
if escaped == 'u' && chars.get(index + 2) == Some(&'{') {
return Err("PowerShell Unicode escape".to_string());
}
value.push(decode_backtick_escape(escaped));
index += 2;
}
ch => {
value.push(ch);
index += 1;
}
}
}
Err("unterminated double-quoted string".to_string())
}
fn decode_backtick_escape(ch: char) -> char {
match ch {
'0' => '\0',
'a' => '\u{7}',
'b' => '\u{8}',
'f' => '\u{c}',
'n' => '\n',
'r' => '\r',
't' => '\t',
'v' => '\u{b}',
other => other,
}
}
fn parse_bare_word(chars: &[char], start: usize) -> Result<(String, usize), String> {
let mut value = String::new();
let mut index = start;
while index < chars.len() && !chars[index].is_whitespace() {
let ch = chars[index];
if ch == '`' {
let escaped = *chars
.get(index + 1)
.ok_or_else(|| "trailing PowerShell escape".to_string())?;
if escaped == 'e' {
return Err("PowerShell-version-dependent escape".to_string());
}
value.push(decode_backtick_escape(escaped));
index += 2;
continue;
}
if is_rejected_bare_character(ch) {
return Err(format!("dynamic or structural bare character: {ch:?}"));
}
value.push(ch);
index += 1;
}
if value.is_empty() {
return Err("empty bare word".to_string());
}
Ok((value, index))
}
fn is_rejected_bare_character(ch: char) -> bool {
matches!(
ch,
'$' | '@'
| '\''
| '"'
| '('
| ')'
| '{'
| '}'
| '['
| ']'
| ';'
| '|'
| '&'
| '>'
| '<'
| ','
)
}
fn reject_unsupported_bare_word(word: &str) -> Result<(), String> {
// These forms require PowerShell-specific value conversion. Keeping them opaque is safer
// than reproducing that conversion in the policy parser.
if word.starts_with('-') && !word.starts_with("--") && word.contains(':') {
return Err("attached PowerShell parameter value".to_string());
}
// Tree-sitter leaves some PowerShell numerics as generic tokens. Keep only canonical decimal
// spellings whose runtime string is obviously identical to the source spelling.
if word.chars().next().is_some_and(|ch| ch.is_ascii_digit())
&& !(word == "0" || (!word.starts_with('0') && word.chars().all(|ch| ch.is_ascii_digit())))
{
return Err("non-canonical numeric-leading bare word".to_string());
}
Ok(())
}
#[cfg(test)]
#[path = "powershell_tree_sitter_tests.rs"]
mod tests;

View File

@@ -0,0 +1,37 @@
use pretty_assertions::assert_eq;
use serde::Deserialize;
use super::try_parse_powershell_commands;
#[derive(Debug, Deserialize)]
struct FixtureCase {
name: String,
script: String,
expected: Option<Vec<Vec<String>>>,
}
#[test]
fn lowers_compact_literal_fixture() {
// Supported outputs were captured from the PowerShell 7 AST subprocess parser. Rare forms
// that need additional PowerShell-specific lowering are intentionally recorded as unsupported.
let cases: Vec<FixtureCase> =
serde_json::from_str(include_str!("fixtures/powershell_lowering.json"))
.expect("valid PowerShell lowering fixture");
for case in cases {
assert_eq!(
try_parse_powershell_commands(&case.script),
case.expected,
"fixture case: {}",
case.name
);
}
}
#[test]
fn rejects_requires_directives() {
assert_eq!(
try_parse_powershell_commands("#requires -Modules Evil\nGet-Location"),
None
);
}

View File

@@ -0,0 +1,849 @@
use crate::command_safety::powershell_tree_sitter::try_parse_powershell_commands;
use once_cell::sync::Lazy;
use regex::Regex;
use shlex::split as shlex_split;
use url::Url;
pub fn is_dangerous_command_windows(command: &[String]) -> bool {
// Prefer structured parsing for PowerShell/CMD so we can spot URL-bearing
// invocations of ShellExecute-style entry points before falling back to
// simple argv heuristics.
if is_dangerous_powershell(command) {
return true;
}
if is_dangerous_cmd(command) {
return true;
}
is_direct_gui_launch(command)
}
fn is_dangerous_powershell(command: &[String]) -> bool {
let Some((exe, rest)) = command.split_first() else {
return false;
};
if !is_powershell_executable(exe) {
return false;
}
let Some(parsed) = parse_powershell_invocation(rest) else {
return false;
};
if let Some(script) = parsed.script
&& let Some(commands) = try_parse_powershell_commands(script)
&& powershell_commands_are_independent(script, &commands)
{
return commands
.iter()
.any(|words| is_dangerous_powershell_literal_words(words));
}
is_dangerous_powershell_words(&parsed.tokens)
}
/// Whether strictly lowered commands can be classified independently of the rest of the script.
pub fn powershell_commands_are_independent(script: &str, commands: &[Vec<String>]) -> bool {
// Deliberately keep even quoted pipes and `||` chains on the existing path. Do not
// model pipeline data, command rebinding, or strings that may execute using script state.
!script.contains('|')
&& commands.iter().all(|words| {
!matches!(
words
.first()
.and_then(|word| executable_basename(word))
.as_deref(),
Some(
"set-alias"
| "sal"
| "new-alias"
| "nal"
| "set-item"
| "si"
| "new-item"
| "ni"
)
) && !words.iter().skip(1).any(|word| {
let word = word.to_ascii_lowercase();
[
"start-process",
"invoke-item",
"shellexecute",
"shell.application",
]
.iter()
.any(|marker| word.contains(marker))
})
})
}
enum PowerShellCommandKind {
Opaque,
IndependentLiteral,
}
pub(crate) fn is_dangerous_powershell_words(words: &[String]) -> bool {
classify_powershell_words(words, PowerShellCommandKind::Opaque)
}
pub(crate) fn is_dangerous_powershell_literal_words(words: &[String]) -> bool {
// Shell and terminal wrappers can interpret later words as commands, including `start`.
let kind = if words.first().is_some_and(|word| {
is_powershell_executable(word)
|| matches!(
executable_basename(word).as_deref(),
Some("cmd" | "cmd.exe" | "wt" | "wt.exe")
)
}) {
PowerShellCommandKind::Opaque
} else {
PowerShellCommandKind::IndependentLiteral
};
classify_powershell_words(words, kind)
}
fn classify_powershell_words(words: &[String], kind: PowerShellCommandKind) -> bool {
let tokens_lc: Vec<String> = words
.iter()
.map(|t| t.trim_matches('\'').trim_matches('"').to_ascii_lowercase())
.collect();
let has_url = args_have_url(words);
if has_url
&& tokens_lc.iter().enumerate().any(|(index, t)| {
((index == 0 || matches!(kind, PowerShellCommandKind::Opaque))
&& matches!(
t.as_str(),
"start-process" | "start" | "saps" | "invoke-item" | "ii"
))
|| t.contains("start-process")
|| t.contains("invoke-item")
})
{
return true;
}
if has_url
&& tokens_lc
.iter()
.any(|t| t.contains("shellexecute") || t.contains("shell.application"))
{
return true;
}
if let Some(first) = tokens_lc.first() {
// Legacy ShellExecute path via url.dll
if first == "rundll32"
&& tokens_lc
.iter()
.any(|t| t.contains("url.dll,fileprotocolhandler"))
&& has_url
{
return true;
}
if first == "mshta" && has_url {
return true;
}
if is_browser_executable(first) && has_url {
return true;
}
if matches!(first.as_str(), "explorer" | "explorer.exe") && has_url {
return true;
}
}
// Check for force delete operations (e.g., Remove-Item -Force)
has_force_delete_cmdlet(&tokens_lc)
}
fn is_dangerous_cmd(command: &[String]) -> bool {
let Some((exe, rest)) = command.split_first() else {
return false;
};
let Some(base) = executable_basename(exe) else {
return false;
};
if base != "cmd" && base != "cmd.exe" {
return false;
}
let mut iter = rest.iter();
for arg in iter.by_ref() {
let lower = arg.to_ascii_lowercase();
match lower.as_str() {
"/c" | "/r" | "-c" => break,
_ if lower.starts_with('/') => continue,
// Unknown tokens before the command body => bail.
_ => return false,
}
}
let remaining: Vec<String> = iter.cloned().collect();
if remaining.is_empty() {
return false;
}
let cmd_tokens: Vec<String> = match remaining.as_slice() {
[only] => shlex_split(only).unwrap_or_else(|| vec![only.clone()]),
_ => remaining,
};
// Refine tokens by splitting concatenated CMD operators (e.g. "echo hi&del")
let tokens: Vec<String> = cmd_tokens
.into_iter()
.flat_map(|t| split_embedded_cmd_operators(&t))
.collect();
const CMD_SEPARATORS: &[&str] = &["&", "&&", "|", "||"];
tokens
.split(|t| CMD_SEPARATORS.contains(&t.as_str()))
.any(|segment| {
let Some(cmd) = segment.first() else {
return false;
};
// Classic `cmd /c ... start https://...` ShellExecute path.
if cmd.eq_ignore_ascii_case("start") && args_have_url(segment) {
return true;
}
// Force delete: del /f, erase /f
if (cmd.eq_ignore_ascii_case("del") || cmd.eq_ignore_ascii_case("erase"))
&& has_force_flag_cmd(segment)
{
return true;
}
// Recursive directory removal: rd /s /q, rmdir /s /q
if (cmd.eq_ignore_ascii_case("rd") || cmd.eq_ignore_ascii_case("rmdir"))
&& has_recursive_flag_cmd(segment)
&& has_quiet_flag_cmd(segment)
{
return true;
}
false
})
}
fn is_direct_gui_launch(command: &[String]) -> bool {
let Some((exe, rest)) = command.split_first() else {
return false;
};
let Some(base) = executable_basename(exe) else {
return false;
};
// Explorer/rundll32/mshta or direct browser exe with a URL anywhere in args.
if matches!(base.as_str(), "explorer" | "explorer.exe") && args_have_url(rest) {
return true;
}
if matches!(base.as_str(), "mshta" | "mshta.exe") && args_have_url(rest) {
return true;
}
if (base == "rundll32" || base == "rundll32.exe")
&& rest.iter().any(|t| {
t.to_ascii_lowercase()
.contains("url.dll,fileprotocolhandler")
})
&& args_have_url(rest)
{
return true;
}
if is_browser_executable(&base) && args_have_url(rest) {
return true;
}
false
}
fn split_embedded_cmd_operators(token: &str) -> Vec<String> {
// Split concatenated CMD operators so `echo hi&del` becomes `["echo hi", "&", "del"]`.
// Handles `&`, `&&`, `|`, `||`. Best-effort (CMD escaping is weird by nature).
let mut parts = Vec::new();
let mut start = 0;
let mut it = token.char_indices().peekable();
while let Some((i, ch)) = it.next() {
if ch == '&' || ch == '|' {
if i > start {
parts.push(token[start..i].to_string());
}
// Detect doubled operator: && or ||
let op_len = match it.peek() {
Some(&(j, next)) if next == ch => {
it.next(); // consume second char
(j + next.len_utf8()) - i
}
_ => ch.len_utf8(),
};
parts.push(token[i..i + op_len].to_string());
start = i + op_len;
}
}
if start < token.len() {
parts.push(token[start..].to_string());
}
parts.retain(|s| !s.trim().is_empty());
parts
}
fn has_force_delete_cmdlet(tokens: &[String]) -> bool {
const DELETE_CMDLETS: &[&str] = &["remove-item", "ri", "rm", "del", "erase", "rd", "rmdir"];
// Hard separators that end a command segment (so -Force must be in same segment)
const SEG_SEPS: &[char] = &[';', '|', '&', '\n', '\r', '\t'];
// Soft separators: punctuation that can stick to tokens (blocks, parens, brackets, commas, etc.)
const SOFT_SEPS: &[char] = &['{', '}', '(', ')', '[', ']', ',', ';'];
// Build rough command segments first
let mut segments: Vec<Vec<String>> = vec![Vec::new()];
for tok in tokens {
// If token itself contains segment separators, split it (best-effort)
let mut cur = String::new();
for ch in tok.chars() {
if SEG_SEPS.contains(&ch) {
let s = cur.trim();
if let Some(msg) = segments.last_mut()
&& !s.is_empty()
{
msg.push(s.to_string());
}
cur.clear();
if let Some(last) = segments.last()
&& !last.is_empty()
{
segments.push(Vec::new());
}
} else {
cur.push(ch);
}
}
let s = cur.trim();
if let Some(segment) = segments.last_mut()
&& !s.is_empty()
{
segment.push(s.to_string());
}
}
// Now, inside each segment, normalize tokens by splitting on soft punctuation
segments.into_iter().any(|seg| {
let atoms = seg
.iter()
.flat_map(|t| t.split(|c| SOFT_SEPS.contains(&c)))
.map(str::trim)
.filter(|s| !s.is_empty());
let mut has_delete = false;
let mut has_force = false;
for a in atoms {
if DELETE_CMDLETS.iter().any(|cmd| a.eq_ignore_ascii_case(cmd)) {
has_delete = true;
}
if a.eq_ignore_ascii_case("-force")
|| a.get(..7)
.is_some_and(|p| p.eq_ignore_ascii_case("-force:"))
{
has_force = true;
}
}
has_delete && has_force
})
}
/// Check for /f or /F flag in CMD del/erase arguments.
fn has_force_flag_cmd(args: &[String]) -> bool {
args.iter().any(|a| a.eq_ignore_ascii_case("/f"))
}
/// Check for /s or /S flag in CMD rd/rmdir arguments.
fn has_recursive_flag_cmd(args: &[String]) -> bool {
args.iter().any(|a| a.eq_ignore_ascii_case("/s"))
}
/// Check for /q or /Q flag in CMD rd/rmdir arguments.
fn has_quiet_flag_cmd(args: &[String]) -> bool {
args.iter().any(|a| a.eq_ignore_ascii_case("/q"))
}
fn args_have_url(args: &[String]) -> bool {
args.iter().any(|arg| looks_like_url(arg))
}
fn looks_like_url(token: &str) -> bool {
// Strip common PowerShell punctuation around inline URLs (quotes, parens, trailing semicolons).
// Capture the middle token after trimming leading quotes/parens/whitespace and trailing semicolons/closing parens.
static RE: Lazy<Option<Regex>> =
Lazy::new(|| Regex::new(r#"^[ "'\(\s]*([^\s"'\);]+)[\s;\)]*$"#).ok());
// If the token embeds a URL alongside other text (e.g., Start-Process('https://...'))
// as a single shlex token, grab the substring starting at the first URL prefix.
let lowercase_token = token.to_ascii_lowercase();
let urlish = lowercase_token
.find("https://")
.or_else(|| lowercase_token.find("http://"))
.map(|idx| &token[idx..])
.unwrap_or(token);
let candidate = RE
.as_ref()
.and_then(|re| re.captures(urlish))
.and_then(|caps| caps.get(1))
.map(|m| m.as_str())
.unwrap_or(urlish);
let Ok(url) = Url::parse(candidate) else {
return false;
};
matches!(url.scheme(), "http" | "https")
}
fn executable_basename(exe: &str) -> Option<String> {
let name = exe
.rsplit(['/', '\\'])
.next()
.filter(|name| !name.is_empty())?;
let name = match name.as_bytes() {
[drive, b':', ..] if drive.is_ascii_alphabetic() => &name[2..],
_ => name,
};
(!name.is_empty()).then(|| name.to_ascii_lowercase())
}
fn is_powershell_executable(exe: &str) -> bool {
matches!(
executable_basename(exe).as_deref(),
Some("powershell") | Some("powershell.exe") | Some("pwsh") | Some("pwsh.exe")
)
}
fn is_browser_executable(name: &str) -> bool {
matches!(
name,
"chrome"
| "chrome.exe"
| "msedge"
| "msedge.exe"
| "firefox"
| "firefox.exe"
| "iexplore"
| "iexplore.exe"
)
}
struct ParsedPowershell<'a> {
tokens: Vec<String>,
script: Option<&'a str>,
}
fn parse_powershell_invocation(args: &[String]) -> Option<ParsedPowershell<'_>> {
if args.is_empty() {
return None;
}
let mut idx = 0;
while idx < args.len() {
let arg = &args[idx];
let lower = arg.to_ascii_lowercase();
match lower.as_str() {
"-command" | "/command" | "-c" => {
let script = args.get(idx + 1)?;
if idx + 2 != args.len() {
return None;
}
let tokens = shlex_split(script)?;
return Some(ParsedPowershell {
tokens,
script: Some(script),
});
}
_ if lower.starts_with("-command:") || lower.starts_with("/command:") => {
if idx + 1 != args.len() {
return None;
}
let (_, script) = arg.split_once(':')?;
let tokens = shlex_split(script)?;
return Some(ParsedPowershell {
tokens,
script: Some(script),
});
}
"-nologo" | "-noprofile" | "-noninteractive" | "-mta" | "-sta" => {
idx += 1;
}
_ if lower.starts_with('-') => {
idx += 1;
}
_ => {
let rest = args[idx..].to_vec();
return Some(ParsedPowershell {
tokens: rest,
script: None,
});
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::is_dangerous_command_windows;
fn vec_str(items: &[&str]) -> Vec<String> {
items.iter().map(std::string::ToString::to_string).collect()
}
#[test]
fn powershell_start_process_url_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"powershell",
"-NoLogo",
"-Command",
"Start-Process 'https://example.com'"
])));
}
#[test]
fn powershell_start_process_url_with_trailing_semicolon_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"powershell",
"-Command",
"Start-Process('https://example.com');"
])));
}
#[test]
fn powershell_start_process_mixed_case_urls_are_dangerous() {
for script in [
"Start-Process('HTTP://example.com');",
"Start-Process('hTtPs://example.com');",
] {
assert!(
is_dangerous_command_windows(&vec_str(&["powershell", "-Command", script])),
"{script}"
);
}
}
#[test]
fn powershell_start_process_local_is_not_flagged() {
assert!(!is_dangerous_command_windows(&vec_str(&[
"powershell",
"-Command",
"Start-Process notepad.exe"
])));
}
#[test]
fn cmd_start_with_url_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd",
"/c",
"start",
"https://example.com"
])));
}
#[test]
fn msedge_with_url_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"msedge.exe",
"https://example.com"
])));
}
#[test]
fn explorer_with_directory_is_not_flagged() {
assert!(!is_dangerous_command_windows(&vec_str(&[
"explorer.exe",
"."
])));
}
// Force delete tests for PowerShell
#[test]
fn powershell_remove_item_force_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"powershell",
"-Command",
"Remove-Item test -Force"
])));
}
#[test]
fn powershell_remove_item_recurse_force_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"powershell",
"-Command",
"Remove-Item test -Recurse -Force"
])));
}
#[test]
fn powershell_ri_alias_force_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"pwsh",
"-Command",
"ri test -Force"
])));
}
#[test]
fn powershell_remove_item_without_force_is_not_flagged() {
assert!(!is_dangerous_command_windows(&vec_str(&[
"powershell",
"-Command",
"Remove-Item test"
])));
}
// Force delete tests for CMD
#[test]
fn cmd_del_force_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd", "/c", "del", "/f", "test.txt"
])));
}
#[test]
fn cmd_erase_force_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd", "/c", "erase", "/f", "test.txt"
])));
}
#[test]
fn cmd_del_without_force_is_not_flagged() {
assert!(!is_dangerous_command_windows(&vec_str(&[
"cmd", "/c", "del", "test.txt"
])));
}
#[test]
fn cmd_rd_recursive_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd", "/c", "rd", "/s", "/q", "test"
])));
}
#[test]
fn cmd_rd_without_quiet_is_not_flagged() {
assert!(!is_dangerous_command_windows(&vec_str(&[
"cmd", "/c", "rd", "/s", "test"
])));
}
#[test]
fn cmd_rmdir_recursive_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd", "/c", "rmdir", "/s", "/q", "test"
])));
}
// Test exact scenario from issue #8567
#[test]
fn powershell_remove_item_path_recurse_force_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"powershell",
"-Command",
"Remove-Item -Path 'test' -Recurse -Force"
])));
}
#[test]
fn powershell_remove_item_force_with_semicolon_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"powershell",
"-Command",
"Remove-Item test -Force; Write-Host done"
])));
}
#[test]
fn powershell_remove_item_force_inside_block_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"powershell",
"-Command",
"if ($true) { Remove-Item test -Force}"
])));
}
#[test]
fn powershell_remove_item_force_inside_brackets_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"powershell",
"-Command",
"[void]( Remove-Item test -Force)]"
])));
}
#[test]
fn cmd_del_path_containing_f_is_not_flagged() {
assert!(!is_dangerous_command_windows(&vec_str(&[
"cmd",
"/c",
"del",
"C:/foo/bar.txt"
])));
}
#[test]
fn cmd_rd_path_containing_s_is_not_flagged() {
assert!(!is_dangerous_command_windows(&vec_str(&[
"cmd",
"/c",
"rd",
"C:/source"
])));
}
#[test]
fn cmd_bypass_chained_del_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd", "/c", "echo", "hello", "&", "del", "/f", "file.txt"
])));
}
#[test]
fn powershell_chained_no_space_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"powershell",
"-Command",
"Write-Host hi;Remove-Item -Force C:\\tmp"
])));
}
#[test]
fn powershell_comma_separated_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"powershell",
"-Command",
"del,-Force,C:\\foo"
])));
}
#[test]
fn cmd_echo_del_is_not_dangerous() {
assert!(!is_dangerous_command_windows(&vec_str(&[
"cmd", "/c", "echo", "del", "/f"
])));
}
#[test]
fn cmd_del_single_string_argument_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd",
"/c",
"del /f file.txt"
])));
}
#[test]
fn cmd_del_chained_single_string_argument_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd",
"/c",
"echo hello & del /f file.txt"
])));
}
#[test]
fn cmd_chained_no_space_del_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd",
"/c",
"echo hi&del /f file.txt"
])));
}
#[test]
fn cmd_chained_andand_no_space_del_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd",
"/c",
"echo hi&&del /f file.txt"
])));
}
#[test]
fn cmd_chained_oror_no_space_del_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd",
"/c",
"echo hi||del /f file.txt"
])));
}
#[test]
fn cmd_start_url_single_string_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd",
"/c",
"start https://example.com"
])));
}
#[test]
fn cmd_chained_no_space_rmdir_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd",
"/c",
"echo hi&rmdir /s /q testdir"
])));
}
#[test]
fn cmd_del_force_uppercase_flag_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd", "/c", "DEL", "/F", "file.txt"
])));
}
#[test]
fn cmdexe_r_del_force_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd.exe", "/r", "del", "/f", "file.txt"
])));
}
#[test]
fn cmd_start_quoted_url_single_string_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd",
"/c",
r#"start "https://example.com""#
])));
}
#[test]
fn cmd_start_title_then_url_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"cmd",
"/c",
r#"start "" https://example.com"#
])));
}
#[test]
fn powershell_rm_alias_force_is_dangerous() {
assert!(is_dangerous_command_windows(&vec_str(&[
"powershell",
"-Command",
"rm test -Force"
])));
}
#[test]
fn powershell_benign_force_separate_command_is_not_dangerous() {
assert!(!is_dangerous_command_windows(&vec_str(&[
"powershell",
"-Command",
"Get-ChildItem -Force; Remove-Item test"
])));
}
}

View File

@@ -0,0 +1,14 @@
//! Command parsing and safety utilities shared across Codex crates.
pub mod shell_detect;
pub mod shell_snapshot;
mod startup;
pub use startup::shell_startup_script;
pub mod bash;
pub(crate) mod command_safety;
pub mod parse_command;
pub mod powershell;
pub use command_safety::is_dangerous_command;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,291 @@
use std::path::PathBuf;
use akode_utils_absolute_path::AbsolutePathBuf;
use crate::command_safety::try_parse_powershell_commands;
use crate::shell_detect::ShellType;
use crate::shell_detect::detect_shell_type;
const POWERSHELL_FLAGS: &[&str] = &["-nologo", "-noprofile", "-command", "-c"];
/// Prefixed command for powershell shell calls to request UTF-8 console output.
pub const UTF8_OUTPUT_PREFIX: &str =
"try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}\n";
pub fn prefix_powershell_script_with_utf8(command: &[String]) -> Vec<String> {
let Some((_, script)) = extract_powershell_command(command) else {
return command.to_vec();
};
let trimmed = script.trim_start();
let script = if trimmed.starts_with(UTF8_OUTPUT_PREFIX) {
script.to_string()
} else {
format!("{UTF8_OUTPUT_PREFIX}{script}")
};
let mut command: Vec<String> = command[..(command.len() - 1)]
.iter()
.map(std::string::ToString::to_string)
.collect();
command.push(script);
command
}
/// Extract the PowerShell script body from an invocation such as:
///
/// - ["pwsh", "-NoProfile", "-Command", "Get-ChildItem -Recurse | Select-String foo"]
/// - ["powershell.exe", "-Command", "Write-Host hi"]
/// - ["powershell", "-NoLogo", "-NoProfile", "-Command", "...script..."]
///
/// Returns (`shell`, `script`) when the first arg is a PowerShell executable and a
/// `-Command` (or `-c`) flag is present followed by a script string.
pub fn extract_powershell_command(command: &[String]) -> Option<(&str, &str)> {
if command.len() < 3 {
return None;
}
let shell = &command[0];
if !matches!(
detect_shell_type(PathBuf::from(shell)),
Some(ShellType::PowerShell)
) {
return None;
}
// Find the first occurrence of -Command (accept common short alias -c as well)
let mut i = 1usize;
while i + 1 < command.len() {
let flag = &command[i];
// Reject unknown flags
if !POWERSHELL_FLAGS.contains(&flag.to_ascii_lowercase().as_str()) {
return None;
}
if flag.eq_ignore_ascii_case("-Command") || flag.eq_ignore_ascii_case("-c") {
let script = &command[i + 1];
return Some((shell, script));
}
i += 1;
}
None
}
/// Parse the script body from a top-level PowerShell wrapper into argv-like commands.
///
/// This only unwraps the `-Command`/`-c` body from a PowerShell invocation we
/// already recognize, then lowers the script in-process.
pub fn parse_powershell_command_into_plain_commands(
command: &[String],
) -> Option<Vec<Vec<String>>> {
let (_, script) = extract_powershell_command(command)?;
try_parse_powershell_commands(script)
}
/// Parse literal PowerShell commands without starting a PowerShell executable.
///
/// Unknown or dynamic syntax stays opaque so unfamiliar executables can be
/// evaluated without running them before approval.
pub fn parse_powershell_script_into_plain_commands(script: &str) -> Option<Vec<Vec<String>>> {
try_parse_powershell_commands(script)
}
/// This function attempts to find a powershell.exe executable on the system.
pub fn try_find_powershell_executable_blocking() -> Option<AbsolutePathBuf> {
try_find_powershellish_executable_in_path(&["powershell.exe"])
}
/// This function attempts to find a pwsh.exe executable on the system.
/// Note that pwsh.exe and powershell.exe are different executables:
///
/// - pwsh.exe is the cross-platform PowerShell Core (v6+) executable
/// - powershell.exe is the Windows PowerShell (v5.1 and earlier) executable
///
/// Further, while powershell.exe is included by default on Windows systems,
/// pwsh.exe must be installed separately by the user. And even when the user
/// has installed pwsh.exe, it may not be available in the system PATH, in which
/// case we attempt to locate it via other means.
pub fn try_find_pwsh_executable_blocking() -> Option<AbsolutePathBuf> {
if let Some(ps_home) = std::process::Command::new("cmd")
.args(["/C", "pwsh", "-NoProfile", "-Command", "$PSHOME"])
.output()
.ok()
.and_then(|out| {
if !out.status.success() {
return None;
}
let stdout = String::from_utf8_lossy(&out.stdout);
let trimmed = stdout.trim();
(!trimmed.is_empty()).then(|| trimmed.to_string())
})
{
let candidate = AbsolutePathBuf::resolve_path_against_base("pwsh.exe", &ps_home);
if is_powershellish_executable_available(candidate.as_path()) {
return Some(candidate);
}
}
try_find_powershellish_executable_in_path(&["pwsh.exe"])
}
fn try_find_powershellish_executable_in_path(candidates: &[&str]) -> Option<AbsolutePathBuf> {
for candidate in candidates {
let Ok(resolved_path) = which::which(candidate) else {
continue;
};
if !is_powershellish_executable_available(&resolved_path) {
continue;
}
let Ok(abs_path) = AbsolutePathBuf::from_absolute_path(resolved_path) else {
continue;
};
return Some(abs_path);
}
None
}
fn is_powershellish_executable_available(powershell_or_pwsh_exe: &std::path::Path) -> bool {
// This test works for both powershell.exe and pwsh.exe.
std::process::Command::new(powershell_or_pwsh_exe)
.args(["-NoLogo", "-NoProfile", "-Command", "Write-Output ok"])
.output()
.map(|output| output.status.success())
.unwrap_or(false)
}
#[cfg(test)]
mod tests {
use super::UTF8_OUTPUT_PREFIX;
use super::extract_powershell_command;
#[cfg(windows)]
use super::parse_powershell_command_into_plain_commands;
use super::parse_powershell_script_into_plain_commands;
use super::prefix_powershell_script_with_utf8;
#[test]
fn extracts_basic_powershell_command() {
let cmd = vec![
"powershell".to_string(),
"-Command".to_string(),
"Write-Host hi".to_string(),
];
let (_shell, script) = extract_powershell_command(&cmd).expect("extract");
assert_eq!(script, "Write-Host hi");
}
#[test]
fn extracts_lowercase_flags() {
let cmd = vec![
"powershell".to_string(),
"-nologo".to_string(),
"-command".to_string(),
"Write-Host hi".to_string(),
];
let (_shell, script) = extract_powershell_command(&cmd).expect("extract");
assert_eq!(script, "Write-Host hi");
}
#[test]
fn extracts_full_path_powershell_command() {
let command = if cfg!(windows) {
"C:\\windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe".to_string()
} else {
"/usr/local/bin/powershell.exe".to_string()
};
let cmd = vec![command, "-Command".to_string(), "Write-Host hi".to_string()];
let (_shell, script) = extract_powershell_command(&cmd).expect("extract");
assert_eq!(script, "Write-Host hi");
}
#[test]
fn extracts_with_noprofile_and_alias() {
let cmd = vec![
"pwsh".to_string(),
"-NoProfile".to_string(),
"-c".to_string(),
"Get-ChildItem | Select-String foo".to_string(),
];
let (_shell, script) = extract_powershell_command(&cmd).expect("extract");
assert_eq!(script, "Get-ChildItem | Select-String foo");
}
#[test]
fn parses_powershell_command_chains_and_preserves_windows_paths() {
assert_eq!(
parse_powershell_script_into_plain_commands(r"echo safe && Remove-Item C:\important"),
Some(vec![
vec!["echo".to_string(), "safe".to_string()],
vec!["Remove-Item".to_string(), r"C:\important".to_string()],
]),
);
}
#[test]
fn prefixes_powershell_command_with_best_effort_utf8() {
let cmd = vec![
"powershell".to_string(),
"-Command".to_string(),
"Write-Host hi".to_string(),
];
let prefixed = prefix_powershell_script_with_utf8(&cmd);
assert_eq!(
prefixed,
vec![
"powershell".to_string(),
"-Command".to_string(),
format!("{UTF8_OUTPUT_PREFIX}Write-Host hi"),
]
);
}
#[test]
fn does_not_duplicate_utf8_prefix() {
let cmd = vec![
"powershell".to_string(),
"-Command".to_string(),
format!("{UTF8_OUTPUT_PREFIX}Write-Host hi"),
];
assert_eq!(prefix_powershell_script_with_utf8(&cmd), cmd);
}
#[cfg(windows)]
#[test]
fn parses_plain_powershell_commands() {
let commands = parse_powershell_command_into_plain_commands(&[
"powershell.exe".to_string(),
"-NoProfile".to_string(),
"-Command".to_string(),
"echo hi".to_string(),
])
.expect("parse");
assert_eq!(commands, vec![vec!["echo".to_string(), "hi".to_string()]]);
}
#[cfg(windows)]
#[test]
fn parses_multiple_plain_powershell_commands() {
let commands = parse_powershell_command_into_plain_commands(&[
"powershell.exe".to_string(),
"-NoProfile".to_string(),
"-Command".to_string(),
"Write-Output foo | Measure-Object".to_string(),
])
.expect("parse");
assert_eq!(
commands,
vec![
vec!["Write-Output".to_string(), "foo".to_string()],
vec!["Measure-Object".to_string()],
]
);
}
}

View File

@@ -0,0 +1,508 @@
use std::path::PathBuf;
use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
pub enum ShellType {
Zsh,
Bash,
PowerShell,
Sh,
Cmd,
}
impl ShellType {
pub fn name(self) -> &'static str {
match self {
Self::Zsh => "zsh",
Self::Bash => "bash",
Self::PowerShell => "powershell",
Self::Sh => "sh",
Self::Cmd => "cmd",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DetectedShell {
pub shell_type: ShellType,
pub shell_path: PathBuf,
}
impl DetectedShell {
pub fn name(&self) -> &'static str {
self.shell_type.name()
}
}
pub fn detect_shell_type(shell_path: impl AsRef<std::path::Path>) -> Option<ShellType> {
let shell_path = shell_path.as_ref();
match shell_path.as_os_str().to_str() {
Some("zsh") => Some(ShellType::Zsh),
Some("sh") => Some(ShellType::Sh),
Some("cmd") => Some(ShellType::Cmd),
Some("bash") => Some(ShellType::Bash),
Some("pwsh") => Some(ShellType::PowerShell),
Some("powershell") => Some(ShellType::PowerShell),
_ => {
let shell_name = shell_path.file_stem();
if let Some(shell_name) = shell_name {
let shell_name_path = std::path::Path::new(shell_name);
if shell_name_path != shell_path {
return detect_shell_type(shell_name_path);
}
}
None
}
}
}
#[cfg(unix)]
fn get_user_shell_path() -> Option<PathBuf> {
get_user_path(|passwd| passwd.pw_shell)
.map(|path| PathBuf::from(path.to_string_lossy().into_owned()))
}
/// Read the current account's home directory without consulting the environment.
#[cfg(unix)]
pub fn get_user_home_path() -> Option<PathBuf> {
get_user_path(|passwd| passwd.pw_dir).filter(|path| !path.as_os_str().is_empty())
}
#[cfg(unix)]
fn get_user_path(field: fn(&libc::passwd) -> *mut libc::c_char) -> Option<PathBuf> {
let uid = unsafe { libc::getuid() };
use std::ffi::CStr;
use std::mem::MaybeUninit;
use std::os::unix::ffi::OsStrExt;
use std::ptr;
let mut passwd = MaybeUninit::<libc::passwd>::uninit();
// We cannot use getpwuid here: it returns pointers into libc-managed
// storage, which is not safe to read concurrently on all targets (the musl
// static build used by the CLI can segfault when parallel callers race on
// that buffer). getpwuid_r keeps the passwd data in caller-owned memory.
let suggested_buffer_len = unsafe { libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) };
let buffer_len = usize::try_from(suggested_buffer_len)
.ok()
.filter(|len| *len > 0)
.unwrap_or(1024);
let mut buffer = vec![0; buffer_len];
loop {
let mut result = ptr::null_mut();
let status = unsafe {
libc::getpwuid_r(
uid,
passwd.as_mut_ptr(),
buffer.as_mut_ptr().cast(),
buffer.len(),
&mut result,
)
};
if status == 0 {
if result.is_null() {
return None;
}
let passwd = unsafe { passwd.assume_init_ref() };
let path = field(passwd);
if path.is_null() {
return None;
}
// Both callers select a field stored in the still-live passwd buffer.
let path = unsafe { CStr::from_ptr(path) };
return Some(PathBuf::from(std::ffi::OsStr::from_bytes(path.to_bytes())));
}
if status != libc::ERANGE {
return None;
}
// Retry with a larger buffer until libc can materialize the passwd entry.
let new_len = buffer.len().checked_mul(2)?;
if new_len > 1024 * 1024 {
return None;
}
buffer.resize(new_len, 0);
}
}
#[cfg(not(unix))]
fn get_user_shell_path() -> Option<PathBuf> {
None
}
fn file_exists(path: &std::path::Path) -> Option<PathBuf> {
if std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file()) {
Some(PathBuf::from(path))
} else {
None
}
}
// Store PowerShell cannot run under MXC and can be inaccessible to the elevated sandbox account;
// WindowsApps also contains valid Codex frameworks.
fn is_inaccessible_windows_apps_powershell_path(path: &std::path::Path) -> bool {
path.as_os_str()
.to_string_lossy()
.split(['\\', '/'])
.skip_while(|component| !component.eq_ignore_ascii_case("WindowsApps"))
.nth(1)
.is_some_and(|component| {
component.eq_ignore_ascii_case("pwsh.exe")
|| component.eq_ignore_ascii_case("powershell.exe")
|| component
.to_ascii_lowercase()
.starts_with("microsoft.powershell")
})
}
fn targets_inaccessible_windows_apps_powershell(path: &std::path::Path) -> bool {
is_inaccessible_windows_apps_powershell_path(path)
|| std::fs::canonicalize(path)
.ok()
.is_some_and(|resolved| is_inaccessible_windows_apps_powershell_path(&resolved))
}
fn is_windows_sandbox_compatible_powershell_path(path: &std::path::Path) -> bool {
if !path
.extension()
.is_some_and(|extension| extension.eq_ignore_ascii_case("exe"))
{
return false;
}
!targets_inaccessible_windows_apps_powershell(path)
}
fn get_windows_sandbox_compatible_powershell_path(
binary_name: &str,
fallback_paths: &[&str],
) -> Option<PathBuf> {
if let Ok(mut paths) = which::which_all(binary_name)
&& let Some(path) = paths.find(|path| is_windows_sandbox_compatible_powershell_path(path))
{
return Some(path);
}
for path in fallback_paths {
let path = std::path::Path::new(path);
if is_windows_sandbox_compatible_powershell_path(path)
&& let Some(path) = file_exists(path)
{
return Some(path);
}
}
None
}
fn get_shell_path(
shell_type: ShellType,
binary_name: &str,
fallback_paths: &[&str],
) -> Option<PathBuf> {
let default_shell_path = get_user_shell_path();
if let Some(default_shell_path) = default_shell_path
&& detect_shell_type(&default_shell_path) == Some(shell_type)
&& file_exists(&default_shell_path).is_some()
{
return Some(default_shell_path);
}
if let Ok(path) = which::which(binary_name) {
return Some(path);
}
for path in fallback_paths {
if let Some(path) = file_exists(std::path::Path::new(path)) {
return Some(path);
}
}
None
}
const ZSH_FALLBACK_PATHS: &[&str] = &["/bin/zsh"];
fn get_zsh_shell() -> Option<DetectedShell> {
let shell_path = get_shell_path(ShellType::Zsh, "zsh", ZSH_FALLBACK_PATHS);
shell_path.map(|shell_path| DetectedShell {
shell_type: ShellType::Zsh,
shell_path,
})
}
const BASH_FALLBACK_PATHS: &[&str] = &["/bin/bash", "/usr/bin/bash"];
fn get_bash_shell() -> Option<DetectedShell> {
let shell_path = get_shell_path(ShellType::Bash, "bash", BASH_FALLBACK_PATHS);
shell_path.map(|shell_path| DetectedShell {
shell_type: ShellType::Bash,
shell_path,
})
}
const SH_FALLBACK_PATHS: &[&str] = &["/bin/sh"];
fn get_sh_shell() -> Option<DetectedShell> {
let shell_path = get_shell_path(ShellType::Sh, "sh", SH_FALLBACK_PATHS);
shell_path.map(|shell_path| DetectedShell {
shell_type: ShellType::Sh,
shell_path,
})
}
// Note the `pwsh` and `powershell` fallback paths are where the respective
// shells are commonly installed on GitHub Actions Windows runners, but may not
// be present on all Windows machines:
// https://docs.github.com/en/actions/tutorials/build-and-test-code/powershell
#[cfg(windows)]
const PWSH_FALLBACK_PATHS: &[&str] = &[r#"C:\Program Files\PowerShell\7\pwsh.exe"#];
#[cfg(not(windows))]
const PWSH_FALLBACK_PATHS: &[&str] = &["/usr/local/bin/pwsh"];
#[cfg(windows)]
const POWERSHELL_FALLBACK_PATHS: &[&str] =
&[r#"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"#];
#[cfg(not(windows))]
const POWERSHELL_FALLBACK_PATHS: &[&str] = &[];
fn get_powershell_shell() -> Option<DetectedShell> {
let shell_path =
get_shell_path(ShellType::PowerShell, "pwsh", PWSH_FALLBACK_PATHS).or_else(|| {
get_shell_path(
ShellType::PowerShell,
"powershell",
POWERSHELL_FALLBACK_PATHS,
)
});
shell_path.map(|shell_path| DetectedShell {
shell_type: ShellType::PowerShell,
shell_path,
})
}
/// Returns a replacement only when shell_path targets Store PowerShell and
/// an unpackaged PowerShell executable can be discovered.
///
/// The caller decides whether the sandbox backend requires a fallback. Normal shell discovery
/// intentionally keeps the user's ordered PATH selection unchanged.
pub fn fallback_powershell_shell_for_windows_sandbox(
shell_path: &std::path::Path,
) -> Option<DetectedShell> {
if !cfg!(windows) || !targets_inaccessible_windows_apps_powershell(shell_path) {
return None;
}
let shell_path = get_windows_sandbox_compatible_powershell_path("pwsh", PWSH_FALLBACK_PATHS)
.or_else(|| {
get_windows_sandbox_compatible_powershell_path("powershell", POWERSHELL_FALLBACK_PATHS)
})?;
Some(DetectedShell {
shell_type: ShellType::PowerShell,
shell_path,
})
}
fn get_cmd_shell() -> Option<DetectedShell> {
let shell_path = get_shell_path(ShellType::Cmd, "cmd", &[]);
shell_path.map(|shell_path| DetectedShell {
shell_type: ShellType::Cmd,
shell_path,
})
}
pub fn ultimate_fallback_shell() -> DetectedShell {
if cfg!(windows) {
DetectedShell {
shell_type: ShellType::Cmd,
shell_path: PathBuf::from("cmd.exe"),
}
} else {
DetectedShell {
shell_type: ShellType::Sh,
shell_path: PathBuf::from("/bin/sh"),
}
}
}
/// Uses the model-provided path only to select a shell type, then discovers its executable.
pub fn get_shell_by_model_provided_path(shell_path: &PathBuf) -> DetectedShell {
detect_shell_type(shell_path)
.and_then(get_shell)
.unwrap_or_else(ultimate_fallback_shell)
}
pub fn get_shell(shell_type: ShellType) -> Option<DetectedShell> {
match shell_type {
ShellType::Zsh => get_zsh_shell(),
ShellType::Bash => get_bash_shell(),
ShellType::PowerShell => get_powershell_shell(),
ShellType::Sh => get_sh_shell(),
ShellType::Cmd => get_cmd_shell(),
}
}
pub fn default_user_shell() -> DetectedShell {
default_user_shell_from_path(get_user_shell_path())
}
pub fn default_user_shell_from_path(user_shell_path: Option<PathBuf>) -> DetectedShell {
if cfg!(windows) {
get_shell(ShellType::PowerShell).unwrap_or_else(ultimate_fallback_shell)
} else {
let user_default_shell = user_shell_path
.and_then(|shell| detect_shell_type(&shell))
.and_then(get_shell);
let shell_with_fallback = if cfg!(target_os = "macos") {
user_default_shell
.or_else(|| get_shell(ShellType::Zsh))
.or_else(|| get_shell(ShellType::Bash))
} else {
user_default_shell
.or_else(|| get_shell(ShellType::Bash))
.or_else(|| get_shell(ShellType::Zsh))
};
shell_with_fallback.unwrap_or_else(ultimate_fallback_shell)
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn elevated_sandbox_filter_rejects_store_and_script_powershell_paths() {
for path in [
r"C:\Program Files\WindowsApps\Microsoft.PowerShell_7.6.4.0_x64__8wekyb3d8bbwe\pwsh.exe",
r"C:\Program Files\WindowsApps\Microsoft.PowerShellPreview_8wekyb3d8bbwe\pwsh.exe",
r"C:\Users\user\AppData\Local\Microsoft\WindowsApps\pwsh.exe",
r"C:\Users\user\AppData\Local\Microsoft\WindowsApps\powershell.exe",
r"C:\Users\user\AppData\Local\Microsoft\WindowsApps\Microsoft.PowerShell_8wekyb3d8bbwe\pwsh.exe",
r"C:\PROGRAM FILES\WINDOWSAPPS\MICROSOFT.POWERSHELL\PWSH.EXE",
r"C:\portable\pwsh.cmd",
] {
assert!(!is_windows_sandbox_compatible_powershell_path(
std::path::Path::new(path)
));
}
for path in [
r"C:\Program Files\PowerShell\7\pwsh.exe",
r"C:\Program Files\WindowsApps\OpenAI.CodexPrimaryRuntime.v26-813-10124-0_26.813.10124.0_x64__3k8sg7r9htsxt\dependencies\native\powershell\pwsh.exe",
r"C:\Program Files\WindowsApps\OpenAI.CodexPrimaryRuntime.v26-813-10124-0_26.813.10124.0_arm64__3k8sg7r9htsxt\dependencies\native\powershell\pwsh.exe",
r"C:\PROGRAM FILES\WINDOWSAPPS\OPENAI.CODEXPRIMARYRUNTIME.V26-813-10124-0\DEPENDENCIES\NATIVE\POWERSHELL\PWSH.EXE",
r"\\?\C:\Program Files\WindowsApps\OpenAI.CodexPrimaryRuntime.v26-813-10124-0\dependencies\native\powershell\pwsh.exe",
r"C:\Users\user\.cache\codex-runtimes\codex-primary-runtime\dependencies\native\powershell\pwsh.exe",
r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",
r"C:\portable\NotWindowsApps\pwsh.EXE",
] {
assert!(is_windows_sandbox_compatible_powershell_path(
std::path::Path::new(path)
));
}
}
#[test]
fn elevated_sandbox_filter_preserves_ordered_fallback() {
let portable = PathBuf::from(
r"C:\Users\user\.cache\codex-runtimes\codex-primary-runtime\dependencies\native\powershell\pwsh.exe",
);
let found = [
PathBuf::from(
r"C:\Program Files\WindowsApps\Microsoft.PowerShell_7.6.4.0_x64__8wekyb3d8bbwe\pwsh.exe",
),
PathBuf::from(r"C:\Users\user\AppData\Local\Microsoft\WindowsApps\pwsh.exe"),
PathBuf::from(r"C:\runtime\dependencies\bin\fallback\pwsh.cmd"),
portable.clone(),
PathBuf::from(r"C:\Program Files\PowerShell\7\pwsh.exe"),
]
.into_iter()
.find(|path| is_windows_sandbox_compatible_powershell_path(path));
assert_eq!(found, Some(portable));
}
#[test]
fn test_detect_shell_type() {
assert_eq!(
detect_shell_type(PathBuf::from("zsh")),
Some(ShellType::Zsh)
);
assert_eq!(
detect_shell_type(PathBuf::from("bash")),
Some(ShellType::Bash)
);
assert_eq!(
detect_shell_type(PathBuf::from("pwsh")),
Some(ShellType::PowerShell)
);
assert_eq!(
detect_shell_type(PathBuf::from("powershell")),
Some(ShellType::PowerShell)
);
assert_eq!(detect_shell_type(PathBuf::from("fish")), None);
assert_eq!(detect_shell_type(PathBuf::from("other")), None);
assert_eq!(
detect_shell_type(PathBuf::from("/bin/zsh")),
Some(ShellType::Zsh)
);
assert_eq!(
detect_shell_type(PathBuf::from("/bin/bash")),
Some(ShellType::Bash)
);
assert_eq!(
detect_shell_type(PathBuf::from("/usr/bin/bash")),
Some(ShellType::Bash)
);
assert_eq!(
detect_shell_type(PathBuf::from("powershell.exe")),
Some(ShellType::PowerShell)
);
assert_eq!(
detect_shell_type(PathBuf::from(if cfg!(windows) {
"C:\\windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
} else {
"/usr/local/bin/pwsh"
})),
Some(ShellType::PowerShell)
);
assert_eq!(
detect_shell_type(PathBuf::from("pwsh.exe")),
Some(ShellType::PowerShell)
);
assert_eq!(
detect_shell_type(PathBuf::from("/usr/local/bin/pwsh")),
Some(ShellType::PowerShell)
);
assert_eq!(
detect_shell_type(PathBuf::from("/bin/sh")),
Some(ShellType::Sh)
);
assert_eq!(detect_shell_type(PathBuf::from("sh")), Some(ShellType::Sh));
assert_eq!(
detect_shell_type(PathBuf::from("cmd")),
Some(ShellType::Cmd)
);
assert_eq!(
detect_shell_type(PathBuf::from("cmd.exe")),
Some(ShellType::Cmd)
);
}
}

View File

@@ -0,0 +1,118 @@
//! Capture, prepare credential-safe state, and render restorable shell snapshots.
#[path = "shell_snapshot_capture.rs"]
mod capture;
#[path = "shell_snapshot_credentials.rs"]
mod credentials;
#[path = "shell_snapshot_exports.rs"]
mod exports;
#[path = "shell_snapshot_literals.rs"]
mod literals;
#[path = "shell_snapshot_render.rs"]
mod render;
#[path = "shell_snapshot_restore.rs"]
mod restore;
pub use capture::CapturedSnapshot;
pub use capture::CapturedStartupEnvironment;
pub use capture::SnapshotCaptureOptions;
pub use capture::snapshot_capture_script;
pub use capture::snapshot_source_capture_script;
pub use credentials::PreparedSnapshot;
pub use credentials::SnapshotCredentialEnvironment;
pub use credentials::prepare_snapshot_credentials;
pub use restore::SNAPSHOT_BROKERED_UNSET_ENV_PREFIX;
pub use restore::SNAPSHOT_BROKERED_VALUE_ENV_PREFIX;
pub use restore::build_brokered_credential_exports;
use capture::BASH_SH_SNAPSHOT_HEADER;
#[cfg(all(test, unix))]
#[path = "shell_snapshot_tests.rs"]
mod tests;
/// Returns the POSIX shell helper used to resolve supported `ENV` startup paths.
///
/// The helper deliberately supports only non-evaluating path forms. Unsupported
/// shell expressions are returned unchanged rather than executed.
pub fn posix_env_path_expansion_function() -> &'static str {
r#"__codex_snapshot_expand_env() (
set +u
__codex_snapshot_getenv() {
# Preserve the value separately from lookup status and its formatting newline.
__codex_env_expanded=$(
if command -v printenv >/dev/null 2>&1; then
printenv "$1"
elif [ "$1" = PATH ]; then
[ "${PATH+x}" = x ] && printf '%s\n' "$PATH"
else
command -p printenv "$1"
fi && printf '.'
) || return 1
__codex_env_expanded=${__codex_env_expanded%?}
__codex_env_expanded=${__codex_env_expanded%?}
}
__codex_env_file=$1
case "$__codex_env_file" in
'~/'*) __codex_env_file="${HOME-}/${__codex_env_file#*/}" ;;
'${PATH%%:*}') __codex_env_file="${PATH%%:*}" ;;
'${PATH%%:*}/'*) __codex_env_file="${PATH%%:*}/${__codex_env_file#*/}" ;;
'${'*)
__codex_env_body=${__codex_env_file#\$\{}
case "$__codex_env_body" in
*\}*)
__codex_env_name=${__codex_env_body%%\}*}
__codex_env_suffix=${__codex_env_body#*\}}
case "$__codex_env_name" in
*:-*)
__codex_env_default=${__codex_env_name#*:-}
__codex_env_name=${__codex_env_name%%:-*}
__codex_env_has_default=1
;;
*) __codex_env_has_default= ;;
esac
case "$__codex_env_name" in
''|[0-9]*|*[!A-Za-z0-9_]*) ;;
*)
case "$__codex_env_suffix" in
''|/*)
if __codex_snapshot_getenv "$__codex_env_name" 2>/dev/null &&
{ [ -n "$__codex_env_expanded" ] || [ -z "$__codex_env_has_default" ]; }; then
__codex_env_file="$__codex_env_expanded$__codex_env_suffix"
elif [ -n "$__codex_env_has_default" ]; then
__codex_env_default=$(__codex_snapshot_expand_env "$__codex_env_default")
__codex_env_file="$__codex_env_default$__codex_env_suffix"
fi
;;
esac
;;
esac
;;
esac
;;
'$'*)
__codex_env_name=${__codex_env_file%%/*}
__codex_env_name=${__codex_env_name#\$}
case "$__codex_env_name" in
''|[0-9]*|*[!A-Za-z0-9_]*) ;;
*)
if __codex_snapshot_getenv "$__codex_env_name" 2>/dev/null; then
if [ "$__codex_env_file" = "\$$__codex_env_name" ]; then
__codex_env_file=$__codex_env_expanded
else
__codex_env_file="$__codex_env_expanded/${__codex_env_file#*/}"
fi
fi
;;
esac
;;
esac
printf '%s' "$__codex_env_file"
)"#
}
#[derive(Clone, Copy)]
pub enum SnapshotStartup {
Interactive,
NonInteractive,
}

View File

@@ -0,0 +1,462 @@
//! Capture native shell state and decode complete export records without applying credential policy.
//! Retain native declaration flags and tied-array boundaries; reject incomplete records.
use super::SnapshotStartup;
use super::exports;
use super::literals;
use super::posix_env_path_expansion_function;
use crate::shell_detect::ShellType;
use crate::shell_startup_script;
use akode_protocol::shell_environment::AKODE_THREAD_ID_ENV_VAR;
use akode_protocol::shell_environment::AKODE_TOOL_CALL_ID_ENV_VAR;
use std::borrow::Cow;
const SNAPSHOT_COMMAND_HELPER: &str = r#"__codex_snapshot_command() {
if command -v "$1" >/dev/null 2>&1; then
"$@"
else
command -p "$@"
fi
}"#;
const SNAPSHOT_ENVIRONMENT: &str = r#"if command -v env >/dev/null 2>&1; then
"env" -0
else
# Resolve the fallback separately: Bash's command -p changes the utility's PATH.
"$(PATH="$(command -p getconf PATH)" command -v env)" -0
fi
"#;
/// Selects startup behavior and the records needed by a snapshot consumer.
/// Shell state and aliases are always captured. Credential preparation needs both
/// declarations and environment values; executor replay needs only the environment.
#[derive(Clone, Copy)]
pub struct SnapshotCaptureOptions {
pub startup: SnapshotStartup,
pub declarations: bool,
pub environment: bool,
}
/// Returns a script that captures native state, aliases, and the requested export records.
///
/// Startup behavior is independent of how the captured records will be rendered.
/// PowerShell and Command Prompt snapshots are not supported by the snapshot callers.
pub fn snapshot_capture_script(
shell_type: ShellType,
options: SnapshotCaptureOptions,
) -> Option<String> {
capture_script(shell_type, options, Replay::Eval)
}
/// Capture state for incremental sourcing. Parse options and aliases together so
/// restored aliases and quoting options cannot reinterpret later declarations.
pub fn snapshot_source_capture_script(
shell_type: ShellType,
options: SnapshotCaptureOptions,
) -> Option<String> {
capture_script(
shell_type,
options,
if shell_type == ShellType::Sh {
Replay::Eval
} else {
Replay::Source
},
)
}
enum Replay {
Eval,
Source,
}
fn capture_script(
shell_type: ShellType,
options: SnapshotCaptureOptions,
replay: Replay,
) -> Option<String> {
let script = match shell_type {
ShellType::Zsh => zsh_snapshot_script(options.startup),
ShellType::Bash => bash_snapshot_script(options.startup),
ShellType::Sh => sh_snapshot_script(options.startup),
ShellType::PowerShell | ShellType::Cmd => return None,
};
let declarations = if options.declarations {
exports::script(shell_type)
} else {
String::new()
};
Some(
script
.replace("SNAPSHOT_OPTIONS_BEGIN", match replay { Replay::Eval => "", Replay::Source => "printf '{\\n'" })
.replace("SNAPSHOT_ALIASES_END", match replay { Replay::Eval => "", Replay::Source => "printf \"case '' in '') ;; esac\\n}\\n\"" })
// The source group is parsed before its options take effect. Serialize
// aliases with the replay shell's initial quoting rules, not RC_QUOTES.
// setopt works without the optional zsh/parameter module.
.replace("SNAPSHOT_ZSH_ALIASES", match replay {
Replay::Eval => "\\alias -L",
Replay::Source => "(\\setopt NO_RC_QUOTES; \\alias -L)",
})
.replace("SNAPSHOT_EXPORTS", &declarations)
.replace(
"SNAPSHOT_DECLARATION_ENVIRONMENT",
if options.declarations { SNAPSHOT_ENVIRONMENT } else { "" },
)
.replace("SNAPSHOT_COMMAND_HELPER", SNAPSHOT_COMMAND_HELPER)
.replace(
"SNAPSHOT_STARTUP_ENVIRONMENT",
if options.declarations && options.environment {
"printf '\\0CODEX_SNAPSHOT_POSIX_STARTUP\\0%s\\0' \"$__codex_env_file\"\n SNAPSHOT_ENVIRONMENT\n printf '\\0'"
} else {
""
},
)
.replace(
"SNAPSHOT_ENVIRONMENT",
if options.environment {
SNAPSHOT_ENVIRONMENT
} else {
""
},
),
)
}
fn zsh_snapshot_script(shell_startup: SnapshotStartup) -> String {
let startup = match shell_startup {
SnapshotStartup::Interactive => shell_startup_script(ShellType::Zsh),
SnapshotStartup::NonInteractive => "",
};
let script = r##"print '# Snapshot file'
print '# Unset all aliases to avoid conflicts with functions'
print 'unalias -a 2>/dev/null || true'
print '# Functions'
functions
print ''
SNAPSHOT_OPTIONS_BEGIN
SNAPSHOT_COMMAND_HELPER
setopt_count=$(setopt | __codex_snapshot_command wc -l | __codex_snapshot_command tr -d ' ')
print "# setopts $setopt_count"
setopt | __codex_snapshot_command sed 's/^/setopt /'
print ''
printf '\0'
alias_count=$(\alias -L | __codex_snapshot_command wc -l | __codex_snapshot_command tr -d ' ')
print "# aliases $alias_count"
SNAPSHOT_ZSH_ALIASES
print ''
SNAPSHOT_ALIASES_END
printf '\0'
SNAPSHOT_EXPORTS
printf '\0'
SNAPSHOT_ENVIRONMENT
"##;
format!("{startup}{script}")
}
fn bash_snapshot_script(shell_startup: SnapshotStartup) -> String {
let startup = match shell_startup {
SnapshotStartup::Interactive => shell_startup_script(ShellType::Bash),
SnapshotStartup::NonInteractive => "",
};
let script = r##"echo '# Snapshot file'
echo '# Unset all aliases to avoid conflicts with functions'
echo 'unalias -a 2>/dev/null || true'
shopt -p || true
echo '# Functions'
declare -f
echo ''
SNAPSHOT_OPTIONS_BEGIN
SNAPSHOT_COMMAND_HELPER
bash_opts=$(set -o | __codex_snapshot_command awk '$2=="on"{print $1}')
bash_opt_count=$(printf '%s\n' "$bash_opts" | __codex_snapshot_command sed '/^$/d' | __codex_snapshot_command wc -l | __codex_snapshot_command tr -d ' ')
echo "# setopts $bash_opt_count"
if [ -n "$bash_opts" ]; then
printf 'set -o %s\n' $bash_opts
fi
echo ''
printf '\0'
alias_count=$(\alias -p | __codex_snapshot_command wc -l | __codex_snapshot_command tr -d ' ')
echo "# aliases $alias_count"
\alias -p
echo ''
SNAPSHOT_ALIASES_END
printf '\0'
SNAPSHOT_EXPORTS
printf '\0'
SNAPSHOT_ENVIRONMENT
"##;
format!("{startup}{script}")
}
pub(super) const BASH_SH_SNAPSHOT_HEADER: &str = "# Snapshot file\n# Bash-backed sh\n";
fn sh_snapshot_script(shell_startup: SnapshotStartup) -> String {
let startup = match shell_startup {
SnapshotStartup::Interactive => [
posix_env_path_expansion_function(),
r##"if [ -n "${ENV-}" ]; then
__codex_env_file=$(__codex_snapshot_expand_env "$ENV")
if [ -r "$__codex_env_file" ] && [ ! -d "$__codex_env_file" ]; then
SNAPSHOT_STARTUP_ENVIRONMENT
case "$__codex_env_file" in
/*) . "$__codex_env_file" ;;
*) . "./$__codex_env_file" ;;
esac
fi
command unset __codex_env_file
fi
command unset -f __codex_snapshot_expand_env
"##,
]
.join("\n"),
SnapshotStartup::NonInteractive => String::new(),
};
let script = r##"echo '# Snapshot file'
if [ -n "${BASH_VERSINFO-}" ]; then
echo '# Bash-backed sh'
shopt -p || true
fi
echo '# Unset all aliases to avoid conflicts with functions'
unalias -a 2>/dev/null || true
echo '# Functions'
if command -v typeset >/dev/null 2>&1; then
typeset -f
elif command -v declare >/dev/null 2>&1; then
declare -f
fi
echo ''
SNAPSHOT_OPTIONS_BEGIN
SNAPSHOT_COMMAND_HELPER
if set -o >/dev/null 2>&1; then
sh_opts=$(set -o | __codex_snapshot_command awk '$2=="on"{print $1}')
sh_opt_count=$(printf '%s\n' "$sh_opts" | __codex_snapshot_command sed '/^$/d' | __codex_snapshot_command wc -l | __codex_snapshot_command tr -d ' ')
echo "# setopts $sh_opt_count"
if [ -n "$sh_opts" ]; then
printf 'set -o %s\n' $sh_opts
fi
else
echo '# setopts 0'
fi
echo ''
printf '\0'
if alias >/dev/null 2>&1; then
alias_count=$(alias | __codex_snapshot_command wc -l | __codex_snapshot_command tr -d ' ')
echo "# aliases $alias_count"
alias
echo ''
else
echo '# aliases 0'
fi
SNAPSHOT_ALIASES_END
printf '\0'
SNAPSHOT_EXPORTS
printf '\0'
SNAPSHOT_DECLARATION_ENVIRONMENT
printf '\0'
SNAPSHOT_ENVIRONMENT
"##;
format!("{startup}{script}")
}
/// Native shell sections captured before applying credential or environment policy.
///
/// Function and alias declarations remain shell source. The shell supplies each export's
/// name and boundary; only tied arrays need syntax decoding. No captured code is evaluated.
pub struct CapturedSnapshot<'a> {
/// Resolved POSIX startup file and its environment immediately before sourcing it.
pub startup_environment: Option<CapturedStartupEnvironment<'a>>,
pub(super) shell_type: ShellType,
pub(super) state: &'a str,
pub(super) aliases: &'a str,
pub(super) exports: Vec<CapturedExport<'a>>,
/// NUL-delimited environment entries from the same shell invocation.
pub environment: &'a [u8],
}
/// Optional pre-startup state captured alongside the final snapshot records.
pub struct CapturedStartupEnvironment<'a> {
pub path: Cow<'a, str>,
pub environment: &'a [u8],
}
pub(super) struct CapturedExport<'a> {
pub source: Cow<'a, str>,
pub key: &'a str,
pub value: ExportValue,
}
pub(super) enum ExportValue {
Plain,
TiedArray(CapturedArray),
UnparsedArray,
}
pub(super) struct CapturedArray {
pub span: std::ops::Range<usize>,
pub values: Vec<Vec<u8>>,
pub separator: Vec<u8>,
}
impl<'a> CapturedSnapshot<'a> {
/// Decode the local capture format emitted by `snapshot_capture_script`.
/// Keep raw environment bytes so callers can discard non-UTF-8 entries independently.
pub fn parse(shell_type: ShellType, captured: &'a [u8]) -> Option<Self> {
if !matches!(shell_type, ShellType::Bash | ShellType::Zsh | ShellType::Sh) {
return None;
}
let mut remaining = captured;
let startup_marker = b"\0CODEX_SNAPSHOT_POSIX_STARTUP\0";
let startup_environment = if shell_type == ShellType::Sh
&& let Some(start) = remaining
.windows(startup_marker.len())
.position(|part| part == startup_marker)
{
remaining = &remaining[start + startup_marker.len()..];
let path = String::from_utf8_lossy(take_record(&mut remaining)?);
let environment = remaining;
while !take_record(&mut remaining)?.is_empty() {}
let environment = &environment[..environment.len() - remaining.len() - 1];
Some(CapturedStartupEnvironment { path, environment })
} else {
None
};
// state NUL aliases NUL (name NUL declaration NUL)* NUL environment.
// POSIX sh additionally captures declaration values as a NUL-delimited environment.
let state = take_record(&mut remaining)?;
let marker = b"# Snapshot file";
let start = state
.windows(marker.len())
.position(|part| part == marker)?;
let state = std::str::from_utf8(&state[start..]).ok()?;
let aliases = std::str::from_utf8(take_record(&mut remaining)?).ok()?;
let mut records = Vec::new();
loop {
let key = std::str::from_utf8(take_record(&mut remaining)?).ok()?;
if key.is_empty() {
if shell_type == ShellType::Sh {
loop {
let entry = take_record(&mut remaining)?;
if entry.is_empty() {
break;
}
let equals = entry.iter().position(|byte| *byte == b'=')?;
let Ok(key) = std::str::from_utf8(&entry[..equals]) else {
continue;
};
if key.is_empty()
|| matches!(key, "PWD" | "OLDPWD")
|| !key.bytes().enumerate().all(|(index, byte)| {
byte == b'_'
|| byte.is_ascii_alphabetic()
|| index > 0 && byte.is_ascii_digit()
})
{
continue;
}
let value = String::from_utf8_lossy(&entry[equals + 1..]);
records.push(CapturedExport {
source: Cow::Owned(format!(
"export {key}={}\n",
shlex::try_quote(&value).ok()?
)),
key,
value: ExportValue::Plain,
});
}
}
// Each launch supplies execution IDs; omit their captured exports.
records.retain(|export| {
!matches!(
export.key,
AKODE_THREAD_ID_ENV_VAR | AKODE_TOOL_CALL_ID_ENV_VAR
)
});
return Some(Self {
startup_environment,
shell_type,
state,
aliases,
exports: records,
environment: remaining,
});
}
let source = String::from_utf8_lossy(take_record(&mut remaining)?);
// Only tied arrays need syntax decoding; scalar values remain native declarations.
let tied = shell_type == ShellType::Zsh
&& source
.split_whitespace()
.skip(/*n*/ 1)
.take_while(|word| word.starts_with('-'))
.any(|flags| flags.contains('T'));
let tree = tied
.then(|| crate::bash::try_parse_shell(&source))
.flatten();
let array = tree.as_ref().and_then(|tree| {
if tree.root_node().has_error() {
return None;
}
let mut cursor = tree.root_node().walk();
tree.root_node()
.named_child(/*i*/ 0)?
.named_children(&mut cursor)
.find_map(|child| {
child
.child_by_field_name("value")
.filter(|value| value.kind() == "array")
})
});
let value = if let Some(array) = array {
let mut cursor = array.walk();
let values = array
.named_children(&mut cursor)
.map(|node| {
literals::literal_word_bytes(
node,
&source,
shell_type,
literals::Quoting::Posix,
)
})
.collect::<Option<Vec<_>>>();
let separator = array.parent().and_then(|node| node.next_named_sibling());
let separator = if let Some(separator) = separator
&& separator.kind() == "variable_name"
{
separator
.utf8_text(source.as_bytes())
.ok()
.map(|value| value.as_bytes().to_vec())
} else if let Some(separator) = separator {
literals::literal_word_bytes(
separator,
&source,
shell_type,
literals::Quoting::Posix,
)
} else {
Some(vec![b':'])
};
match (values, separator) {
(Some(values), Some(separator)) => ExportValue::TiedArray(CapturedArray {
span: array.byte_range(),
values,
separator,
}),
_ => ExportValue::UnparsedArray,
}
} else if tied {
ExportValue::UnparsedArray
} else {
ExportValue::Plain
};
records.push(CapturedExport { source, key, value });
}
}
}
fn take_record<'a>(remaining: &mut &'a [u8]) -> Option<&'a [u8]> {
let boundary = remaining.iter().position(|byte| *byte == 0)?;
let record = &remaining[..boundary];
*remaining = &remaining[boundary + 1..];
Some(record)
}

View File

@@ -0,0 +1,358 @@
//! Apply credential and environment policy to captured exports, producing typed render values.
//! The shared literal decoder still validates alias and function bodies without evaluating them.
use super::capture::CapturedSnapshot;
use super::capture::ExportValue;
use super::literals;
use super::render;
use super::render::Export;
use super::render::Value;
use super::render::ValuePart;
use crate::shell_detect::ShellType;
use std::collections::HashMap;
/// Environment views used to render protected credential references into a shell snapshot.
pub struct SnapshotCredentialEnvironment<'a> {
pub original: &'a HashMap<String, String>,
pub restored: &'a HashMap<String, String>,
pub configured: &'a HashMap<String, String>,
pub discovered: &'a HashMap<String, String>,
pub allowed: &'a HashMap<String, String>,
/// Applies environment policy to export-only names absent from the captured environment.
pub is_allowed_unset: &'a dyn Fn(&str) -> bool,
pub brokered_keys: &'a [String],
pub brokered_alias_keys: &'a [String],
pub allowed_brokered_keys: &'a [String],
}
/// Credential-checked replay script and aliases to restore after shell startup.
pub struct PreparedSnapshot {
pub script: String,
pub aliases: HashMap<String, String>,
pub rejected_alias_keys: Vec<String>,
}
/// Prepare a replay script from captured state without changing the captured data.
///
/// Credential policy is applied before rendering. A rejected capture produces no script,
/// including when executable source reconstructs a credential through shell quoting.
pub fn prepare_snapshot_credentials(
captured: &CapturedSnapshot<'_>,
environment: SnapshotCredentialEnvironment<'_>,
mut virtualize_text: impl FnMut(&mut String) -> bool,
) -> Option<PreparedSnapshot> {
let SnapshotCredentialEnvironment {
original,
restored,
configured,
discovered,
allowed,
is_allowed_unset,
brokered_keys,
brokered_alias_keys,
allowed_brokered_keys,
} = environment;
let real_credential_value = |key: &str| restored.get(key).or_else(|| configured.get(key));
let mut credential_aliases = original
.iter()
.filter(|(key, _)| !brokered_keys.contains(key) && !brokered_alias_keys.contains(key))
.filter_map(|(key, value)| {
let credential_keys = brokered_keys
.iter()
.filter(|credential_key| {
real_credential_value(credential_key).is_some_and(|real| {
value == real
|| value.contains(real)
&& (real.len() >= 16
|| discovered.get(*credential_key).is_some_and(|dummy| {
discovered.get(key).is_some_and(|virtualized| {
virtualized != value && virtualized.contains(dummy)
})
}))
}) || [
original.get(*credential_key),
discovered.get(*credential_key),
]
.into_iter()
.flatten()
.filter(|dummy| !dummy.is_empty())
.any(|dummy| {
value == dummy
|| value.contains(dummy)
&& (dummy.len() >= 16
|| real_credential_value(credential_key).is_some_and(|real| {
// Confirm short spans with the broker's path and pattern rules.
let mut restored = value.replace(dummy, real);
restored != *value
&& virtualize_text(&mut restored)
&& discovered.get(key) == Some(&restored)
}))
})
})
.map(String::as_str)
.collect::<Vec<_>>();
(!credential_keys.is_empty()).then_some((key.as_str(), credential_keys))
})
.filter(|(key, _)| {
key.bytes().enumerate().all(|(index, byte)| {
byte == b'_' || byte.is_ascii_alphabetic() || (index != 0 && byte.is_ascii_digit())
})
})
.collect::<HashMap<_, _>>();
let credential_alias_assignment = |value: &str, credential_keys: &[&str]| {
let mut remaining = value;
let mut assignment = Value::default();
let mut normalized = String::new();
while !remaining.is_empty() {
let next_credential = credential_keys
.iter()
.filter_map(|credential_key| {
let dummy = discovered
.get(*credential_key)
.filter(|dummy| !dummy.is_empty())?;
let real = real_credential_value(credential_key)?;
let allowed_key = allowed_brokered_keys
.iter()
.find(|allowed_key| allowed_key.as_str() == *credential_key)
.or_else(|| {
allowed_brokered_keys.iter().find(|allowed_key| {
real_credential_value(allowed_key) == Some(real)
})
})?;
remaining
.find(dummy)
.map(|index| (index, allowed_key.as_str(), dummy.as_str()))
})
.min_by_key(|(index, _, _)| *index);
let Some((index, credential_key, dummy)) = next_credential else {
assignment
.parts
.push(ValuePart::Literal(remaining.to_string()));
normalized.push_str(remaining);
break;
};
if index != 0 {
assignment
.parts
.push(ValuePart::Literal(remaining[..index].to_string()));
normalized.push_str(&remaining[..index]);
}
assignment.parts.push(ValuePart::Credential {
key: credential_key.to_string(),
});
normalized.push_str(allowed.get(credential_key)?);
remaining = &remaining[index + dummy.len()..];
}
Some((assignment, normalized))
};
let credential_alias_is_allowed = |credential_keys: &[&str]| {
credential_keys.iter().all(|credential_key| {
real_credential_value(credential_key).is_some_and(|real| {
allowed_brokered_keys
.iter()
.any(|allowed_key| real_credential_value(allowed_key) == Some(real))
})
})
};
let is_disallowed_credential_alias =
|key: &str, virtualize_text: &mut dyn FnMut(&mut String) -> bool| {
original.get(key).is_some_and(|value| {
let mut virtualized = value.clone();
!virtualize_text(&mut virtualized)
})
};
let mut alias_values = HashMap::new();
let mut rejected_alias_keys = Vec::new();
let mut invalid_export = false;
let exports = captured
.exports
.iter()
.filter_map(|export| {
let line = export.source.as_ref();
let key = export.key;
if (!allowed.contains_key(key)
&& (original.contains_key(key) || !is_allowed_unset(key)))
|| brokered_keys
.iter()
.any(|credential_key| credential_key == key)
{
return None;
}
if configured.contains_key(key)
&& let ExportValue::TiedArray(array) = &export.value
{
let value = allowed.get(key)?;
let mut virtualized = value.clone();
if !virtualize_text(&mut virtualized) || virtualized != *value {
invalid_export = true;
return Some(Export::Captured(line));
}
if credential_aliases.remove(key).is_some() {
alias_values.insert(key.to_string(), value.clone());
}
// An explicit scalar override replaces captured elements, not the array binding.
return Some(Export::ArrayBinding {
key,
declaration: line[..array.span.start].strip_suffix('=')?,
suffix: &line[array.span.end..],
});
}
if is_disallowed_credential_alias(key, &mut virtualize_text) {
return None;
}
if brokered_alias_keys.iter().any(|alias_key| alias_key == key) {
// Source-less aliases keep their live scalar value, including explicit unsets.
return match &export.value {
ExportValue::TiedArray(array) => Some(Export::ArrayBinding {
key,
declaration: line[..array.span.start].strip_suffix('=')?,
suffix: &line[array.span.end..],
}),
ExportValue::Plain | ExportValue::UnparsedArray => None,
};
}
if let Some(credential_keys) = credential_aliases.remove(key) {
if !credential_alias_is_allowed(&credential_keys) {
rejected_alias_keys.push(key.to_string());
return None;
}
let declaration = line
.split_once('=')
.map_or(line.trim_end(), |(prefix, _)| prefix);
let (assignment, value) =
credential_alias_assignment(allowed.get(key)?, &credential_keys)?;
alias_values.insert(key.to_string(), value);
if let ExportValue::TiedArray(array) = &export.value {
let scalar = array.values.join(array.separator.as_slice());
let crosses_element = credential_keys
.iter()
.flat_map(|key| {
[
real_credential_value(key),
original.get(*key),
discovered.get(*key),
]
})
.flatten()
.filter(|credential| !credential.is_empty())
.any(|credential| {
scalar
.windows(credential.len())
.enumerate()
.any(|(start, bytes)| {
if bytes != credential.as_bytes() {
return false;
}
let mut offset = 0;
!array.values.iter().any(|value| {
let contains = offset <= start
&& start + credential.len() <= offset + value.len();
offset += value.len() + array.separator.len();
contains
})
})
});
if crosses_element {
invalid_export = true;
return Some(Export::Captured(line));
}
let Some((elements, normalized)) = array
.values
.iter()
.map(|bytes| {
let mut text = String::from_utf8(bytes.clone()).ok()?;
if !virtualize_text(&mut text) {
return None;
}
credential_alias_assignment(&text, &credential_keys)
})
.collect::<Option<Vec<_>>>()
.map(|values| values.into_iter().unzip::<_, _, Vec<_>, Vec<_>>())
else {
invalid_export = true;
return Some(Export::Captured(line));
};
// Never replay a known credential that crosses array-element boundaries.
if normalized
.iter()
.map(String::as_bytes)
.collect::<Vec<_>>()
.join(array.separator.as_slice())
!= allowed.get(key)?.as_bytes()
{
invalid_export = true;
return Some(Export::Captured(line));
}
return Some(Export::Array {
prefix: &line[..array.span.start],
elements,
suffix: &line[array.span.end..],
});
}
if matches!(export.value, ExportValue::UnparsedArray) {
invalid_export = true;
return Some(Export::Captured(line));
}
return Some(Export::Assignment {
declaration: if captured.shell_type == ShellType::Zsh
&& configured.contains_key(key)
{
format!("export {key}").into()
} else {
declaration.into()
},
value: assignment,
});
}
// Explicit scalar overrides must not inherit captured coercion attributes.
if captured.shell_type == ShellType::Zsh
&& configured.contains_key(key)
&& matches!(export.value, ExportValue::Plain)
{
return None;
}
Some(Export::Captured(line))
})
.collect::<Vec<_>>();
let snapshot = render::render(captured.state, captured.aliases, &exports)?;
if invalid_export {
return None;
}
for (key, credential_keys) in credential_aliases {
if !is_disallowed_credential_alias(key, &mut virtualize_text)
&& credential_alias_is_allowed(&credential_keys)
&& let Some((_, value)) = allowed
.get(key)
.and_then(|value| credential_alias_assignment(value, &credential_keys))
{
// Native capture can deliberately omit readonly exports; retain only their metadata.
alias_values.insert(key.to_string(), value);
} else {
rejected_alias_keys.push(key.to_string());
}
}
let mut virtualized = snapshot.clone();
if !virtualize_text(&mut virtualized) || virtualized != snapshot {
return None;
}
literals::literal_words(&snapshot, captured.shell_type)?
.into_iter()
.all(|word| {
let mut virtualized = word.clone();
virtualize_text(&mut virtualized) && virtualized == word
})
.then_some(PreparedSnapshot {
script: snapshot,
aliases: alias_values,
rejected_alias_keys,
})
}

View File

@@ -0,0 +1,81 @@
//! Capture native export declarations and unset POSIX exports.
//! Set POSIX values are captured in bulk for quoting in Rust.
use crate::shell_detect::ShellType;
pub(super) fn script(shell_type: ShellType) -> String {
let script = match shell_type {
ShellType::Bash => {
r#"(
while IFS= read -r __codex_snapshot_export_name; do
case "$__codex_snapshot_export_name" in
""|[0-9]*|*[!A-Za-z0-9_]*|PWD|OLDPWD) continue ;;
esac
RECORD_START
declare -xp "$__codex_snapshot_export_name" 2>/dev/null || true
RECORD_END
done < <(compgen -e)
)
"#
}
ShellType::Zsh => {
r#"(
unsetopt rcquotes
# Some Zsh builds do not include the zsh/parameter module.
for __codex_snapshot_export_name in ${(f)"$(typeset +x)"}; do
case "$__codex_snapshot_export_name" in
""|[0-9]*|*[!A-Za-z0-9_]*|PWD|OLDPWD) continue ;;
esac
case "${(tP)__codex_snapshot_export_name}" in
*readonly*) continue ;;
*export*) ;;
*) continue ;;
esac
RECORD_START
typeset -xp "$__codex_snapshot_export_name"
RECORD_END
done
)
"#
}
ShellType::Sh => {
r#"if export -p >/dev/null 2>&1; then
export -p | __codex_snapshot_command awk '
/^(export|declare -x|typeset -x) [A-Za-z_][A-Za-z0-9_]*$/ {
name=$0
sub(/^(export|declare -x|typeset -x) /, "", name)
if (name ~ /^(PWD|OLDPWD)$/) {
next
}
if (!seen[name]++) {
print name
}
}' | while IFS= read -r __codex_snapshot_export_name; do
# Only the validated identifier enters eval. Set values come from the bulk environment.
if eval '[ "${'"$__codex_snapshot_export_name"'+x}" = x ]'; then
continue
fi
# Only preserve an unset export if the native shell confirms it already exists.
if (
set +a
set -- "$__codex_snapshot_export_name" "$(export -p)"
export "$1"
[ "$2" = "$(export -p)" ]
); then
RECORD_START
printf 'export %s\n' "$__codex_snapshot_export_name"
RECORD_END
fi
done
fi
"#
}
ShellType::PowerShell | ShellType::Cmd => return String::new(),
};
script
.replace(
"RECORD_START",
"printf '%s\\0' \"$__codex_snapshot_export_name\"",
)
.replace("RECORD_END", "printf '\\0'")
}

View File

@@ -0,0 +1,715 @@
use crate::bash::try_parse_shell;
use crate::shell_detect::ShellType;
use std::collections::HashSet;
use tree_sitter::Node;
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub(super) enum Quoting {
Posix,
LegacyBash,
ZshRcQuotes,
}
impl Quoting {
fn deferred_modes(shell_type: ShellType) -> &'static [Self] {
if matches!(shell_type, ShellType::Bash | ShellType::Sh) {
&[Self::Posix, Self::LegacyBash]
} else {
&[Self::Posix, Self::ZshRcQuotes]
}
}
}
#[derive(Clone, Copy)]
enum Parsing {
Snapshot,
Deferred(Quoting),
}
pub(super) fn literal_words(script: &str, shell_type: ShellType) -> Option<Vec<String>> {
// Bash invoked as sh still parses its array and alias syntax; other sh dialects do not.
let shell_type =
if shell_type == ShellType::Sh && script.starts_with(super::BASH_SH_SNAPSHOT_HEADER) {
ShellType::Bash
} else {
shell_type
};
let mut checked_aliases = HashSet::new();
let mut words =
literal_words_with_quoting(script, shell_type, Parsing::Snapshot, &mut checked_aliases)?;
if matches!(shell_type, ShellType::Bash | ShellType::Sh) {
words.extend(literal_words_with_quoting(
script,
shell_type,
Parsing::Deferred(Quoting::LegacyBash),
&mut checked_aliases,
)?);
}
Some(words)
}
fn literal_words_with_quoting(
script: &str,
shell_type: ShellType,
parsing: Parsing,
checked_aliases: &mut HashSet<(String, Quoting)>,
) -> Option<Vec<String>> {
let tree = try_parse_shell(script)?;
let mut cursor = tree.root_node().walk();
let mut quoting = match parsing {
Parsing::Snapshot => Quoting::Posix,
Parsing::Deferred(quoting) => quoting,
};
let mut pending = Vec::new();
// Zsh snapshots emit function definitions before restoring options and aliases.
for node in tree.root_node().named_children(&mut cursor) {
if matches!(parsing, Parsing::Snapshot) && node.kind() == "command" {
match node.utf8_text(script.as_bytes()).ok()? {
"setopt rcquotes" => quoting = Quoting::ZshRcQuotes,
"unsetopt rcquotes" => quoting = Quoting::Posix,
_ => {}
}
}
pending.push((node, quoting));
}
let mut words = Vec::new();
let mut checked_nodes = HashSet::new();
while let Some((node, quoting)) = pending.pop() {
if !checked_nodes.insert((node.id(), quoting)) {
continue;
}
if matches!(node.kind(), "command_substitution" | "process_substitution") {
if let Some(body) = node
.utf8_text(script.as_bytes())
.ok()?
.strip_prefix('`')
.and_then(|body| body.strip_suffix('`'))
{
// Backticks remove one escape layer before their command body is parsed.
let mut context = node.parent();
if shell_type == ShellType::Zsh {
while context.is_some_and(|parent| {
matches!(parent.kind(), "expansion" | "concatenation")
}) {
context = context.and_then(|parent| parent.parent());
}
}
let in_double_quotes = context.is_some_and(|parent| parent.kind() == "string");
let mut chars = body.chars().peekable();
let mut body = String::new();
while let Some(character) = chars.next() {
if character == '\\' {
match chars.peek() {
Some('\n') => {
chars.next();
continue;
}
Some('$' | '`' | '\\') => {
body.push(chars.next()?);
continue;
}
Some('"') if in_double_quotes => {
body.push(chars.next()?);
continue;
}
_ => {}
}
}
body.push(character);
}
for &quoting in Quoting::deferred_modes(shell_type) {
if checked_aliases.insert((body.clone(), quoting)) {
words.extend(literal_words_with_quoting(
&body,
shell_type,
Parsing::Deferred(quoting),
checked_aliases,
)?);
}
}
continue;
}
// Deferred bodies may be parsed after the snapshot restores RC_QUOTES.
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
pending.extend(
Quoting::deferred_modes(shell_type)
.iter()
.map(|&quoting| (child, quoting)),
);
}
continue;
}
if node.kind() == "heredoc_body" {
let parent = node.parent()?;
let mut cursor = parent.walk();
let delimiter = parent
.named_children(&mut cursor)
.find(|child| child.kind() == "heredoc_start")?
.utf8_text(script.as_bytes())
.ok()?;
let quoted = delimiter.contains(['\'', '"', '\\']);
let strip_tabs = parent
.children(&mut cursor)
.any(|child| child.kind() == "<<-");
let mut start = node.start_byte();
let mut cursor = node.walk();
// Decode static heredoc text without joining across an expansion.
for end in node
.named_children(&mut cursor)
.filter(|child| !quoted && child.kind() != "heredoc_content")
.map(Some)
.chain(std::iter::once(None))
{
let text = &script[start..end.map_or(node.end_byte(), |child| child.start_byte())];
let text = if strip_tabs {
text.split_inclusive('\n')
.map(|line| line.trim_start_matches('\t'))
.collect::<String>()
} else {
text.to_string()
};
let mut chars = text.chars().peekable();
let mut decoded = String::new();
while let Some(character) = chars.next() {
if !quoted && character == '\\' {
match chars.peek() {
Some('\n') => {
chars.next();
continue;
}
Some('$' | '`' | '\\') => {
decoded.push(chars.next()?);
continue;
}
_ => {}
}
}
decoded.push(character);
}
words.push(decoded);
if let Some(child) = end {
start = child.end_byte();
pending.push((child, quoting));
}
}
continue;
}
let mut command_words: Vec<(std::ops::Range<usize>, Option<Vec<u8>>)> = Vec::new();
let declaration = if node.kind() == "command" {
let mut cursor = node.walk();
for argument in node
.child_by_field_name("name")
.into_iter()
.chain(node.children_by_field_name("argument", &mut cursor))
{
let word = literal_word_bytes(argument, script, shell_type, quoting);
if shell_type == ShellType::Zsh
&& let Some((previous_range, previous_word)) = command_words.last_mut()
&& has_continuation_gap(script, previous_range.end, argument.start_byte())
{
*previous_word = previous_word.take().zip(word).map(|(mut previous, word)| {
previous.extend(word);
previous
});
previous_range.end = argument.end_byte();
} else {
command_words.push((argument.byte_range(), word));
}
}
let mut arguments = command_words.iter().map(|(_, word)| {
word.as_ref()
.map(|word| String::from_utf8_lossy(word).into_owned())
});
let mut name = arguments.next().flatten();
loop {
match name.take().as_deref() {
Some(
name @ ("alias" | "declare" | "typeset" | "local" | "readonly" | "export"),
) => {
break Some(name.to_string());
}
Some("noglob" | "-") if shell_type == ShellType::Zsh => {
name = arguments.next().flatten();
}
Some("time") => {
name = arguments.next().flatten();
if shell_type == ShellType::Bash && name.as_deref() == Some("-p") {
name = arguments.next().flatten();
}
}
Some(prefix @ ("builtin" | "command")) => {
name = arguments.next().flatten();
if prefix == "command" {
while name.as_deref().is_some_and(|argument| {
argument.strip_prefix('-').is_some_and(|options| {
!options.is_empty() && options.bytes().all(|byte| byte == b'p')
})
}) {
name = arguments.next().flatten();
}
}
if (prefix == "command"
|| prefix == "builtin" && shell_type != ShellType::Zsh)
&& name.as_deref() == Some("--")
{
name = arguments.next().flatten();
}
}
_ => break None,
}
}
} else {
None
};
let is_alias = declaration.as_deref() == Some("alias");
let may_initialize_array = shell_type == ShellType::Bash
&& (node.kind() == "declaration_command" || declaration.is_some() && !is_alias);
if is_alias || may_initialize_array {
// Bash can inherit an array's type from an earlier declaration or calling scope.
// Aliases and quoted compound-array initializers are parsed again by the shell.
let mut cursor = node.walk();
for argument in node.named_children(&mut cursor) {
if command_words.iter().any(|(range, _)| {
range.start < argument.start_byte() && argument.end_byte() <= range.end
}) {
continue;
}
let continued = command_words.iter().find(|(range, _)| {
range.start == argument.start_byte() && range.end > argument.end_byte()
});
if let Some(assignment) = continued
.map_or_else(
|| literal_word_bytes(argument, script, shell_type, quoting),
|(_, word)| word.clone(),
)
.or_else(|| {
// A dynamic edge prevents full decoding, but not inspection of the
// static fragments in the rest of the continued argument.
let end = continued.map_or(argument.end_byte(), |(range, _)| range.end);
let mut pieces = std::iter::successors(Some(argument), |piece| {
piece.next_named_sibling()
})
.take_while(|piece| piece.end_byte() <= end)
.collect::<Vec<_>>();
pieces.reverse();
let mut word = Vec::new();
while let Some(piece) = pieces.pop() {
if let Some(literal) =
literal_word_bytes(piece, script, shell_type, quoting)
{
word.extend(literal);
} else {
match piece.kind() {
"variable_assignment" => {
word.extend_from_slice(b"_=");
pieces.push(piece.child_by_field_name("value")?);
}
"concatenation" | "string" => pieces.extend(
(0..piece.named_child_count())
.rev()
.filter_map(|index| piece.named_child(index)),
),
"string_content" => {
let text = piece.utf8_text(script.as_bytes()).ok()?;
let decoded = shlex::split(&format!("\"{text}\""))?;
let [literal] = decoded.as_slice() else {
return None;
};
word.extend_from_slice(literal.as_bytes());
}
"simple_expansion"
| "expansion"
| "command_substitution"
| "process_substitution"
| "arithmetic_expansion" => {
word.extend_from_slice(b"${__codex_snapshot_dynamic}");
}
_ => return None,
}
}
}
Some(word)
})
.map(|word| String::from_utf8_lossy(&word).into_owned())
&& let Some((_, body)) = assignment.split_once('=')
{
let body = if may_initialize_array {
let body = body
.trim_start_matches("${__codex_snapshot_dynamic}")
.trim_end_matches("${__codex_snapshot_dynamic}");
if !body.starts_with('(') || !body.ends_with(')') {
continue;
}
format!("_={body}")
} else {
body.to_string()
};
for &quoting in Quoting::deferred_modes(shell_type) {
if checked_aliases.insert((body.clone(), quoting)) {
words.extend(literal_words_with_quoting(
&body,
shell_type,
Parsing::Deferred(quoting),
checked_aliases,
)?);
}
}
}
}
}
let mut pieces = vec![node];
if shell_type == ShellType::Zsh
&& node.prev_named_sibling().is_none_or(|previous| {
!has_continuation_gap(script, previous.end_byte(), node.start_byte())
})
{
// Tree-sitter splits unquoted continuations into sibling words. Decode the
// pieces separately: removing the gap would change adjacent RC_QUOTES strings.
let mut previous = node;
while let Some(next) = previous.next_named_sibling() {
if !has_continuation_gap(script, previous.end_byte(), next.start_byte()) {
break;
}
pieces.push(next);
previous = next;
}
}
let continued = pieces.len() > 1;
if node.kind() == "ansi_c_string" {
words.push(decode_ansi_c(
node.utf8_text(script.as_bytes()).ok()?,
shell_type,
quoting,
)?);
if !continued {
continue;
}
} else if let Some(word) = literal_word(node, script, shell_type, quoting) {
words.push(word);
if !continued {
continue;
}
}
if continued || matches!(node.kind(), "string" | "concatenation") {
// Join adjacent static pieces, but never join across an expansion.
pieces.reverse();
let mut literal = Vec::new();
let mut raw_string_end = None;
while let Some(piece) = pieces.pop() {
if let Some(word) = literal_word_bytes(piece, script, shell_type, quoting) {
if matches!(quoting, Quoting::ZshRcQuotes)
&& piece.kind() == "raw_string"
&& raw_string_end == Some(piece.start_byte())
{
literal.push(b'\'');
}
literal.extend(word);
raw_string_end = (piece.kind() == "raw_string").then_some(piece.end_byte());
} else if piece.kind() == "variable_assignment" {
if !literal.is_empty() {
words.push(String::from_utf8_lossy(&literal).into_owned());
literal.clear();
}
// Only the value can continue into the next word, never the assignment name.
pieces.extend(piece.child_by_field_name("value"));
} else if piece.kind() == "string_content" {
let content = piece.utf8_text(script.as_bytes()).ok()?;
let decoded = shlex::split(&format!("\"{content}\""))?;
let [word] = decoded.as_slice() else {
return None;
};
literal.extend_from_slice(word.as_bytes());
} else if matches!(piece.kind(), "string" | "concatenation" | "command_name") {
if shell_type == ShellType::Zsh
&& piece.prev_sibling().is_some_and(|previous| {
previous.kind() == "$" && previous.end_byte() == piece.start_byte()
})
{
literal.push(b'$');
}
pieces.extend(
(0..piece.named_child_count())
.rev()
.filter_map(|index| piece.named_child(index)),
);
} else if !literal.is_empty() {
words.push(String::from_utf8_lossy(&literal).into_owned());
literal.clear();
}
}
if !literal.is_empty() {
words.push(String::from_utf8_lossy(&literal).into_owned());
}
}
let mut cursor = node.walk();
pending.extend(
node.named_children(&mut cursor)
.map(|child| (child, quoting)),
);
}
Some(words)
}
fn has_continuation_gap(script: &str, left_end: usize, right_start: usize) -> bool {
let gap = &script[left_end..right_start];
!gap.is_empty() && gap.as_bytes().chunks(2).all(|pair| pair == b"\\\n")
}
fn literal_word(
node: Node<'_>,
script: &str,
shell_type: ShellType,
quoting: Quoting,
) -> Option<String> {
let bytes = literal_word_bytes(node, script, shell_type, quoting)?;
Some(String::from_utf8_lossy(&bytes).into_owned())
}
pub(super) fn literal_word_bytes(
node: Node<'_>,
script: &str,
shell_type: ShellType,
quoting: Quoting,
) -> Option<Vec<u8>> {
let mut word = match node.kind() {
"command_name" => node
.named_child(0)
.and_then(|name| literal_word_bytes(name, script, shell_type, quoting)),
"concatenation" => {
let mut cursor = node.walk();
let mut word = Vec::new();
let mut raw_string_end = None;
for child in node.named_children(&mut cursor) {
// RC_QUOTES treats adjacent single-quoted strings as one quoted apostrophe.
if matches!(quoting, Quoting::ZshRcQuotes)
&& child.kind() == "raw_string"
&& raw_string_end == Some(child.start_byte())
{
word.push(b'\'');
}
word.extend(literal_word_bytes(child, script, shell_type, quoting)?);
raw_string_end = (child.kind() == "raw_string").then_some(child.end_byte());
}
Some(word)
}
"ansi_c_string" => {
decode_ansi_c_bytes(node.utf8_text(script.as_bytes()).ok()?, shell_type, quoting)
}
"word" | "number" | "string" | "raw_string" => {
let mut cursor = node.walk();
if node
.named_children(&mut cursor)
.any(|child| child.kind() != "string_content")
{
return None;
}
let text = node.utf8_text(script.as_bytes()).ok()?;
let mut context = node.parent();
while context
.is_some_and(|parent| matches!(parent.kind(), "expansion" | "concatenation"))
{
context = context.and_then(|parent| parent.parent());
}
let words = if shell_type == ShellType::Zsh
&& node.kind() == "word"
&& context.is_some_and(|parent| parent.kind() == "string")
{
shlex::split(&format!("\"{text}\""))?
} else {
shlex::split(text)?
};
let [word] = words.as_slice() else {
return None;
};
Some(word.as_bytes().to_vec())
}
_ => None,
}?;
if shell_type == ShellType::Zsh
&& matches!(node.kind(), "string" | "concatenation")
&& node.prev_sibling().is_some_and(|previous| {
previous.kind() == "$" && previous.end_byte() == node.start_byte()
})
{
word.insert(0, b'$');
}
Some(word)
}
// Decode the literal quoting emitted by Bash and Zsh, never shell expansions.
fn decode_ansi_c(raw: &str, shell_type: ShellType, quoting: Quoting) -> Option<String> {
let bytes = decode_ansi_c_bytes(raw, shell_type, quoting)?;
Some(String::from_utf8_lossy(&bytes).into_owned())
}
fn decode_ansi_c_bytes(raw: &str, shell_type: ShellType, quoting: Quoting) -> Option<Vec<u8>> {
let body = raw.strip_prefix("$'")?;
let body = body.strip_suffix('\'').or_else(|| {
// Array-shaped scalar templates may contain incomplete shell syntax.
(shell_type == ShellType::Bash).then_some(body)
})?;
let mut chars = body.chars().peekable();
let mut decoded = Vec::new();
let mut modifiers = ZshByteModifiers::default();
while let Some(character) = chars.next() {
if character != '\\' {
let mut bytes = [0; 4];
let bytes = character.encode_utf8(&mut bytes).as_bytes();
decoded.push(modifiers.apply(bytes[0]));
decoded.extend_from_slice(&bytes[1..]);
continue;
}
let Some(escape) = chars.next() else {
if shell_type == ShellType::Zsh {
return None;
}
decoded.push(b'\\');
break;
};
let byte = match escape {
'a' => 7,
'b' => 8,
'e' | 'E' => 27,
'f' => 12,
'n' => b'\n',
'r' => b'\r',
't' => b'\t',
'v' => 11,
'\\' | '\'' | '"' | '?' => escape as u8,
'c' if shell_type != ShellType::Zsh => {
let Some(character) = chars.next() else {
decoded.push(b'\\');
if quoting != Quoting::LegacyBash {
decoded.push(b'c');
}
break;
};
// Bash 3.2 leaves the second backslash; newer Bash consumes the pair.
if character == '\\'
&& quoting != Quoting::LegacyBash
&& chars.peek() == Some(&'\\')
{
chars.next();
}
let mut bytes = [0; 4];
let bytes = character.encode_utf8(&mut bytes).as_bytes();
decoded.push(if bytes[0] == b'?' { 127 } else { bytes[0] & 31 });
decoded.extend_from_slice(&bytes[1..]);
continue;
}
'C' | 'M' if shell_type == ShellType::Zsh => {
if chars.peek() == Some(&'-') {
chars.next();
}
if escape == 'C' {
modifiers.control = true;
} else {
modifiers.meta = Some(if modifiers.control {
MetaOrder::BeforeControl
} else {
MetaOrder::AfterControl
});
}
continue;
}
'0'..='7' | 'x' | 'u' | 'U' => {
if matches!(escape, 'u' | 'U') && quoting == Quoting::LegacyBash {
decoded.extend_from_slice(&[b'\\', escape as u8]);
continue;
}
let (radix, digits) = match escape {
'x' => (16, 2),
'u' => (16, 4),
'U' => (16, 8),
_ => (8, 2),
};
let mut value = escape.to_digit(8).unwrap_or(0);
let mut found = escape.is_ascii_digit();
for _ in 0..digits {
let Some(digit) = chars.peek().and_then(|next| next.to_digit(radix)) else {
break;
};
chars.next();
value = value.checked_mul(radix)?.checked_add(digit)?;
found = true;
}
if !found {
if shell_type == ShellType::Zsh {
return None;
}
decoded.extend_from_slice(&[b'\\', escape as u8]);
continue;
}
if matches!(escape, 'u' | 'U') {
let Some(character) = char::from_u32(value) else {
if shell_type == ShellType::Zsh {
return None;
}
// Bash emits extended UTF-8, including surrogate and 5/6-byte values.
let length = match value {
0..=0xffff => 3,
0x10000..=0x1fffff => 4,
0x200000..=0x3ffffff => 5,
0x4000000..=0x7fffffff => 6,
_ => continue,
};
let mut bytes = [0; 6];
for index in (1..length).rev() {
bytes[index] = 0x80 | (value & 0x3f) as u8;
value >>= 6;
}
bytes[0] = (0xff << (8 - length)) | value as u8;
decoded.extend_from_slice(&bytes[..length]);
continue;
};
// Zsh leaves byte modifiers pending across Unicode escapes.
let mut bytes = [0; 4];
decoded.extend_from_slice(character.encode_utf8(&mut bytes).as_bytes());
continue;
}
value as u8
}
_ => {
if shell_type != ShellType::Zsh {
decoded.push(b'\\');
}
let mut bytes = [0; 4];
let bytes = escape.encode_utf8(&mut bytes).as_bytes();
decoded.push(modifiers.apply(bytes[0]));
decoded.extend_from_slice(&bytes[1..]);
continue;
}
};
decoded.push(modifiers.apply(byte));
}
Some(decoded)
}
enum MetaOrder {
BeforeControl,
AfterControl,
}
#[derive(Default)]
struct ZshByteModifiers {
control: bool,
meta: Option<MetaOrder>,
}
impl ZshByteModifiers {
fn apply(&mut self, mut byte: u8) -> u8 {
// Escape order matters for control-? and bytes whose high bit is already set.
let meta = self.meta.take();
if matches!(meta, Some(MetaOrder::BeforeControl)) {
byte |= 0x80;
}
if std::mem::take(&mut self.control) {
byte = if byte == b'?' { 0x7f } else { byte & 0x9f };
}
if matches!(meta, Some(MetaOrder::AfterControl)) {
byte |= 0x80;
}
byte
}
}

View File

@@ -0,0 +1,119 @@
//! Serialize prepared snapshot values and apply export-name policy without executing shell code.
//! Native declarations stay unchanged unless the credential stage supplies a replacement.
use super::capture::CapturedSnapshot;
use akode_protocol::config_types::ShellEnvironmentPolicy;
use akode_protocol::shell_environment::create_env_from_vars;
use std::borrow::Cow;
impl CapturedSnapshot<'_> {
/// Render native functions, options, and aliases; the executor restores environment separately.
pub fn render_state(&self) -> String {
format!("{}{}", self.state, self.aliases)
}
/// Persist only exports admitted by the policy. Explicit overrides are supplied
/// by the command environment; never retain their original captured values.
pub fn render_script(&self, policy: &ShellEnvironmentPolicy) -> String {
let allowed = create_env_from_vars(
self.exports
.iter()
.map(|export| (export.key.to_string(), String::new())),
policy,
/*thread_id*/ None,
);
let mut script = self.render_state();
script.push_str("# exports (native declarations)\n");
for export in &self.exports {
if allowed.contains_key(export.key) && !policy.r#set.contains_key(export.key) {
script.push_str(&export.source);
}
}
script
}
}
#[derive(Default)]
pub(super) struct Value {
pub parts: Vec<ValuePart>,
}
pub(super) enum ValuePart {
Literal(String),
Credential { key: String },
}
pub(super) enum Export<'a> {
Captured(&'a str),
Assignment {
declaration: Cow<'a, str>,
value: Value,
},
Array {
prefix: &'a str,
elements: Vec<Value>,
suffix: &'a str,
},
ArrayBinding {
key: &'a str,
declaration: &'a str,
suffix: &'a str,
},
}
impl Value {
fn render(&self) -> Option<String> {
let mut output = String::new();
for part in &self.parts {
match part {
ValuePart::Literal(value) => {
output.push_str(shlex::try_quote(value).ok()?.as_ref())
}
ValuePart::Credential { key } => {
output.push_str(&format!("\"${{{key}-}}\""));
}
}
}
if output.is_empty() {
output.push_str("''");
}
Some(output)
}
}
pub(super) fn render(state: &str, aliases: &str, exports: &[Export<'_>]) -> Option<String> {
let mut output = format!("{state}{aliases}");
if !exports.is_empty() {
output.push_str("# exports (native declarations)\n");
}
for export in exports {
match export {
Export::Captured(source) => output.push_str(source),
Export::Assignment { declaration, value } => {
output.push_str(&format!("{declaration}={}\n", value.render()?));
}
Export::Array {
prefix,
elements,
suffix,
} => {
let elements = elements
.iter()
.map(Value::render)
.collect::<Option<Vec<_>>>()?;
output.push_str(&format!("{prefix}({}){suffix}", elements.join(" ")));
}
Export::ArrayBinding {
key,
declaration,
suffix,
} => {
output.push_str(&format!(
"if [ \"${{{key}+x}}\" = x ]; then\n{declaration}{}\nfi\n",
suffix.trim_end()
));
}
}
}
Some(output)
}

View File

@@ -0,0 +1,80 @@
//! Restore brokered values after shell startup and snapshot replay.
use std::collections::HashMap;
pub const SNAPSHOT_BROKERED_VALUE_ENV_PREFIX: &str = "AKODE_NETWORK_PROXY_SNAPSHOT_BROKERED_VALUE_";
pub const SNAPSHOT_BROKERED_UNSET_ENV_PREFIX: &str = "AKODE_NETWORK_PROXY_SNAPSHOT_BROKERED_UNSET_";
/// Restore protected credential copies and unsets after shell startup.
/// Keep the copies for another replay stage, or remove them before the user command.
pub fn build_brokered_credential_exports(
env: &HashMap<String, String>,
remove_copies: bool,
) -> String {
let mut value_copies = env
.keys()
.filter_map(|copy_key| {
let key = copy_key.strip_prefix(SNAPSHOT_BROKERED_VALUE_ENV_PREFIX)?;
is_valid_shell_variable_name(key).then_some((key, copy_key))
})
.collect::<Vec<_>>();
value_copies.sort_unstable();
let value_exports = value_copies
.into_iter()
.map(|(key, copy_key)| {
let restore = format!(
"if [ -z \"${{{copy_key}+x}}\" ]; then exit 1; fi\nif [ -n \"${{{key}+x}}\" ] && [ -n \"${{{key}}}\" ] && [ \"${{{key}}}\" != \"${{{copy_key}}}\" ]; then export {key}=\"${{{copy_key}}}\" || exit 1; fi\nif [ -n \"${{{key}+x}}\" ] && [ -n \"${{{key}}}\" ] && [ \"${{{key}}}\" != \"${{{copy_key}}}\" ]; then exit 1; fi"
);
if remove_copies {
format!("{restore}\nunset {copy_key} || exit 1")
} else {
restore
}
})
.collect::<Vec<_>>()
.join("\n");
let mut unset_markers = env
.keys()
.filter_map(|marker_key| {
let key = marker_key.strip_prefix(SNAPSHOT_BROKERED_UNSET_ENV_PREFIX)?;
is_valid_shell_variable_name(key).then_some((key, marker_key))
})
.collect::<Vec<_>>();
unset_markers.sort_unstable();
let unset_exports = unset_markers
.into_iter()
.map(|(key, marker_key)| {
let restore = format!(
"if [ -z \"${{{marker_key}+x}}\" ]; then exit 1; fi\nif [ -n \"${{{key}+x}}\" ] && [ -n \"${{{key}}}\" ]; then unset {key} || exit 1; fi\nif [ -n \"${{{key}+x}}\" ] && [ -n \"${{{key}}}\" ]; then exit 1; fi"
);
if remove_copies {
format!("{restore}\nunset {marker_key} || exit 1")
} else {
restore
}
})
.collect::<Vec<_>>()
.join("\n");
let exports = [value_exports, unset_exports]
.into_iter()
.filter(|block| !block.is_empty())
.collect::<Vec<_>>()
.join("\n");
if exports.is_empty() {
return exports;
}
format!(
"case $- in\n *x*) __CODEX_SNAPSHOT_BROKER_XTRACE=1; set +x ;;\n *) __CODEX_SNAPSHOT_BROKER_XTRACE= ;;\nesac\n{exports}\nif [ -n \"$__CODEX_SNAPSHOT_BROKER_XTRACE\" ]; then\n unset __CODEX_SNAPSHOT_BROKER_XTRACE\n set -x\nelse\n unset __CODEX_SNAPSHOT_BROKER_XTRACE\nfi"
)
}
fn is_valid_shell_variable_name(name: &str) -> bool {
let mut chars = name.chars();
let Some(first) = chars.next() else {
return false;
};
if !(first == '_' || first.is_ascii_alphabetic()) {
return false;
}
chars.all(|c| c == '_' || c.is_ascii_alphanumeric())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,30 @@
//! Profile seeding shared by shell snapshot capture and other initialized shells.
//! Preserve the existing scripts; callers own the shell's launch flags and lifecycle.
use crate::shell_detect::ShellType;
/// Load the interactive configuration used by snapshot capture in a login shell.
/// The caller must already launch the shell with its usual login startup flags.
/// Only Bash and Zsh are supported here; POSIX sh's ENV handling remains in capture.
pub fn shell_startup_script(shell_type: ShellType) -> &'static str {
match shell_type {
ShellType::Zsh => {
r#"if [[ -n "${ZDOTDIR-}" ]]; then
rc="$ZDOTDIR/.zshrc"
elif [[ -n "${HOME-}" ]]; then
rc="$HOME/.zshrc"
else
rc=
fi
[[ -r "$rc" ]] && . "$rc"
"#
}
ShellType::Bash => {
r#"if [ -z "${BASH_ENV-}" ] && [ -n "${HOME-}" ] && [ -r "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi
"#
}
ShellType::Sh | ShellType::PowerShell | ShellType::Cmd => "",
}
}