Skip to content

The agent that grows with you

fix(plugins): tighten plugin OAuth clients after review

Ilya Balobanov0d8005121e08
diff --git a/hermes_cli/plugin_oauth.py b/hermes_cli/plugin_oauth.py
index a0d71888599..3dc92580723 100644
--- a/hermes_cli/plugin_oauth.py
+++ b/hermes_cli/plugin_oauth.py
@@ -57,10 +57,23 @@ class OAuthClient:
# ── Manifest ───────────────────────────────────────────────────────────────────────────────────────
+def _parse_url(url: Any):
+ """``urlparse`` of *url*; None for a non-string or a URL it cannot read (bad IPv6 literal or port)."""
+ if not isinstance(url, str):
+ return None
+ try:
+ parsed = urlparse(url)
+ _ = parsed.port # urlparse checks the port only when it is read
+ except ValueError:
+ return None
+ return parsed
+
+
def _url_problems(where: str, url: Any) -> list[str]:
- parsed = urlparse(url) if isinstance(url, str) else None
- if parsed is None or not parsed.hostname or parsed.username is not None or parsed.password is not None:
- return [f"{where}: must be an absolute URL without user info"]
+ parsed = _parse_url(url)
+ if (parsed is None or not parsed.hostname or parsed.username is not None or parsed.password is not None
+ or parsed.fragment):
+ return [f"{where}: must be an absolute URL without user info or fragment"]
if parsed.scheme != "https" and not (parsed.scheme == "http" and parsed.hostname in _LOOPBACK_LITERALS):
return [f"{where}: must use https (plain http only for a loopback address)"]
return []
@@ -98,7 +111,7 @@ def _client(entry: dict) -> OAuthClient:
def parse_oauth_clients(manifest: Mapping[str, Any]) -> tuple[list[OAuthClient], list[str]]:
"""``oauth:`` from a manifest dict: the well-formed clients, and one problem string per defect."""
raw = (manifest or {}).get("oauth")
- if raw in (None, [], {}):
+ if raw is None or raw == []:
return [], []
if not isinstance(raw, list):
return [], ["oauth: must be a list of client entries"]
@@ -184,7 +197,7 @@ def token_url_mentions(manifest: Mapping[str, Any], plugin_dir: Path) -> list[st
warnings: list[str] = []
for path in sorted(plugin_dir.rglob("*.py")):
try:
- text = path.read_text(encoding="utf-8", errors="replace")
+ text = path.read_text(encoding="utf-8-sig", errors="replace")
except OSError:
continue
warnings += [f"oauth: {path.relative_to(plugin_dir).as_posix()} names the token URL {url}; Hermes "
@@ -278,7 +291,7 @@ def _token_request(client: OAuthClient, key: str) -> Callable[[dict[str, str]],
except httpx.HTTPError as exc:
raise _auth_error(key, f"the token request failed ({type(exc).__name__}).", "oauth_refresh_failed") from None
payload = _json_object(response)
- if response.status_code >= 400:
+ if not 200 <= response.status_code < 300: # a redirect is a failure too: it is never followed
raise _token_error(key, response.status_code, payload)
if fields.get("grant_type") == "authorization_code":
_require_granted_scopes(client, payload, key)
@@ -365,8 +378,11 @@ def _bearer(plugin_dir: Path, client: OAuthClient) -> str:
return _live_token(row) or _refresh(client, key, row)
-def plugin_oauth_spec(plugin_dir: Path, provider: str):
- """``(origins, resolver)`` for *provider* when the calling plugin declares it under ``oauth:``, else None."""
+def _plugin_oauth_spec(plugin_dir: Path, provider: str):
+ """``(origins, resolver)`` for *provider* when the calling plugin declares it under ``oauth:``, else None.
+
+ Core-only, like the ``_PROVIDERS`` resolvers: the resolver returns the bearer, so plugins go through
+ ``credentialed_provider_request``, which attributes the caller and checks the origin first."""
client = next((c for c in _declared_clients(plugin_dir) if c.id == provider), None)
if client is None:
return None
@@ -473,5 +489,5 @@ def handle_auth_action(action: str, args: Any, provider: str) -> Optional[bool]:
__all__ = [
"OAuthClient", "handle_auth_action", "oauth_admission_problems", "oauth_notice", "oauth_surface",
- "parse_oauth_clients", "plugin_key", "plugin_oauth_spec", "token_url_mentions",
+ "parse_oauth_clients", "plugin_key", "token_url_mentions",
]
diff --git a/hermes_cli/plugin_provider_requests.py b/hermes_cli/plugin_provider_requests.py
index 89ac04fd7de..2096b3f76bb 100644
--- a/hermes_cli/plugin_provider_requests.py
+++ b/hermes_cli/plugin_provider_requests.py
@@ -138,13 +138,13 @@ def credentialed_provider_request(
allowlist; raises :class:`ProviderNotSignedIn` when this profile has no sign-in. Redirects are
returned as-is, never followed. The result carries no credential.
"""
- from hermes_cli.plugin_oauth import plugin_oauth_spec
+ from hermes_cli.plugin_oauth import _plugin_oauth_spec
plugin_dir = _calling_plugin_dir()
if plugin_dir is None:
raise PermissionError("credentialed_provider_request must be called from an installed plugin's code")
# The plugin's own oauth: entry first, so a core provider added later under the same id cannot take it over.
- spec = plugin_oauth_spec(plugin_dir, provider)
+ spec = _plugin_oauth_spec(plugin_dir, provider)
if spec is None:
spec = _PROVIDERS.get(provider)
if spec is None:
diff --git a/hermes_cli/plugin_validate.py b/hermes_cli/plugin_validate.py
index a6c8d33f289..9b8448b8f7a 100644
--- a/hermes_cli/plugin_validate.py
+++ b/hermes_cli/plugin_validate.py
@@ -190,7 +190,7 @@ def _check_oauth(report: ValidationReport, manifest: dict, plugin_dir: Path) ->
code that names a token URL is a reviewer warning, since Hermes refreshes the grant itself."""
from hermes_cli.plugin_oauth import oauth_admission_problems, token_url_mentions
- if not manifest.get("oauth"):
+ if manifest.get("oauth") in (None, []):
report.add("oauth", True, "not declared")
return
problems = oauth_admission_problems(manifest, plugin_dir)
diff --git a/tests/hermes_cli/test_plugin_oauth.py b/tests/hermes_cli/test_plugin_oauth.py
index 828a98d5fe6..6b54e991a72 100644
--- a/tests/hermes_cli/test_plugin_oauth.py
+++ b/tests/hermes_cli/test_plugin_oauth.py
@@ -75,11 +75,12 @@ def _entry(idp: FakeIdP, **overrides) -> dict:
return {**entry, **overrides}
-def _plugin(name: str = "voice", oauth: list | None = None):
- """Write ``plugins/<name>`` (manifest plus a module that calls the helper) and import it like a plugin."""
+def _plugin(name: str = "voice", oauth: list | None = None, display: str | None = None):
+ """Write ``plugins/<name>`` (manifest plus a module that calls the helper) and import it like a plugin.
+ *display* is a manifest ``name`` other than the directory."""
root = _home() / "plugins" / name
root.mkdir(parents=True, exist_ok=True)
- manifest = {"name": name, "version": "1.0.0", "description": "test plugin",
+ manifest = {"name": display or name, "version": "1.0.0", "description": "test plugin",
"requires_env": [{"name": "VOICE_CLIENT_ID"}, {"name": "VOICE_CLIENT_SECRET"}]}
if oauth is not None:
manifest["oauth"] = oauth
@@ -254,6 +255,40 @@ def test_expiring_token_is_refreshed_once_and_the_rotation_kept(idp, api):
assert [s["headers"]["Authorization"] for s in allowed.seen] == [f"Bearer {grant['access_token']}"] * 2
+def test_refresh_without_a_new_refresh_token_keeps_the_old_one(idp, api):
+ """Google answers a refresh with an access token only; the stored refresh token must survive it."""
+ allowed, _ = api
+ plugin = _signed_in(idp)
+ old_refresh = _grant()["refresh_token"]
+ _set_grant(expires_at_ms=0)
+ idp.token_answer = (200, {"access_token": "at-google-style", "expires_in": 3599, "token_type": "Bearer"})
+
+ assert plugin.call("google", allowed.url).status == 200
+
+ grant = _grant()
+ assert (grant["access_token"], grant["refresh_token"]) == ("at-google-style", old_refresh)
+ assert allowed.seen[-1]["headers"]["Authorization"] == "Bearer at-google-style"
+
+
+def test_a_redirect_from_the_token_endpoint_is_a_failure_not_a_token(idp, api):
+ allowed, _ = api
+ redirect = (302, {"access_token": "at-from-a-redirect", "refresh_token": "rt-x", "expires_in": 3600})
+ _plugin(oauth=[_entry(idp)])
+ idp.token_answer = redirect
+ with pytest.raises(SystemExit, match="HTTP 302"):
+ _auth("add")
+ assert not (_home() / "auth.json").exists() or _grant() is None
+
+ idp.token_answer = None
+ plugin = _signed_in(idp)
+ _set_grant(expires_at_ms=0)
+ before = _grant()
+ idp.token_answer = redirect
+ with pytest.raises(AuthError) as excinfo:
+ plugin.call("google", allowed.url)
+ assert excinfo.value.code == "oauth_refresh_failed" and _grant() == before and allowed.seen == []
+
+
def test_two_threads_with_an_expiring_token_refresh_once(idp, api):
allowed, _ = api
plugin = _signed_in(idp)
@@ -309,7 +344,7 @@ def test_rejected_client_is_an_auth_error_that_leaves_the_grant(idp, api):
allowed, _ = api
plugin = _signed_in(idp)
_set_grant(expires_at_ms=0)
- idp.token_error = (401, {"error": "invalid_client", "error_description": "The OAuth client was not found."})
+ idp.token_answer = (401, {"error": "invalid_client", "error_description": "The OAuth client was not found."})
for _ in range(2):
with pytest.raises(AuthError) as excinfo:
plugin.call("google", allowed.url)
@@ -334,6 +369,9 @@ def test_missing_client_env_fails_before_any_request(idp, api, monkeypatch):
{"hosts": ["api.example.com", "collect.example.net"]},
{"scopes": SCOPES[:1]},
{"client_id_env": "OTHER_CLIENT_ID"},
+ {"client_secret_env": "OTHER_CLIENT_SECRET"},
+ {"authorize_url": "https://login.example.net/authorize"},
+ {"authorize_params": {"access_type": "online"}},
])
def test_entry_changed_since_sign_in_is_not_used(idp, api, change):
allowed, _ = api
@@ -373,7 +411,7 @@ def test_client_secret_stays_out_of_config_repr_logs_and_errors(idp, api, caplog
assert SECRET not in repr(plugin_oauth._pkce_config(client, KEY))
_set_grant(expires_at_ms=0)
- idp.token_error = (500, {"error": "server_error", "error_description": SECRET})
+ idp.token_answer = (500, {"error": "server_error", "error_description": SECRET})
with pytest.raises(AuthError) as excinfo:
plugin.call("google", allowed.url)
out = capsys.readouterr()
@@ -407,6 +445,17 @@ def test_install_notice_and_repin_delta_name_the_oauth_entry(idp, tmp_path):
assert len(lines) == 1 and lines[0].startswith("your OAuth sign-in for") and "collect.example.net" in lines[0]
+def test_the_notice_command_finds_a_plugin_whose_name_differs_from_its_directory(idp, api):
+ allowed, _ = api
+ plugin = _plugin("voice-dir", oauth=[_entry(idp)], display="gemini-voice")
+ manifest = json.loads((_home() / "plugins" / "voice-dir" / "plugin.yaml").read_text(encoding="utf-8"))
+ assert "hermes auth add gemini-voice:google" in ppr.requires_auth_notice(manifest)
+
+ assert _auth("add", "gemini-voice:google") is True
+ assert _grant("voice-dir:google")["refresh_token"] in idp.refresh_tokens
+ assert plugin.call("google", allowed.url).status == 200
+
+
def test_hermes_auth_commands_route_a_plugin_grant(idp, capsys):
from hermes_cli import auth_commands
diff --git a/tests/hermes_cli/test_plugin_validate.py b/tests/hermes_cli/test_plugin_validate.py
index cbdb0f2d4f3..84e52375908 100644
--- a/tests/hermes_cli/test_plugin_validate.py
+++ b/tests/hermes_cli/test_plugin_validate.py
@@ -539,6 +539,9 @@ def test_oauth_block_passes_and_a_token_url_in_code_is_only_a_warning(tmp_path):
@pytest.mark.parametrize("change, problem", [
({"id": "Google"}, "id"),
({"authorize_url": "http://accounts.example.com/o/oauth2/auth"}, "authorize_url"),
+ ({"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"),
({"scopes": []}, "scopes"),
({"hosts": ["https://docs.example.com"]}, "hosts"),
({"hosts": ["docs.example.com:8443"]}, "hosts"),
@@ -556,6 +559,15 @@ def test_oauth_form_errors_fail_admission(tmp_path, change, problem):
assert any(problem in failure for failure in report.failures), report.failures
+def test_oauth_given_as_a_mapping_fails_admission(tmp_path):
+ plugin = _make_plugin(tmp_path, manifest=dict(OAUTH_MANIFEST, oauth={}))
+
+ report = validate_plugin_dir(plugin)
+
+ assert [ok for name, ok, _ in report.checks if name == "oauth"] == [False]
+ assert any("must be a list" in failure for failure in report.failures), report.failures
+
+
def test_oauth_in_a_plugin_keyed_custom_fails_admission(tmp_path):
plugin = _make_plugin(tmp_path, manifest=dict(OAUTH_MANIFEST, name="custom", oauth=[_oauth_entry()]))
diff --git a/tests/providers/fake_pkce_idp.py b/tests/providers/fake_pkce_idp.py
index 73893698308..1d281545669 100644
--- a/tests/providers/fake_pkce_idp.py
+++ b/tests/providers/fake_pkce_idp.py
@@ -46,8 +46,8 @@ class FakeIdP:
body = parse_qs(self.rfile.read(int(self.headers.get("Content-Length", 0))).decode())
form = {k: v[0] for k, v in body.items()}
idp.token_requests.append(form)
- if idp.token_error is not None:
- return self._json(*idp.token_error)
+ if idp.token_answer is not None:
+ return self._json(*idp.token_answer)
grant = form.get("grant_type")
if grant == "authorization_code":
challenge = idp.codes.pop(form.get("code", ""), None)
@@ -79,7 +79,7 @@ class FakeIdP:
self.override_state: str | None = None
self.granted_scope: str | None = None # ``scope`` echoed in token responses (None = omitted)
- self.token_error: tuple[int, dict] | None = None # (status, JSON) answered to every token POST
+ self.token_answer: tuple[int, dict] | None = None # (status, JSON) answered to every token POST instead
self.server = HTTPServer(("127.0.0.1", 0), Handler)
self.base = f"http://127.0.0.1:{self.server.server_address[1]}"
self._thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True)