Skip to content

The agent that grows with you

fix(plugins): close the review gaps in plugin OAuth cleanup and error scrubbing

Teknium5dc648c2afda
diff --git a/hermes_cli/plugin_oauth.py b/hermes_cli/plugin_oauth.py
index 467bd535aea..56688593c8b 100644
--- a/hermes_cli/plugin_oauth.py
+++ b/hermes_cli/plugin_oauth.py
@@ -79,16 +79,17 @@ def _url_problems(where: str, url: Any) -> list[str]:
def _hermes_owned_env(name: str) -> bool:
- """A variable Hermes itself reads (a provider key, a platform token): never a plugin's client variable,
+ """A variable Hermes itself reads (a provider key, a platform secret): never a plugin's client variable,
or a manifest could have Hermes POST that secret to the token URL it names."""
from hermes_cli.auth import PROVIDER_REGISTRY
- from hermes_cli.config_defaults import OPTIONAL_ENV_VARS
+ from hermes_cli.config_env_routing import is_registered_env_name
- return name in OPTIONAL_ENV_VARS or any(name in p.api_key_env_vars for p in PROVIDER_REGISTRY.values())
+ return is_registered_env_name(name) or any(name in p.api_key_env_vars for p in PROVIDER_REGISTRY.values())
def _entry_problems(entry: dict, where: str) -> list[str]:
- problems = [] if _ID_RE.match(str(entry.get("id") or "")) else [
+ oauth_id = entry.get("id")
+ problems = [] if isinstance(oauth_id, str) and _ID_RE.match(oauth_id) else [
f"{where}.id: {entry.get('id')!r} must be lowercase letters, digits and dashes"]
for field in ("authorize_url", "token_url"):
problems += _url_problems(f"{where}.{field}", entry.get(field))
@@ -208,7 +209,10 @@ def oauth_admission_problems(manifest: Mapping[str, Any], plugin_dir: Path) -> l
def _parent(host: str) -> str:
- return ".".join(host.split(".")[-2:])
+ """Registered domain, roughly: ``vendor.co.uk`` keeps three labels (no public-suffix list in core)."""
+ labels = host.split(".")
+ keep = 3 if len(labels) > 2 and len(labels[-1]) == 2 and len(labels[-2]) <= 3 else 2
+ return ".".join(labels[-keep:])
def oauth_admission_warnings(manifest: Mapping[str, Any], plugin_dir: Path) -> list[str]:
@@ -521,6 +525,15 @@ def _cli_logout(args: Any, client: OAuthClient, key: str) -> bool:
return True
+def _logout_key(plugin: str, oauth_id: str) -> Optional[str]:
+ """The stored grant key ``hermes auth logout <plugin>:<id>`` means, without parsing the manifest."""
+ from hermes_cli.plugins_cmd import _find_plugin_entry
+
+ entry = _find_plugin_entry(plugin)
+ names = [f"{plugin_key(Path(str(entry[4])))}:{oauth_id}"] if entry is not None and entry[4] else []
+ return next((key for key in (*names, f"{plugin}:{oauth_id}") if _read_grant(key) is not None), None)
+
+
_CLI_ACTIONS = {"add": _cli_add, "status": _cli_status, "refresh": _cli_refresh, "logout": _cli_logout}
@@ -531,14 +544,14 @@ def handle_auth_action(action: str, args: Any, provider: str) -> Optional[bool]:
handler = _CLI_ACTIONS.get(action)
if handler is None or not (sep and plugin and oauth_id) or plugin == "custom":
return None
+ if action == "logout" and (key := _logout_key(plugin, oauth_id)) is not None:
+ _write_grant(key, None) # needs no valid oauth: entry: the plugin may be gone or its manifest broken
+ print(f"Signed out of {key}; the grant was removed from this profile.")
+ return True
try:
found = _installed_client(plugin, oauth_id)
except ValueError as exc:
raise SystemExit(str(exc)) from None
- if found is None and action == "logout" and _read_grant(provider) is not None:
- _write_grant(provider, None) # the plugin is gone; its grant still goes
- print(f"Signed out of {provider}; the grant was removed from this profile.")
- return True
if found is None:
return None
plugin_dir, client = found
diff --git a/hermes_cli/plugin_provider_requests.py b/hermes_cli/plugin_provider_requests.py
index 0f3bc4745d0..46fbc65b994 100644
--- a/hermes_cli/plugin_provider_requests.py
+++ b/hermes_cli/plugin_provider_requests.py
@@ -171,6 +171,8 @@ def credentialed_provider_request(
request = client.build_request(method, url, json=json, headers=dict(headers or {})) # no credential yet
try:
auth_headers, credential_base = resolve(url)
+ except httpx.HTTPError as exc: # a resolver's own refresh POST failed: its request holds the refresh token
+ refusal = type(exc)(str(exc))
except (RuntimeError, OSError, ValueError, LookupError, TypeError) as exc:
refusal = _detached(exc)
else:
diff --git a/hermes_cli/plugins_cmd_remove.py b/hermes_cli/plugins_cmd_remove.py
index 7c0cbf7c6ba..e3b53a733f3 100644
--- a/hermes_cli/plugins_cmd_remove.py
+++ b/hermes_cli/plugins_cmd_remove.py
@@ -133,10 +133,11 @@ def _remove_user_plugin(plugins_dir: Path, name: str, target: Path) -> dict[str,
entry = next((e for e in _pc()._discover_all_plugins() if Path(str(e[4])) == target), None)
key = entry[5] if entry else target.name
aliases = _pc()._plugin_aliases(key) | {target.name}
+ from hermes_cli.plugin_oauth import forget_plugin_grants, plugin_key
+ grant_key = plugin_key(target) # grants are stored by directory key, which the manifest name may not match
_pc()._toggle_plugin_toolset(key, enable=False)
_remove_plugin_core(target)
- from hermes_cli.plugin_oauth import forget_plugin_grants
- forget_plugin_grants(key) # a later plugin installed under the same key must not inherit the sign-in
+ forget_plugin_grants(grant_key) # a later plugin installed under the same key must not inherit the sign-in
return {"ok": True, "name": name, **_pc()._forget_plugin_config(aliases)}
diff --git a/tests/hermes_cli/test_plugin_oauth.py b/tests/hermes_cli/test_plugin_oauth.py
index e6248176e6c..2c1f984546f 100644
--- a/tests/hermes_cli/test_plugin_oauth.py
+++ b/tests/hermes_cli/test_plugin_oauth.py
@@ -511,6 +511,23 @@ def test_errors_raised_to_the_plugin_carry_no_token_refresh_token_or_secret(idp,
text = _reachable_text(exc)
assert refresh not in text and SECRET not in text
+ import httpx # a core resolver (Codex) whose own refresh POST fails raises httpx with that request attached
+
+ def resolver(url):
+ httpx.post(f"http://127.0.0.1:{allowed.origin[2]}/token", data={"refresh_token": "rt-core-canary"}, timeout=2)
+
+ _ppr_providers = dict(ppr._PROVIDERS)
+ ppr._PROVIDERS["core-x"] = (frozenset({allowed.origin}), resolver)
+ try:
+ bare = _plugin("bare-core")
+ (_home() / "plugins" / "bare-core" / "plugin.yaml").write_text(json.dumps(
+ {"name": "bare-core", "version": "1", "requires_auth": ["core-x"]}), encoding="utf-8")
+ exc = _caught(lambda: bare.call("core-x", allowed.url + "/v1"))
+ finally:
+ ppr._PROVIDERS.clear()
+ ppr._PROVIDERS.update(_ppr_providers)
+ assert type(exc).__name__ == "ConnectError" and "rt-core-canary" not in _reachable_text(exc)
+
def _caught(fn) -> BaseException:
try:
@@ -531,9 +548,19 @@ def test_revoked_grant_keeps_no_tokens_and_uninstall_drops_the_grant(idp, api):
from hermes_cli.plugins_cmd_remove import _remove_user_plugin
+ # Broken manifest after sign-in: logout still removes the grant.
assert _auth("add") is True and _grant()["access_token"]
- _remove_user_plugin(_home() / "plugins", "voice", _home() / "plugins" / "voice")
- assert _grant() is None # a later plugin installed as "voice" does not inherit the sign-in
+ manifest = _home() / "plugins" / "voice" / "plugin.yaml"
+ good = manifest.read_text(encoding="utf-8-sig")
+ manifest.write_text(good.replace('"hosts": ["api.example.com"]', '"hosts": ["http://bad"]'), encoding="utf-8")
+ assert _auth("logout") is True and _grant() is None
+ manifest.write_text(good, encoding="utf-8")
+
+ # Uninstall drops the grant, also when the manifest name differs from the directory it is stored under.
+ _plugin("voice-dir", oauth=[_entry(idp)], display="gemini-voice")
+ assert _auth("add", "gemini-voice:google") is True and _grant("voice-dir:google")
+ _remove_user_plugin(_home() / "plugins", "gemini-voice", _home() / "plugins" / "voice-dir")
+ assert _grant("voice-dir:google") is None # a later plugin under that key does not inherit the sign-in
def test_sign_in_is_refused_where_nobody_can_answer_the_browser(idp, monkeypatch):
diff --git a/tests/hermes_cli/test_plugin_validate.py b/tests/hermes_cli/test_plugin_validate.py
index 84c543a0c5f..a2fddfe1d3e 100644
--- a/tests/hermes_cli/test_plugin_validate.py
+++ b/tests/hermes_cli/test_plugin_validate.py
@@ -547,6 +547,8 @@ def test_oauth_block_passes_and_a_token_url_in_code_is_only_a_warning(tmp_path):
({"token_url": "http://[::1]:8080/token"}, "must use https"),
({"client_secret_env": "OPENROUTER_API_KEY"}, "Hermes uses itself"), # would be POSTed to token_url
({"client_id_env": "TELEGRAM_BOT_TOKEN"}, "Hermes uses itself"),
+ ({"client_secret_env": "MATRIX_PASSWORD"}, "Hermes uses itself"), # platform secrets too
+ ({"id": 123}, "id"),
({"authorize_url": "https://accounts.example.com/o/oauth2/auth#consent"}, "authorize_url"),
({"token_url": "https://[oauth2.example.com/token"}, "token_url"),
({"token_url": "https://oauth2.example.com:https/token"}, "token_url"),