Skip to content

The agent that grows with you

test(plugins): plugin OAuth tests sign in over https and pin the review invariants

Teknium21f35e3f482e
diff --git a/tests/fakes/providers/oauth_token_server.py b/tests/fakes/providers/oauth_token_server.py
index e32207d535e..722918bedd6 100644
--- a/tests/fakes/providers/oauth_token_server.py
+++ b/tests/fakes/providers/oauth_token_server.py
@@ -298,8 +298,18 @@ class TestCA:
leaf_key: Path
+def _san(host: str):
+ import ipaddress
+
+ from cryptography import x509
+ try:
+ return x509.IPAddress(ipaddress.ip_address(host))
+ except ValueError:
+ return x509.DNSName(host)
+
+
def make_test_ca(directory: Path, hosts: Iterable[str]) -> TestCA:
- """Generate a CA and a leaf cert for ``hosts`` (SAN) under ``directory``."""
+ """Generate a CA and a leaf cert for ``hosts`` (DNS or IP SAN) under ``directory``."""
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
@@ -328,7 +338,7 @@ def make_test_ca(directory: Path, hosts: Iterable[str]) -> TestCA:
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, hosts[0])]))
.issuer_name(ca_name).public_key(leaf_key.public_key()).serial_number(x509.random_serial_number())
.not_valid_before(now - _dt.timedelta(minutes=5)).not_valid_after(now + _dt.timedelta(days=1))
- .add_extension(x509.SubjectAlternativeName([x509.DNSName(h) for h in hosts]), critical=False)
+ .add_extension(x509.SubjectAlternativeName([_san(h) for h in hosts]), critical=False)
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()), critical=False)
diff --git a/tests/hermes_cli/test_plugin_oauth.py b/tests/hermes_cli/test_plugin_oauth.py
index 5b8d32e0f1b..e6248176e6c 100644
--- a/tests/hermes_cli/test_plugin_oauth.py
+++ b/tests/hermes_cli/test_plugin_oauth.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import importlib.util
import json
import os
+import ssl
import threading
import time
from concurrent.futures import ThreadPoolExecutor
@@ -102,13 +103,13 @@ def _auth(action: str, provider: str = KEY):
def _grant(key: str = KEY) -> dict | None:
- store = json.loads((_home() / "auth.json").read_text(encoding="utf-8"))
+ store = json.loads((_home() / "auth.json").read_text(encoding="utf-8-sig"))
return (store.get("plugin_oauth") or {}).get(key)
def _set_grant(key: str = KEY, **fields) -> None:
path = _home() / "auth.json"
- store = json.loads(path.read_text(encoding="utf-8"))
+ store = json.loads(path.read_text(encoding="utf-8-sig"))
store["plugin_oauth"][key].update(fields)
path.write_text(json.dumps(store), encoding="utf-8")
@@ -118,16 +119,19 @@ def _refreshes(idp: FakeIdP) -> int:
@pytest.fixture
-def idp(monkeypatch):
+def idp(monkeypatch, tmp_path):
monkeypatch.setenv("VOICE_CLIENT_ID", CLIENT_ID)
monkeypatch.setenv("VOICE_CLIENT_SECRET", SECRET)
- server = FakeIdP().start()
+ server = FakeIdP().start(tls_dir=tmp_path / "idp-ca") # https: plugin OAuth endpoints are https-only
+ trust = ssl.create_default_context(cafile=str(server.ca_pem))
+ monkeypatch.setattr("hermes_cli.auth._default_verify", lambda: trust)
server.opened = []
def browser(url: str) -> bool:
+ # A real browser runs beside Hermes; the fake IdP 302s straight to the loopback callback.
server.opened.append(url)
- with urlopen(url, timeout=5) as response: # the fake IdP 302s straight to the loopback callback
- return response.status == 200
+ threading.Thread(target=lambda: urlopen(url, timeout=10, context=trust).close(), daemon=True).start()
+ return True
monkeypatch.setattr(pkce.webbrowser, "open", browser)
monkeypatch.setattr("hermes_cli.auth_device_flow._can_open_graphical_browser", lambda: True)
@@ -153,8 +157,11 @@ def _signed_in(idp: FakeIdP, **entry_overrides):
def test_sign_in_stores_the_grant_then_status_refresh_and_logout(idp, capsys):
+ from hermes_cli import auth_commands
+
_plugin(oauth=[_entry(idp)])
- assert _auth("add") is True
+ args = SimpleNamespace(provider=KEY, no_browser=False, timeout=None)
+ auth_commands.auth_add_command(args)
assert "access_type=offline" in idp.opened[-1] and "prompt=consent" in idp.opened[-1]
exchange = idp.token_requests[-1]
@@ -162,13 +169,15 @@ def test_sign_in_stores_the_grant_then_status_refresh_and_logout(idp, capsys):
assert (exchange["client_id"], exchange["client_secret"]) == (CLIENT_ID, SECRET)
grant = _grant()
assert grant["refresh_token"] in idp.refresh_tokens and grant["access_token"] and grant["expires_at_ms"]
- assert SECRET not in (_home() / "auth.json").read_text(encoding="utf-8")
+ assert SECRET not in (_home() / "auth.json").read_text(encoding="utf-8-sig")
- assert _auth("status") is True
- assert _auth("refresh") is True and _refreshes(idp) == 1
- assert _auth("logout") is True and _grant() is None
+ auth_commands.auth_status_command(args)
+ auth_commands.auth_refresh_command(args)
+ assert _refreshes(idp) == 1
+ auth_commands.auth_logout_command(args)
+ assert _grant() is None
out = capsys.readouterr()
- assert "logged in" in out.out and SECRET not in out.out + out.err
+ assert "voice:google: logged in" in out.out and SECRET not in out.out + out.err
def test_bearer_reaches_the_declared_host_and_never_the_plugin(idp, api):
@@ -406,7 +415,7 @@ def test_grant_belongs_to_one_profile(idp, api, monkeypatch, tmp_path):
def test_client_secret_stays_out_of_config_repr_logs_and_errors(idp, api, caplog, capsys):
allowed, _ = api
plugin = _signed_in(idp)
- manifest = json.loads((_home() / "plugins" / "voice" / "plugin.yaml").read_text(encoding="utf-8"))
+ manifest = json.loads((_home() / "plugins" / "voice" / "plugin.yaml").read_text(encoding="utf-8-sig"))
client = plugin_oauth.parse_oauth_clients(manifest)[0][0]
assert SECRET not in repr(plugin_oauth._pkce_config(client, KEY))
@@ -444,11 +453,7 @@ def test_install_notice_and_repin_delta_name_the_oauth_entry(idp, tmp_path):
lines = surface_delta_lines(surface_delta(plugin_surface(manifest, tmp_path), plugin_surface(widened, tmp_path)))
assert len(lines) == 1 and lines[0].startswith("your OAuth sign-in for") and "collect.example.net" in lines[0]
-
-def test_repin_delta_names_a_changed_authorize_host(idp, tmp_path):
- from hermes_cli.plugins_cmd_catalog import plugin_surface, surface_delta, surface_delta_lines
-
- installed = plugin_surface({"name": "voice", "oauth": [_entry(idp)]}, tmp_path)
+ installed = plugin_surface(manifest, tmp_path)
moved = {"name": "voice", "oauth": [_entry(idp, authorize_url="https://signin.example.net/authorize")]}
lines = surface_delta_lines(surface_delta(installed, plugin_surface(moved, tmp_path)))
assert len(lines) == 1 and "signin.example.net" in lines[0]
@@ -460,7 +465,7 @@ def test_repin_delta_names_a_changed_authorize_host(idp, tmp_path):
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"))
+ manifest = json.loads((_home() / "plugins" / "voice-dir" / "plugin.yaml").read_text(encoding="utf-8-sig"))
assert "hermes auth add gemini-voice:google" in ppr.requires_auth_notice(manifest)
assert _auth("add", "gemini-voice:google") is True
@@ -468,17 +473,72 @@ def test_the_notice_command_finds_a_plugin_whose_name_differs_from_its_directory
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
+# ── Security invariants (review of #139985) ─────────────────────────────────────────────────────────
- _plugin(oauth=[_entry(idp)])
- args = SimpleNamespace(provider=KEY, no_browser=False, timeout=None)
- auth_commands.auth_add_command(args)
- assert _grant()["refresh_token"] in idp.refresh_tokens
- auth_commands.auth_status_command(args)
- auth_commands.auth_refresh_command(args)
- auth_commands.auth_logout_command(args)
+def _reachable_text(exc: BaseException) -> str:
+ """Everything plugin code can read off a caught exception: repr, chain, httpx request, frame locals."""
+ import traceback
+
+ parts, seen = [], set()
+ while exc is not None and id(exc) not in seen:
+ seen.add(id(exc))
+ parts.append("".join(traceback.TracebackException.from_exception(exc, capture_locals=True).format()))
+ try:
+ request = exc.request # httpx errors carry the request they sent
+ except (AttributeError, RuntimeError):
+ request = None
+ if request is not None:
+ parts += [repr(dict(request.headers)), request.content.decode("utf-8", "replace")]
+ exc = exc.__cause__ or exc.__context__
+ return "\n".join(parts)
- assert _grant() is None and _refreshes(idp) == 1
- assert "voice:google: logged in" in capsys.readouterr().out
+
+def test_errors_raised_to_the_plugin_carry_no_token_refresh_token_or_secret(idp, api):
+ """A failed API call or refresh hands the plugin an exception; nothing in it may lead back to a credential."""
+ allowed, _ = api
+ plugin = _signed_in(idp)
+ token = _grant()["access_token"]
+ allowed.close() # the API host is down: httpx raises with the request it tried to send
+ exc = _caught(lambda: plugin.call("google", allowed.url + "/v1"))
+ assert type(exc).__name__ == "ConnectError" and token not in _reachable_text(exc)
+
+ refresh = _grant()["refresh_token"]
+ _set_grant(expires_at_ms=0)
+ idp.stop() # the token endpoint is down mid-refresh
+ exc = _caught(lambda: plugin.call("google", allowed.url + "/v1"))
+ assert isinstance(exc, AuthError) and exc.code == "oauth_refresh_failed"
+ text = _reachable_text(exc)
+ assert refresh not in text and SECRET not in text
+
+
+def _caught(fn) -> BaseException:
+ try:
+ fn()
+ except Exception as exc: # what plugin code would catch
+ return exc
+ raise AssertionError("expected an error")
+
+
+def test_revoked_grant_keeps_no_tokens_and_uninstall_drops_the_grant(idp, api):
+ allowed, _ = api
+ plugin = _signed_in(idp)
+ idp.refresh_tokens.clear()
+ _set_grant(expires_at_ms=0)
+ with pytest.raises(ppr.ProviderNotSignedIn, match="revoked"):
+ plugin.call("google", allowed.url)
+ assert set(_grant()) == {"dead", "fingerprint"}
+
+ from hermes_cli.plugins_cmd_remove import _remove_user_plugin
+
+ 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
+
+
+def test_sign_in_is_refused_where_nobody_can_answer_the_browser(idp, monkeypatch):
+ _plugin(oauth=[_entry(idp)])
+ monkeypatch.setenv("HERMES_CRON_SESSION", "1")
+ with pytest.raises(SystemExit, match="your own terminal"):
+ _auth("add")
+ assert idp.token_requests == [] and idp.opened == []
diff --git a/tests/hermes_cli/test_plugin_validate.py b/tests/hermes_cli/test_plugin_validate.py
index 84e52375908..84c543a0c5f 100644
--- a/tests/hermes_cli/test_plugin_validate.py
+++ b/tests/hermes_cli/test_plugin_validate.py
@@ -526,7 +526,8 @@ def _oauth_entry(**overrides) -> dict:
def test_oauth_block_passes_and_a_token_url_in_code_is_only_a_warning(tmp_path):
- plugin = _make_plugin(tmp_path, manifest=dict(OAUTH_MANIFEST, oauth=[_oauth_entry()]))
+ plugin = _make_plugin(tmp_path, manifest=dict(OAUTH_MANIFEST, oauth=[_oauth_entry(hosts=["docs.example.com",
+ "collect.example.net"])]))
(plugin / "client.py").write_text('TOKEN_URL = "https://oauth2.example.com/token"\n', encoding="utf-8")
report = validate_plugin_dir(plugin)
@@ -534,11 +535,18 @@ def test_oauth_block_passes_and_a_token_url_in_code_is_only_a_warning(tmp_path):
assert report.ok, report.failures
assert [ok for name, ok, _ in report.checks if name == "oauth"] == [True]
assert any("oauth2.example.com/token" in warning for warning in report.warnings)
+ assert [w for w in report.warnings if "shares no domain" in w] == [
+ "oauth 'google': host collect.example.net shares no domain with accounts.example.com, oauth2.example.com; "
+ "check the provider owns it"]
@pytest.mark.parametrize("change, problem", [
({"id": "Google"}, "id"),
({"authorize_url": "http://accounts.example.com/o/oauth2/auth"}, "authorize_url"),
+ ({"authorize_url": "http://127.0.0.1:8080/auth"}, "must use https"), # no loopback exception
+ ({"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"),
({"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"),
diff --git a/tests/providers/fake_pkce_idp.py b/tests/providers/fake_pkce_idp.py
index 1d281545669..8f1d24ec9fd 100644
--- a/tests/providers/fake_pkce_idp.py
+++ b/tests/providers/fake_pkce_idp.py
@@ -16,7 +16,7 @@ from urllib.parse import parse_qs, urlencode, urlparse
class FakeIdP:
- def __init__(self) -> None:
+ def __init__(self, host: str = "127.0.0.1", port: int = 0) -> None:
self.codes: dict[str, str] = {} # code -> code_challenge
self.refresh_tokens: set[str] = set()
self.token_requests: list[dict] = []
@@ -80,11 +80,26 @@ class FakeIdP:
self.override_state: str | None = None
self.granted_scope: str | None = None # ``scope`` echoed in token responses (None = omitted)
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.server = HTTPServer((host, port), Handler)
+ self.base = f"http://{host}:{self.server.server_address[1]}"
self._thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True)
- def start(self) -> FakeIdP:
+ def start(self, *, tls_dir=None, name: str | None = None) -> FakeIdP:
+ """Serve; with *tls_dir*, over HTTPS with a throwaway CA written there (``self.ca_pem`` to trust).
+ *name* is the DNS name the certificate (and ``self.base``) use instead of the bound address."""
+ if tls_dir is not None:
+ import ssl
+ from pathlib import Path
+
+ from tests.fakes.providers.oauth_token_server import make_test_ca
+
+ host, port = self.server.server_address[:2]
+ ca = make_test_ca(Path(tls_dir), [name or host])
+ context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
+ context.load_cert_chain(ca.leaf_pem, ca.leaf_key)
+ self.server.socket = context.wrap_socket(self.server.socket, server_side=True)
+ self.base = f"https://{name or host}" + ("" if port == 443 else f":{port}")
+ self.ca_pem = ca.ca_pem
self._thread.start()
return self