hermes-agent/tests/tools/test_snapshot_session_id_leak.py
Teknium 39975613b1
test: prune wave 2 + speed fixes — 28,106 → 19,757 test functions, suite wall 315s → 294s
Second, deeper pass over tools/gateway/hermes_cli plus first pass over
the trees wave 1 missed (acp, acp_adapter, skills, computer_use, docker,
dashboard, conformance, monitoring, secret_sources, hermes_state,
providers). Same rubric as wave 1 (AGENTS.md test policy); security,
alternation/caching invariants, issue-number regressions, and E2E kept.

Real test-quality fixes found and rooted out along the way:
- tests/tools/test_command_guards.py made real auxiliary-LLM HTTPS calls
  (DEFAULT_CONFIG smart-approval leaked in) — pinned approval
  mode=manual via autouse fixture: 17.4s → 0.4s.
- test_model_switch_custom_providers.py / test_user_providers_model_switch.py
  silently probed live provider catalogs (~2s/test) — stubbed
  cached_provider_model_ids/provider_model_ids/fetch_api_models.
- test_telegram_noise_filter.py: 15-platform copy-paste matrix over
  shared gateway.run logic → 3 representative platforms (55s → 3.9s).
- test_gateway_shutdown.py: stop()'s 5s interrupt-deadline loop spun on
  MagicMock agents — interrupt.side_effect now clears _running_agents
  (22s → 1.0s).
- test_gateway_inactivity_timeout.py poll-harness timings shrunk 3-5x
  (24s → 1.1s); test_mcp_stability.py backoff/SIGTERM-grace sleeps
  patched (15.4s → 2.5s); test_async_delegation.py negative-drain wait
  5s → 0.5s.
- test_telegram_init_deadline.py: loop-block margin restored to 1.0s
  with rationale comment — the watchdog-dump assertion needs the loop
  blocked well past deadline+grace under parallel load (flaked once in
  the 40-worker verification run at a 0.2s margin).

Verification: full hermetic suite via scripts/run_tests.sh —
2,438 files, 21,718 tests passed, 0 failed, 293.9s wall.
Suite totals vs original baseline: 46,820 → 19,757 test functions
(−57.8%), wall 583.5s → 293.9s (−50%), subprocess CPU 13,564s → 11,623s.
2026-07-29 13:39:40 -07:00

107 lines
4.3 KiB
Python

"""Cross-session HERMES_SESSION_ID leak via the shared bash snapshot.
Regression coverage for the bug where a single long-lived backend serves many
sessions through ONE ``_active_environments["default"]`` LocalEnvironment (the
messaging gateway, TUI, and desktop/web dashboard all collapse the terminal to
"default"). That environment persists a bash *session snapshot* file and
``source``s it before every command. ``export -p`` dumped the FIRST session's
``HERMES_SESSION_ID`` into the snapshot, so every LATER session ``source``d that
stale value and its ``echo $HERMES_SESSION_ID`` reported a FOREIGN session's id
— overriding the correct per-command Popen env injected by
``_inject_session_context_env``.
The fix strips the per-session bridged vars (HERMES_SESSION_* / UI /
CRON_AUTO_DELIVER_) from the snapshot at both dump sites in
``tools/environments/base.py``; they are re-injected fresh on every command.
"""
import os
import re
import sys
import pytest
from tools.environments.base import (
_SNAPSHOT_EXCLUDED_ENV_REGEX,
_export_dump_excluding_session_vars,
)
# ---------------------------------------------------------------------------
# Unit: the exclusion regex matches exactly the bridged vars, nothing else.
# ---------------------------------------------------------------------------
def test_regex_matches_bridged_session_vars():
rx = re.compile(_SNAPSHOT_EXCLUDED_ENV_REGEX)
# Every var the gateway bridges must be excluded.
from gateway.session_context import _VAR_MAP
for name in _VAR_MAP:
line = f'declare -x {name}="whatever"'
assert rx.search(line), f"{name} should be excluded from the snapshot"
def test_export_snippet_shape():
snippet = _export_dump_excluding_session_vars("/tmp/snap.tmp.$BASHPID")
assert "export -p" in snippet
# Unset-by-name (not line-grep): multi-line declare values must not leave
# continuation lines in the snapshot (issue #71296).
assert "unset" in snippet
assert "${!HERMES_SESSION_*}" in snippet
assert "${!HERMES_CRON_AUTO_DELIVER_*}" in snippet
assert "HERMES_UI_SESSION_ID" in snippet
assert "grep -vE" not in snippet
assert "/tmp/snap.tmp.$BASHPID" in snippet
# The redirection must be attached to a brace group wrapping the dump,
# NOT to a pipeline segment: a redirect on a pipeline segment expands
# $BASHPID inside that segment's subshell (a different PID than the parent
# that expands the follow-up ``mv`` operand), silently orphaning the dump
# and breaking snapshot env persistence entirely.
assert snippet.lstrip().startswith("{ ")
assert "|| true; }" in snippet
assert snippet.rstrip().endswith("> /tmp/snap.tmp.$BASHPID")
# ---------------------------------------------------------------------------
# Integration: real LocalEnvironment, two sessions, no cross-contamination.
# ---------------------------------------------------------------------------
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX bash snapshot path")
def test_shared_snapshot_no_cross_session_leak(tmp_path):
import threading
from gateway.session_context import _VAR_MAP, _UNSET, set_session_vars
from tools.environments.local import LocalEnvironment
env = LocalEnvironment(cwd=str(tmp_path), timeout=30)
env.init_session()
try:
def run_as(sid):
out = {}
def worker():
for v in _VAR_MAP.values():
v.set(_UNSET)
set_session_vars(session_key="k" + sid, session_id=sid, source="desktop")
out["r"] = env.execute('echo "[$HERMES_SESSION_ID]"')
t = threading.Thread(target=worker)
t.start()
t.join()
return out["r"].get("output", "")
out_a = run_as("SIDAAA")
out_b = run_as("SIDBBB")
assert "SIDAAA" in out_a, f"session A saw {out_a!r}"
# The core assertion: B must see its OWN id, not A's leaked via snapshot.
assert "SIDBBB" in out_b, f"session B saw {out_b!r}"
assert "SIDAAA" not in out_b, f"session B leaked A's id: {out_b!r}"
# And the snapshot file must not carry the session id at all.
snap = env._snapshot_path
if os.path.exists(snap):
with open(snap) as f:
assert "HERMES_SESSION_ID" not in f.read()
finally:
env.cleanup()