AI coding agents can edit files, run shell commands, and touch infrastructure. One bad rm -rf, force-push, or docker compose down -v can wipe hours of work or production data.
| 1 | # SPDX-License-Identifier: MIT |
| 2 | """Conservative command parser — never executes input.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | import re |
| 7 | import shlex |
| 8 | from typing import Final |
| 9 | |
| 10 | from agent_guard.models import ParsedCommand |
| 11 | |
| 12 | SHELL_OPERATORS: Final[tuple[str, ...]] = ( |
| 13 | "&&", |
| 14 | "||", |
| 15 | ";", |
| 16 | "|", |
| 17 | ">", |
| 18 | ">>", |
| 19 | "<", |
| 20 | "$(", |
| 21 | "`", |
| 22 | ) |
| 23 | |
| 24 | _OPERATOR_SPLIT = re.compile( |
| 25 | r"(&&|\|\||;|\|(?!\|)|>>|>|<|`|\$\()", |
| 26 | ) |
| 27 | |
| 28 | |
| 29 | def _safe_split(command: str) -> tuple[list[str], str | None]: |
| 30 | """Tokenize with shlex; fall back to whitespace on failure.""" |
| 31 | if "\x00" in command: |
| 32 | return [], "null bytes are not allowed" |
| 33 | try: |
| 34 | # posix=True handles quotes; Windows paths with backslashes need care |
| 35 | tokens = shlex.split(command, posix=True) |
| 36 | return tokens, None |
| 37 | except ValueError as exc: |
| 38 | # Malformed quotes — fail safely with a best-effort split |
| 39 | try: |
| 40 | tokens = shlex.split(command, posix=False) |
| 41 | return tokens, f"quote parse warning: {exc}" |
| 42 | except ValueError as exc2: |
| 43 | parts = command.split() |
| 44 | return parts, f"parse error: {exc2}" |
| 45 | |
| 46 | |
| 47 | def _extract_flags(tokens: list[str]) -> tuple[list[str], list[str]]: |
| 48 | flags: list[str] = [] |
| 49 | positional: list[str] = [] |
| 50 | for tok in tokens: |
| 51 | if tok.startswith("-") and tok != "-": |
| 52 | flags.append(tok) |
| 53 | else: |
| 54 | positional.append(tok) |
| 55 | return flags, positional |
| 56 | |
| 57 | |
| 58 | def _detect_operators(command: str) -> tuple[bool, tuple[str, ...]]: |
| 59 | found: list[str] = [] |
| 60 | for op in SHELL_OPERATORS: |
| 61 | if op in command: |
| 62 | found.append(op) |
| 63 | # Deduplicate preserving order |
| 64 | seen: set[str] = set() |
| 65 | unique: list[str] = [] |
| 66 | for op in found: |
| 67 | if op not in seen: |
| 68 | seen.add(op) |
| 69 | unique.append(op) |
| 70 | return bool(unique), tuple(unique) |
| 71 | |
| 72 | |
| 73 | def _split_segments(command: str) -> tuple[str, ...]: |
| 74 | """Split on common chain operators for multi-command detection.""" |
| 75 | parts = re.split(r"\s*(?:&&|\|\||;)\s*", command) |
| 76 | return tuple(p.strip() for p in parts if p.strip()) |
| 77 | |
| 78 | |
| 79 | def parse_command(command: str) -> ParsedCommand: |
| 80 | """ |
| 81 | Conservatively parse a command string. |
| 82 | |
| 83 | Limitations (by design): |
| 84 | - Not a full shell grammar |
| 85 | - Does not expand variables, globs, or aliases |
| 86 | - Does not execute anything |
| 87 | - Complex quoting / nesting may be approximated |
| 88 | """ |
| 89 | raw = command if command is not None else "" |
| 90 | stripped = raw.strip() |
| 91 | if not stripped: |
| 92 | return ParsedCommand( |
| 93 | raw=raw, |
| 94 | program="", |
| 95 | arguments=(), |
| 96 | flags=(), |
| 97 | positional=(), |
| 98 | parse_error="empty command", |
| 99 | ) |
| 100 | |
| 101 | # Cap extreme input size to remain robust |
| 102 | if len(stripped) > 100_000: |
| 103 | return ParsedCommand( |
| 104 | raw=raw[:200] + "...", |
| 105 | program="", |
| 106 | arguments=(), |
| 107 | flags=(), |
| 108 | positional=(), |
| 109 | parse_error="command too large", |
| 110 | ) |
| 111 | |
| 112 | has_ops, ops = _detect_operators(stripped) |
| 113 | segments = _split_segments(stripped) |
| 114 | |
| 115 | # Parse the first segment as the primary command |
| 116 | primary = segments[0] if segments else stripped |
| 117 | tokens, err = _safe_split(primary) |
| 118 | |
| 119 | if not tokens: |
| 120 | return ParsedCommand( |
| 121 | raw=raw, |
| 122 | program="", |
| 123 | arguments=(), |
| 124 | flags=(), |
| 125 | positional=(), |
| 126 | has_shell_operators=has_ops, |
| 127 | shell_operators=ops, |
| 128 | segments=segments, |
| 129 | parse_error=err or "no tokens", |
| 130 | ) |
| 131 | |
| 132 | program = tokens[0] |
| 133 | arguments = tuple(tokens[1:]) |
| 134 | flags, positional = _extract_flags(list(arguments)) |
| 135 | |
| 136 | subcommand: str | None = None |
| 137 | # Common tools with subcommands |
| 138 | if program.lower() in { |
| 139 | "git", |
| 140 | "docker", |
| 141 | "docker-compose", |
| 142 | "podman-compose", |
| 143 | "npm", |
| 144 | "npx", |
| 145 | "pip", |
| 146 | "cargo", |
| 147 | "kubectl", |
| 148 | "gh", |
| 149 | "aws", |
| 150 | "gcloud", |
| 151 | "az", |
| 152 | "poetry", |
| 153 | "uv", |
| 154 | "compose", |
| 155 | }: |
| 156 | # docker compose is a two-word program |
| 157 | if program.lower() == "docker" and positional and positional[0].lower() == "compose": |
| 158 | subcommand = "compose" |
| 159 | # next positional after compose may be the compose subcommand |
| 160 | rest_pos = positional[1:] |
| 161 | if rest_pos: |
| 162 | subcommand = f"compose {rest_pos[0]}" |
| 163 | elif positional: |
| 164 | subcommand = positional[0] |
| 165 | |
| 166 | return ParsedCommand( |
| 167 | raw=raw, |
| 168 | program=program, |
| 169 | arguments=arguments, |
| 170 | flags=tuple(flags), |
| 171 | positional=tuple(positional), |
| 172 | subcommand=subcommand, |
| 173 | has_shell_operators=has_ops, |
| 174 | shell_operators=ops, |
| 175 | segments=segments, |
| 176 | parse_error=err, |
| 177 | ) |
| 178 | |
| 179 | |
| 180 | def parse_argv(argv: list[str]) -> ParsedCommand: |
| 181 | """Parse an already-split argv list (preferred for ``run``).""" |
| 182 | if not argv: |
| 183 | return ParsedCommand( |
| 184 | raw="", |
| 185 | program="", |
| 186 | arguments=(), |
| 187 | flags=(), |
| 188 | positional=(), |
| 189 | parse_error="empty argv", |
| 190 | ) |
| 191 | raw = " ".join(shlex.quote(a) for a in argv) |
| 192 | program = argv[0] |
| 193 | arguments = tuple(argv[1:]) |
| 194 | flags, positional = _extract_flags(list(arguments)) |
| 195 | subcommand: str | None = None |
| 196 | prog_lower = program.lower().replace("\\", "/").split("/")[-1] |
| 197 | # Strip .exe on Windows |
| 198 | if prog_lower.endswith(".exe"): |
| 199 | prog_lower = prog_lower[:-4] |
| 200 | if prog_lower in {"git", "docker", "npm", "kubectl", "gh"}: |
| 201 | if prog_lower == "docker" and positional and positional[0].lower() == "compose": |
| 202 | rest = positional[1:] |
| 203 | subcommand = f"compose {rest[0]}" if rest else "compose" |
| 204 | elif positional: |
| 205 | subcommand = positional[0] |
| 206 | return ParsedCommand( |
| 207 | raw=raw, |
| 208 | program=program, |
| 209 | arguments=arguments, |
| 210 | flags=tuple(flags), |
| 211 | positional=tuple(positional), |
| 212 | subcommand=subcommand, |
| 213 | segments=(raw,), |
| 214 | ) |