Skip to content

The agent that grows with you

fix(docker): scan docker_extra_args env flags under pflag shorthand semantics

beardthelion10c30c826409
diff --git a/tests/tools/test_docker_environment.py b/tests/tools/test_docker_environment.py
index e3dc94cc9fb..c8e14563235 100644
--- a/tests/tools/test_docker_environment.py
+++ b/tests/tools/test_docker_environment.py
@@ -6,6 +6,7 @@ import subprocess
import pytest
from tools.environments import docker as docker_env
+from tools.environments.docker_egress import _extra_args_egress_collisions
def _mock_subprocess_run(monkeypatch):
@@ -1032,6 +1033,125 @@ def test_forward_env_non_suffixed_egress_name_refuses_under_egress(monkeypatch):
_make_dummy_env(forward_env=["AWS_SECRET_ACCESS_KEY"])
+_CRITICAL = {"HTTPS_PROXY", "AWS_SECRET_ACCESS_KEY"}
+
+
+ "extra_args",
+ [
+ # Baseline forms the scanner already caught.
+ ["-e", "HTTPS_PROXY=http://evil"],
+ ["-e=HTTPS_PROXY=http://evil"],
+ ["--env", "HTTPS_PROXY=http://evil"],
+ ["--env=HTTPS_PROXY=http://evil"],
+ # pflag joined shorthand: docker parses "-eNAME=v" as "-e NAME=v".
+ ["-eHTTPS_PROXY=http://evil"],
+ # Name-only passthrough shorthand injects the host's real variable.
+ ["-eAWS_SECRET_ACCESS_KEY"],
+ # Chained after docker run's boolean shorthands (-d -i -t -P -q).
+ ["-iteHTTPS_PROXY=http://evil"],
+ ["-deHTTPS_PROXY=http://evil"],
+ # A chain ending in bare "e" takes the next arg as its value.
+ ["-ite", "HTTPS_PROXY=http://evil"],
+ ["-dit", "-eHTTPS_PROXY=http://evil"],
+ # A value-taking flag's operand is not a positional: the env flag
+ # after it is still parsed by docker and must still collide.
+ ["--entrypoint", "/bin/sh", "-e", "HTTPS_PROXY=x"],
+ ["-w", "/app", "-eHTTPS_PROXY=x"],
+ ["--name", "ctr", "--env", "AWS_SECRET_ACCESS_KEY"],
+ ],
+)
+def test_extra_args_egress_collision_shorthand_forms(extra_args):
+ """Docker's pflag CLI accepts a value-taking shorthand joined to its value
+ and chained after boolean shorthands; every spelling of ``-e`` that injects
+ a critical env name must collide."""
+ collisions = _extra_args_egress_collisions(extra_args, _CRITICAL)
+ assert collisions, f"{extra_args} injects a critical env name under docker's own parsing"
+
+
+ "extra_args",
+ [
+ ["-dit"], # boolean chain only
+ ["-p8080:80"], # non-env value shorthand, joined
+ ["-v/tmp:/tmp"], # volume shorthand, joined
+ ["-w/app"], # workdir shorthand, joined
+ ["-eFOO=bar"], # joined env, non-critical name
+ ["-e", "FOO=bar"], # two-arg env, non-critical
+ ["--", "-e", "HTTPS_PROXY=x"], # pflag terminator: rest is image/cmd
+ ["-x"], # unknown shorthand; docker errors
+ ["--entrypoint=/bin/sh"],
+ ["--name", "ctr"],
+ ],
+)
+def test_extra_args_egress_collision_non_env_forms(extra_args):
+ """Args that cannot inject env under docker's parsing must not collide."""
+ assert _extra_args_egress_collisions(extra_args, _CRITICAL) == []
+
+
+def test_extra_args_env_file_shorthand_and_terminator():
+ """--env-file collides unconditionally; the scan honors the terminator."""
+ assert _extra_args_egress_collisions(["--env-file", "f"], _CRITICAL) == ["--env-file"]
+ assert _extra_args_egress_collisions(["--env-file=f"], _CRITICAL) == ["--env-file"]
+ assert _extra_args_egress_collisions(
+ ["--", "--env-file", "f"], _CRITICAL) == []
+
+
+def test_extra_args_joined_shorthand_refuses_under_egress(monkeypatch):
+ """End to end: a combined ``-eNAME=v`` in docker_extra_args must trip the
+ enforced-egress guard exactly like the spaced ``-e NAME=v`` form."""
+ monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker")
+ monkeypatch.setattr(
+ docker_env,
+ "_egress_proxy_args_for_docker",
+ lambda: ([], {"HTTPS_PROXY": "http://host.docker.internal:9090"}, []),
+ )
+ _mock_subprocess_run(monkeypatch)
+
+ with pytest.raises(RuntimeError, match="docker_extra_args.*HTTPS_PROXY"):
+ _make_dummy_env(extra_args=["-eHTTPS_PROXY=http://10.0.0.9:3128"])
+
+
+def test_extra_args_joined_shorthand_real_egress_chain(monkeypatch, tmp_path):
+ """Deepest e2e: the real ``_egress_proxy_args_for_docker`` plumbing (config,
+ iron-proxy status, token mappings) produces the critical-name set, and a
+ joined ``-e<name>=v`` shorthand collides before ``docker run`` is invoked.
+ A mapped credential name (OPENAI_API_KEY) is critical by suffix, so this
+ also covers real-credential injection, not only proxy-control vars."""
+ import agent.proxy_sources.iron_proxy as ip
+ from hermes_cli import config as hc
+
+ monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker")
+ ca = tmp_path / "hermes-egress-ca.crt"
+ ca.write_text("x")
+ proxy_cfg = tmp_path / "proxy.yaml"
+ proxy_cfg.write_text("x")
+ monkeypatch.setattr(
+ hc, "load_config",
+ lambda: {"proxy": {"enabled": True, "enforce_on_docker": True}})
+ monkeypatch.setattr(
+ ip, "get_status",
+ lambda: ip.ProxyStatus(
+ enabled=True, config_path=proxy_cfg, ca_cert_path=ca,
+ pid=4321, listening=True))
+ monkeypatch.setattr(
+ ip, "load_mappings",
+ lambda: [ip.TokenMapping(
+ proxy_token="tok", real_env_name="OPENAI_API_KEY",
+ upstream_hosts=("api.openai.com",))])
+ calls = _mock_subprocess_run(monkeypatch)
+
+ with pytest.raises(RuntimeError, match="docker_extra_args.*OPENAI_API_KEY"):
+ _make_dummy_env(extra_args=["-eOPENAI_API_KEY=sk-real"])
+
+ run_calls = [
+ c for c in calls
+ if isinstance(c[0], list) and len(c[0]) >= 2 and c[0][1] == "run"
+ and "sleep" not in c[0]
+ ]
+ assert not run_calls, "the collision must refuse before docker run"
+
+
def test_reuse_starts_stopped_container_before_attaching(monkeypatch):
"""A labeled container in ``exited`` state must be restarted via
``docker start`` before the new Hermes process uses it. Without this
diff --git a/tools/environments/docker_egress.py b/tools/environments/docker_egress.py
index b8c463ac1e8..33e2453cdb3 100644
--- a/tools/environments/docker_egress.py
+++ b/tools/environments/docker_egress.py
@@ -146,23 +146,61 @@ def _critical_egress_env_names(env_overrides: dict[str, str]) -> set[str]:
return set(_PROXY_CONTROL_ENV) | {"NODE_OPTIONS"} | set(env_overrides)
+# ``docker run`` boolean shorthands that may precede a value-taking shorthand
+# in a single-dash chain (pflag: "-iteNAME=v" parses as -i -t -e NAME=v).
+_DOCKER_RUN_BOOL_SHORTHANDS = frozenset("ditPq")
+
+
+def _env_flag_value(arg: str) -> tuple[str, str | None] | None:
+ """``("env"|"env-file", inline_value)`` when ``arg`` spells a docker env flag
+ under pflag parsing, else ``None``. ``inline_value`` is the joined value
+ (``--env=N=v``, ``-eN=v``) or ``None`` when the flag consumes the next arg
+ (``-e``, ``--env``, ``-ite``)."""
+ if arg.startswith("--"):
+ flag, sep, inline = arg.partition("=")
+ if flag in ("--env", "--env-file"):
+ return flag[2:], inline if sep else None
+ return None
+ # A single dash heads a shorthand chain: every letter before the last must
+ # be a boolean shorthand, and the last takes the rest of the arg (or the
+ # next arg when bare) as its value.
+ for pos, ch in enumerate(arg[1:]):
+ if ch in _DOCKER_RUN_BOOL_SHORTHANDS:
+ continue
+ if ch == "e":
+ rest = arg[pos + 2:]
+ if rest.startswith("="):
+ rest = rest[1:]
+ return "env", rest or None
+ return None
+ return None
+
+
def _extra_args_egress_collisions(extra_args: list[str], critical_names: set[str]) -> list[str]:
"""Return docker_extra_args entries that can override egress controls."""
collisions: list[str] = []
i = 0
while i < len(extra_args):
arg = extra_args[i]
- flag, sep, inline_value = arg.partition("=") # ``-e NAME=v`` vs ``-e=NAME=v`` / ``--env-file=f``
- if flag in ("-e", "--env", "--env-file"):
- value = inline_value if sep else (extra_args[i + 1] if i + 1 < len(extra_args) else "")
- name = value.split("=", 1)[0]
- if flag == "--env-file":
- collisions.append(flag)
- elif name in critical_names:
- collisions.append(name)
- i += 1 if sep else 2
+ # pflag stops flag parsing at "--"; the rest is image/command. Bare
+ # positionals keep being scanned: a preceding long flag may consume
+ # them as its value, and over-scanning errs toward enforcement.
+ if arg == "--":
+ break
+ parsed = _env_flag_value(arg)
+ if parsed is not None:
+ kind, inline_value = parsed
+ if kind == "env-file":
+ collisions.append("--env-file")
+ else:
+ value = inline_value if inline_value is not None else (
+ extra_args[i + 1] if i + 1 < len(extra_args) else "")
+ name = value.split("=", 1)[0]
+ if name in critical_names:
+ collisions.append(name)
+ i += 1 if inline_value is not None else 2
continue
- if flag in ("--network", "--net"):
+ if arg.partition("=")[0] in ("--network", "--net"):
collisions.append(arg)
i += 1
return sorted(set(collisions))