fix(dashboard+auth): cap HTTP JSON response body reads

Dashboard-side urllib readers (gateway health probe, ElevenLabs voices)
and self-hosted OIDC httpx readers (discovery, token exchange, revocation)
buffered remote response bodies with no size bound — a hostile or
compromised upstream could exhaust memory. Both halves now read with a
1 MiB hard cap: a shared _read_dashboard_json_response for urllib JSON
reads and a streaming _request_limited_response for IdP endpoints that
prechecks Content-Length and caps the chunked body regardless.

Adapted from #54809 and #55122 (credit @ooiuuii) to current main, where
the token exchange lives in plugins/dashboard_auth/_shared.py and the
health probe in hermes_cli/web_server_gateway.py.

Fixes #54808, Fixes #55121
This commit is contained in:
Austin Pickett
2026-10-06 10:50:20 -04:00
parent e93446126d
commit ca38caeea0
9 changed files with 367 additions and 77 deletions

View File

@@ -20,7 +20,7 @@ from fastapi import APIRouter
from hermes_cli.web_routers._common import http_failure
from hermes_cli.web_deps import late
from hermes_cli.web_server_chat import _ws_auth_ok, _ws_request_is_allowed
from hermes_cli.web_server_gateway import _split_text_for_speak_stream
from hermes_cli.web_server_gateway import _read_dashboard_json_response, _split_text_for_speak_stream
from fastapi import HTTPException, WebSocket, WebSocketDisconnect
from hermes_cli.web_models import (
AudioTranscriptionRequest,
@@ -250,7 +250,7 @@ async def get_elevenlabs_voices(profile: Optional[str] = None):
def _fetch() -> Dict[str, Any]:
with urllib.request.urlopen(request, timeout=10) as response:
return json.loads(response.read().decode("utf-8"))
return _read_dashboard_json_response(response)
payload = await loop.run_in_executor(None, _fetch)
except urllib.error.HTTPError as exc:

View File

@@ -20,6 +20,22 @@ from hermes_cli.config import get_hermes_home
_log = logging.getLogger("hermes_cli.web_server")
# Defense against a hostile/compromised upstream serving an unbounded body to
# the dashboard's JSON readers: refuse to buffer past this size.
_DASHBOARD_JSON_RESPONSE_BODY_MAX_BYTES = 1024 * 1024
def _read_dashboard_json_response(response) -> Any:
"""Read a JSON HTTP response body with a hard size cap (issue #54808)."""
raw = response.read(_DASHBOARD_JSON_RESPONSE_BODY_MAX_BYTES + 1)
if len(raw) > _DASHBOARD_JSON_RESPONSE_BODY_MAX_BYTES:
raise ValueError(
"dashboard HTTP JSON response exceeded "
f"{_DASHBOARD_JSON_RESPONSE_BODY_MAX_BYTES} bytes"
)
return json.loads(raw.decode("utf-8"))
def _probe_gateway_health() -> tuple[bool, dict | None]:
"""Probe the gateway's HTTP health endpoint (cross-container). Blocking — run in an executor.
@@ -36,7 +52,7 @@ def _probe_gateway_health() -> tuple[bool, dict | None]:
req = urllib.request.Request(path, method="GET")
with urllib.request.urlopen(req, timeout=_GATEWAY_HEALTH_TIMEOUT) as resp:
if resp.status == 200:
return True, json.loads(resp.read())
return True, _read_dashboard_json_response(resp)
except Exception:
continue
return False, None

View File

@@ -33,6 +33,49 @@ JSON_HEADERS = {"Accept": "application/json"}
# drift seen in the field (#47815) without meaningfully extending token lifetime.
DEFAULT_TOKEN_LEEWAY_SECONDS = 60.0
# Defense against a hostile/compromised IdP serving unbounded responses to the
# dashboard auth providers: refuse to buffer past this size (issue #55121).
_OIDC_RESPONSE_BODY_LIMIT_BYTES = 1 * 1024 * 1024
_OIDC_RESPONSE_CHUNK_BYTES = 64 * 1024
def _request_limited_response(method: str, url: str, **kwargs: Any) -> httpx.Response:
"""``httpx.request`` that never buffers an unbounded IdP response body.
Content-Length is prechecked when declared; the streamed body is capped
chunk-by-chunk either way (a lying/absent header cannot bypass the bound).
Returns a fully-read ``httpx.Response`` with the same status/headers.
"""
with httpx.stream(method, url, **kwargs) as response:
declared = response.headers.get("content-length")
if declared:
try:
if int(declared) > _OIDC_RESPONSE_BODY_LIMIT_BYTES:
raise ProviderError(
f"endpoint response exceeds {_OIDC_RESPONSE_BODY_LIMIT_BYTES} bytes"
)
except ValueError:
pass # malformed header — the chunk cap below still bounds the read
chunks: list[bytes] = []
total = 0
for chunk in response.iter_bytes(chunk_size=_OIDC_RESPONSE_CHUNK_BYTES):
if not chunk:
continue
total += len(chunk)
if total > _OIDC_RESPONSE_BODY_LIMIT_BYTES:
raise ProviderError(
f"endpoint response exceeds {_OIDC_RESPONSE_BODY_LIMIT_BYTES} bytes"
)
chunks.append(chunk)
return httpx.Response(
status_code=response.status_code,
headers=response.headers,
content=b"".join(chunks),
request=response.request,
)
# ---- Config / env resolution ----
@@ -170,7 +213,8 @@ def exchange_token(
deliberately NOT followed: the body carries an auth code / refresh token.
"""
try:
response = httpx.post(url, data=data, headers={**JSON_HEADERS, **(headers or {})}, timeout=TOKEN_ENDPOINT_TIMEOUT_SEC)
response = _request_limited_response(
"POST", url, data=data, headers={**JSON_HEADERS, **(headers or {})}, timeout=TOKEN_ENDPOINT_TIMEOUT_SEC)
except httpx.RequestError as exc:
raise ProviderError(f"{endpoint} unreachable: {exc}") from exc
if response.status_code == 400:

View File

@@ -28,6 +28,7 @@ from plugins.dashboard_auth._shared import (
TOKEN_ENDPOINT_TIMEOUT_SEC as _TOKEN_ENDPOINT_TIMEOUT_SEC,
JwtOAuthProvider,
SkipRegistration,
_request_limited_response,
exchange_token,
load_config_section,
parse_json_body,
@@ -137,7 +138,8 @@ class SelfHostedOIDCProvider(JwtOAuthProvider):
extra_data, extra_headers = self._token_endpoint_auth(disco)
data = {"token": refresh_token, "token_type_hint": "refresh_token", "client_id": self._client_id, **extra_data}
try:
httpx.post(endpoint, data=data, headers={**JSON_HEADERS, **extra_headers}, timeout=_TOKEN_ENDPOINT_TIMEOUT_SEC)
_request_limited_response(
"POST", endpoint, data=data, headers={**JSON_HEADERS, **extra_headers}, timeout=_TOKEN_ENDPOINT_TIMEOUT_SEC)
except Exception as exc: # noqa: BLE001 — best-effort
logger.debug("self-hosted OIDC: revoke failed (ignored): %s", exc)
return None
@@ -213,7 +215,8 @@ class SelfHostedOIDCProvider(JwtOAuthProvider):
# canonicalises .well-known; proxies upgrade http→https) and httpx defaults to
# not following. The token/revocation POSTs deliberately do NOT follow
# redirects (they carry an auth code / refresh token).
response = httpx.get(url, headers=JSON_HEADERS, timeout=_DISCOVERY_TIMEOUT_SEC, follow_redirects=True)
response = _request_limited_response(
"GET", url, headers=JSON_HEADERS, timeout=_DISCOVERY_TIMEOUT_SEC, follow_redirects=True)
except httpx.RequestError as exc:
raise ProviderError(f"OIDC discovery unreachable: {exc}") from exc
if response.status_code != 200:

View File

@@ -7,7 +7,10 @@ under multiplex). Only the unscoped default-profile path (UnscopedSecretError)
may read the env.
"""
import json
import pytest
from fastapi import HTTPException
@pytest.fixture(autouse=True)
@@ -56,3 +59,66 @@ async def test_voices_route_scope_failure_never_borrows_env(tmp_path, monkeypatc
ss.set_multiplex_active(was_active)
assert result == {"available": False, "voices": []}
@pytest.mark.asyncio
async def test_voices_route_bounds_response_read(monkeypatch, tmp_path):
"""The ElevenLabs voices fetch must read the body with a size cap."""
from hermes_cli import web_server_gateway
import hermes_cli.web_routers.audio as audio
monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
(tmp_path / ".hermes").mkdir()
monkeypatch.setenv("ELEVENLABS_API_KEY", "sk-test")
captured = {}
class _Resp:
def __enter__(self):
return self
def __exit__(self, *a):
return False
def read(self, size=-1):
captured["size"] = size
data = json.dumps(
{"voices": [{"voice_id": "voice-1", "name": "Voice One"}]}
).encode()
return data if size < 0 else data[:size]
monkeypatch.setattr(audio.urllib.request, "urlopen", lambda req, timeout=None: _Resp())
result = await audio.get_elevenlabs_voices()
assert result["available"] is True
assert result["voices"][0]["voice_id"] == "voice-1"
assert captured["size"] == (
web_server_gateway._DASHBOARD_JSON_RESPONSE_BODY_MAX_BYTES + 1
)
@pytest.mark.asyncio
async def test_voices_route_rejects_oversized_response(monkeypatch, tmp_path):
"""An oversized ElevenLabs voices body must fail as 502, not buffer."""
from hermes_cli import web_server_gateway
import hermes_cli.web_routers.audio as audio
monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
(tmp_path / ".hermes").mkdir()
monkeypatch.setenv("ELEVENLABS_API_KEY", "sk-test")
monkeypatch.setattr(
web_server_gateway, "_DASHBOARD_JSON_RESPONSE_BODY_MAX_BYTES", 8
)
class _Resp:
def __enter__(self):
return self
def __exit__(self, *a):
return False
def read(self, size=-1):
return b"x" * size
monkeypatch.setattr(audio.urllib.request, "urlopen", lambda req, timeout=None: _Resp())
with pytest.raises(HTTPException) as exc_info:
await audio.get_elevenlabs_voices()
assert exc_info.value.status_code == 502

View File

@@ -3655,7 +3655,6 @@ class TestOrphanedOwnerReclaim:
``(claimed, published, fake_procs)``.
"""
import types
from unittest.mock import MagicMock
from gateway import host_rendezvous as hr
import hermes_cli.web_server as web_server
from hermes_cli import process_identity as pi
@@ -3954,57 +3953,6 @@ class TestModelInfoEndpoint:
# ---------------------------------------------------------------------------
class TestProbeGatewayHealth:
"""Tests for _probe_gateway_health() — cross-container gateway detection."""
def test_probe_uses_configured_short_timeout(self, monkeypatch):
"""The HTTP probe must not fall through to the OS TCP timeout."""
import hermes_cli.web_server as ws
monkeypatch.setattr(ws, "_GATEWAY_HEALTH_URL", "http://gw:8642")
monkeypatch.setattr(ws, "_GATEWAY_HEALTH_TIMEOUT", 0.75)
timeouts = []
def mock_urlopen(req, **kwargs):
timeouts.append(kwargs.get("timeout"))
raise TimeoutError("mock timeout")
monkeypatch.setattr(ws.urllib.request, "urlopen", mock_urlopen)
alive, body = _web_server_gateway._probe_gateway_health()
assert alive is False
assert body is None
assert timeouts == [0.75, 0.75]
def test_detailed_fails_falls_back_to_simple_health(self, monkeypatch):
"""If /health/detailed fails, falls back to /health."""
import hermes_cli.web_server as ws
monkeypatch.setattr(ws, "_GATEWAY_HEALTH_URL", "http://gw:8642")
monkeypatch.setattr(ws, "_GATEWAY_HEALTH_TIMEOUT", 1)
call_count = [0]
def mock_urlopen(req, **kwargs):
call_count[0] += 1
if call_count[0] == 1:
raise ConnectionError("detailed failed")
mock_resp = MagicMock()
mock_resp.status = 200
mock_resp.read.return_value = json.dumps({"status": "ok"}).encode()
mock_resp.__enter__ = MagicMock(return_value=mock_resp)
mock_resp.__exit__ = MagicMock(return_value=False)
return mock_resp
monkeypatch.setattr(ws.urllib.request, "urlopen", mock_urlopen)
alive, body = _web_server_gateway._probe_gateway_health()
assert alive is True
assert body["status"] == "ok"
assert call_count[0] == 2
class TestStatusRemoteGateway:
"""Tests for /api/status with remote gateway health fallback."""

View File

@@ -0,0 +1,127 @@
"""Tests for _probe_gateway_health() — cross-container gateway detection,
including the bounded JSON response body reads (moved from test_web_server.py
so that file keeps its main-pinned line cap; moved code keeps its cap)."""
import json
from unittest.mock import MagicMock
import hermes_cli.web_server as ws
import hermes_cli.web_server_gateway as _web_server_gateway
class TestProbeGatewayHealth:
"""Tests for _probe_gateway_health() — cross-container gateway detection."""
def test_probe_uses_configured_short_timeout(self, monkeypatch):
"""The HTTP probe must not fall through to the OS TCP timeout."""
monkeypatch.setattr(ws, "_GATEWAY_HEALTH_URL", "http://gw:8642")
monkeypatch.setattr(ws, "_GATEWAY_HEALTH_TIMEOUT", 0.75)
timeouts = []
def mock_urlopen(req, **kwargs):
timeouts.append(kwargs.get("timeout"))
raise TimeoutError("mock timeout")
monkeypatch.setattr(_web_server_gateway.urllib.request, "urlopen", mock_urlopen)
alive, body = _web_server_gateway._probe_gateway_health()
assert alive is False
assert body is None
assert timeouts == [0.75, 0.75]
def test_detailed_fails_falls_back_to_simple_health(self, monkeypatch):
"""If /health/detailed fails, falls back to /health."""
monkeypatch.setattr(ws, "_GATEWAY_HEALTH_URL", "http://gw:8642")
monkeypatch.setattr(ws, "_GATEWAY_HEALTH_TIMEOUT", 1)
call_count = [0]
def mock_urlopen(req, **kwargs):
call_count[0] += 1
if call_count[0] == 1:
raise ConnectionError("detailed failed")
mock_resp = MagicMock()
mock_resp.status = 200
mock_resp.read.return_value = json.dumps({"status": "ok"}).encode()
mock_resp.__enter__ = MagicMock(return_value=mock_resp)
mock_resp.__exit__ = MagicMock(return_value=False)
return mock_resp
monkeypatch.setattr(_web_server_gateway.urllib.request, "urlopen", mock_urlopen)
alive, body = _web_server_gateway._probe_gateway_health()
assert alive is True
assert body is not None
assert body["status"] == "ok"
assert call_count[0] == 2
def test_successful_probe_bounds_response_read(self, monkeypatch):
"""Gateway health JSON must be read with a defensive size cap."""
monkeypatch.setattr(ws, "_GATEWAY_HEALTH_URL", "http://gw:8642")
monkeypatch.setattr(ws, "_GATEWAY_HEALTH_TIMEOUT", 1)
captured = {}
class _Resp:
status = 200
def __enter__(self):
return self
def __exit__(self, *a):
return False
def read(self, size=-1):
captured["size"] = size
data = json.dumps({"status": "ok", "pid": 42}).encode()
return data if size < 0 else data[:size]
monkeypatch.setattr(
_web_server_gateway.urllib.request, "urlopen", lambda req, **kw: _Resp()
)
alive, body = _web_server_gateway._probe_gateway_health()
assert alive is True
assert body is not None
assert body["pid"] == 42
assert captured["size"] == (
_web_server_gateway._DASHBOARD_JSON_RESPONSE_BODY_MAX_BYTES + 1
)
def test_oversized_detailed_probe_falls_back_to_simple_health(self, monkeypatch):
"""An oversized detailed health body must not block the fallback path."""
monkeypatch.setattr(ws, "_GATEWAY_HEALTH_URL", "http://gw:8642")
monkeypatch.setattr(ws, "_GATEWAY_HEALTH_TIMEOUT", 1)
monkeypatch.setattr(
_web_server_gateway, "_DASHBOARD_JSON_RESPONSE_BODY_MAX_BYTES", 16
)
calls = []
class _Resp:
status = 200
def __init__(self, payload):
self.payload = payload
def __enter__(self):
return self
def __exit__(self, *a):
return False
def read(self, size=-1):
return self.payload if size < 0 else self.payload[:size]
def mock_urlopen(req, **kwargs):
calls.append(req.full_url)
if len(calls) == 1:
return _Resp(b"x" * 17)
return _Resp(json.dumps({"status": "ok"}).encode())
monkeypatch.setattr(_web_server_gateway.urllib.request, "urlopen", mock_urlopen)
alive, body = _web_server_gateway._probe_gateway_health()
assert alive is True
assert body is not None
assert body["status"] == "ok"
assert calls == [
"http://gw:8642/health/detailed",
"http://gw:8642/health",
]

View File

@@ -354,7 +354,7 @@ class TestCompleteLogin:
"refresh_token": "rt_initial_value",
},
)
with patch("plugins.dashboard_auth._shared.httpx.post", return_value=mock_resp):
with patch("plugins.dashboard_auth._shared._request_limited_response", return_value=mock_resp):
session = provider.complete_login(
code="abc",
state="state-val",
@@ -374,7 +374,7 @@ class TestCompleteLogin:
def test_400_raises_invalid_code(self, provider):
mock_resp = self._mock_post(400, {"error": "invalid_grant"})
with patch("plugins.dashboard_auth._shared.httpx.post", return_value=mock_resp):
with patch("plugins.dashboard_auth._shared._request_limited_response", return_value=mock_resp):
with pytest.raises(InvalidCodeError, match="invalid_grant"):
provider.complete_login(
code="bad", state="s", code_verifier="v",
@@ -384,7 +384,7 @@ class TestCompleteLogin:
def test_500_raises_provider_error(self, provider):
mock_resp = self._mock_post(500, "internal server error", ctype="text/plain")
mock_resp.text = "internal server error"
with patch("plugins.dashboard_auth._shared.httpx.post", return_value=mock_resp):
with patch("plugins.dashboard_auth._shared._request_limited_response", return_value=mock_resp):
with pytest.raises(ProviderError, match="500"):
provider.complete_login(
code="x", state="s", code_verifier="v",
@@ -393,7 +393,7 @@ class TestCompleteLogin:
def test_missing_access_token_raises(self, provider):
mock_resp = self._mock_post(200, {"token_type": "Bearer"})
with patch("plugins.dashboard_auth._shared.httpx.post", return_value=mock_resp):
with patch("plugins.dashboard_auth._shared._request_limited_response", return_value=mock_resp):
with pytest.raises(ProviderError, match="access_token"):
provider.complete_login(
code="x", state="s", code_verifier="v",
@@ -405,7 +405,7 @@ class TestCompleteLogin:
mock_resp = self._mock_post(
200, {"access_token": access_token, "token_type": "DPoP"}
)
with patch("plugins.dashboard_auth._shared.httpx.post", return_value=mock_resp):
with patch("plugins.dashboard_auth._shared._request_limited_response", return_value=mock_resp):
with pytest.raises(ProviderError, match="token_type"):
provider.complete_login(
code="x", state="s", code_verifier="v",
@@ -414,7 +414,7 @@ class TestCompleteLogin:
def test_network_error_raises_provider_error(self, provider):
with patch(
"plugins.dashboard_auth._shared.httpx.post",
"plugins.dashboard_auth._shared._request_limited_response",
side_effect=httpx.ConnectError("conn refused"),
):
with pytest.raises(ProviderError, match="unreachable"):
@@ -525,7 +525,7 @@ class TestRefreshAndRevoke:
},
)
with patch(
"plugins.dashboard_auth._shared.httpx.post", return_value=mock_resp
"plugins.dashboard_auth._shared._request_limited_response", return_value=mock_resp
) as mock_post:
session = provider.refresh_session(refresh_token="rt_old_value")

View File

@@ -28,6 +28,7 @@ import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
import plugins.dashboard_auth._shared as shared
import plugins.dashboard_auth.self_hosted as oidc_plugin
from hermes_cli.dashboard_auth import (
InvalidCodeError,
@@ -164,7 +165,7 @@ def _make_provider(
return p
def _mock_post(status_code: int, body: Any, *, ctype: str = "application/json"):
def _mock_post(status_code: int, body: Any, *, ctype: str = "application/json") -> MagicMock:
resp = MagicMock(spec=httpx.Response)
resp.status_code = status_code
if isinstance(body, dict):
@@ -177,6 +178,28 @@ def _mock_post(status_code: int, body: Any, *, ctype: str = "application/json"):
return resp
class _FakeStreamResponse:
"""A streaming httpx.Response stand-in yielding fixed chunks."""
def __init__(self, method: str, url: str, *, chunks, status_code: int = 200,
headers: Dict[str, str] | None = None) -> None:
self.status_code = status_code
self.headers = headers or {}
self.request = httpx.Request(method, url)
self.url = httpx.URL(url)
self._chunks = chunks
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
return False
def iter_bytes(self, chunk_size: int = 65536):
_ = chunk_size
yield from self._chunks
# ---------------------------------------------------------------------------
# Construction
# ---------------------------------------------------------------------------
@@ -225,7 +248,7 @@ class TestDiscovery:
p = self._provider()
mock_resp = self._mock_get(200, dict(_DISCOVERY_DOC))
with patch(
"plugins.dashboard_auth.self_hosted.httpx.get", return_value=mock_resp
"plugins.dashboard_auth.self_hosted._request_limited_response", return_value=mock_resp
) as mock_get:
disco1 = p._get_discovery()
disco2 = p._get_discovery()
@@ -251,7 +274,7 @@ class TestDiscovery:
200, forged, url="https://attacker.example/openid-configuration"
)
with patch(
"plugins.dashboard_auth.self_hosted.httpx.get", return_value=resp
"plugins.dashboard_auth.self_hosted._request_limited_response", return_value=resp
):
with pytest.raises(ProviderError, match="origin"):
p._fetch_discovery()
@@ -262,7 +285,7 @@ class TestDiscovery:
200, dict(_DISCOVERY_DOC), url="http://auth.example.com/discovery"
)
with patch(
"plugins.dashboard_auth.self_hosted.httpx.get", return_value=resp
"plugins.dashboard_auth.self_hosted._request_limited_response", return_value=resp
):
with pytest.raises(ProviderError, match="origin"):
p._fetch_discovery()
@@ -275,7 +298,7 @@ class TestDiscovery:
url="https://auth.example.com/.well-known/openid-configuration/application/o/hermes",
)
with patch(
"plugins.dashboard_auth.self_hosted.httpx.get", return_value=resp
"plugins.dashboard_auth.self_hosted._request_limited_response", return_value=resp
):
disco = p._fetch_discovery()
assert disco["token_endpoint"] == f"{_ISSUER}/token"
@@ -287,11 +310,53 @@ class TestDiscovery:
200, dict(_DISCOVERY_DOC), url="https://auth.example.com:443/x"
)
with patch(
"plugins.dashboard_auth.self_hosted.httpx.get", return_value=resp
"plugins.dashboard_auth.self_hosted._request_limited_response", return_value=resp
):
assert p._fetch_discovery()["issuer"] == _ISSUER
def test_discovery_rejects_oversized_response_body(self, monkeypatch):
"""A discovery body larger than the cap must raise, not buffer."""
p = self._provider()
def fake_stream(method, url, **kwargs):
return _FakeStreamResponse(
method, url,
chunks=[b"a" * 6, b"b" * 6],
headers={"content-type": "application/json"},
)
monkeypatch.setattr(shared.httpx, "stream", fake_stream)
monkeypatch.setattr(shared, "_OIDC_RESPONSE_BODY_LIMIT_BYTES", 10)
with pytest.raises(ProviderError, match="exceeds 10 bytes"):
p._get_discovery()
def test_discovery_rejects_oversized_content_length(self, monkeypatch):
"""An oversized declared Content-Length must reject before body read."""
p = self._provider()
read_attempted = []
class _ContentLengthResp(_FakeStreamResponse):
def iter_bytes(self, chunk_size=65536):
read_attempted.append(True)
yield from ()
def fake_stream(method, url, **kwargs):
return _ContentLengthResp(
method, url,
chunks=[],
headers={"content-type": "application/json", "content-length": "1048577"},
)
monkeypatch.setattr(shared.httpx, "stream", fake_stream)
monkeypatch.setattr(shared, "_OIDC_RESPONSE_BODY_LIMIT_BYTES", 1048576)
with pytest.raises(ProviderError, match="exceeds"):
p._get_discovery()
assert not read_attempted
# ---------------------------------------------------------------------------
# OIDC discovery against a REAL HTTP server that redirects (regression)
# ---------------------------------------------------------------------------
@@ -483,7 +548,7 @@ class TestCompleteLogin:
},
)
with patch(
"plugins.dashboard_auth.self_hosted.httpx.post", return_value=mock_resp
"plugins.dashboard_auth._shared._request_limited_response", return_value=mock_resp
):
session = provider.complete_login(
code="abc",
@@ -506,7 +571,7 @@ class TestCompleteLogin:
200, {"id_token": id_token, "token_type": "Bearer"}
)
with patch(
"plugins.dashboard_auth.self_hosted.httpx.post", return_value=mock_resp
"plugins.dashboard_auth._shared._request_limited_response", return_value=mock_resp
):
session = provider.complete_login(
code="abc",
@@ -521,7 +586,7 @@ class TestCompleteLogin:
200, {"access_token": "opaque", "token_type": "Bearer"}
)
with patch(
"plugins.dashboard_auth.self_hosted.httpx.post", return_value=mock_resp
"plugins.dashboard_auth._shared._request_limited_response", return_value=mock_resp
):
with pytest.raises(ProviderError, match="id_token"):
provider.complete_login(
@@ -531,10 +596,31 @@ class TestCompleteLogin:
redirect_uri="https://hermes.example/auth/callback",
)
def test_token_endpoint_rejects_oversized_response_body(self, provider, monkeypatch):
"""An IDP token response larger than the cap must raise, not buffer."""
def fake_stream(method, url, **kwargs):
return _FakeStreamResponse(
method, url,
chunks=[b"x" * 8, b"y" * 8],
headers={"content-type": "application/json"},
)
monkeypatch.setattr(shared.httpx, "stream", fake_stream)
monkeypatch.setattr(shared, "_OIDC_RESPONSE_BODY_LIMIT_BYTES", 10)
with pytest.raises(ProviderError, match="exceeds 10 bytes"):
provider.complete_login(
code="x",
state="s",
code_verifier="v",
redirect_uri="https://hermes.example/auth/callback",
)
def test_400_raises_invalid_code(self, provider):
mock_resp = _mock_post(400, {"error": "invalid_grant"})
with patch(
"plugins.dashboard_auth.self_hosted.httpx.post", return_value=mock_resp
"plugins.dashboard_auth._shared._request_limited_response", return_value=mock_resp
):
with pytest.raises(InvalidCodeError, match="invalid_grant"):
provider.complete_login(
@@ -572,7 +658,7 @@ class TestConfidentialClient:
id_token = _mint_id_token(rsa_keypair)
mock_resp = _mock_post(200, {"id_token": id_token, **_GOOD_TOKEN_RESP_KEYS})
with patch(
"plugins.dashboard_auth.self_hosted.httpx.post", return_value=mock_resp
"plugins.dashboard_auth._shared._request_limited_response", return_value=mock_resp
) as mock_post:
provider.complete_login(
code="the-code",
@@ -644,7 +730,7 @@ class TestConfidentialClient:
200, {"id_token": id_token, "token_type": "Bearer", "refresh_token": "rt2"}
)
with patch(
"plugins.dashboard_auth.self_hosted.httpx.post", return_value=mock_resp
"plugins.dashboard_auth._shared._request_limited_response", return_value=mock_resp
) as mock_post:
provider.refresh_session(refresh_token="rt_old")
_, kwargs = mock_post.call_args