Skip to content

API Reference parrot.security.command_sanitizer

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.security.command_sanitizer

View source

Command Sanitizer — Shared Security Engine (FEAT-252).

Relocated from parrot_tools.shell_tool.security into core so that both shell_tool (via re-export shim) and the new PythonCodeSanitizer / OutputScrubber can depend on it without requiring core to import parrot_tools.

Layers (when used via CommandSanitizer.validate): 0. Basic sanity (empty, length) 1. Parse & extract base command 2. Dangerous pattern detection (metacharacters, injection vectors) 3. Command allow/deny list enforcement by SecurityLevel 4. Per-command argument restrictions (CommandRule) 5. Path traversal / sandbox enforcement 6. Custom denied patterns

Note: SecureShellMixin is kept in parrot_tools.shell_tool.security because it is shell-specific. The generic primitives here are intentionally stdlib-only (logging, os, re, shlex, dataclasses, enum, pathlib, typing).

Class CommandRule

Per-command security rule for argument-level restrictions.

Parameter Type Default Description
name str
allowed_args Optional[Set[str]] None
denied_args Set[str] set()
denied_patterns List[str] list()
max_args Optional[int] None
require_absolute_path bool False
sandbox_paths Optional[List[str]] None
allow_pipe bool False
allow_redirect bool False
risk_base float 0.0

Fields:

Field Type Default Description
name str The command this rule applies to (e.g. "curl", "find").
allowed_args Optional[Set[str]] None If set, only these flags/subcommands are permitted.
denied_args Set[str] field(default_factory=set) These flags are always denied regardless of context.
denied_patterns List[str] field(default_factory=list) Regex patterns applied to the full command string. Any match denies the command.
max_args Optional[int] None Maximum number of arguments (excluding the command itself).
require_absolute_path bool False If True, path arguments must be absolute.
sandbox_paths Optional[List[str]] None If set, path arguments must be under one of these dirs. Inherits global sandbox_dir if None.
allow_pipe bool False Allow this command to appear in pipe chains.
allow_redirect bool False Allow output redirection for this command.
risk_base float 0.0 Base risk score contribution (0.0–1.0) added when this command is used. Individual violations add on top of this.

Class CommandSanitizer

Multi-layered command sanitizer for shell / agent tool integration.

Runs a 6-layer validation pipeline to check a command string against the configured SecurityPolicy before it reaches the subprocess.

Parameter Type Default Description
policy SecurityPolicy The security policy governing validation behaviour.

Method CommandSanitizer.validate

Validate a command string through all 6 security layers.

validate(command: str) -> ValidationResult

Parameter Type Default Description
command str The raw command string to validate.

Returns: ValidationResult — A ValidationResult with the verdict, reasons, and risk score.

Method CommandSanitizer.validate_batch

Validate multiple commands, returning one result per command.

validate_batch(commands: List[str]) -> List[ValidationResult]

Parameter Type Default Description
commands List[str] List of raw command strings to validate.

Returns: List[ValidationResult] — List of ValidationResult in the same order as commands.

Method CommandSanitizer.validate_path

Validate a filesystem path against sandbox and dangerous path patterns.

Lightweight check for file-oriented actions (WriteFile, ReadFile, etc.) that receive a path string rather than a full command string.

validate_path(path: str) -> ValidationResult

Parameter Type Default Description
path str The filesystem path to validate.

Returns: ValidationResult — A ValidationResult with the verdict and any triggered reasons.

Class CommandSecurityError

Raised when a command fails security validation.

Parameter Type Default Description
message str Human-readable description of the denial.
result ValidationResult The ValidationResult that caused the error.

Attributes:

Attribute Type Description
result The ValidationResult that triggered the denial.

Class CommandVerdict

Result of command validation.

Class SecurityLevel

Security policy levels.

Class SecurityPolicy

Configurable security policy for command execution.

Three preset factory methods are available covering the most common use cases. For fine-grained control, instantiate directly and set individual fields.

Parameter Type Default Description
level SecurityLevel SecurityLevel.MODERATE
allowed_commands Set[str] set()
denied_commands Set[str] (lambda: _DEFAULT_DENIED_COMMANDS.copy())()
command_rules Dict[str, CommandRule] _default_command_rules()
sandbox_dir Optional[str] None
max_command_length int 4096
max_output_bytes int 1048576
max_stderr_bytes int 262144
allow_shell_operators bool False
allow_chaining bool False
allow_env_expansion bool False
allow_command_substitution bool False
allow_glob bool True
denied_patterns List[str] list()
audit_log bool True

