diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b23372..32060bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased: rename to Typewright +- AI Gateway example routes now require the exact pinned HTTPS URL for each route + (approved endpoint policy). A worker whose `.env.local` points routes 3-5 at any + other host, port or path now fails at startup, before any credential is sent. + Redirects are refused and errors never echo the configured URL (#88). - Frozen hierarchy artifacts are now checked for lexical scope on load: node origins must match their export chain, references, `after` edges, and finals may not cross subgraph scopes (except through the inputs an export passes down), and exports must have descendant nodes (#85). diff --git a/examples/ai-gateway/README.md b/examples/ai-gateway/README.md index 35388c0..a0bd54d 100644 --- a/examples/ai-gateway/README.md +++ b/examples/ai-gateway/README.md @@ -116,3 +116,33 @@ equal to its row count has no spare attempts for retries. If exhausted, the runner must retain the selected program, mark the arm incomplete without a score, and continue other arms. It must not silently refill budgets or count a partial calibration as complete. + +### Exact endpoint policy (#88) + +The local adapter now accepts only these exact HTTPS destination strings: + +| Route | Destination | +|---|---| +| Vercel keys 1 and 2 | `https://ai-gateway.vercel.sh/typesafe/v1/systemone` | +| BeatAPI | `https://api.beatapi.io/v1/systemone` | +| OpenCode Zen | `https://opencode.ai/zen/v1/systemone` | +| Classifier.dev | `https://classifier.dev/v1/systemone` | + +This strict policy was approved by the endpoint-policy owner on 2026-11-12 and +is enforced by the adapter. The three configurable third-party destinations match +the public `.env.example`. A worker whose `.env.local` points routes 3-5 at any +other destination now fails at startup, before any credential is sent. No operator +`.env.local` was inspected, no live worker configuration was changed and no live +route qualification was performed for this patch, so existing workers should +confirm their destinations match before restarting. Alternate hosts, proxies, +explicit ports (including 443), path variations, case variations, userinfo, query +strings, fragments, whitespace and malformed URLs all fail closed. Supporting a different endpoint requires a reviewed policy +change; environment configuration alone cannot authorize it. + +Validation runs while constructing route settings, before constructing the HTTP +client, and again before each dispatch. Native adapters copy their configuration +and reject later destination drift before serializing study state. Redirects are +disabled at client construction and explicitly at dispatch; every non-200 response, +including redirects, is an error. Offline regression tests use fake credentials, +synthetic state and local HTTP transport doubles only. They provide security +mechanics evidence, not provider qualification. diff --git a/examples/ai-gateway/paced_routes.py b/examples/ai-gateway/paced_routes.py index 5f5d635..37658e4 100644 --- a/examples/ai-gateway/paced_routes.py +++ b/examples/ai-gateway/paced_routes.py @@ -8,6 +8,7 @@ import os from datetime import datetime, timezone from email.utils import parsedate_to_datetime +from types import MappingProxyType import httpx from dotenv import dotenv_values @@ -20,6 +21,23 @@ PIN = "jev-1.13.0" # A hostile or buggy Retry-After must not freeze a whole route group indefinitely. MAX_COOLDOWN_SECONDS = 600 +# Approved exact endpoint policy (#88, owner-approved 2026-11-12); enforced, not configurable. +ROUTE_DESTINATIONS = MappingProxyType({ + "gateway-1": "https://ai-gateway.vercel.sh/typesafe/v1/systemone", + "gateway-2": "https://ai-gateway.vercel.sh/typesafe/v1/systemone", + "beatapi": "https://api.beatapi.io/v1/systemone", + "opencode-zen": "https://opencode.ai/zen/v1/systemone", + "classifier": "https://classifier.dev/v1/systemone", +}) + + +def validate_destination(name, url): + """Exact comparison rejects alternate hosts and URL parser normalization tricks.""" + expected = ROUTE_DESTINATIONS.get(name) + if expected is None or type(url) is not str or url != expected: + # Never echo an untrusted URL: it may contain credentials or private data. + raise ConfigurationError("Route destination differs from the approved exact HTTPS policy (#88).") + return expected def retry_after(value, now=None): @@ -149,13 +167,17 @@ class Native: synthetic = False def __init__(self, name, config, key): + validate_destination(name, config.get("url")) self.identity = name - self.config = config + self.config = dict(config) self.provider_attempts = 0 self.providers = set() - self.client = httpx.Client(headers={"Authorization": "Bearer " + key}, timeout=60) + self.client = httpx.Client( + headers={"Authorization": "Bearer " + key}, timeout=60, follow_redirects=False + ) def evaluate(self, program, state): + url = validate_destination(self.identity, self.config.get("url")) if program.model != PIN: raise BackendError("Unapproved program model.") payload = { @@ -166,7 +188,7 @@ def evaluate(self, program, state): if self.identity.startswith("gateway-"): payload["providerOptions"] = {"gateway": {"only": ["typesafe-ai"]}} start = time.perf_counter() - response = self.client.post(self.config["url"], json=payload) + response = self.client.post(url, json=payload, follow_redirects=False) if response.status_code != 200: raise HTTPFailure(response) body = response.json() @@ -396,6 +418,7 @@ def configurations(settings): } if i == 5: configs[name].update(questions_per_second=50, questions_per_minute=3000, questions_daily=20000) + validate_destination(name, configs[name]["url"]) return configs diff --git a/tests/test_gateway_routes.py b/tests/test_gateway_routes.py index e6fe9f9..fa19a1a 100644 --- a/tests/test_gateway_routes.py +++ b/tests/test_gateway_routes.py @@ -304,3 +304,163 @@ def test_every_gateway_route_including_one_and_two_needs_its_enable_flag(): assert list(enabled) == ["direct", "gateway-1", "gateway-2"] only_two = r.configurations({"AI_GATEWAY_ROUTE_2_ENABLED": "true"}) assert list(only_two) == ["direct", "gateway-2"] + + +UNSAFE_DESTINATIONS = [ + "http://api.beatapi.io/v1/systemone", + "https://unapproved.example/v1/systemone", + "https://api.beatapi.io.attacker.example/v1/systemone", + "https://fake-user:fake-secret@api.beatapi.io/v1/systemone", + "https://api.beatapi.io:443/v1/systemone", + "https://api.beatapi.io/v1/systemone?secret=fake", + "https://api.beatapi.io/v1/systemone#fragment", + "https://api.beatapi.io/v1/systemone?", + "https://api.beatapi.io/v1/systemone#", + "https://api.beatapi.io/v1/systemone/", + "https://api.beatapi.io/v1/../v1/systemone", + "https://api.beatapi.io/v1/%73ystemone", + "https://API.BEATAPI.IO/v1/systemone", + "https://api.beatapi.io./v1/systemone", + " https://api.beatapi.io/v1/systemone", + "https://api.beatapi.io/v1/systemone\n", + "https://api.beatapi.io\\@unapproved.example/v1/systemone", + "https://127.0.0.1/v1/systemone", + "https://[::1]/v1/systemone", + "https://api.beatapi.io:bad/v1/systemone", + "not-a-url", "", None, +] + + +@pytest.mark.parametrize("url", UNSAFE_DESTINATIONS) +def test_unsafe_destination_rejected_before_client_construction(monkeypatch, url): + called = [] + monkeypatch.setattr(r.httpx, "Client", lambda **kwargs: called.append(kwargs)) + with pytest.raises(r.ConfigurationError, match="approved exact HTTPS policy") as exc: + r.Native("beatapi", {"url": url, "model": "jev-1.13-free"}, "fake-test-key") + assert called == [] + assert "fake-secret" not in str(exc.value) + assert "unapproved.example" not in str(exc.value) + + +@pytest.mark.parametrize("route,name", [(3, "beatapi"), (4, "opencode-zen"), (5, "classifier")]) +def test_settings_reject_destination_for_wrong_route(route, name): + settings = { + f"AI_GATEWAY_ROUTE_{route}_ENABLED": "true", + f"AI_GATEWAY_ROUTE_{route}_MODEL": r.PIN if route == 5 else "jev-1.13-free", + f"AI_GATEWAY_ROUTE_{route}_SYSTEMONE_URL": r.ROUTE_DESTINATIONS["gateway-1"], + } + with pytest.raises(r.ConfigurationError): + r.configurations(settings) + settings[f"AI_GATEWAY_ROUTE_{route}_SYSTEMONE_URL"] = r.ROUTE_DESTINATIONS[name] + assert r.configurations(settings)[name]["url"] == r.ROUTE_DESTINATIONS[name] + + +def test_pinned_destinations_match_public_example(): + settings = r.dotenv_values(Path(r.__file__).parent / ".env.example") + for route, name in [(3, "beatapi"), (4, "opencode-zen"), (5, "classifier")]: + assert settings[f"AI_GATEWAY_ROUTE_{route}_SYSTEMONE_URL"] == r.ROUTE_DESTINATIONS[name] + + +@pytest.mark.parametrize("url", UNSAFE_DESTINATIONS) +def test_mutated_destination_rejected_before_state_serialization_or_transport(monkeypatch, url): + calls = [] + original_client = httpx.Client + monkeypatch.setattr(r.httpx, "Client", lambda **kwargs: original_client( + transport=httpx.MockTransport(lambda request: calls.append(request)), **kwargs + )) + config = {"url": r.ROUTE_DESTINATIONS["beatapi"], "model": "jev-1.13-free"} + backend = r.Native("beatapi", config, "fake-test-key") + try: + config["url"] = url + assert backend.config["url"] == r.ROUTE_DESTINATIONS["beatapi"] + backend.config["url"] = url + # No program/state access is needed before rejecting destination drift. + with pytest.raises(r.ConfigurationError): + backend.evaluate(None, object()) + assert calls == [] + finally: + backend.close() + + +@pytest.mark.parametrize("name", list(r.ROUTE_DESTINATIONS)) +def test_exact_destination_dispatch_with_local_transport(monkeypatch, name): + import json + calls = [] + model = "typesafe-ai/jev" if name.startswith("gateway-") else ( + r.PIN if name == "classifier" else "jev-1.13-free" + ) + + def respond(request): + calls.append(request) + return httpx.Response(200, json={"answers": {}, "model": model}) + + original_client = httpx.Client + monkeypatch.setattr(r.httpx, "Client", lambda **kwargs: original_client( + transport=httpx.MockTransport(respond), **kwargs + )) + backend = r.Native(name, {"url": r.ROUTE_DESTINATIONS[name], "model": model}, "fake-test-key") + try: + response = backend.evaluate(SimpleNamespace(model=r.PIN, questions={}), {"fixture": "synthetic"}) + assert response.model == model + assert len(calls) == 1 + assert str(calls[0].url) == r.ROUTE_DESTINATIONS[name] + assert calls[0].headers["authorization"] == "Bearer fake-test-key" + assert json.loads(calls[0].content)["state"] == {"fixture": "synthetic"} + finally: + backend.close() + + +@pytest.mark.parametrize("status", [301, 302, 303, 307, 308]) +def test_redirects_never_forward_credentials_or_study_state(monkeypatch, status): + calls = [] + + def redirect(request): + calls.append(request) + return httpx.Response(status, headers={"location": "https://unapproved.example/stolen"}) + + original_client = httpx.Client + monkeypatch.setattr(r.httpx, "Client", lambda **kwargs: original_client( + transport=httpx.MockTransport(redirect), **kwargs + )) + backend = r.Native("beatapi", { + "url": r.ROUTE_DESTINATIONS["beatapi"], "model": "jev-1.13-free" + }, "fake-test-key") + try: + assert backend.client.follow_redirects is False + backend.client.follow_redirects = True # Per-dispatch policy still wins. + with pytest.raises(r.HTTPFailure) as exc: + backend.evaluate(SimpleNamespace(model=r.PIN, questions={}), {"fixture": "synthetic"}) + assert exc.value.status_code == status + assert len(calls) == 1 + assert str(calls[0].url) == r.ROUTE_DESTINATIONS["beatapi"] + assert r.failure(exc.value)[0] is False + finally: + backend.close() + + +def test_unknown_native_route_is_rejected_before_credentials(monkeypatch): + calls = [] + monkeypatch.setattr(r.httpx, "Client", lambda **kwargs: calls.append(kwargs)) + with pytest.raises(r.ConfigurationError): + r.Native("unknown", {"url": r.ROUTE_DESTINATIONS["beatapi"]}, "fake-test-key") + assert calls == [] + + +@pytest.mark.parametrize("route", [3, 4, 5]) +@pytest.mark.parametrize("url", UNSAFE_DESTINATIONS) +def test_unsafe_destination_rejected_during_settings_construction(route, url): + settings = { + f"AI_GATEWAY_ROUTE_{route}_ENABLED": "true", + f"AI_GATEWAY_ROUTE_{route}_MODEL": r.PIN if route == 5 else "jev-1.13-free", + f"AI_GATEWAY_ROUTE_{route}_SYSTEMONE_URL": url, + } + with pytest.raises(r.ConfigurationError, match="approved exact HTTPS policy"): + r.configurations(settings) + + +def test_destination_policy_rejects_accidental_in_process_reconfiguration(): + with pytest.raises(TypeError): + r.ROUTE_DESTINATIONS["beatapi"] = "https://unapproved.example/v1/systemone" + assert r.validate_destination("beatapi", "https://api.beatapi.io/v1/systemone") == ( + "https://api.beatapi.io/v1/systemone" + )