Skip to content

The agent that grows with you

fix(scope): failed profile-scoped secret reads must not borrow os.environ

beardthelion0cbe552888c2
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index 4668b3989bf..f16ef1529e4 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -1115,15 +1115,17 @@ def _scoped_key_env(name: str) -> str:
"""Read a provider API key (or its paired base-URL) env var through the profile secret scope.
In agent turns the scope's verdict is authoritative (a scoped miss must not borrow another
- profile's key); unscoped startup/CLI paths fall back to os.environ.
+ profile's key); only the unscoped default-profile path (``UnscopedSecretError``) reads
+ ``os.environ`` -- any other scope failure propagates instead of borrowing the ambient env.
"""
if not name:
return ""
- with contextlib.suppress(Exception):
- from agent.secret_scope import UnscopedSecretError, get_secret
- with contextlib.suppress(UnscopedSecretError):
- return (get_secret(name) or "").strip()
- return (os.getenv(name) or "").strip()
+ from agent.secret_scope import UnscopedSecretError, get_secret
+
+ try:
+ return (get_secret(name) or "").strip()
+ except UnscopedSecretError:
+ return (os.getenv(name) or "").strip()
# Codex Responses → chat.completions adapter, so aux consumers need no changes.
diff --git a/gateway/pairing.py b/gateway/pairing.py
index bac6f74e780..e5c1e49a324 100644
--- a/gateway/pairing.py
+++ b/gateway/pairing.py
@@ -128,20 +128,18 @@ def _matching_ids(platform: str, approved: dict, user_id: str) -> list:
def _read_allowlist_env(env_var: str) -> str:
"""Read a platform allowlist env var through the profile secret scope.
- Under multiplexing the process env may hold ANOTHER profile's allowlist, so a scoped
- miss must return empty rather than borrow it; unscoped callers keep the legacy
- ``os.getenv`` read. Writes (``save_env_value``/``remove_env_value``) target the
- active profile's ``.env`` / installed scope, not ``os.environ``.
+ Under multiplexing the process env may hold ANOTHER profile's allowlist, so a
+ scoped miss must return empty rather than borrow it. The shared reader owns the
+ contract: a bound-scope failure propagates (never silently borrows the env),
+ while the unscoped default-profile path keeps the legacy ``os.getenv`` read.
+ Writes (``save_env_value``/``remove_env_value``) target the active profile's
+ ``.env`` / installed scope, not ``os.environ``.
See #88441.
"""
- with contextlib.suppress(Exception):
- from agent.secret_scope import UnscopedSecretError, get_secret
- try:
- return (get_secret(env_var) or "").strip()
- except UnscopedSecretError:
- pass
- return (os.getenv(env_var) or "").strip()
+ from gateway.platforms._shared import get_scoped_secret
+
+ return (get_scoped_secret(env_var, "") or "").strip()
def _configured_allowlist(platform: str):
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 6b436aedc2d..2ee324b18ed 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -2767,16 +2767,14 @@ class GatewayTurnMixin:
return self._proxy_error_result("⚠️ Proxy URL not configured (GATEWAY_PROXY_URL or gateway.proxy_url)")
# The proxy key is a per-profile credential: honor the installed secret scope under multiplex.
- # Only UnscopedSecretError / import failures fall back to the env; any other get_secret()
- # error propagates (same as BASE) rather than silently degrading to the ambient key.
- try:
- from agent.secret_scope import UnscopedSecretError, get_secret
+ # Only UnscopedSecretError (the unscoped default-profile path) falls back to the env; any
+ # other get_secret() error propagates (same as BASE) rather than silently degrading to the
+ # ambient key, which may hold another profile's credential.
+ from agent.secret_scope import UnscopedSecretError, get_secret
- try:
- proxy_key = (get_secret("GATEWAY_PROXY_KEY") or "").strip()
- except UnscopedSecretError:
- proxy_key = os.getenv("GATEWAY_PROXY_KEY", "").strip()
- except Exception:
+ try:
+ proxy_key = (get_secret("GATEWAY_PROXY_KEY") or "").strip()
+ except UnscopedSecretError:
proxy_key = os.getenv("GATEWAY_PROXY_KEY", "").strip()
_run_still_current = self._run_still_current_fn(session_key, run_generation)
diff --git a/gateway/session.py b/gateway/session.py
index 5127074d852..99d872bc403 100644
--- a/gateway/session.py
+++ b/gateway/session.py
@@ -217,13 +217,18 @@ def _slack_tools_loaded() -> bool:
except Exception:
pass
- # Profile secret scope, not bare env: under multiplex the env may hold another profile's token.
+ # Profile secret scope, not bare env: under multiplex the env may hold another
+ # profile's token. Only the unscoped default-profile path (UnscopedSecretError)
+ # reads the env; any other scoped-read failure fails closed rather than borrowing.
try:
- from agent.secret_scope import get_secret
+ from agent.secret_scope import UnscopedSecretError, get_secret
- token = get_secret("SLACK_BOT_TOKEN") or ""
- except Exception: # includes UnscopedSecretError
- token = os.environ.get("SLACK_BOT_TOKEN") or ""
+ try:
+ token = get_secret("SLACK_BOT_TOKEN") or ""
+ except UnscopedSecretError:
+ token = os.environ.get("SLACK_BOT_TOKEN") or ""
+ except Exception:
+ return False
if not token.strip():
return False
try:
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index a007ad63ee9..60eccfea23e 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -2813,17 +2813,13 @@ def reload_env() -> int:
def _scoped_environ_get(key: str) -> Optional[str]:
"""Read ``key`` from ``os.environ`` through ``agent.secret_scope.get_secret`` so an active
profile scope (multiplexed gateway turn) never leaks another profile's raw value. Falls back to
- a plain environ read when the scope module is unavailable; ``UnscopedSecretError`` propagates."""
+ a plain environ read when the scope module is unavailable; ``UnscopedSecretError`` and scope
+ failures propagate -- a failed scoped read must never borrow the ambient env."""
try:
- from agent.secret_scope import UnscopedSecretError, get_secret as _get_secret
- except Exception:
- return os.environ.get(key)
- try:
- return _get_secret(key)
- except UnscopedSecretError:
- raise
+ from agent.secret_scope import get_secret as _get_secret
except Exception:
return os.environ.get(key)
+ return _get_secret(key)
def get_env_value(key: str) -> Optional[str]:
diff --git a/hermes_cli/web_routers/audio.py b/hermes_cli/web_routers/audio.py
index b56a68ad744..0b73120e8f7 100644
--- a/hermes_cli/web_routers/audio.py
+++ b/hermes_cli/web_routers/audio.py
@@ -218,7 +218,8 @@ async def get_elevenlabs_voices(profile: Optional[str] = None):
if not api_key:
# Fallback for env-only deployments — scope-aware: under multiplex
# os.environ may hold another profile's key, so honor the installed
- # scope's verdict before touching the env.
+ # scope's verdict. Only the unscoped default-profile path
+ # (UnscopedSecretError) reads the env; any other failure stays empty.
try:
from agent.secret_scope import UnscopedSecretError, get_secret
@@ -227,7 +228,7 @@ async def get_elevenlabs_voices(profile: Optional[str] = None):
except UnscopedSecretError:
api_key = (os.environ.get("ELEVENLABS_API_KEY") or "").strip()
except Exception:
- api_key = (os.environ.get("ELEVENLABS_API_KEY") or "").strip()
+ pass
if not api_key:
return {"available": False, "voices": []}
diff --git a/tests/agent/test_secret_scope_tier1_migration.py b/tests/agent/test_secret_scope_tier1_migration.py
index 92f38ffe6ef..233bc83ad80 100644
--- a/tests/agent/test_secret_scope_tier1_migration.py
+++ b/tests/agent/test_secret_scope_tier1_migration.py
@@ -40,6 +40,12 @@ class _Scope:
ss.reset_secret_scope(self.token)
+class _ExplodingScope(dict):
+ """A bound secret scope whose resolution fails (resolver/backend error)."""
+ def get(self, name, default=None):
+ raise RuntimeError("resolver boom")
+
+
# ── Cluster A: gateway/pairing.py allowlist reads ─────────────────────────
class TestPairingAllowlistRead:
@@ -67,6 +73,17 @@ class TestPairingAllowlistRead:
ss.set_multiplex_active(True)
assert _read_allowlist_env("TELEGRAM_ALLOWED_USERS") == "own-env"
+ def test_scope_failure_never_borrows_env(self, monkeypatch):
+ # A bound scope that errors must propagate -- a blanket suppress would
+ # silently borrow the default profile's os.environ allowlist.
+ from gateway.pairing import _read_allowlist_env
+
+ monkeypatch.setenv("TELEGRAM_ALLOWED_USERS", "other-profile")
+ ss.set_multiplex_active(True)
+ with _Scope(_ExplodingScope()):
+ with pytest.raises(RuntimeError, match="resolver boom"):
+ _read_allowlist_env("TELEGRAM_ALLOWED_USERS")
+
# ── Cluster A: gateway/authz_mixin.py gate reads ───────────────────────────
@@ -181,6 +198,15 @@ class TestToolGatewayUserToken:
ss.set_multiplex_active(True)
assert _read_user_token_override() == "own-env-tok"
+ def test_scope_failure_never_borrows_env(self, monkeypatch):
+ from tools.managed_tool_gateway import _read_user_token_override
+
+ monkeypatch.setenv("TOOL_GATEWAY_USER_TOKEN", "other-profile-tok")
+ ss.set_multiplex_active(True)
+ with _Scope(_ExplodingScope()):
+ with pytest.raises(RuntimeError, match="resolver boom"):
+ _read_user_token_override()
+
class TestOpenRouterCheckApiKey:
def test_scoped_value_wins(self, monkeypatch):
@@ -199,6 +225,15 @@ class TestOpenRouterCheckApiKey:
with _Scope({"UNRELATED": "x"}):
assert check_api_key() is False
+ def test_scope_failure_never_borrows_env(self, monkeypatch):
+ from tools.openrouter_client import check_api_key
+
+ monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-other-profile")
+ ss.set_multiplex_active(True)
+ with _Scope(_ExplodingScope()):
+ with pytest.raises(RuntimeError, match="resolver boom"):
+ check_api_key()
+
# ── Cluster D: auxiliary client key resolution ──────────────────────────────
@@ -231,6 +266,47 @@ class TestAuxiliaryScopedKeyEnv:
assert _scoped_key_env("") == ""
+ def test_scope_failure_never_borrows_env(self, monkeypatch):
+ from agent.auxiliary_client import _scoped_key_env
+
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-other-profile")
+ ss.set_multiplex_active(True)
+ with _Scope(_ExplodingScope()):
+ with pytest.raises(RuntimeError, match="resolver boom"):
+ _scoped_key_env("OPENAI_API_KEY")
+
+
+# ── Cluster F: hermes_cli config env readers ───────────────────────────────
+
+class TestScopedEnvironGet:
+ """``_scoped_environ_get`` (feeds ``get_env_value`` / ``get_env_value_prefer_dotenv``)
+ documents that ``UnscopedSecretError`` propagates; a blanket ``except Exception``
+ after the call would silently borrow the launch profile's env on a bound-scope
+ failure."""
+
+ def test_scope_failure_never_borrows_env(self, monkeypatch):
+ from hermes_cli.config import _scoped_environ_get
+
+ monkeypatch.setenv("SOME_PROFILE_KEY", "other-profile")
+ ss.set_multiplex_active(True)
+ with _Scope(_ExplodingScope()):
+ with pytest.raises(RuntimeError, match="resolver boom"):
+ _scoped_environ_get("SOME_PROFILE_KEY")
+
+ def test_unscoped_multiplex_propagates(self, monkeypatch):
+ from hermes_cli.config import _scoped_environ_get
+
+ monkeypatch.setenv("SOME_PROFILE_KEY", "launch-env")
+ ss.set_multiplex_active(True)
+ with pytest.raises(ss.UnscopedSecretError):
+ _scoped_environ_get("SOME_PROFILE_KEY")
+
+ def test_single_profile_env_read(self, monkeypatch):
+ from hermes_cli.config import _scoped_environ_get
+
+ monkeypatch.setenv("SOME_PROFILE_KEY", "own-env")
+ assert _scoped_environ_get("SOME_PROFILE_KEY") == "own-env"
+
# ── Cluster E: azure identity presence reads ────────────────────────────────
diff --git a/tests/gateway/test_multiplex_pairing_stores.py b/tests/gateway/test_multiplex_pairing_stores.py
index 78dc2f3e1d1..d72e0d24e5e 100644
--- a/tests/gateway/test_multiplex_pairing_stores.py
+++ b/tests/gateway/test_multiplex_pairing_stores.py
@@ -122,3 +122,109 @@ def test_routed_pairing_grant_mirror_stays_in_profile_scope(tmp_path, monkeypatc
# Single-profile: no multiplex -> save still publishes to the process env.
save_env_value("DISCORD_ALLOWED_USERS", "default-admin,222")
assert os.environ["DISCORD_ALLOWED_USERS"] == "default-admin,222"
+
+
+class _ExplodingScope(dict):
+ """A bound secret scope whose resolution fails (resolver/backend error)."""
+ def get(self, name, default=None):
+ raise RuntimeError("resolver boom")
+
+
+def test_allowlist_env_read_never_borrows_on_scope_failure(tmp_path, monkeypatch):
+ """A bound-scope allowlist read that fails must propagate -- never borrow the
+ default profile's ``os.environ`` value. The unscoped path under multiplex keeps
+ the deliberate env read (launch profile's own value, the "Slack pattern").
+ Single-profile deployments keep the legacy ``os.environ`` read.
+ """
+ import os
+
+ import pytest
+
+ from agent import secret_scope as ss
+ from gateway import pairing
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ monkeypatch.setenv("DISCORD_ALLOWED_USERS", "default-admin")
+
+ was_active = ss.is_multiplex_active()
+ ss.set_multiplex_active(True)
+ try:
+ # Deliberate: unscoped under multiplex is the launch profile's own env.
+ assert pairing._read_allowlist_env("DISCORD_ALLOWED_USERS") == "default-admin"
+
+ # Defect arm: a bound scope that errors must propagate, not borrow.
+ token = ss.set_secret_scope(_ExplodingScope())
+ try:
+ with pytest.raises(RuntimeError, match="resolver boom"):
+ pairing._read_allowlist_env("DISCORD_ALLOWED_USERS")
+ finally:
+ ss.reset_secret_scope(token)
+ finally:
+ ss.set_multiplex_active(was_active)
+
+ # Control: unscoped single-profile reads still see the process env.
+ assert pairing._read_allowlist_env("DISCORD_ALLOWED_USERS") == "default-admin"
+
+
+def test_allowlist_sync_does_not_persist_foreign_allowlist(tmp_path, monkeypatch):
+ """End-to-end: ``_sync_allowlist_add`` under a bound scope whose read fails
+ must propagate rather than borrow ``os.environ`` and persist the DEFAULT
+ profile's allowlist into a profile ``.env`` / the process env.
+ """
+ import os
+
+ import pytest
+
+ from agent import secret_scope as ss
+ from gateway import pairing
+
+ root = tmp_path / ".hermes"
+ root.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(root))
+ monkeypatch.setenv("DISCORD_ALLOWED_USERS", "default-admin")
+
+ was_active = ss.is_multiplex_active()
+ ss.set_multiplex_active(True)
+ token = ss.set_secret_scope(_ExplodingScope())
+ try:
+ with pytest.raises(RuntimeError, match="resolver boom"):
+ pairing._sync_allowlist_add("discord", "111")
+ finally:
+ ss.reset_secret_scope(token)
+ ss.set_multiplex_active(was_active)
+
+ # The foreign allowlist was neither persisted nor merged into the process env.
+ env_file = root / ".env"
+ assert "111" not in (env_file.read_text() if env_file.exists() else "")
+ assert os.environ["DISCORD_ALLOWED_USERS"] == "default-admin"
+
+
+def test_allowlist_scoped_miss_configures_nothing(tmp_path, monkeypatch):
+ """A bound scope that lacks the var returns "" -- the allowlist is
+ unconfigured for this profile, so the sync is a no-op and nothing is
+ written (never the default profile's ``os.environ`` value).
+ """
+ import os
+
+ from agent import secret_scope as ss
+ from gateway import pairing
+ from gateway.run import _profile_runtime_scope
+
+ root = tmp_path / ".hermes"
+ prof = root / "profiles" / "b"
+ prof.mkdir(parents=True)
+ (prof / ".env").write_text("OTHER_KEY=x\n")
+ monkeypatch.setenv("HERMES_HOME", str(root))
+ monkeypatch.setenv("DISCORD_ALLOWED_USERS", "default-admin")
+
+ was_active = ss.is_multiplex_active()
+ ss.set_multiplex_active(True)
+ try:
+ with _profile_runtime_scope(prof):
+ assert pairing._read_allowlist_env("DISCORD_ALLOWED_USERS") == ""
+ pairing._sync_allowlist_add("discord", "111")
+ finally:
+ ss.set_multiplex_active(was_active)
+
+ assert (prof / ".env").read_text().strip() == "OTHER_KEY=x"
+ assert os.environ["DISCORD_ALLOWED_USERS"] == "default-admin"
diff --git a/tests/gateway/test_proxy_mode.py b/tests/gateway/test_proxy_mode.py
index 5a7f107f059..d5979343191 100644
--- a/tests/gateway/test_proxy_mode.py
+++ b/tests/gateway/test_proxy_mode.py
@@ -109,6 +109,38 @@ class TestGetProxyUrl:
assert runner._get_proxy_url() == "http://10.0.0.1:8642"
+class _SelectiveScope(dict):
+ """Bound scope that resolves GATEWAY_PROXY_URL but fails on the KEY read."""
+ def get(self, name, default=None):
+ if name == "GATEWAY_PROXY_URL":
+ return "http://proxy.local:8642"
+ if name == "GATEWAY_PROXY_KEY":
+ raise RuntimeError("resolver boom")
+ return dict.get(self, name, default)
+
+
+class TestProxyKeyScopeFailure:
+ """The proxy key read must propagate a bound-scope failure -- the ambient env
+ may hold another profile's credential (pre-fix: ``except Exception -> os.getenv``)."""
+
+ @pytest.mark.asyncio
+ async def test_proxy_key_scope_failure_never_borrows_env(self, monkeypatch):
+ from agent import secret_scope as ss
+
+ monkeypatch.setenv("GATEWAY_PROXY_KEY", "foreign-key")
+ runner = _make_runner()
+ runner._run_still_current_fn = lambda *a, **k: True
+
+ ss.set_multiplex_active(True)
+ token = ss.set_secret_scope(_SelectiveScope())
+ try:
+ with pytest.raises(RuntimeError, match="resolver boom"):
+ await runner._run_agent_via_proxy("hi", "ctx", [], _make_source(), "sess-1")
+ finally:
+ ss.reset_secret_scope(token)
+ ss.set_multiplex_active(False)
+
+
class TestResolveProxyUrl:
def test_no_proxy_bypasses_matching_host(self, monkeypatch):
diff --git a/tests/gateway/test_session.py b/tests/gateway/test_session.py
index 4f7f1f89ba0..d30f62c4d73 100644
--- a/tests/gateway/test_session.py
+++ b/tests/gateway/test_session.py
@@ -100,6 +100,30 @@ class TestBuildSessionContextPrompt:
+ def test_slack_tools_loaded_scope_failure_fails_closed(self, monkeypatch):
+ """A bound scope whose SLACK_BOT_TOKEN read fails must fail closed --
+ never borrow the ambient env token (another profile's). Pre-fix the
+ ``except Exception -> os.environ`` tail returned True here."""
+ from unittest.mock import patch
+ from agent import secret_scope as ss
+ from gateway.session import _slack_tools_loaded
+
+ class _ExplodingScope(dict):
+ def get(self, name, default=None):
+ raise RuntimeError("resolver boom")
+
+ monkeypatch.setenv("SLACK_BOT_TOKEN", "xoxb-foreign")
+ ss.set_multiplex_active(True)
+ token = ss.set_secret_scope(_ExplodingScope())
+ try:
+ with patch("tools.mcp_tool_discovery.get_registered_mcp_server_names", return_value=[]), \
+ patch("hermes_cli.config.load_config", return_value={}), \
+ patch("hermes_cli.tools_config._get_platform_tools", return_value=["slack"]):
+ assert _slack_tools_loaded() is False
+ finally:
+ ss.reset_secret_scope(token)
+ ss.set_multiplex_active(False)
+
def test_slack_tools_loaded_detects_real_mcp_registration(self):
"""Regression (review of #63234): a connected MCP server whose tools
are ACTUALLY registered in the live registry must be detected as
diff --git a/tests/hermes_cli/test_audio_router_scope.py b/tests/hermes_cli/test_audio_router_scope.py
new file mode 100644
index 00000000000..ed4db75c170
--- /dev/null
+++ b/tests/hermes_cli/test_audio_router_scope.py
@@ -0,0 +1,58 @@
+"""Scope-isolation regression for the ElevenLabs voices route's env fallback.
+
+``get_elevenlabs_voices`` reads ``ELEVENLABS_API_KEY`` through the secret scope
+when ``.env`` has no key. A bound scope whose read fails must leave the route
+unavailable -- never borrow the ambient ``os.environ`` key (another profile's
+under multiplex). Only the unscoped default-profile path (UnscopedSecretError)
+may read the env.
+"""
+
+import pytest
+
+
[email protected](autouse=True)
+def _restore_process_scope_state():
+ """``_config_profile_scope``/``launch_secret_scope`` can freeze the launch-env
+ snapshot (one-way process state); restore it so sibling suites are unaffected."""
+ import agent.secret_scope as secret_scope
+ from tui_gateway import launch_profile_policy
+
+ was_active = secret_scope.is_multiplex_active()
+ snapshot = launch_profile_policy._snapshot
+ try:
+ yield
+ finally:
+ secret_scope.set_multiplex_active(was_active)
+ launch_profile_policy._snapshot = snapshot
+
+
+class _ExplodingScope(dict):
+ """A bound secret scope whose resolution fails (resolver/backend error)."""
+ def get(self, name, default=None):
+ raise RuntimeError("resolver boom")
+
+
+async def test_voices_route_scope_failure_never_borrows_env(tmp_path, monkeypatch):
+ from agent import secret_scope as ss
+ from hermes_cli.web_routers.audio import get_elevenlabs_voices
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ (tmp_path / ".hermes").mkdir()
+ monkeypatch.setenv("ELEVENLABS_API_KEY", "sk-foreign-profile")
+
+ def _urlopen(*a, **k):
+ raise AssertionError("network must not be reached without a key")
+
+ monkeypatch.setattr("urllib.request.urlopen", _urlopen)
+
+ was_active = ss.is_multiplex_active()
+ ss.set_multiplex_active(True)
+ token = ss.set_secret_scope(_ExplodingScope())
+ try:
+ result = await get_elevenlabs_voices()
+ finally:
+ ss.reset_secret_scope(token)
+ ss.set_multiplex_active(was_active)
+
+ assert result == {"available": False, "voices": []}
diff --git a/tools/managed_tool_gateway.py b/tools/managed_tool_gateway.py
index ff45545e04a..3406c22dbc9 100644
--- a/tools/managed_tool_gateway.py
+++ b/tools/managed_tool_gateway.py
@@ -79,15 +79,14 @@ def _access_token_is_expiring(expires_at: object, skew_seconds: int) -> bool:
def _read_user_token_override() -> Optional[str]:
"""Read the TOOL_GATEWAY_USER_TOKEN override through the secret scope. Scope verdict is authoritative
- when installed (a scoped miss must NOT borrow the process env under multiplex); ``os.environ`` only when unscoped."""
- try:
- from agent.secret_scope import UnscopedSecretError, get_secret
+ when installed (a scoped miss must NOT borrow the process env under multiplex); ``os.environ`` only
+ when unscoped. Any non-UnscopedSecretError failure propagates -- a failed scoped read must never
+ silently borrow the ambient env."""
+ from agent.secret_scope import UnscopedSecretError, get_secret
- try:
- explicit = get_secret("TOOL_GATEWAY_USER_TOKEN")
- except UnscopedSecretError:
- explicit = os.getenv("TOOL_GATEWAY_USER_TOKEN")
- except Exception:
+ try:
+ explicit = get_secret("TOOL_GATEWAY_USER_TOKEN")
+ except UnscopedSecretError:
explicit = os.getenv("TOOL_GATEWAY_USER_TOKEN")
return _clean(explicit)
diff --git a/tools/openrouter_client.py b/tools/openrouter_client.py
index 9037f3ab0df..1f49c812fdd 100644
--- a/tools/openrouter_client.py
+++ b/tools/openrouter_client.py
@@ -7,17 +7,16 @@ def check_api_key() -> bool:
"""Return True if OPENROUTER_API_KEY is present.
Scope-aware: an installed profile secret scope is authoritative under
- multiplex; unscoped CLI probes fall back to the plain env read.
+ multiplex; unscoped CLI probes fall back to the plain env read. Any other
+ scope failure propagates -- a failed scoped read must never silently
+ borrow another profile's key from ``os.environ``.
"""
+ from agent.secret_scope import UnscopedSecretError, get_secret
+
try:
- from agent.secret_scope import UnscopedSecretError, get_secret
- try:
- return bool(get_secret("OPENROUTER_API_KEY"))
- except UnscopedSecretError:
- pass
- except Exception:
- pass
- return bool(os.getenv("OPENROUTER_API_KEY"))
+ return bool(get_secret("OPENROUTER_API_KEY"))
+ except UnscopedSecretError:
+ return bool(os.getenv("OPENROUTER_API_KEY"))
# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----