hermes-agent/tests/secret_sources/test_error_remediation.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

151 lines
4.7 KiB
Python

"""Error remediation for secret sources.
Covers the ErrorKind classification of Bitwarden's `invalid_client`
identity reject, the bws stderr summarizer, the per-source
``remediation()`` hook, and the env_loader startup hint printer.
"""
from __future__ import annotations
from pathlib import Path
from unittest import mock
import pytest
from agent.secret_sources import bitwarden as bw
from agent.secret_sources import onepassword as op
from agent.secret_sources.base import ErrorKind, SecretSource
from agent.secret_sources.bitwarden import (
BitwardenSource,
_classify_bws_error,
_summarize_bws_stderr,
)
from agent.secret_sources.onepassword import OnePasswordSource
_BWS_INVALID_CLIENT_DUMP = """\
Error:
0: Received error message from server: [400 Bad Request] {"error":"invalid_client"}
Location:
crates/bws/src/main.rs:108
Backtrace omitted. Run with RUST_BACKTRACE=1 environment variable to display it.
Run with RUST_BACKTRACE=full to include source snippets.
"""
# ---------------------------------------------------------------------------
# _summarize_bws_stderr
# ---------------------------------------------------------------------------
def test_summarize_strips_rust_report_noise():
summary = _summarize_bws_stderr(_BWS_INVALID_CLIENT_DUMP)
assert "invalid_client" in summary
assert "Location:" not in summary
assert "main.rs" not in summary
assert "Backtrace" not in summary
assert "Error:" not in summary
# ---------------------------------------------------------------------------
# _classify_bws_error — the invalid_client identity reject is an auth failure
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# BitwardenSource.fetch — auth failures get a human explanation
# ---------------------------------------------------------------------------
def test_fetch_auth_failure_gets_friendly_error(monkeypatch, tmp_path):
src = BitwardenSource()
monkeypatch.setenv("BWS_ACCESS_TOKEN", "0.dead")
monkeypatch.setattr(bw, "find_bws", lambda install_if_missing=True: tmp_path / "bws")
def boom(**kwargs):
raise RuntimeError(
'bws exited 1: Received error message from server: '
'[400 Bad Request] {"error":"invalid_client"}'
)
monkeypatch.setattr(bw, "fetch_bitwarden_secrets", boom)
result = src.fetch({"enabled": True, "project_id": "p"}, tmp_path)
assert result.error_kind == ErrorKind.AUTH_FAILED
assert "revoked, expired" in result.error
assert "BWS_ACCESS_TOKEN" in result.error
assert "invalid_client" in result.error # mechanics preserved
# ---------------------------------------------------------------------------
# remediation() hook
# ---------------------------------------------------------------------------
def test_onepassword_auth_remediation_points_at_token_command():
hint = OnePasswordSource().remediation(ErrorKind.AUTH_FAILED, {})
assert "hermes secrets onepassword token" in hint
assert "OP_SERVICE_ACCOUNT_TOKEN" in hint
def test_remediation_never_raises_on_junk_cfg():
for cfg in (None, [], "nope", 42):
assert isinstance(BitwardenSource().remediation(ErrorKind.AUTH_FAILED, cfg), str)
assert isinstance(OnePasswordSource().remediation(ErrorKind.AUTH_FAILED, cfg), str)
# ---------------------------------------------------------------------------
# env_loader startup hint
# ---------------------------------------------------------------------------
def test_env_loader_prints_remediation_hint(tmp_path, monkeypatch, capsys):
from hermes_cli import env_loader
from agent.secret_sources import registry
registry._reset_registry_for_tests()
env_loader.reset_secret_source_cache()
home = tmp_path / ".hermes"
home.mkdir()
(home / "config.yaml").write_text(
"secrets:\n"
" bitwarden:\n"
" enabled: true\n"
" project_id: proj\n"
)
monkeypatch.setenv("BWS_ACCESS_TOKEN", "0.dead")
monkeypatch.setattr(bw, "find_bws", lambda install_if_missing=True: tmp_path / "bws")
def boom(**kwargs):
raise RuntimeError(
'bws exited 1: Received error message from server: '
'[400 Bad Request] {"error":"invalid_client"}'
)
monkeypatch.setattr(bw, "fetch_bitwarden_secrets", boom)
try:
env_loader._apply_external_secret_sources(home)
finally:
registry._reset_registry_for_tests()
env_loader.reset_secret_source_cache()
err = capsys.readouterr().err
assert "rejected the machine-account access token" in err
assert "hermes secrets bitwarden token" in err