Files
hermes-agent/tests/tools/test_execution_flag_detection.py
ethernet e8fcb007b9 Merge remote-tracking branch 'upstream/main' into ethie/pm-clean
# Conflicts:
#	AGENTS.md
#	acp_adapter/edit_approval.py
#	acp_adapter/server.py
#	agent/agent_init.py
#	agent/anthropic_adapter.py
#	agent/anthropic_credentials.py
#	agent/auxiliary_client.py
#	agent/azure_identity_adapter.py
#	agent/bedrock_adapter.py
#	agent/browser_registry.py
#	agent/chat_completion_helpers.py
#	agent/coding_context.py
#	agent/context_references.py
#	agent/conversation_loop.py
#	agent/copilot_acp_client.py
#	agent/credits_tracker.py
#	agent/curator.py
#	agent/curator_backup.py
#	agent/deadline.py
#	agent/display.py
#	agent/errors.py
#	agent/estop.py
#	agent/i18n.py
#	agent/image_gen_registry.py
#	agent/image_routing.py
#	agent/learning_graph.py
#	agent/learning_mutations.py
#	agent/lsp/servers.py
#	agent/model_metadata.py
#	agent/models_dev.py
#	agent/monitoring/gateway_health_export.py
#	agent/monitoring/otlp_exporter.py
#	agent/pet/store.py
#	agent/process_bootstrap.py
#	agent/prompt_builder.py
#	agent/proxy_sources/iron_proxy.py
#	agent/secret_sources/_cache.py
#	agent/secret_sources/bitwarden.py
#	agent/secret_sources/registry.py
#	agent/shell_hooks.py
#	agent/skill_bundles.py
#	agent/skill_commands.py
#	agent/skill_utils.py
#	agent/ssl_guard.py
#	agent/ssl_verify.py
#	agent/system_prompt.py
#	agent/terminal_env_registry.py
#	agent/trace_upload.py
#	agent/transcription_registry.py
#	agent/tts_registry.py
#	agent/verify/environment.py
#	agent/vertex_adapter.py
#	agent/video_gen_registry.py
#	agent/web_search_registry.py
#	cli.py
#	cron/jobs.py
#	cron/scheduler.py
#	gateway/agent_cache_pressure.py
#	gateway/cgroup_cleanup.py
#	gateway/channel_directory.py
#	gateway/config.py
#	gateway/control_socket.py
#	gateway/dead_targets.py
#	gateway/drain_control.py
#	gateway/hooks.py
#	gateway/kanban_watchers.py
#	gateway/lifecycle_ledger.py
#	gateway/mirror.py
#	gateway/pairing.py
#	gateway/platform_registry.py
#	gateway/platforms/helpers.py
#	gateway/platforms/weixin.py
#	gateway/readiness.py
#	gateway/restart_loop_guard.py
#	gateway/rich_sent_store.py
#	gateway/run.py
#	gateway/session.py
#	gateway/shutdown_flush.py
#	gateway/shutdown_forensics.py
#	gateway/slash_commands.py
#	gateway/status.py
#	gateway/sticker_cache.py
#	gateway/whatsapp_identity.py
#	hermes_bootstrap.py
#	hermes_cli/_early_recovery.py
#	hermes_cli/_install_repair.py
#	hermes_cli/_startup_fast.py
#	hermes_cli/_subprocess_compat.py
#	hermes_cli/agent_plugins.py
#	hermes_cli/auth.py
#	hermes_cli/backup.py
#	hermes_cli/banner.py
#	hermes_cli/browser_connect.py
#	hermes_cli/build_info.py
#	hermes_cli/cli_agent_setup_mixin.py
#	hermes_cli/cli_commands_mixin.py
#	hermes_cli/codex_models.py
#	hermes_cli/config.py
#	hermes_cli/config_defaults.py
#	hermes_cli/config_migrations.py
#	hermes_cli/container_boot.py
#	hermes_cli/dashboard_auth/registry.py
#	hermes_cli/debug.py
#	hermes_cli/dep_ensure.py
#	hermes_cli/doctor.py
#	hermes_cli/doctor_live.py
#	hermes_cli/dump.py
#	hermes_cli/env_loader.py
#	hermes_cli/foreign_sessions.py
#	hermes_cli/gateway.py
#	hermes_cli/gateway_windows.py
#	hermes_cli/gui_uninstall.py
#	hermes_cli/image_provenance.py
#	hermes_cli/install_identity.py
#	hermes_cli/kanban.py
#	hermes_cli/kanban_db.py
#	hermes_cli/linux_desktop_entry.py
#	hermes_cli/local_runtime/binaries.py
#	hermes_cli/local_runtime/endpoint.py
#	hermes_cli/local_runtime/growth.py
#	hermes_cli/local_runtime/supervisor.py
#	hermes_cli/logs.py
#	hermes_cli/macos_tcc_anchor.py
#	hermes_cli/main.py
#	hermes_cli/memory_setup.py
#	hermes_cli/model_catalog.py
#	hermes_cli/models.py
#	hermes_cli/nous_subscription.py
#	hermes_cli/npm_engine.py
#	hermes_cli/plugin_index.py
#	hermes_cli/plugins.py
#	hermes_cli/plugins_cmd.py
#	hermes_cli/profile_distribution.py
#	hermes_cli/profiles.py
#	hermes_cli/prompt_size.py
#	hermes_cli/psutil_android.py
#	hermes_cli/runtime_repair.py
#	hermes_cli/security_advisories.py
#	hermes_cli/security_audit.py
#	hermes_cli/security_audit_startup.py
#	hermes_cli/service_manager.py
#	hermes_cli/session_export_md.py
#	hermes_cli/setup.py
#	hermes_cli/skills_hub.py
#	hermes_cli/slack_cli.py
#	hermes_cli/status.py
#	hermes_cli/subcommands/gateway.py
#	hermes_cli/subcommands/uninstall.py
#	hermes_cli/tools_config.py
#	hermes_cli/uninstall.py
#	hermes_cli/update_cmd.py
#	hermes_cli/update_contract.py
#	hermes_cli/update_inventory.py
#	hermes_cli/update_lock.py
#	hermes_cli/update_receipt.py
#	hermes_cli/urllib_security.py
#	hermes_cli/web_routers/local_models.py
#	hermes_cli/web_routers/profiles.py
#	hermes_cli/web_routers/skills.py
#	hermes_cli/web_server.py
#	hermes_constants.py
#	hermes_state.py
#	plugins/disk-cleanup/__init__.py
#	plugins/disk-cleanup/disk_cleanup.py
#	plugins/google_meet/node/registry.py
#	plugins/google_meet/node/server.py
#	plugins/google_meet/process_manager.py
#	plugins/google_meet/realtime/openai_client.py
#	plugins/hermes-achievements/dashboard/plugin_api.py
#	plugins/memory/hindsight/__init__.py
#	plugins/memory/honcho/__init__.py
#	plugins/memory/honcho/cli.py
#	plugins/memory/honcho/client.py
#	plugins/memory/honcho/oauth.py
#	plugins/memory/honcho/session.py
#	plugins/memory/mem0/__init__.py
#	plugins/memory/mem0/_setup.py
#	plugins/memory/openviking/__init__.py
#	plugins/memory/retaindb/__init__.py
#	plugins/memory/supermemory/__init__.py
#	plugins/platforms/a2a/protocol.py
#	plugins/platforms/dingtalk/adapter.py
#	plugins/platforms/discord/adapter.py
#	plugins/platforms/feishu/adapter.py
#	plugins/platforms/google_chat/adapter.py
#	plugins/platforms/matrix/adapter.py
#	plugins/platforms/photon/adapter.py
#	plugins/platforms/photon/auth.py
#	plugins/platforms/photon/cli.py
#	plugins/platforms/slack/adapter.py
#	plugins/platforms/teams/adapter.py
#	plugins/platforms/telegram/adapter.py
#	plugins/platforms/wecom/callback_adapter.py
#	plugins/platforms/whatsapp/adapter.py
#	plugins/teams_pipeline/store.py
#	plugins/video_gen/fal/__init__.py
#	plugins/web/ddgs/provider.py
#	plugins/web/exa/provider.py
#	plugins/web/firecrawl/provider.py
#	plugins/web/parallel/provider.py
#	tests/agent/test_ssl_ca_guard.py
#	tests/hermes_cli/test_certifi_repair.py
#	tests/hermes_cli/test_cmd_update.py
#	tests/hermes_cli/test_cmd_update_apt.py
#	tests/hermes_cli/test_dashboard_unified_launch.py
#	tests/hermes_cli/test_dep_ensure.py
#	tests/hermes_cli/test_doctor.py
#	tests/hermes_cli/test_doctor_live.py
#	tests/hermes_cli/test_gui_command.py
#	tests/hermes_cli/test_kanban_boards.py
#	tests/hermes_cli/test_kanban_db.py
#	tests/hermes_cli/test_lazy_refresh_venv_repair.py
#	tests/hermes_cli/test_memory_setup_provider_arg.py
#	tests/hermes_cli/test_nous_subscription.py
#	tests/hermes_cli/test_pip_install_detection.py
#	tests/hermes_cli/test_profile_export_credentials.py
#	tests/hermes_cli/test_psutil_android_extract.py
#	tests/hermes_cli/test_status.py
#	tests/hermes_cli/test_tui_npm_install.py
#	tests/hermes_cli/test_update_fleet_restart_pending.py
#	tests/hermes_cli/test_update_head_moved_gate.py
#	tests/hermes_cli/test_update_interrupted_recovery.py
#	tests/hermes_cli/test_web_server.py
#	tests/hermes_cli/test_web_ui_build.py
#	tests/test_hermes_logging.py
#	tests/test_managed_runtime_resolution.py
#	tests/tools/test_browser_chromium_autoinstall.py
#	tests/tools/test_browser_chromium_check.py
#	tests/tools/test_browser_homebrew_paths.py
#	tests/tools/test_browser_lightpanda.py
#	tests/tools/test_browser_npx_warmup.py
#	tests/tools/test_browser_open_timeout.py
#	tests/tools/test_browser_orphan_reaper.py
#	tests/tools/test_browser_real_profile.py
#	tests/tools/test_browser_suspect_recycle.py
#	tests/tools/test_find_shell.py
#	tests/tools/test_local_env_blocklist.py
#	tests/tools/test_macos_protected_search.py
#	tests/tui_gateway/test_compute_host.py
#	tools/approval.py
#	tools/blueprints.py
#	tools/bot_mode_dm.py
#	tools/bot_mode_probe.py
#	tools/bot_relay.py
#	tools/browser_tool.py
#	tools/browser_use_cli.py
#	tools/checkpoint_manager.py
#	tools/code_execution_tool.py
#	tools/code_kernel.py
#	tools/computer_use/cua_backend.py
#	tools/cronjob_tools.py
#	tools/discord_tool.py
#	tools/environments/base.py
#	tools/environments/daytona.py
#	tools/environments/local.py
#	tools/environments/modal.py
#	tools/environments/vercel_sandbox.py
#	tools/fal_common.py
#	tools/file_operations.py
#	tools/lazy_deps.py
#	tools/mcp_tool.py
#	tools/neutts_synth.py
#	tools/process_registry.py
#	tools/read_extract.py
#	tools/registry.py
#	tools/skill_ledger.py
#	tools/skill_linter.py
#	tools/skill_manager_tool.py
#	tools/skill_usage.py
#	tools/skills_ast_audit.py
#	tools/skills_guard.py
#	tools/skills_hub.py
#	tools/skills_sync.py
#	tools/skills_sync_client.py
#	tools/skills_tool.py
#	tools/terminal_scope.py
#	tools/terminal_tool.py
#	tools/tirith_security.py
#	tools/transcription_tools.py
#	tools/tts_tool.py
#	tools/vision_tools.py
#	tools/voice_mode.py
#	tools/wake_word.py
#	tools/web_result_cache.py
#	tools/website_policy.py
#	tools/working_diff.py
#	tools/write_approval.py
#	tui_gateway/entry.py
#	tui_gateway/methods_tools.py
#	tui_gateway/server.py
2026-09-04 13:03:39 -04:00

