Skip to content

The agent that grows with you

fix(plugins): plugin OAuth grants are dropped on revoke and uninstall; sign-in needs a person

Tekniumbe46373c5b04
diff --git a/hermes_cli/plugin_oauth.py b/hermes_cli/plugin_oauth.py
index 690446466b1..467bd535aea 100644
--- a/hermes_cli/plugin_oauth.py
+++ b/hermes_cli/plugin_oauth.py
@@ -239,6 +239,20 @@ def _read_grant(key: str) -> Optional[dict]:
return dict(row) if isinstance(row, dict) else None
+def forget_plugin_grants(plugin: str) -> None:
+ """Drop every grant of plugin key *plugin* from the active profile (``hermes plugins remove``)."""
+ from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store
+
+ with _auth_store_lock():
+ store = _load_auth_store()
+ section = store.get(_SECTION)
+ stale = [k for k in section if k.rsplit(":", 1)[0] == plugin] if isinstance(section, dict) else []
+ if stale:
+ for key in stale:
+ section.pop(key)
+ _save_auth_store(store)
+
+
def _write_grant(key: str, row: Optional[dict]) -> None:
"""Replace one grant (``None`` removes it) under the auth-store lock; other sections stay as they are."""
from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store, _store_section
@@ -384,7 +398,7 @@ def _refresh(client: OAuthClient, key: str, row: dict) -> str:
{"grant_type": "refresh_token", "refresh_token": refresh_token}, code="oauth_refresh_failed")
except AuthError as exc:
if exc.code in _OAUTH_GRANT_DEAD_CODES:
- _write_grant(key, {**row, "dead": exc.code})
+ _write_grant(key, {"dead": exc.code, "fingerprint": row.get("fingerprint")}) # keep no dead tokens
raise _revoked(client, key, str(exc.code)) from None
raise
_write_grant(key, {**row, **fields})
@@ -443,10 +457,23 @@ def _installed_client(plugin: str, oauth_id: str) -> Optional[tuple[Path, OAuthC
return (plugin_dir, client) if client is not None else None
+def _unattended() -> bool:
+ from tools.approval_context import _is_gateway_approval_context, _no_user_can_answer
+
+ return _no_user_can_answer() or _is_gateway_approval_context()
+
+
def _cli_add(args: Any, client: OAuthClient, key: str) -> bool:
from hermes_cli.auth_constants import AuthError
from hermes_cli.auth_oauth_pkce_plugin import login
+ if _unattended():
+ raise SystemExit(f"`hermes auth add {key}` signs you in through a browser; run it in your own terminal, "
+ "not from a gateway, cron job or agent session.")
+ secret = " and the client secret" if client.client_secret_env else ""
+ print(f"Plugin '{key.rsplit(':', 1)[0]}' signs in to {client.id} at {urlparse(client.authorize_url).hostname}. "
+ f"The sign-in code{secret} go to {urlparse(client.token_url).hostname}; the token is sent only to "
+ f"{', '.join(client.hosts)}.")
try:
fields = login(key, _pkce_config(client, key, timeout=getattr(args, "timeout", None)),
open_browser=not getattr(args, "no_browser", False))
@@ -508,6 +535,10 @@ def handle_auth_action(action: str, args: Any, provider: str) -> Optional[bool]:
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
@@ -515,6 +546,6 @@ def handle_auth_action(action: str, args: Any, provider: str) -> Optional[bool]:
__all__ = [
- "OAuthClient", "handle_auth_action", "oauth_admission_problems", "oauth_admission_warnings",
- "oauth_notice", "oauth_surface", "parse_oauth_clients", "plugin_key",
+ "OAuthClient", "forget_plugin_grants", "handle_auth_action", "oauth_admission_problems",
+ "oauth_admission_warnings", "oauth_notice", "oauth_surface", "parse_oauth_clients", "plugin_key",
]
diff --git a/hermes_cli/plugins_cmd_remove.py b/hermes_cli/plugins_cmd_remove.py
index 4bcdccf844b..7c0cbf7c6ba 100644
--- a/hermes_cli/plugins_cmd_remove.py
+++ b/hermes_cli/plugins_cmd_remove.py
@@ -135,6 +135,8 @@ def _remove_user_plugin(plugins_dir: Path, name: str, target: Path) -> dict[str,
aliases = _pc()._plugin_aliases(key) | {target.name}
_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
return {"ok": True, "name": name, **_pc()._forget_plugin_config(aliases)}
diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.md
index a1c5f7a135c..dc1c04fcf05 100644
--- a/website/docs/developer-guide/plugins/index.md
+++ b/website/docs/developer-guide/plugins/index.md
@@ -521,9 +521,16 @@ def create_document(title: str) -> dict:
The Codex rules above apply, plus:
+- **HTTPS only.** `authorize_url`, `token_url` and every `hosts` entry are
+ `https` (there is no loopback exception); `hermes plugins validate` and
+ catalog admission fail anything else.
- **Declared hosts only.** The bearer goes to `https://<host>` (port 443) for
- the entry's `hosts`. Any other URL, `http`, or a URL with user info raises
- `PermissionError` before a request is made.
+ the entry's `hosts`, matched exactly (no subdomains). Any other URL, `http`,
+ or a URL with user info raises `PermissionError` before a request is made.
+ A host outside the sign-in provider's domains is a warning reviewers check.
+- **Your own client variables.** `client_id_env` and `client_secret_env` name
+ the plugin's own variables; a variable Hermes itself uses (a provider API key,
+ a platform token) is refused, since Hermes sends these to `token_url`.
- **The plugin's own grant.** The grant is stored under the calling plugin's
key, so another plugin declaring the same `id` cannot use it, and the plugin's
own entry wins over a Hermes sign-in of the same name.
@@ -538,7 +545,14 @@ The Codex rules above apply, plus:
`unauthorized_client` and `invalid_scope` (the IdP rejected the client; the
user has to fix it), `oauth_refresh_failed` (network or server error; try
later). A revoked grant (`invalid_grant`) is retired: nothing goes to the
- network until the next sign-in.
+ network until the next sign-in. Errors reach the plugin without a traceback,
+ chain or request object, so none leads back to the token, refresh token or
+ client secret.
+- **Sign-in and removal.** `hermes auth add` prints which hosts get the code,
+ the client secret and the token before opening the browser, and refuses to
+ run from the gateway, cron or an agent session. `hermes plugins remove` drops
+ the plugin's grants, and `hermes auth logout <plugin>:<id>` still works after
+ the plugin is gone.
`hermes plugins validate` checks the `oauth:` block and that its client
variables are declared, and warns when plugin code names the token URL. Like