diff --git a/agents/dataset-eval/README.md b/agents/dataset-eval/README.md index cab24f66fd..2d95234eb6 100644 --- a/agents/dataset-eval/README.md +++ b/agents/dataset-eval/README.md @@ -108,6 +108,8 @@ FIREFOX_GIT_REPO=/path/to/firefox DATASET=:latest JUDGE_RUBRIC= `.env` needs `ANTHROPIC_API_KEY` and `WANDB_API_KEY` (and `CODEX_API_KEY` for the `codex` harness, and `OTARI_API_KEY`, with the `usage:read` scope, and `OTARI_BASE_URL`, e.g. `https://api.otari.ai/api`, for the open-model harnesses). +Deployed, `OTARI_FEDERATION_RULE_ID` replaces `OTARI_API_KEY`: the job authenticates +to otari as its service account ([`otari_wif.py`](hackbot_agents/dataset_eval/prompt_executor/harnesses/otari_wif.py)). The local Firefox clone is mounted read-only and lends its objects to the tree, so nothing is cloned; the run uses its checked-out HEAD, or `SOURCE_REF`. diff --git a/agents/dataset-eval/hackbot_agents/dataset_eval/prompt_executor/__main__.py b/agents/dataset-eval/hackbot_agents/dataset_eval/prompt_executor/__main__.py index 18f335e0ba..68c9f7612f 100644 --- a/agents/dataset-eval/hackbot_agents/dataset_eval/prompt_executor/__main__.py +++ b/agents/dataset-eval/hackbot_agents/dataset_eval/prompt_executor/__main__.py @@ -10,6 +10,7 @@ """ import asyncio +import contextlib import os import time from pathlib import Path @@ -19,7 +20,7 @@ from opentelemetry.sdk.trace import SpanProcessor, TracerProvider from pydantic_settings import BaseSettings, SettingsConfigDict -from .harnesses import Looping, Run, get_harness +from .harnesses import Looping, Run, get_harness, otari, otari_wif # Weave surfaces it as ``attributes.hackbot.harness`` on every call of the run. HARNESS_SPAN_ATTRIBUTE = "wandb.attributes.hackbot.harness" @@ -76,8 +77,14 @@ async def main(ctx: HackbotContext) -> PromptExecutorResult: run = Run(transcript=[{"role": "user", "content": inputs.prompt}]) timed_out = looped = False try: - async with asyncio.timeout(inputs.timeout_s): - await get_harness(inputs.harness).run( + harness = get_harness(inputs.harness) + auth = ( + otari_wif.serving() + if harness.vendor == otari.PROVIDER + else contextlib.nullcontext() + ) + async with auth, asyncio.timeout(inputs.timeout_s): + await harness.run( inputs.prompt, inputs.source_repo, inputs.model, inputs.effort, run ) except TimeoutError: diff --git a/agents/dataset-eval/hackbot_agents/dataset_eval/prompt_executor/harnesses/otari_wif.py b/agents/dataset-eval/hackbot_agents/dataset_eval/prompt_executor/harnesses/otari_wif.py new file mode 100644 index 0000000000..af01a57855 --- /dev/null +++ b/agents/dataset-eval/hackbot_agents/dataset_eval/prompt_executor/harnesses/otari_wif.py @@ -0,0 +1,175 @@ +# -*- coding: utf-8 -*- +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this file, +# You can obtain one at http://mozilla.org/MPL/2.0/. + +"""otari auth by GCP Workload Identity Federation, instead of an API key. + +With ``OTARI_FEDERATION_RULE_ID`` set, the workload's Google identity token is +exchanged for short-lived otari access tokens. The harnesses read one static key +when they start, so they reach otari through a local proxy that puts a fresh +token on every request: ``OTARI_BASE_URL`` points at the proxy and +``OTARI_API_KEY`` is a placeholder for as long as it runs. + +See https://docs.otari.ai/self-hosting/operations/workload-identity +""" + +import asyncio +import contextlib +import os +import time +from collections.abc import AsyncIterator +from urllib.parse import urlsplit + +import google.auth.transport.requests +import google.oauth2.id_token +import httpx +import uvicorn +from starlette.applications import Starlette +from starlette.background import BackgroundTask +from starlette.requests import Request +from starlette.responses import StreamingResponse +from starlette.routing import Route + +from . import otari + +RULE_ID_ENV = "OTARI_FEDERATION_RULE_ID" +GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer" +# A token is renewed this long before it expires. +RENEW_MARGIN_S = 60 +# otari's default access token lifetime, for a response that does not say. +DEFAULT_TOKEN_TTL_S = 600 +# Hop-by-hop, or set again for the upstream request. +DROPPED_REQUEST_HEADERS = { + "host", + "content-length", + "connection", + "authorization", + "otari-key", + "x-api-key", +} +DROPPED_RESPONSE_HEADERS = {"connection", "transfer-encoding", "keep-alive"} + + +def enabled() -> bool: + return bool(os.environ.get(RULE_ID_ENV)) + + +def _identity_token(audience: str) -> str: + request = google.auth.transport.requests.Request() + return google.oauth2.id_token.fetch_id_token(request, audience) + + +class AccessToken: + """otari access tokens exchanged for the workload's identity, renewed as they expire.""" + + def __init__(self, client: httpx.AsyncClient, base: str, rule_id: str): + self._client, self._base, self._rule_id = client, base, rule_id + parts = urlsplit(base) + self._audience = f"{parts.scheme}://{parts.netloc}" + self._token, self._expires = "", 0.0 + self._lock = asyncio.Lock() + + async def get(self) -> str: + async with self._lock: + if time.monotonic() > self._expires - RENEW_MARGIN_S: + await self._exchange() + return self._token + + async def _exchange(self) -> None: + identity = await asyncio.to_thread(_identity_token, self._audience) + response = await self._client.post( + f"{self._base}/v1/oauth/token", + json={ + "grant_type": GRANT_TYPE, + "assertion": identity, + "federation_rule_id": self._rule_id, + }, + ) + response.raise_for_status() + grant = response.json() + self._token = grant["access_token"] + ttl = grant.get("expires_in") or DEFAULT_TOKEN_TTL_S + self._expires = time.monotonic() + ttl + + +def proxy(client: httpx.AsyncClient, base: str, token: AccessToken) -> Starlette: + """Forwards ``/api/...`` to ``base``, the real API root, as the workload.""" + + async def forward(request: Request) -> StreamingResponse: + headers = { + k: v + for k, v in request.headers.items() + if k.lower() not in DROPPED_REQUEST_HEADERS + } + headers["Authorization"] = f"Bearer {await token.get()}" + upstream = client.build_request( + request.method, + base + request.url.path.removeprefix("/api"), + params=request.query_params, + headers=headers, + content=await request.body(), + ) + response = await client.send(upstream, stream=True) + return StreamingResponse( + response.aiter_raw(), + status_code=response.status_code, + headers={ + k: v + for k, v in response.headers.items() + if k.lower() not in DROPPED_RESPONSE_HEADERS + }, + background=BackgroundTask(response.aclose), + ) + + methods = ["GET", "POST", "PUT", "PATCH", "DELETE"] + return Starlette(routes=[Route("/api/{path:path}", forward, methods=methods)]) + + +class _Server(uvicorn.Server): + """Leaves the process's signal handling alone.""" + + @contextlib.contextmanager + def capture_signals(self): + yield + + +@contextlib.asynccontextmanager +async def serving() -> AsyncIterator[None]: + """Route otari through a federated proxy while in effect; inert without a rule.""" + if not enabled(): + yield + return + base = otari.api_url().removesuffix("/v1") + async with httpx.AsyncClient(timeout=httpx.Timeout(30, read=None)) as client: + token = AccessToken(client, base, os.environ[RULE_ID_ENV]) + # Fail here, not inside a harness, when the workload can't get a token. + await token.get() + server = _Server( + uvicorn.Config( + proxy(client, base, token), + host="127.0.0.1", + port=0, + log_level="warning", + lifespan="off", + ) + ) + task = asyncio.create_task(server.serve()) + while not server.started: + if task.done(): + task.result() + await asyncio.sleep(0.05) + port = server.servers[0].sockets[0].getsockname()[1] + saved = {k: os.environ.get(k) for k in ("OTARI_BASE_URL", otari.API_KEY_ENV)} + os.environ["OTARI_BASE_URL"] = f"http://127.0.0.1:{port}/api" + os.environ[otari.API_KEY_ENV] = "federated" + try: + yield + finally: + for name, value in saved.items(): + if value is None: + os.environ.pop(name, None) + else: + os.environ[name] = value + server.should_exit = True + await task diff --git a/agents/dataset-eval/pyproject.toml b/agents/dataset-eval/pyproject.toml index 6ced1dbff8..27ffd41067 100644 --- a/agents/dataset-eval/pyproject.toml +++ b/agents/dataset-eval/pyproject.toml @@ -11,6 +11,8 @@ dependencies = [ "anthropic", "openai-codex==0.167.0", "deepseek-harness-runtime-bin==0.2.2rc2", + "starlette", + "uvicorn", ] [project.optional-dependencies] diff --git a/agents/dataset-eval/tests/test_evals.py b/agents/dataset-eval/tests/test_evals.py index a9bfc31f47..e250c603ca 100644 --- a/agents/dataset-eval/tests/test_evals.py +++ b/agents/dataset-eval/tests/test_evals.py @@ -16,6 +16,7 @@ Run, harness_env, otari, + otari_wif, record, record_usage, trace, @@ -813,6 +814,100 @@ async def usage(tag, model): assert run.cost_usd == 2.0 +def _otari_upstream(seen): + """An otari that grants numbered tokens and echoes what it was sent.""" + import httpx + + def handle(request): + if request.url.path == "/api/v1/oauth/token": + grant = json.loads(request.content) + assert grant["grant_type"] == otari_wif.GRANT_TYPE + assert grant["assertion"] == "google-jwt" + assert grant["federation_rule_id"] == "fdrl_1" + seen.append("exchange") + return httpx.Response( + 200, json={"access_token": f"tok{len(seen)}", "expires_in": 600} + ) + seen.append((request.url.path, request.headers["authorization"])) + return httpx.Response(200, stream=httpx.ByteStream(b"data: hi\n\n")) + + return httpx.MockTransport(handle) + + +def test_otari_federation_renews_its_token_and_proxies_with_it(monkeypatch): + import httpx + + monkeypatch.setattr(otari_wif, "_identity_token", lambda audience: "google-jwt") + clock = [0.0] + monkeypatch.setattr(otari_wif.time, "monotonic", lambda: clock[0]) + seen = [] + base = "https://otari.test/api" + + async def go(): + async with httpx.AsyncClient(transport=_otari_upstream(seen)) as upstream: + token = otari_wif.AccessToken(upstream, base, "fdrl_1") + app = otari_wif.proxy(upstream, base, token) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://proxy" + ) as harness: + headers = {"Authorization": "Bearer federated", "Otari-Tags": "t"} + first = await harness.post("/api/v1/chat/completions", headers=headers) + clock[0] = 500 + await harness.post("/api/v1/chat/completions", headers=headers) + clock[0] = 545 + await harness.post("/api/v1/chat/completions", headers=headers) + return first + + first = asyncio.run(go()) + assert first.text == "data: hi\n\n" + assert seen == [ + "exchange", + ("/api/v1/chat/completions", "Bearer tok1"), + ("/api/v1/chat/completions", "Bearer tok1"), + "exchange", + ("/api/v1/chat/completions", "Bearer tok4"), + ] + + +def test_otari_federation_serves_the_harnesses_only_with_a_rule(monkeypatch): + import httpx + + monkeypatch.delenv(otari_wif.RULE_ID_ENV, raising=False) + monkeypatch.setenv("OTARI_BASE_URL", "https://otari.test/api") + monkeypatch.setenv("OTARI_API_KEY", "key") + + async def inert(): + async with otari_wif.serving(): + return os.environ["OTARI_BASE_URL"] + + assert asyncio.run(inert()) == "https://otari.test/api" + + seen = [] + client = httpx.AsyncClient + monkeypatch.setattr( + otari_wif.httpx, + "AsyncClient", + lambda **kw: client(transport=_otari_upstream(seen), **kw), + ) + monkeypatch.setattr(otari_wif, "_identity_token", lambda audience: "google-jwt") + monkeypatch.setenv(otari_wif.RULE_ID_ENV, "fdrl_1") + + async def federated(): + async with otari_wif.serving(): + url, key = os.environ["OTARI_BASE_URL"], os.environ["OTARI_API_KEY"] + async with client() as harness: + response = await harness.get( + f"{url}/v1/models/x", headers={"Authorization": f"Bearer {key}"} + ) + return url, response + + url, response = asyncio.run(federated()) + assert url.startswith("http://127.0.0.1:") and response.status_code == 200 + assert seen == ["exchange", ("/api/v1/models/x", "Bearer tok1")] + assert os.environ["OTARI_BASE_URL"] == "https://otari.test/api" + assert os.environ["OTARI_API_KEY"] == "key" + + def test_otari_settle_prices_the_stream_without_usage_access(monkeypatch): import httpx diff --git a/docs/hackbot/deployment.md b/docs/hackbot/deployment.md index 71b84e5964..bf9468ae03 100644 --- a/docs/hackbot/deployment.md +++ b/docs/hackbot/deployment.md @@ -76,8 +76,9 @@ Two things those files do not tell you: API (`RUN_ID`, the results bucket/prefix/policy, one var per input-schema field, and `PARENT_ARTIFACTS` for a chained run); static Job env fixed at deploy time (`BROKER_URL`, `SOURCE_REPO`, the Anthropic federation ids, - `OPENAI_FEDERATION_RULE_ID`, `WEAVE_PROJECT`); and local-only fallbacks - (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `WANDB_API_KEY`, `ARTIFACTS_DIR`). Only the first + `OPENAI_FEDERATION_RULE_ID`, `OTARI_FEDERATION_RULE_ID`, `WEAVE_PROJECT`); and local-only + fallbacks (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `OTARI_API_KEY`, `WANDB_API_KEY`, + `ARTIFACTS_DIR`). Only the first varies per run. The listener also honours `DRY_RUN=true`, which logs intended calls without POSTing them. diff --git a/docs/hackbot/security.md b/docs/hackbot/security.md index 6fe2175e99..8017dd3d83 100644 --- a/docs/hackbot/security.md +++ b/docs/hackbot/security.md @@ -60,6 +60,12 @@ which exposes the token through `OPENAI_IDENTITY_TOKEN_FILE`. The token's audien to `https://api.openai.com/v1` and can be overridden with `OPENAI_WIF_AUDIENCE`. Here WIF has precedence over an `OPENAI_API_KEY`, so a leftover key only logs a warning. +otari, the gateway `dataset-eval`'s open-model harnesses use, federates the same way when +`OTARI_FEDERATION_RULE_ID` is set. Those harnesses read a static key once, so they reach +otari through a local proxy that exchanges the identity token and puts a fresh access token +on every request +([otari_wif.py](../../agents/dataset-eval/hackbot_agents/dataset_eval/prompt_executor/harnesses/otari_wif.py)). + ## The signed upload policy The agent Job has **no GCP write identity**. Its only write capability is a V4 signed GCS diff --git a/uv.lock b/uv.lock index a68e709334..f8a5057eec 100644 --- a/uv.lock +++ b/uv.lock @@ -2569,6 +2569,8 @@ dependencies = [ { name = "hackbot-runtime", extra = ["claude-sdk"] }, { name = "openai-codex" }, { name = "pydantic-settings" }, + { name = "starlette" }, + { name = "uvicorn" }, ] [package.optional-dependencies] @@ -2586,6 +2588,8 @@ requires-dist = [ { name = "openai-codex", specifier = "==0.167.0" }, { name = "pydantic-settings" }, { name = "pygobject", marker = "extra == 'a11y'", specifier = ">=3.52" }, + { name = "starlette" }, + { name = "uvicorn" }, ] provides-extras = ["a11y"]