300 lines
10 KiB
Python

"""Execution-bearing option detection across interpreters and read-only tools."""
import os
import shlex
import shutil
import subprocess
import time
import pytest
from tools.approval import detect_dangerous_command, detect_hardline_command
@pytest.mark.parametrize(
("argv", "stdin", "expected_returncode", "expected_output"),
[
(["rg", "--", "--pre"], "ordinary text\n", 1, ""),
(["sort", "--", "--compress-program"], "", 2, ""),
(["rg", "--pre-glob", "--pre", "needle"], "needle\n", 0, "needle\n"),
],
)
@pytest.mark.platforms("linux")
def test_real_read_tool_binaries_confirm_option_ownership(
argv, stdin, expected_returncode, expected_output
):
"""Pin the CLI grammar that the approval detector models."""
if shutil.which(argv[0]) is None:
pytest.skip(f"{argv[0]} is not installed")
completed = subprocess.run(argv, input=stdin, text=True, capture_output=True)
assert completed.returncode == expected_returncode
assert completed.stdout == expected_output
@pytest.mark.parametrize(
("tool", "args", "stdin", "needs_tty"),
[
("rg", ["--pre", "-payload-marker", "needle", "{input}"], None, False),
("rg", ["--hostname-bin=-payload-marker", "needle", "{input}"], None, False),
("sort", ["--buffer-size=1K", "--compress-program", "-payload-marker"], "{bulk}", False),
("ag", ["--pager=-payload-marker", "needle", "{input}"], None, True),
("man", ["--pager", "-payload-marker", "ls"], None, True),
("man", ["-P", "-payload-marker", "ls"], None, True),
],
)
@pytest.mark.platforms("linux")
def test_real_binaries_execute_leading_dash_program_payload(
tmp_path, tool, args, stdin, needs_tty
):
"""A PATH marker proves these binaries do not reparse '-program' as an option."""
if shutil.which(tool) is None or (needs_tty and shutil.which("script") is None):
pytest.skip(f"{tool} or script is not installed")
marker = tmp_path / "executed"
payload = tmp_path / "-payload-marker"
payload.write_text("#!/bin/sh\nprintf executed > \"$MARKER\"\ncat\n")
payload.chmod(0o755)
input_file = tmp_path / "input.txt"
input_file.write_text("needle\n")
resolved_args = [arg.format(input=str(input_file)) for arg in args]
input_text = (
"\n".join(str(number) for number in range(10_000, 0, -1)) + "\n"
if stdin == "{bulk}"
else stdin
)
env = {
**os.environ,
"PATH": f"{tmp_path}{os.pathsep}{os.environ['PATH']}",
"MARKER": str(marker),
"TERM": "xterm",
}
argv = [tool, *resolved_args]
if needs_tty:
argv = ["script", "-qec", shlex.join(argv), "/dev/null"]
subprocess.run(argv, input=input_text, text=True, capture_output=True, env=env, timeout=20)
assert marker.read_text() == "executed"
@pytest.mark.parametrize(
"command",
[
"rg -- --pre sh",
"sort -- --compress-program sh",
"rg --pre-glob --pre needle",
"sort --output --compress-program names.txt",
"man --config-file --pager printf",
"ag --ignore --pager needle",
"rg -g --pre needle",
"sort -o --compress-program names.txt",
"man -C --pager printf",
"ag -G --pager needle",
],
)
def test_read_tool_exec_like_operands_owned_by_other_syntax_are_not_flagged(command):
assert detect_dangerous_command(command) == (False, None, None)
assert detect_hardline_command(command) == (False, None)
@pytest.mark.parametrize(
"command",
[
"python3 -W ignore -c 'print(1)'",
"python3.11 -c 'print(1)'",
"node --no-warnings --eval=\"require('fs')\"",
"node -p '1+1'",
"perl -wne 'print' file.txt",
"ruby3.2 -e 'puts 1'",
"php -r 'echo 1;'",
"powershell -ExecutionPolicy Bypass -File helper.ps1",
"pwsh -Command 'Get-Process'",
"python3.11 << 'PY'\nprint(1)\nPY",
],
)
def test_interpreter_execution_mechanisms_require_approval(command):
dangerous, _, _ = detect_dangerous_command(command)
assert dangerous is True
@pytest.mark.parametrize(
"command",
[
"sort --compress-program=sh names.txt",
"rg --pre sh -e . names.txt",
"rg --hostname-bin=sh pattern",
"ag --pager sh foo",
"man -Psh ls",
"man --pager=sh ls",
"man -H sh ls",
"man --html=sh ls",
],
)
def test_read_only_tool_exec_flags_require_approval(command):
dangerous, _, description = detect_dangerous_command(command)
assert dangerous is True
assert "execution" in description
def test_ag_pager_less_is_an_executable_option_and_requires_approval():
assert detect_dangerous_command("ag --pager=less needle src/") == (
True,
"arbitrary program execution via ag --pager",
"arbitrary program execution via ag --pager",
)
@pytest.mark.parametrize(
("command", "description"),
[
("rg --pre -payload-marker needle", "arbitrary program execution via rg --pre"),
("rg --hostname-bin=-payload-marker needle", "arbitrary program execution via rg --hostname-bin"),
("sort --compress-program -payload-marker names", "arbitrary program execution via sort --compress-program"),
("ag --pager=-payload-marker needle", "arbitrary program execution via ag --pager"),
("man --pager -payload-marker ls", "arbitrary program execution via man --pager"),
("man -P -payload-marker ls", "arbitrary program execution via man -P"),
("man -H-payload-marker ls", "arbitrary program execution via man -H"),
],
)
def test_leading_dash_program_payloads_require_approval(command, description):
"""Program options own the next argv even when its spelling starts with '-'."""
assert detect_dangerous_command(command) == (True, description, description)
@pytest.mark.parametrize(
"command",
[
"rg --pre '-payload; rm -rf --no-preserve-root /' needle",
"sort --compress-program='-payload; rm -rf --no-preserve-root /' names",
"ag --pager='-payload; rm -rf --no-preserve-root /' needle",
"man --pager '-payload; rm -rf --no-preserve-root /' ls",
"man -P '-payload; rm -rf --no-preserve-root /' ls",
"man -H'-payload; rm -rf --no-preserve-root /' ls",
],
)
def test_leading_dash_program_payloads_reach_hardline_floor(command):
assert detect_hardline_command(command) == (
True,
"recursive delete of root filesystem",
)
@pytest.mark.parametrize(
"command",
[
"sort --compress-program='rm -rf --no-preserve-root /' names.txt",
"rg --pre 'rm -rf --no-preserve-root /' -e . x",
"ag --pager 'rm -rf --no-preserve-root /' foo",
"man -P 'rm -rf --no-preserve-root /' ls",
],
)
def test_exec_flag_payload_reaches_hardline_floor(command):
hardline, description = detect_hardline_command(command)
assert hardline is True
assert description == "recursive delete of root filesystem"
@pytest.mark.parametrize(
"command",
[
"node -c script.js",
"node --check script.js",
"ruby -c script.rb",
"python3 -m http.server",
"python3 --version",
"sort names.txt",
"rg --pretty pattern src/",
"pip install --pre somepackage",
"man -k pager",
"man -p e ls",
],
)
def test_non_executing_flags_are_not_flagged(command):
hardline, _ = detect_hardline_command(command)
dangerous, _, _ = detect_dangerous_command(command)
assert hardline is False
assert dangerous is False
@pytest.mark.parametrize(
"command",
[
"pip install --pre 'rm -rf --no-preserve-root /'",
"grep -P 'rm -rf --no-preserve-root /' file.txt",
"printf '%s' 'man -P rm -rf --no-preserve-root /'",
],
)
def test_unrelated_options_do_not_promote_payload_text_to_hardline(command):
hardline, _ = detect_hardline_command(command)
assert hardline is False
def test_grep_pcre_pattern_with_grouped_root_delete_text_stays_safe():
"""Regex syntax is grep data, even when it contains a hardline command."""
command = "grep -P '(?:safe|rm -rf --no-preserve-root /)' audit.log"
assert detect_hardline_command(command) == (False, None)
def test_interpreter_heredoc_keeps_legacy_approval_key_compatibility():
from tools.approval import _approval_key_aliases
aliases = _approval_key_aliases("script execution via heredoc")
assert r"(python[23]?|perl|ruby|node)\s+<<" in aliases
@pytest.mark.parametrize(
"flag",
["-c", "-lc", "-ic", "-lic", "-cl", "-cil", "-lci", "-ilc", "-cli", "-abc"],
)
def test_shell_exact_short_exec_flags_require_approval(flag):
dangerous, _, description = detect_dangerous_command(f"bash {flag} 'printf safe'")
assert dangerous is True
assert description == "shell command via -c/-lc flag"
@pytest.mark.parametrize(
"command",
[
"sort --compress-program=\"sh -c 'unterminated names",
"rg --pre=\"bash -lc 'unterminated pattern files",
"man --pager=\"sh -c 'unterminated ls",
],
)
def test_malformed_quoted_executable_payloads_fail_closed(command):
dangerous, _, description = detect_dangerous_command(command)
assert dangerous is True
assert description == "command parser limit or malformed executable payload"
def _time_benign_segments(count):
command = ";".join(f"printf segment-{index}" for index in range(count))
started = time.perf_counter()
result = detect_dangerous_command(command)
return time.perf_counter() - started, result
def test_benign_segment_scaling_benchmark():
"""Retain real metrics without making correctness depend on wall-clock ratios."""
small, small_result = _time_benign_segments(2_000)
large, large_result = _time_benign_segments(4_000)
assert small_result == (False, None, None)
assert large_result == (False, None, None)
print(f"benign segment benchmark: 2k={small:.3f}s, 4k={large:.3f}s")
def test_max_accepted_separator_free_input_is_fast():
from tools.approval_detection import _MAX_SEPARATOR_FREE_COMMAND_CHARS
command = "x" * _MAX_SEPARATOR_FREE_COMMAND_CHARS
started = time.perf_counter()
result = detect_dangerous_command(command)
elapsed = time.perf_counter() - started
assert result == (False, None, None)
# Loose bound: catches the O(n^2)/backtracking regression class without
# flaking on CI scheduler stalls (see comment above).
assert elapsed < 2.0, f"max accepted token took {elapsed:.3f}s"