diff --git a/docs/grpc-api.md b/docs/grpc-api.md index 82266d8..059d13a 100644 --- a/docs/grpc-api.md +++ b/docs/grpc-api.md @@ -51,6 +51,9 @@ Errors use standard gRPC status codes with a `google.rpc.ErrorInfo` detail whose |---------|---------| | `--api-grpc-port` or `AGENTEVALS_API_GRPC_PORT` | Port, default `8002`; `0` turns the API off | | `--api-grpc-only` or `AGENTEVALS_API_GRPC_ONLY=true` | Serve only the gRPC API on `--host`, see below | +| `--api-grpc-auth` or `AGENTEVALS_API_GRPC_AUTH` | `none` (default) or `kubernetes`, see [Security](#security) | +| `--api-grpc-auth-audience` or `AGENTEVALS_API_GRPC_AUTH_AUDIENCE` | Token audience, default `agentevals` | +| `--api-grpc-auth-allowed-service-account` or `AGENTEVALS_API_GRPC_AUTH_ALLOWED_SERVICE_ACCOUNTS` | Allowed ServiceAccount as `namespace/name`; repeat the flag, or comma separate the env var | | `AGENTEVALS_GRPC_REFLECTION=true` | Turn on server reflection | | `AGENTEVALS_API_TRACES=true` | Export traces of the API server itself (see below) | @@ -81,6 +84,28 @@ AGENTEVALS_API_TRACES=true OTEL_TRACES_EXPORTER=console uv run agentevals serve ## Security -The API has no authentication. Any caller that can reach the port can read sessions, run evaluations with the server's credentials, and submit runs. Expose port 8002 only to trusted callers, for example inside a cluster behind a NetworkPolicy, and put authentication in front of it when you need it. +By default the API has no authentication. Any caller that can reach the port can read sessions, run evaluations with the server's credentials, and submit runs. Expose port 8002 only to trusted callers. On a laptop `agentevals serve` listens on all interfaces. Pass `--host 127.0.0.1` to keep every port local. + +### Kubernetes ServiceAccount authentication + +Inside a cluster, the server can admit only the ServiceAccounts you name: + +```bash +agentevals serve --api-grpc-only \ + --api-grpc-auth kubernetes \ + --api-grpc-auth-allowed-service-account evals/controller +``` + +Callers send a ServiceAccount token minted for the audience as `authorization: Bearer ` metadata, for example a [projected token](https://kubernetes.io/docs/concepts/storage/projected-volumes/#serviceaccounttoken) with `audience: agentevals`. The server checks it with a TokenReview, so its own ServiceAccount needs `create` on `tokenreviews.authentication.k8s.io`. + +| Result | Status | +|--------|--------| +| No token, a malformed or expired token, a token for another audience, or a user that is not a ServiceAccount | `UNAUTHENTICATED` | +| A valid ServiceAccount that is not on the list | `PERMISSION_DENIED` | +| The TokenReview fails, for example because the Kubernetes API is down | `UNAVAILABLE` | + +The list is required: any pod can mint a token for any audience, so the audience alone proves nothing. The server refuses to start with an empty list, and never lets a call through when a check fails. A successful check is cached for up to 30 seconds and never past the token's expiry. Health checks need no token. Reflection, when turned on, needs one like every other call: `grpcurl -H "authorization: Bearer $TOKEN" ...`. + +Authentication covers only the gRPC API. Combine it with `--api-grpc-only` so the REST API, the OTLP receivers and MCP stay on `127.0.0.1`; without it the server prints a warning. diff --git a/src/agentevals/api/app.py b/src/agentevals/api/app.py index a61c7f3..77d8f54 100644 --- a/src/agentevals/api/app.py +++ b/src/agentevals/api/app.py @@ -137,7 +137,7 @@ async def lifespan(app: FastAPI): from .rpc.services import ApiContext context = ApiContext(manager=mgr, run_service=getattr(app.state, "run_service", None), ports=api_grpc.ports) - api_server = await start_api_server(context, api_grpc.host, api_grpc.port) + api_server = await start_api_server(context, api_grpc.host, api_grpc.port, api_grpc.auth) yield diff --git a/src/agentevals/api/rpc/auth.py b/src/agentevals/api/rpc/auth.py new file mode 100644 index 0000000..c71a14f --- /dev/null +++ b/src/agentevals/api/rpc/auth.py @@ -0,0 +1,292 @@ +"""Optional Kubernetes ServiceAccount authentication for the gRPC API. + +A caller sends ``authorization: Bearer `` with a ServiceAccount token minted for the configured +audience. The server verifies the token with a TokenReview and accepts only the ServiceAccounts on an +explicit allowlist: any pod can mint a token for any audience, so the audience alone authorizes +nothing. Health checks stay open; reflection, when turned on, needs a token like every other +service. A failed check never falls back to unauthenticated access. +""" + +from __future__ import annotations + +import asyncio +import base64 +import hashlib +import json +import logging +import re +import time +from collections import OrderedDict +from collections.abc import Callable, Iterable +from dataclasses import dataclass +from typing import Any + +import grpc + +logger = logging.getLogger(__name__) + +DEFAULT_AUDIENCE = "agentevals" +SERVICE_ACCOUNT_PREFIX = "system:serviceaccount:" +CACHE_TTL_SECONDS = 30.0 +CACHE_MAX_ENTRIES = 1024 +REVIEW_TIMEOUT_SECONDS = 10 +OPEN_SERVICES = frozenset({"grpc.health.v1.Health"}) + +UNAUTHENTICATED_MESSAGE = "missing or invalid bearer token" +PERMISSION_DENIED_MESSAGE = "this service account may not call the API" +UNAVAILABLE_MESSAGE = "credential verification is unavailable" + +_NAMESPACE = re.compile(r"[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?") +_NAME = re.compile(r"[a-z0-9]([-a-z0-9.]{0,251}[a-z0-9])?") + + +class Unauthenticated(Exception): + """The token is missing, malformed, expired or rejected by the TokenReview.""" + + +class ReviewUnavailable(Exception): + """The TokenReview could not be completed.""" + + +def parse_service_account(value: str) -> str: + """Normalize ``namespace/name``, rejecting anything Kubernetes would not accept as one.""" + namespace, sep, name = value.strip().partition("/") + if not sep or not _NAMESPACE.fullmatch(namespace) or not _NAME.fullmatch(name): + raise ValueError(f"expected a ServiceAccount as namespace/name, got {value!r}") + return f"{namespace}/{name}" + + +@dataclass(frozen=True, slots=True) +class KubernetesAuth: + audience: str + allowed_service_accounts: frozenset[str] + # An ``AuthenticationV1Api`` or anything with the same ``create_token_review``. + token_reviews: Any + + def __post_init__(self) -> None: + if not self.audience: + raise ValueError("Kubernetes authentication needs an audience") + if not self.allowed_service_accounts: + raise ValueError("Kubernetes authentication needs at least one allowed ServiceAccount") + + +def kubernetes_token_reviews() -> Any: + """An ``AuthenticationV1Api`` from in-cluster config, or the local kubeconfig for development.""" + try: + from kubernetes import client, config + except ImportError as exc: + raise RuntimeError( + "Kubernetes authentication requires the 'kubernetes' extra; install agentevals-cli[kubernetes]" + ) from exc + + try: + config.load_incluster_config() + except config.ConfigException: + config.load_kube_config() + return client.AuthenticationV1Api() + + +@dataclass(frozen=True, slots=True) +class _Verified: + username: str + valid_until: float + + +class TokenReviewVerifier: + """Verifies ServiceAccount tokens for one audience. + + Successful reviews are cached by a SHA-256 of the audience and token for at most ``ttl`` seconds + and never past the token's ``exp``. Failures are never cached. Concurrent lookups of one token + share a single review. + """ + + def __init__( + self, + token_reviews: Any, + audience: str, + *, + clock: Callable[[], float] = time.time, + ttl: float = CACHE_TTL_SECONDS, + max_entries: int = CACHE_MAX_ENTRIES, + ) -> None: + self._token_reviews = token_reviews + self._audience = audience + self._clock = clock + self._ttl = ttl + self._max_entries = max_entries + self._verified: OrderedDict[str, _Verified] = OrderedDict() + self._lookups: dict[str, asyncio.Future[_Verified]] = {} + + async def verify(self, token: str) -> str: + """The ServiceAccount username of a valid token; raises :class:`Unauthenticated` or + :class:`ReviewUnavailable`.""" + key = hashlib.sha256(f"{self._audience}\0{token}".encode()).hexdigest() + entry = self._cached(key) + if entry is None: + lookup = self._lookups.get(key) + if lookup is None or lookup.done(): + lookup = asyncio.ensure_future(self._review(key, token)) + self._lookups[key] = lookup + lookup.add_done_callback(lambda done: self._lookup_done(key, done)) + # A caller that goes away cancels its own wait, not the review others share. + entry = await asyncio.shield(lookup) + return entry.username + + def _cached(self, key: str) -> _Verified | None: + entry = self._verified.get(key) + if entry is None: + return None + if self._clock() < entry.valid_until: + self._verified.move_to_end(key) + return entry + del self._verified[key] + return None + + def _lookup_done(self, key: str, lookup: asyncio.Future[_Verified]) -> None: + if self._lookups.get(key) is lookup: + del self._lookups[key] + if not lookup.cancelled(): + # Marks the failure as retrieved when every waiter has gone away. + lookup.exception() + + async def _review(self, key: str, token: str) -> _Verified: + expires_at = _expiration(_unverified_claims(token), self._clock()) + # The TTL starts before the request so API server latency cannot extend it. + valid_until = self._clock() + self._ttl + if expires_at is not None: + valid_until = min(valid_until, expires_at) + + body = { + "apiVersion": "authentication.k8s.io/v1", + "kind": "TokenReview", + "spec": {"token": token, "audiences": [self._audience]}, + } + try: + review = await asyncio.to_thread( + self._token_reviews.create_token_review, body, _request_timeout=REVIEW_TIMEOUT_SECONDS + ) + except Exception as exc: + # A TokenReview response echoes the token, so neither the error nor its body is logged. + logger.warning("TokenReview failed: %s %s", type(exc).__name__, getattr(exc, "status", "") or "") + raise ReviewUnavailable from None + + status = getattr(review, "status", None) + user = getattr(status, "user", None) + username = getattr(user, "username", None) or "" + if ( + status is None + or status.authenticated is not True + or status.error + or not getattr(user, "uid", None) + or not username.startswith(SERVICE_ACCOUNT_PREFIX) + or self._audience not in (status.audiences or []) + or not self._clock() < valid_until + ): + raise Unauthenticated + + entry = _Verified(username=username, valid_until=valid_until) + self._verified[key] = entry + self._verified.move_to_end(key) + while len(self._verified) > self._max_entries: + self._verified.popitem(last=False) + return entry + + +class ServiceAccountInterceptor(grpc.aio.ServerInterceptor): + """Rejects every call outside :data:`OPEN_SERVICES` unless it carries the token of an allowed + ServiceAccount: ``UNAUTHENTICATED`` for a missing or invalid token, ``PERMISSION_DENIED`` for a + ServiceAccount outside the allowlist, ``UNAVAILABLE`` when the TokenReview fails.""" + + def __init__(self, verifier: TokenReviewVerifier, allowed_service_accounts: Iterable[str]) -> None: + self._verifier = verifier + self._allowed = frozenset(allowed_service_accounts) + + async def intercept_service(self, continuation, handler_call_details): + handler = await continuation(handler_call_details) + method = handler_call_details.method + if handler is None or method.lstrip("/").partition("/")[0] in OPEN_SERVICES: + return handler + denial = await self._check(method, handler_call_details.invocation_metadata or ()) + return handler if denial is None else _denying(handler, *denial) + + async def _check(self, method: str, metadata: Iterable[tuple[str, Any]]) -> tuple[grpc.StatusCode, str] | None: + token = _bearer_token([value for key, value in metadata if key == "authorization"]) + try: + if token is None: + raise Unauthenticated + username = await self._verifier.verify(token) + except Unauthenticated: + logger.info("RPC %s rejected: missing or invalid bearer token", method) + return grpc.StatusCode.UNAUTHENTICATED, UNAUTHENTICATED_MESSAGE + except ReviewUnavailable: + return grpc.StatusCode.UNAVAILABLE, UNAVAILABLE_MESSAGE + except Exception as exc: + logger.error("RPC %s rejected: credential check failed with %s", method, type(exc).__name__) + return grpc.StatusCode.INTERNAL, "internal server error" + + account = username.removeprefix(SERVICE_ACCOUNT_PREFIX).replace(":", "/", 1) + if account not in self._allowed: + logger.info("RPC %s rejected: ServiceAccount %s is not allowed", method, account) + return grpc.StatusCode.PERMISSION_DENIED, PERMISSION_DENIED_MESSAGE + return None + + +def build_interceptor(auth: KubernetesAuth) -> ServiceAccountInterceptor: + return ServiceAccountInterceptor( + TokenReviewVerifier(auth.token_reviews, auth.audience), auth.allowed_service_accounts + ) + + +def _bearer_token(values: list[Any]) -> str | None: + if len(values) != 1 or not isinstance(values[0], str): + return None + scheme, _, token = values[0].partition(" ") + if scheme.lower() != "bearer" or not token: + return None + return token + + +def _unverified_claims(token: str) -> dict[str, Any]: + """The JWT payload, read without checking the signature; the TokenReview verifies the token.""" + parts = token.split(".") + if len(parts) != 3: + raise Unauthenticated + payload = parts[1] + try: + claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) + except (ValueError, RecursionError): + raise Unauthenticated from None + if not isinstance(claims, dict): + raise Unauthenticated + return claims + + +def _expiration(claims: dict[str, Any], now: float) -> float | None: + """``exp`` as a timestamp, ``None`` when the token has none; raises when it is invalid or past.""" + if "exp" not in claims: + return None + exp = claims["exp"] + if isinstance(exp, bool) or not isinstance(exp, int | float) or not exp > now: + raise Unauthenticated + return float(exp) + + +def _denying(handler: grpc.RpcMethodHandler, code: grpc.StatusCode, details: str) -> grpc.RpcMethodHandler: + """A handler of the same kind as ``handler`` that only aborts.""" + + async def deny(request, context): + await context.abort(code, details) + + if handler.unary_unary: + factory = grpc.unary_unary_rpc_method_handler + elif handler.unary_stream: + factory = grpc.unary_stream_rpc_method_handler + elif handler.stream_unary: + factory = grpc.stream_unary_rpc_method_handler + else: + factory = grpc.stream_stream_rpc_method_handler + return factory( + deny, + request_deserializer=handler.request_deserializer, + response_serializer=handler.response_serializer, + ) diff --git a/src/agentevals/api/rpc/server.py b/src/agentevals/api/rpc/server.py index 8c5f369..59a1534 100644 --- a/src/agentevals/api/rpc/server.py +++ b/src/agentevals/api/rpc/server.py @@ -2,7 +2,8 @@ opt in tracing with the upstream gRPC instrumentation. A browser cannot speak native gRPC (no HTTP/2 trailers from ``fetch``), so this listener is out of -reach of web pages. Every caller that can reach it is trusted: expose it only to trusted callers. +reach of web pages. Without ``auth`` every caller that can reach it is trusted: expose it only to +trusted callers. """ from __future__ import annotations @@ -16,6 +17,7 @@ from ...telemetry import api_tracer_provider, env_flag from ..otlp_grpc import listen_address +from .auth import KubernetesAuth, build_interceptor from .policy import check_policies from .services import ApiContext, Ports, servicers @@ -41,6 +43,7 @@ class ApiGrpcSettings: host: str port: int ports: Ports + auth: KubernetesAuth | None = None @dataclass(slots=True) @@ -51,7 +54,7 @@ class ApiServer: port: int -async def start_api_server(context: ApiContext, host: str, port: int) -> ApiServer: +async def start_api_server(context: ApiContext, host: str, port: int, auth: KubernetesAuth | None = None) -> ApiServer: tracer_provider = api_tracer_provider() interceptors = [] if tracer_provider is not None: @@ -59,6 +62,8 @@ async def start_api_server(context: ApiContext, host: str, port: int) -> ApiServ noise = filters.any_of(filters.health_check(), filters.service_prefix("grpc.reflection.")) interceptors.append(aio_server_interceptor(tracer_provider=tracer_provider, filter_=filters.negate(noise))) + if auth is not None: + interceptors.append(build_interceptor(auth)) server = grpc.aio.server( interceptors=interceptors, options=SERVER_OPTIONS, maximum_concurrent_rpcs=MAX_CONCURRENT_RPCS @@ -85,10 +90,13 @@ async def start_api_server(context: ApiContext, host: str, port: int) -> ApiServ raise RuntimeError(f"Failed to bind the API gRPC server to {address}") await server.start() logger.info( - "API gRPC server on %s (reflection %s, tracing %s)", + "API gRPC server on %s (reflection %s, tracing %s, auth %s)", listen_address(host, bound), "on" if env_flag(REFLECTION_ENV) else "off", "on" if tracer_provider is not None else "off", + f"kubernetes, audience {auth.audience}, {len(auth.allowed_service_accounts)} allowed ServiceAccounts" + if auth is not None + else "off", ) return ApiServer(server=server, health=health_servicer, tracer_provider=tracer_provider, port=bound) diff --git a/src/agentevals/cli.py b/src/agentevals/cli.py index 1c345ec..ea45e21 100644 --- a/src/agentevals/cli.py +++ b/src/agentevals/cli.py @@ -15,12 +15,16 @@ import os import sys from datetime import datetime, timezone +from typing import TYPE_CHECKING import click from . import __version__ from .api.otlp_grpc import create_otlp_grpc_server, stop_otlp_grpc_server +if TYPE_CHECKING: + from .api.rpc.auth import KubernetesAuth + LOOPBACK_HOST = "127.0.0.1" @@ -544,6 +548,7 @@ async def _run_servers( *, api_grpc_port: int = 0, api_grpc_only: bool = False, + api_grpc_auth: KubernetesAuth | None = None, mcp_port: int | None = None, log_level: str = "warning", ) -> None: @@ -576,6 +581,7 @@ async def _run_servers( host=host, port=api_grpc_port, ports=Ports(http=port, otlp_http=otlp_http_port, otlp_grpc=otlp_grpc_port, api_grpc=api_grpc_port), + auth=api_grpc_auth, ) if api_grpc_port else None, @@ -616,6 +622,40 @@ async def _run_servers( await stop_otlp_grpc_server(otlp_grpc_server) +def _service_accounts(values: tuple[str, ...]) -> frozenset[str]: + from .api.rpc.auth import parse_service_account + + try: + return frozenset(parse_service_account(item) for value in values for item in value.split(",") if item.strip()) + except ValueError as exc: + raise click.BadParameter(str(exc), param_hint="--api-grpc-auth-allowed-service-account") from None + + +def _api_grpc_auth(mode: str, audience: str, allowed: frozenset[str], *, api_grpc_port: int) -> KubernetesAuth | None: + """Validate the auth options and connect to the Kubernetes API, refusing to start on any doubt.""" + if mode == "none": + if allowed: + raise click.UsageError("--api-grpc-auth-allowed-service-account needs --api-grpc-auth kubernetes") + return None + if not api_grpc_port: + raise click.UsageError("--api-grpc-auth needs the gRPC API; set --api-grpc-port to a port other than 0") + if not audience.strip(): + raise click.UsageError("--api-grpc-auth-audience must not be empty") + if not allowed: + raise click.UsageError( + "--api-grpc-auth kubernetes needs at least one --api-grpc-auth-allowed-service-account: " + "any pod can mint a token for any audience, so the audience alone authorizes nothing" + ) + + from .api.rpc.auth import KubernetesAuth, kubernetes_token_reviews + + try: + token_reviews = kubernetes_token_reviews() + except Exception as exc: + raise click.ClickException(f"cannot set up Kubernetes authentication: {exc}") from None + return KubernetesAuth(audience=audience.strip(), allowed_service_accounts=allowed, token_reviews=token_reviews) + + @main.command("serve") @click.option( "--dev", @@ -663,6 +703,36 @@ async def _run_servers( "on 127.0.0.1. Check health with grpc.health.v1 on the gRPC API port." ), ) +@click.option( + "--api-grpc-auth", + type=click.Choice(["none", "kubernetes"]), + default="none", + show_default=True, + envvar="AGENTEVALS_API_GRPC_AUTH", + show_envvar=True, + help=( + "Authenticate gRPC API callers. 'kubernetes' verifies ServiceAccount bearer tokens with a " + "TokenReview and admits only --api-grpc-auth-allowed-service-account. Health checks stay open." + ), +) +@click.option( + "--api-grpc-auth-audience", + default="agentevals", + show_default=True, + envvar="AGENTEVALS_API_GRPC_AUTH_AUDIENCE", + show_envvar=True, + help="Audience the callers' ServiceAccount tokens must be minted for.", +) +@click.option( + "--api-grpc-auth-allowed-service-account", + "api_grpc_auth_allowed_service_accounts", + multiple=True, + metavar="NAMESPACE/NAME", + envvar="AGENTEVALS_API_GRPC_AUTH_ALLOWED_SERVICE_ACCOUNTS", + show_envvar=True, + callback=lambda ctx, param, values: _service_accounts(values), + help="ServiceAccount allowed to call the gRPC API; repeat for more. The env var takes a comma separated list.", +) @click.option( "--mcp-port", default=None, @@ -703,6 +773,9 @@ def serve( otlp_grpc_port: int, api_grpc_port: int, api_grpc_only: bool, + api_grpc_auth: str, + api_grpc_auth_audience: str, + api_grpc_auth_allowed_service_accounts: frozenset[str], mcp_port: int | None, eval_sets: str | None, headless: bool, @@ -717,6 +790,15 @@ def serve( if api_grpc_only and not api_grpc_port: raise click.UsageError("--api-grpc-only needs the gRPC API; set --api-grpc-port to a port other than 0") + auth = _api_grpc_auth( + api_grpc_auth, api_grpc_auth_audience, api_grpc_auth_allowed_service_accounts, api_grpc_port=api_grpc_port + ) + if auth is not None and not api_grpc_only: + click.echo( + f"warning: --api-grpc-auth covers only the gRPC API; the REST API, the OTLP receivers and MCP " + f"stay unauthenticated on {host}. Add --api-grpc-only to keep them on 127.0.0.1.", + err=True, + ) level = logging.WARNING if verbose == 1: @@ -766,7 +848,7 @@ def serve( click.echo(f" OTLP HTTP: http://{side_host}:{otlp_http_port}") click.echo(f" OTLP gRPC: {side_host}:{otlp_grpc_port}") if api_grpc_port: - click.echo(f" gRPC API: {host}:{api_grpc_port}") + click.echo(f" gRPC API: {host}:{api_grpc_port}" + (" (auth: kubernetes)" if auth is not None else "")) if mcp_port is not None: click.echo(f" MCP: http://{side_host}:{mcp_port}/mcp") if dev: @@ -786,6 +868,7 @@ def serve( otlp_grpc_port, api_grpc_port=api_grpc_port, api_grpc_only=api_grpc_only, + api_grpc_auth=auth, mcp_port=mcp_port, log_level="info" if dev else "warning", ) diff --git a/tests/api/test_grpc_auth.py b/tests/api/test_grpc_auth.py new file mode 100644 index 0000000..b4a09ac --- /dev/null +++ b/tests/api/test_grpc_auth.py @@ -0,0 +1,341 @@ +"""Kubernetes ServiceAccount authentication on the gRPC API, against a fake TokenReview client.""" + +from __future__ import annotations + +import asyncio +import base64 +import json +import logging +import threading +from types import SimpleNamespace + +import grpc +import pytest +from grpc_health.v1 import health_pb2, health_pb2_grpc +from grpc_reflection.v1alpha import reflection_pb2, reflection_pb2_grpc + +from agentevals.api.rpc.auth import ( + KubernetesAuth, + ReviewUnavailable, + TokenReviewVerifier, + Unauthenticated, + parse_service_account, +) +from agentevals.api.rpc.server import start_api_server, stop_api_server +from agentevals.api.rpc.services import ApiContext, Ports +from agentevals.api.v1alpha1 import sessions_pb2, sessions_pb2_grpc, system_pb2, system_pb2_grpc +from agentevals.streaming.manager import LiveManager + +AUDIENCE = "agentevals" +CALLER = "system:serviceaccount:team:caller" +NOW = 1_800_000_000.0 + + +def _segment(data: dict) -> str: + return base64.urlsafe_b64encode(json.dumps(data).encode()).rstrip(b"=").decode() + + +def _token(**claims) -> str: + claims.setdefault("exp", NOW + 3600) + claims.setdefault("sub", CALLER) + return f"{_segment({'alg': 'RS256'})}.{_segment(claims)}.signature" + + +def _status( + *, + authenticated=True, + error="", + username=CALLER, + uid="0b9c1f1e", + audiences=(AUDIENCE,), +) -> SimpleNamespace: + return SimpleNamespace( + authenticated=authenticated, + error=error, + user=SimpleNamespace(username=username, uid=uid), + audiences=list(audiences), + ) + + +class FakeTokenReviews: + """Stands in for ``kubernetes.client.AuthenticationV1Api``.""" + + def __init__(self, status: SimpleNamespace | None = None) -> None: + self.status = status or _status() + self.error: Exception | None = None + self.calls: list[dict] = [] + self.gate: threading.Event | None = None + + def create_token_review(self, body, _request_timeout=None): + self.calls.append(body) + if self.gate is not None: + self.gate.wait(5) + if self.error is not None: + raise self.error + return SimpleNamespace(spec=body["spec"], status=self.status) + + +class Clock: + def __init__(self) -> None: + self.now = NOW + + def __call__(self) -> float: + return self.now + + +@pytest.fixture +def reviews(): + return FakeTokenReviews() + + +@pytest.fixture +def clock(): + return Clock() + + +@pytest.fixture +def verifier(reviews, clock): + return TokenReviewVerifier(reviews, AUDIENCE, clock=clock) + + +@pytest.fixture +async def channel(reviews, monkeypatch): + monkeypatch.delenv("AGENTEVALS_API_TRACES", raising=False) + monkeypatch.setenv("AGENTEVALS_GRPC_REFLECTION", "true") + context = ApiContext( + manager=LiveManager(), run_service=None, ports=Ports(http=8001, otlp_http=4318, otlp_grpc=4317, api_grpc=8002) + ) + auth = KubernetesAuth(audience=AUDIENCE, allowed_service_accounts=frozenset({"team/caller"}), token_reviews=reviews) + api = await start_api_server(context, "127.0.0.1", 0, auth) + try: + async with grpc.aio.insecure_channel(f"127.0.0.1:{api.port}") as channel: + yield channel + finally: + await stop_api_server(api) + + +async def _get_version(channel, metadata=None) -> grpc.StatusCode: + try: + await system_pb2_grpc.SystemServiceStub(channel).GetVersion(system_pb2.GetVersionRequest(), metadata=metadata) + except grpc.aio.AioRpcError as exc: + return exc.code() + return grpc.StatusCode.OK + + +def _bearer(token: str) -> tuple[tuple[str, str], ...]: + return (("authorization", f"Bearer {token}"),) + + +class TestServer: + async def test_an_allowed_service_account_is_accepted(self, channel, reviews): + assert await _get_version(channel, _bearer(_token(exp=4_000_000_000))) == grpc.StatusCode.OK + [body] = reviews.calls + assert body["spec"]["audiences"] == [AUDIENCE] + + async def test_health_needs_no_token(self, channel, reviews): + response = await health_pb2_grpc.HealthStub(channel).Check(health_pb2.HealthCheckRequest()) + assert response.status == health_pb2.HealthCheckResponse.SERVING + assert reviews.calls == [] + + async def test_reflection_needs_a_token(self, channel): + stub = reflection_pb2_grpc.ServerReflectionStub(channel) + request = reflection_pb2.ServerReflectionRequest(list_services="") + with pytest.raises(grpc.aio.AioRpcError) as raised: + [message async for message in stub.ServerReflectionInfo(iter([request]))] + assert raised.value.code() == grpc.StatusCode.UNAUTHENTICATED + + call = stub.ServerReflectionInfo(iter([request]), metadata=_bearer(_token(exp=4_000_000_000))) + [listing] = [message async for message in call] + assert listing.list_services_response.service + + @pytest.mark.parametrize( + "metadata", + [ + None, + (("authorization", "Bearer "),), + (("authorization", "Basic dXNlcjpwYXNz"),), + (("authorization", "not-a-jwt"),), + (("authorization", "Bearer not-a-jwt"),), + (("authorization", "Bearer a.b.c"),), + (("authorization", f"Bearer {_token(exp=4_000_000_000)}"),) * 2, + ], + ids=["missing", "empty", "basic", "no-scheme", "not-a-jwt", "bad-payload", "two-headers"], + ) + async def test_a_missing_or_malformed_token_is_unauthenticated(self, channel, reviews, metadata): + assert await _get_version(channel, metadata) == grpc.StatusCode.UNAUTHENTICATED + assert reviews.calls == [] + + @pytest.mark.parametrize( + "status", + [ + _status(authenticated=False), + _status(error="token has been invalidated"), + _status(username="alice"), + _status(username="system:node:worker-1"), + _status(uid=""), + _status(audiences=()), + _status(audiences=("https://kubernetes.default.svc",)), + ], + ids=["not-authenticated", "error", "user", "node", "no-uid", "no-audience", "other-audience"], + ) + async def test_a_rejected_review_is_unauthenticated(self, channel, reviews, status): + reviews.status = status + assert await _get_version(channel, _bearer(_token(exp=4_000_000_000))) == grpc.StatusCode.UNAUTHENTICATED + + async def test_a_service_account_outside_the_allowlist_is_denied(self, channel, reviews): + reviews.status = _status(username="system:serviceaccount:team:other") + assert await _get_version(channel, _bearer(_token(exp=4_000_000_000))) == grpc.StatusCode.PERMISSION_DENIED + + async def test_an_unreachable_api_server_is_unavailable_and_never_falls_back(self, channel, reviews): + reviews.error = ConnectionRefusedError() + token = _token(exp=4_000_000_000) + assert await _get_version(channel, _bearer(token)) == grpc.StatusCode.UNAVAILABLE + assert await _get_version(channel, _bearer(token)) == grpc.StatusCode.UNAVAILABLE + assert await _get_version(channel) == grpc.StatusCode.UNAUTHENTICATED + assert len(reviews.calls) == 2 + + reviews.error = None + assert await _get_version(channel, _bearer(token)) == grpc.StatusCode.OK + + async def test_streaming_calls_are_checked(self, channel): + stub = sessions_pb2_grpc.SessionServiceStub(channel) + with pytest.raises(grpc.aio.AioRpcError) as raised: + async for _ in stub.WatchSessions(sessions_pb2.WatchSessionsRequest()): + pass + assert raised.value.code() == grpc.StatusCode.UNAUTHENTICATED + + call = stub.WatchSessions(sessions_pb2.WatchSessionsRequest(), metadata=_bearer(_token(exp=4_000_000_000))) + first = await call.read() + assert first.HasField("synced") + call.cancel() + + async def test_the_token_never_reaches_the_log(self, channel, reviews, caplog): + token = _token(exp=4_000_000_000) + reviews.error = RuntimeError(f"response body echoing {token}") + with caplog.at_level(logging.DEBUG, logger="agentevals"): + assert await _get_version(channel, _bearer(token)) == grpc.StatusCode.UNAVAILABLE + reviews.error = None + reviews.status = _status(username="system:serviceaccount:team:other") + assert await _get_version(channel, _bearer(token)) == grpc.StatusCode.PERMISSION_DENIED + assert "TokenReview failed" in caplog.text + assert token.split(".")[1] not in caplog.text + + +class TestVerifier: + async def test_a_success_is_cached_for_the_ttl(self, verifier, reviews, clock): + token = _token() + assert await verifier.verify(token) == CALLER + clock.now += 29 + assert await verifier.verify(token) == CALLER + assert len(reviews.calls) == 1 + + clock.now += 1 + assert await verifier.verify(token) == CALLER + assert len(reviews.calls) == 2 + + async def test_the_cache_never_outlives_the_token(self, verifier, reviews, clock): + token = _token(exp=NOW + 10) + await verifier.verify(token) + clock.now += 9 + await verifier.verify(token) + assert len(reviews.calls) == 1 + + clock.now += 1 + with pytest.raises(Unauthenticated): + await verifier.verify(token) + assert len(reviews.calls) == 1 + + @pytest.mark.parametrize("exp", [NOW, NOW - 1, "4000000000", True, None, float("nan")]) + async def test_an_expired_or_invalid_exp_is_rejected_without_a_review(self, verifier, reviews, exp): + with pytest.raises(Unauthenticated): + await verifier.verify(_token(exp=exp)) + assert reviews.calls == [] + + async def test_a_token_without_exp_is_bounded_by_the_ttl(self, verifier, reviews, clock): + claims = {"sub": CALLER} + token = f"{_segment({'alg': 'RS256'})}.{_segment(claims)}.signature" + await verifier.verify(token) + clock.now += 30 + await verifier.verify(token) + assert len(reviews.calls) == 2 + + async def test_a_deeply_nested_payload_is_rejected(self, verifier, reviews): + payload = base64.urlsafe_b64encode(b"[" * 200_000).rstrip(b"=").decode() + with pytest.raises(Unauthenticated): + await verifier.verify(f"e30.{payload}.signature") + assert reviews.calls == [] + + async def test_failures_are_never_cached(self, verifier, reviews): + token = _token() + reviews.status = _status(authenticated=False) + with pytest.raises(Unauthenticated): + await verifier.verify(token) + reviews.error = TimeoutError() + with pytest.raises(ReviewUnavailable): + await verifier.verify(token) + + reviews.error = None + reviews.status = _status() + assert await verifier.verify(token) == CALLER + assert len(reviews.calls) == 3 + + async def test_concurrent_lookups_share_one_review(self, verifier, reviews): + reviews.gate = threading.Event() + token = _token() + waiters = [asyncio.ensure_future(verifier.verify(token)) for _ in range(8)] + await asyncio.sleep(0.05) + reviews.gate.set() + assert await asyncio.gather(*waiters) == [CALLER] * 8 + assert len(reviews.calls) == 1 + + async def test_a_shared_failure_reaches_every_waiter_and_is_not_kept(self, verifier, reviews): + reviews.gate = threading.Event() + reviews.error = ConnectionResetError() + token = _token() + waiters = [asyncio.ensure_future(verifier.verify(token)) for _ in range(3)] + await asyncio.sleep(0.05) + reviews.gate.set() + results = await asyncio.gather(*waiters, return_exceptions=True) + assert all(isinstance(result, ReviewUnavailable) for result in results) + + reviews.gate = None + reviews.error = None + assert await verifier.verify(token) == CALLER + assert len(reviews.calls) == 2 + + async def test_a_cancelled_waiter_does_not_cancel_the_shared_review(self, verifier, reviews): + reviews.gate = threading.Event() + token = _token() + leaving = asyncio.ensure_future(verifier.verify(token)) + staying = asyncio.ensure_future(verifier.verify(token)) + await asyncio.sleep(0.05) + leaving.cancel() + reviews.gate.set() + assert await staying == CALLER + assert len(reviews.calls) == 1 + + async def test_the_cache_is_bounded(self, reviews, clock): + verifier = TokenReviewVerifier(reviews, AUDIENCE, clock=clock, max_entries=2) + first, second, third = (_token(jti=str(n)) for n in range(3)) + for token in (first, second, third): + await verifier.verify(token) + await verifier.verify(third) + await verifier.verify(second) + assert len(reviews.calls) == 3 + + await verifier.verify(first) + assert len(reviews.calls) == 4 + + +class TestSettings: + def test_an_empty_allowlist_refuses_to_start(self, reviews): + with pytest.raises(ValueError, match="at least one allowed ServiceAccount"): + KubernetesAuth(audience=AUDIENCE, allowed_service_accounts=frozenset(), token_reviews=reviews) + + @pytest.mark.parametrize("value", ["caller", "team/", "/caller", "Team/caller", "team/caller/x", "team:caller"]) + def test_a_malformed_service_account_is_rejected(self, value): + with pytest.raises(ValueError): + parse_service_account(value) + + def test_a_service_account_is_normalized(self): + assert parse_service_account(" team/caller.v2 ") == "team/caller.v2" diff --git a/tests/test_cli.py b/tests/test_cli.py index 8f46939..779cade 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -169,6 +169,81 @@ def test_serve_api_grpc_only_from_env(monkeypatch): assert "gRPC API: 0.0.0.0:8002" in result.output +@pytest.mark.parametrize( + ("args", "message"), + [ + (["--api-grpc-auth", "kubernetes"], "needs at least one --api-grpc-auth-allowed-service-account"), + (["--api-grpc-auth-allowed-service-account", "team/caller"], "needs --api-grpc-auth kubernetes"), + ( + ["--api-grpc-auth", "kubernetes", "--api-grpc-auth-allowed-service-account", "team"], + "expected a ServiceAccount as namespace/name", + ), + ( + ["--api-grpc-auth", "kubernetes", "--api-grpc-auth-allowed-service-account", "team/caller"] + + ["--api-grpc-port", "0"], + "--api-grpc-auth needs the gRPC API", + ), + ], + ids=["empty-allowlist", "allowlist-without-auth", "malformed", "no-grpc-api"], +) +def test_serve_refuses_an_incomplete_auth_setup(monkeypatch, args, message): + run_servers = AsyncMock() + monkeypatch.setattr(cli, "_run_servers", run_servers) + + result = CliRunner().invoke(cli.main, ["serve", *args]) + + assert result.exit_code == 2 + assert message in result.output + run_servers.assert_not_called() + + +def test_serve_refuses_to_start_without_a_kubernetes_client(monkeypatch): + from agentevals.api.rpc import auth + + def no_cluster(): + raise RuntimeError("no cluster configuration") + + run_servers = AsyncMock() + monkeypatch.setattr(cli, "_run_servers", run_servers) + monkeypatch.setattr(auth, "kubernetes_token_reviews", no_cluster) + + result = CliRunner().invoke( + cli.main, ["serve", "--api-grpc-auth", "kubernetes", "--api-grpc-auth-allowed-service-account", "team/caller"] + ) + + assert result.exit_code == 1 + assert "cannot set up Kubernetes authentication: no cluster configuration" in result.output + run_servers.assert_not_called() + + +def test_serve_reads_auth_from_env(monkeypatch): + from agentevals.api.rpc import auth + + for name in ("AGENTEVALS_HEADLESS", "AGENTEVALS_LIVE"): + monkeypatch.setenv(name, "") + token_reviews = object() + run_servers = AsyncMock() + monkeypatch.setattr(cli, "_run_servers", run_servers) + monkeypatch.setattr(auth, "kubernetes_token_reviews", lambda: token_reviews) + + result = CliRunner().invoke( + cli.main, + ["serve", "--headless"], + env={ + "AGENTEVALS_API_GRPC_AUTH": "kubernetes", + "AGENTEVALS_API_GRPC_AUTH_AUDIENCE": "evals", + "AGENTEVALS_API_GRPC_AUTH_ALLOWED_SERVICE_ACCOUNTS": "team/caller, ops/runner", + }, + ) + + assert result.exit_code == 0, result.output + settings = run_servers.call_args.kwargs["api_grpc_auth"] + assert settings.audience == "evals" + assert settings.allowed_service_accounts == {"team/caller", "ops/runner"} + assert settings.token_reviews is token_reviews + assert "stay unauthenticated on 0.0.0.0" in result.stderr + + def test_run_preserves_config_file_settings_when_flags_omitted(monkeypatch, tmp_path): trace_file = tmp_path / "trace.json" trace_file.write_text("{}", encoding="utf-8")