fix(mcp): skip malformed cached OAuth redirect_uris instead of crashing
_cached_redirect wrapped urlparse() in try/except to skip malformed DCR-supplied entries, but .port and .hostname are lazy properties that raise ValueError on access — outside the try. A client.json containing e.g. http://127.0.0.1:abc/callback made every OAuth attempt for that server die in _configure_callback_port until the file was removed. Same crash class one level up: a truthy non-dict client.json raised AttributeError on .get, and a non-iterable redirect_uris raised TypeError on the for. Resolve the lazy properties inside the try and guard both container shapes so any malformed payload degrades to (None, None) instead of propagating.
This commit is contained in:
1 parent
6950959fa5
commit
f8f89b20d2
2 files changed
+57
-4
No files matched your search
@@ -639,6 +639,54 @@ class TestCallbackPortReservation:
|
||||
assert result.code == "flowA"
|
||||
assert result.state == "sA"
|
||||
|
||||
def _seed_client_info(self, tmp_path, monkeypatch, redirect_uris):
|
||||
import json as _json
|
||||
import tools.mcp_oauth as mod
|
||||
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
storage = HermesTokenStorage("srv")
|
||||
d = tmp_path / "mcp-tokens"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
(d / "srv.client.json").write_text(_json.dumps({
|
||||
"client_id": "client-a", "redirect_uris": redirect_uris}))
|
||||
return storage, mod
|
||||
|
||||
@pytest.mark.parametrize("bad_uri", [
|
||||
"http://127.0.0.1:abc/callback", # .port raises: non-numeric
|
||||
"http://127.0.0.1:99999/callback", # .port raises: out of range
|
||||
"http://[bad/callback", # urlparse itself raises: bad IPv6 bracket
|
||||
])
|
||||
def test_cached_redirect_skips_malformed_entries(self, tmp_path, monkeypatch, bad_uri):
|
||||
"""DCR-supplied redirect_uris persist to client.json. urlparse() alone does not
|
||||
validate ports — .port is lazy and raises ValueError on access — so the try/except
|
||||
around urlparse never fires. A poisoned entry must be skipped like every other
|
||||
malformed one, not crash the whole OAuth flow."""
|
||||
storage, mod = self._seed_client_info(
|
||||
tmp_path, monkeypatch,
|
||||
[bad_uri, "http://127.0.0.1:1455/callback", "https://proxy.example.com/cb"])
|
||||
assert mod._cached_redirect(storage) == ("https://proxy.example.com/cb", 1455)
|
||||
|
||||
@pytest.mark.parametrize("payload", [
|
||||
["not", "a", "dict"], # non-dict client.json: .get would AttributeError
|
||||
{"redirect_uris": 123}, # non-iterable redirect_uris: for would TypeError
|
||||
{"redirect_uris": {"a": 1}}, # dict redirect_uris: iterate keys, nothing matches
|
||||
{"redirect_uris": None}, # explicit null
|
||||
{"client_id": "c"}, # missing key entirely
|
||||
])
|
||||
def test_cached_redirect_tolerates_misshaped_client_info(self, tmp_path, monkeypatch, payload):
|
||||
"""_read_json returns whatever the file holds — the crash class isn't limited to
|
||||
bad URIs inside a well-formed list. Any misshaped payload must degrade to
|
||||
(None, None), not propagate AttributeError/TypeError through the OAuth flow."""
|
||||
import json as _json
|
||||
import tools.mcp_oauth as mod
|
||||
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
storage = HermesTokenStorage("srv")
|
||||
d = tmp_path / "mcp-tokens"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
(d / "srv.client.json").write_text(_json.dumps(payload))
|
||||
assert mod._cached_redirect(storage) == (None, None)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# remove_oauth_tokens
|
||||
|
||||
+9
-4
@@ -287,16 +287,21 @@ def _cached_redirect(storage: "HermesTokenStorage | None") -> "tuple[str | None,
|
||||
absent): a DCR ``client_id`` is bound to its registered redirect URI, so a new random port under
|
||||
it gets ``redirect_uri does not match any registered URIs``."""
|
||||
uri = port = None
|
||||
for raw in (_cached_client_info(storage) or {}).get("redirect_uris") or []:
|
||||
info = _cached_client_info(storage)
|
||||
uris = info.get("redirect_uris") if isinstance(info, dict) else None
|
||||
for raw in uris if isinstance(uris, (list, tuple)) else ():
|
||||
try:
|
||||
parsed = urlparse(str(raw))
|
||||
# .port/.hostname are lazy properties that can raise ValueError on access —
|
||||
# resolve them inside the try so a malformed entry is skipped, not fatal.
|
||||
parsed_hostname, parsed_port = parsed.hostname, parsed.port
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if uri is None and parsed.scheme == "https" and parsed.netloc:
|
||||
uri = str(raw)
|
||||
is_loopback_callback = parsed.scheme == "http" and parsed.path == "/callback" and parsed.hostname in {"127.0.0.1", "localhost"}
|
||||
if port is None and is_loopback_callback and parsed.port is not None:
|
||||
port = int(parsed.port)
|
||||
is_loopback_callback = parsed.scheme == "http" and parsed.path == "/callback" and parsed_hostname in {"127.0.0.1", "localhost"}
|
||||
if port is None and is_loopback_callback and parsed_port is not None:
|
||||
port = int(parsed_port)
|
||||
return uri, port
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user