From 6c00d505283f3c3c7c1ba6ba59a865f2c960de81 Mon Sep 17 00:00:00 2001 From: Timothy Wayne Gregg Date: Sat, 3 Oct 2026 07:12:56 -0400 Subject: [PATCH 1/3] Validate gateway destinations before credentialed dispatch --- examples/ai-gateway/README.md | 29 ++++++ examples/ai-gateway/paced_routes.py | 28 ++++- tests/test_gateway_routes.py | 152 ++++++++++++++++++++++++++++ 3 files changed, 206 insertions(+), 3 deletions(-) diff --git a/examples/ai-gateway/README.md b/examples/ai-gateway/README.md index 35388c0..5613ac4 100644 --- a/examples/ai-gateway/README.md +++ b/examples/ai-gateway/README.md @@ -116,3 +116,32 @@ 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. + +### Proposed 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 is a proposal requiring endpoint-policy owner approval before +live use or adoption by an existing benchmark worker. The three configurable +third-party destinations match the public `.env.example`. No operator +`.env.local` was inspected and no live worker configuration was changed for this +patch. The owner must review destination compatibility privately before adopting +it; 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 or endpoint-owner approval. diff --git a/examples/ai-gateway/paced_routes.py b/examples/ai-gateway/paced_routes.py index 5f5d635..6faccd2 100644 --- a/examples/ai-gateway/paced_routes.py +++ b/examples/ai-gateway/paced_routes.py @@ -20,6 +20,23 @@ PIN = "jev-1.13.0" # A hostile or buggy Retry-After must not freeze a whole route group indefinitely. MAX_COOLDOWN_SECONDS = 600 +# Proposed strict endpoint policy; live adoption requires endpoint-owner review. +ROUTE_DESTINATIONS = { + "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 proposed exact HTTPS policy.") + return expected def retry_after(value, now=None): @@ -149,13 +166,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 +187,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 +417,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..3399777 100644 --- a/tests/test_gateway_routes.py +++ b/tests/test_gateway_routes.py @@ -304,3 +304,155 @@ 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="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_proposed_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="exact HTTPS policy"): + r.configurations(settings) From 7a9e77ebde1ea7766bcbb3a02a62934be6b27653 Mon Sep 17 00:00:00 2001 From: Timothy Wayne Gregg Date: Sat, 3 Oct 2026 07:14:17 -0400 Subject: [PATCH 2/3] Make gateway endpoint policy immutable --- examples/ai-gateway/paced_routes.py | 5 +++-- tests/test_gateway_routes.py | 8 ++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/examples/ai-gateway/paced_routes.py b/examples/ai-gateway/paced_routes.py index 6faccd2..40f8dc4 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 @@ -21,13 +22,13 @@ # A hostile or buggy Retry-After must not freeze a whole route group indefinitely. MAX_COOLDOWN_SECONDS = 600 # Proposed strict endpoint policy; live adoption requires endpoint-owner review. -ROUTE_DESTINATIONS = { +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): diff --git a/tests/test_gateway_routes.py b/tests/test_gateway_routes.py index 3399777..19f4a4a 100644 --- a/tests/test_gateway_routes.py +++ b/tests/test_gateway_routes.py @@ -456,3 +456,11 @@ def test_unsafe_destination_rejected_during_settings_construction(route, url): } with pytest.raises(r.ConfigurationError, match="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" + ) From edbc82d5b117970bea7fdf8a72eaaf36fac94be3 Mon Sep 17 00:00:00 2001 From: Timothy Wayne Gregg Date: Thu, 12 Nov 2026 21:49:45 -0500 Subject: [PATCH 3/3] Record approved gateway endpoint policy and changelog entry The exact HTTPS URL pinning for gateway routes is now owner-approved (#88). Replace "proposed / pending approval" wording in the README, the policy comment and the user-facing error with the approved, enforced policy, keeping the caveat that no operator .env.local was inspected and no live route qualification was done. Tighten the two tests that match the error text to the new wording, and add a CHANGELOG entry for the fail-at-startup behavior change. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++++ examples/ai-gateway/README.md | 21 +++++++++++---------- examples/ai-gateway/paced_routes.py | 4 ++-- tests/test_gateway_routes.py | 6 +++--- 4 files changed, 20 insertions(+), 15 deletions(-) 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 5613ac4..a0bd54d 100644 --- a/examples/ai-gateway/README.md +++ b/examples/ai-gateway/README.md @@ -117,7 +117,7 @@ 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. -### Proposed exact endpoint policy (#88) +### Exact endpoint policy (#88) The local adapter now accepts only these exact HTTPS destination strings: @@ -128,14 +128,15 @@ The local adapter now accepts only these exact HTTPS destination strings: | OpenCode Zen | `https://opencode.ai/zen/v1/systemone` | | Classifier.dev | `https://classifier.dev/v1/systemone` | -This strict policy is a proposal requiring endpoint-policy owner approval before -live use or adoption by an existing benchmark worker. The three configurable -third-party destinations match the public `.env.example`. No operator -`.env.local` was inspected and no live worker configuration was changed for this -patch. The owner must review destination compatibility privately before adopting -it; 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 +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 @@ -144,4 +145,4 @@ 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 or endpoint-owner approval. +mechanics evidence, not provider qualification. diff --git a/examples/ai-gateway/paced_routes.py b/examples/ai-gateway/paced_routes.py index 40f8dc4..37658e4 100644 --- a/examples/ai-gateway/paced_routes.py +++ b/examples/ai-gateway/paced_routes.py @@ -21,7 +21,7 @@ PIN = "jev-1.13.0" # A hostile or buggy Retry-After must not freeze a whole route group indefinitely. MAX_COOLDOWN_SECONDS = 600 -# Proposed strict endpoint policy; live adoption requires endpoint-owner review. +# 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", @@ -36,7 +36,7 @@ def validate_destination(name, url): 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 proposed exact HTTPS policy.") + raise ConfigurationError("Route destination differs from the approved exact HTTPS policy (#88).") return expected diff --git a/tests/test_gateway_routes.py b/tests/test_gateway_routes.py index 19f4a4a..fa19a1a 100644 --- a/tests/test_gateway_routes.py +++ b/tests/test_gateway_routes.py @@ -335,7 +335,7 @@ def test_every_gateway_route_including_one_and_two_needs_its_enable_flag(): 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="exact HTTPS policy") as exc: + 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) @@ -355,7 +355,7 @@ def test_settings_reject_destination_for_wrong_route(route, name): assert r.configurations(settings)[name]["url"] == r.ROUTE_DESTINATIONS[name] -def test_proposed_destinations_match_public_example(): +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] @@ -454,7 +454,7 @@ def test_unsafe_destination_rejected_during_settings_construction(route, url): 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="exact HTTPS policy"): + with pytest.raises(r.ConfigurationError, match="approved exact HTTPS policy"): r.configurations(settings)