diff --git a/gateway/app/core/health.py b/gateway/app/core/health.py index 40ae893f2..0338d79bc 100644 --- a/gateway/app/core/health.py +++ b/gateway/app/core/health.py @@ -542,49 +542,47 @@ async def _check_sentinel(simulation_modes: dict[str, bool]) -> dict[str, Any]: return {"status": "up"} -async def gather_dependency_report() -> dict[str, Any]: +async def gather_dependency_report( + only: frozenset[str] | None = None, +) -> dict[str, Any]: """ - Run every dependency check in parallel and return a consolidated report. + Run the dependency checks in parallel and return a consolidated report. Overall status degrades to ``degraded`` if any required dependency returns ``down``. ``not_configured`` and ``not_used`` are both considered healthy. + + ``only`` limits the probes that are started to the named dependencies and + the report to their entries. A probe that is not named is never started, + so it makes no outbound call. The unauthenticated route passes + ``PUBLIC_DEPENDENCY_KEYS`` when proof surfaces are unmounted: it would + discard the other verdicts, so probing Stripe, the LLM provider, the MQTT + broker or Sentinel there is outbound work and latency that an anonymous + caller could trigger for nothing. ``None`` runs every probe. """ settings = get_settings() sim_modes = get_simulation_modes() - ( - postgres, - redis_res, - mqtt, - stripe_res, - llm, - upstream_mcp, - signing_key, - sentinel, - ) = await asyncio.gather( - _run_check("postgres", _check_postgres), - _run_check("redis", _check_redis), - _run_check("mqtt", lambda: _check_mqtt(sim_modes)), - _run_check("stripe", _check_stripe), - _run_check("llm", lambda: _check_llm(sim_modes)), - _run_check("upstream_mcp", _check_upstream_mcp), - _run_check("signing_key", _check_signing_key), - _run_check("sentinel", lambda: _check_sentinel(sim_modes)), + # Declaration order is the order of the keys in the report. + probes: dict[str, Callable[[], Awaitable[dict[str, Any]]]] = { + "postgres": _check_postgres, + "redis": _check_redis, + "mqtt": lambda: _check_mqtt(sim_modes), + "stripe": _check_stripe, + "llm": lambda: _check_llm(sim_modes), + "upstream_mcp": _check_upstream_mcp, + "signing_key": _check_signing_key, + "sentinel": lambda: _check_sentinel(sim_modes), + } + selected = [name for name in probes if only is None or name in only] + results = await asyncio.gather( + *(_run_check(name, probes[name]) for name in selected) ) - - dependencies = { - "postgres": postgres, - "redis": redis_res, + dependencies = dict(zip(selected, results, strict=True)) + if "mqtt" in dependencies: # The full report is served unauthenticated wherever proof surfaces # are mounted, so the broker address is projected out here too. - "mqtt": _public_mqtt_probe(mqtt), - "stripe": stripe_res, - "llm": llm, - "upstream_mcp": upstream_mcp, - "signing_key": signing_key, - "sentinel": sentinel, - } + dependencies["mqtt"] = _public_mqtt_probe(dependencies["mqtt"]) unhealthy = [ name for name, r in dependencies.items() if r.get("status") not in _OK_STATUSES diff --git a/gateway/app/main.py b/gateway/app/main.py index 8abe0b551..d2bfca547 100644 --- a/gateway/app/main.py +++ b/gateway/app/main.py @@ -37,6 +37,7 @@ ) from .core.health import ( CHECK_TIMEOUT_SECONDS, + PUBLIC_DEPENDENCY_KEYS, build_public_dependency_report, check_redis_liveness, check_database_readiness, @@ -1366,13 +1367,15 @@ async def health_ready(): ), ) async def health_dependencies(): - report = await gather_dependency_report() if get_settings().ENABLE_PROOF_SURFACES: # Proof surfaces are mounted and reachable, so their dependency truth # and simulation flags are live, relevant disclosures. - return report + return await gather_dependency_report() # Production posture: report the wedge, not a billboard of unmounted # surfaces. Full truth stays in the startup log (phase="runtime_posture"). + # The other probes are not started: their verdicts would be discarded, and + # an anonymous caller must not be able to trigger outbound calls for them. + report = await gather_dependency_report(only=PUBLIC_DEPENDENCY_KEYS) return build_public_dependency_report(report) diff --git a/gateway/tests/test_health_public_probes.py b/gateway/tests/test_health_public_probes.py new file mode 100644 index 000000000..25c80a075 --- /dev/null +++ b/gateway/tests/test_health_public_probes.py @@ -0,0 +1,139 @@ +"""The public dependency route must not start probes whose verdicts it discards. + +With proof surfaces unmounted, ``GET /health/dependencies`` reports only the +wedge dependencies. Stripe, the LLM provider, the MQTT broker and Sentinel are +projected out of that payload, so an anonymous caller must not be able to make +the gateway call them. Calls are counted by patching the Stripe SDK class and +the HTTP client class, never a singleton instance. +""" + +from __future__ import annotations + +import secrets +from types import SimpleNamespace + +import httpx +import pytest +import stripe +from httpx import ASGITransport, AsyncClient + +from app.core.config import get_settings +from app.core.health import ( + PUBLIC_DEPENDENCY_KEYS, + build_public_dependency_report, + gather_dependency_report, +) +from app.main import app + +SENTINEL_ORIGIN = "http://127.0.0.1:9" +SENTINEL_HEALTH_URL = f"{SENTINEL_ORIGIN}/health" + + +@pytest.fixture +async def client(clean_database): + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as c: + yield c + + +@pytest.fixture +def probe_counts(monkeypatch): + """Configure Stripe and Sentinel as reachable and count calls to each.""" + counts = {"stripe": 0, "sentinel": 0} + + def fake_retrieve(*_args, **_kwargs): + counts["stripe"] += 1 + return SimpleNamespace(livemode=False) + + real_get = httpx.AsyncClient.get + + async def counting_get(self, url, *args, **kwargs): + if str(url) == SENTINEL_HEALTH_URL: + counts["sentinel"] += 1 + return httpx.Response(200, request=httpx.Request("GET", str(url))) + return await real_get(self, url, *args, **kwargs) + + monkeypatch.setattr(stripe.Balance, "retrieve", staticmethod(fake_retrieve)) + monkeypatch.setattr(httpx.AsyncClient, "get", counting_get) + + cfg = get_settings() + names = ( + "STRIPE_SECRET_KEY", + "SENTINEL_API_URL", + "SENTINEL_API_KEY", + "SIMULATION_MODE_HUMAN_APPROVAL", + "ENABLE_PROOF_SURFACES", + ) + previous = {name: getattr(cfg, name) for name in names} + cfg.STRIPE_SECRET_KEY = f"sk_test_{secrets.token_urlsafe(24)}" + cfg.SENTINEL_API_URL = SENTINEL_ORIGIN + cfg.SENTINEL_API_KEY = secrets.token_urlsafe(24) + cfg.SIMULATION_MODE_HUMAN_APPROVAL = False + cfg.ENABLE_PROOF_SURFACES = False + try: + yield counts + finally: + for name, value in previous.items(): + setattr(cfg, name, value) + + +def _without_latency(payload): + if isinstance(payload, dict): + return {k: _without_latency(v) for k, v in payload.items() if k != "latency_ms"} + return payload + + +@pytest.mark.anyio +async def test_anonymous_public_request_starts_no_stripe_or_sentinel_probe( + client, probe_counts +): + resp = await client.get("/health/dependencies") + + assert resp.status_code == 200 + assert set(resp.json()["dependencies"]) == set(PUBLIC_DEPENDENCY_KEYS) + assert probe_counts == {"stripe": 0, "sentinel": 0} + + +@pytest.mark.anyio +async def test_public_body_is_what_the_full_report_projects_to(client, probe_counts): + resp = await client.get("/health/dependencies") + full = await gather_dependency_report() + expected = build_public_dependency_report(full) + + assert _without_latency(resp.json()) == _without_latency(expected) + + +@pytest.mark.anyio +async def test_mounted_proof_surfaces_still_run_every_probe(client, probe_counts): + get_settings().ENABLE_PROOF_SURFACES = True + + resp = await client.get("/health/dependencies") + + body = resp.json() + assert {"mqtt", "stripe", "llm", "sentinel"} <= set(body["dependencies"]) + assert probe_counts == {"stripe": 1, "sentinel": 1} + + +@pytest.mark.anyio +async def test_only_limits_the_probes_started_and_the_entries_reported(probe_counts): + report = await gather_dependency_report(only=frozenset({"postgres", "redis"})) + + assert list(report["dependencies"]) == ["postgres", "redis"] + assert probe_counts == {"stripe": 0, "sentinel": 0} + + +@pytest.mark.anyio +async def test_gather_without_only_runs_every_probe(probe_counts): + report = await gather_dependency_report() + + assert set(report["dependencies"]) == { + "postgres", + "redis", + "mqtt", + "stripe", + "llm", + "upstream_mcp", + "signing_key", + "sentinel", + } + assert probe_counts == {"stripe": 1, "sentinel": 1}