Fields:

Field Type Default Description
level SecurityLevel SecurityLevel.MODERATE The broad security level governing default allow/deny behaviour.
allowed_commands Set[str] field(default_factory=set) Commands explicitly permitted. In RESTRICTIVE mode only these commands may run. In MODERATE mode these are merged with the safe defaults.
denied_commands Set[str] field(default_factory=lambda: _DEFAULT_DENIED_COMMANDS.copy()) Commands explicitly denied regardless of level.
command_rules Dict[str, CommandRule] field(default_factory=_default_command_rules) Per-command argument restrictions keyed by command name.
sandbox_dir Optional[str] None If set, all path arguments must resolve under this directory.
max_command_length int 4096 Maximum number of characters in a single command.
max_output_bytes int 1048576 Maximum stdout bytes collected before truncation.
max_stderr_bytes int 262144 Maximum stderr bytes collected before truncation.
allow_shell_operators bool False Allow pipe (|) and output redirect (>, >>).
allow_chaining bool False Allow command chaining (;, &&, ||).
allow_env_expansion bool False Allow environment variable expansion ($VAR, ${VAR}).
allow_command_substitution bool False Allow $(...) and backtick substitution.
allow_glob bool True Allow glob patterns (*, ?, [...]).
denied_patterns List[str] field(default_factory=list) Extra regex patterns applied to every command string.
audit_log bool True Log all validation decisions at WARNING level when denied.

Method SecurityPolicy.restrictive

Create a restrictive policy — only explicitly allowed commands run.

This is the recommended default for AI agent tools where the set of permitted operations is known in advance.

restrictive(allowed_commands: Optional[Set[str]] = None, sandbox_dir: Optional[str] = None, command_rules: Optional[Dict[str, CommandRule]] = None) -> 'SecurityPolicy'

Parameter Type Default Description
allowed_commands Optional[Set[str]] None Exact set of commands the agent may execute.
sandbox_dir Optional[str] None All path arguments must resolve under this directory.
command_rules Optional[Dict[str, CommandRule]] None Per-command argument rules (defaults to empty dict in restrictive mode to avoid unexpected complexity).

Returns: 'SecurityPolicy' — A SecurityPolicy configured for maximum restriction.

Method SecurityPolicy.moderate

Create a moderate policy — safe defaults plus user-specified commands.

Pipes are permitted but chaining (;, &&, ||) and variable/command expansion are blocked. Per-command argument rules apply.

moderate(allowed_commands: Optional[Set[str]] = None, sandbox_dir: Optional[str] = None) -> 'SecurityPolicy'

Parameter Type Default Description
allowed_commands Optional[Set[str]] None Additional commands to permit on top of the built-in safe defaults. Merged with _MODERATE_SAFE_DEFAULTS.
sandbox_dir Optional[str] None All path arguments must resolve under this directory.

Returns: 'SecurityPolicy' — A SecurityPolicy configured for moderate restriction.

Method SecurityPolicy.permissive

Create a permissive policy — everything allowed except denied commands.

Chaining and environment variable expansion are permitted. Command substitution remains blocked. Use only in trusted environments.

permissive(denied_commands: Optional[Set[str]] = None, sandbox_dir: Optional[str] = None) -> 'SecurityPolicy'

Parameter Type Default Description
denied_commands Optional[Set[str]] None Commands to deny. Defaults to _DEFAULT_DENIED_COMMANDS.
sandbox_dir Optional[str] None All path arguments must resolve under this directory.

Returns: 'SecurityPolicy' — A SecurityPolicy configured for minimal restriction.

Class ValidationResult

Immutable result of command validation.

Parameter Type Default Description
verdict CommandVerdict
command str
reasons Tuple[str, ...] ()
sanitized_command Optional[str] None
risk_score float 0.0

Fields:

Field Type Default Description
verdict CommandVerdict Final decision for the command.
command str The original command string that was validated.
reasons Tuple[str, ...] () Tuple of human-readable reasons for the verdict.
sanitized_command Optional[str] None Optional cleaned version of the command (reserved for future use).
risk_score float 0.0 Aggregate risk score in range [0.0, 1.0]. 0.0 = completely safe, 1.0 = critical danger.

Attributes:

Attribute Type Description
is_allowed bool Return True if the command is allowed to execute.
is_denied bool Return True if the command was denied.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally