From 2869df390b1a830029139ca855c91c61b6319927 Mon Sep 17 00:00:00 2001 From: Amber Agent Date: Sun, 1 Mar 2026 22:12:05 +0000 Subject: [PATCH 1/2] security(runner): reject direct AG-UI connections that bypass backend proxy Adds a shared proxy secret (RUNNER_PROXY_SECRET) that the backend sends as Authorization: Bearer when forwarding requests to runner pods. The runner validates this header on all write endpoints, returning 403 for requests that lack a valid token. Middleware is a no-op when RUNNER_PROXY_SECRET is unset (dev/test environments). - operator: generates a static proxy-secret UUID in the runner token secret at session creation; injects RUNNER_PROXY_SECRET env var into runner pods - backend: reads proxy-secret from K8s secret and sets Authorization header on all proxied calls (run, interrupt, feedback, capabilities, mcp/status) - runner: ProxyAuthMiddleware validates Authorization: Bearer on POST/PUT/ PATCH/DELETE endpoints; /health is always public for liveness probes Co-Authored-By: Claude Sonnet 4.6 --- components/backend/websocket/agui_proxy.go | 61 ++++++- components/operator/go.mod | 2 +- .../operator/internal/handlers/sessions.go | 23 ++- .../claude-code-runner/ambient_runner/app.py | 7 +- .../ambient_runner/middleware/__init__.py | 3 +- .../ambient_runner/middleware/proxy_auth.py | 75 ++++++++ .../tests/test_proxy_auth.py | 168 ++++++++++++++++++ 7 files changed, 331 insertions(+), 8 deletions(-) create mode 100644 components/runners/claude-code-runner/ambient_runner/middleware/proxy_auth.py create mode 100644 components/runners/claude-code-runner/tests/test_proxy_auth.py diff --git a/components/backend/websocket/agui_proxy.go b/components/backend/websocket/agui_proxy.go index 735b9309ec..239133819b 100644 --- a/components/backend/websocket/agui_proxy.go +++ b/components/backend/websocket/agui_proxy.go @@ -34,6 +34,39 @@ import ( "k8s.io/client-go/kubernetes" ) +// runnerProxySecretCache caches proxy secrets per session to avoid repeated K8s API calls. +// Key: "namespace/sessionName", Value: proxy secret string. +var runnerProxySecretCache sync.Map + +// getRunnerProxySecret reads the proxy-secret key from the runner token secret. +// Returns empty string if the secret does not exist or the key is absent (graceful degradation +// for sessions created before proxy authentication was introduced). +func getRunnerProxySecret(projectName, sessionName string) string { + cacheKey := projectName + "/" + sessionName + if cached, ok := runnerProxySecretCache.Load(cacheKey); ok { + return cached.(string) + } + + if handlers.K8sClientMw == nil { + return "" + } + + secretName := fmt.Sprintf("ambient-runner-token-%s", sessionName) + secret, err := handlers.K8sClientMw.CoreV1().Secrets(projectName).Get( + context.Background(), secretName, metav1.GetOptions{}, + ) + if err != nil { + log.Printf("AGUI Proxy: could not read runner proxy secret for %s/%s: %v", projectName, sessionName, err) + return "" + } + + proxySecret := strings.TrimSpace(string(secret.Data["proxy-secret"])) + if proxySecret != "" { + runnerProxySecretCache.Store(cacheKey, proxySecret) + } + return proxySecret +} + const ( // activityDebounceInterval is the minimum interval between CR status updates for lastActivityTime. // Inactivity timeout is measured in hours, so minute-level granularity is sufficient. @@ -238,9 +271,10 @@ func HandleAGUIRunProxy(c *gin.Context) { } runnerURL := getRunnerEndpoint(projectName, sessionName) + proxySecret := getRunnerProxySecret(projectName, sessionName) // Start background goroutine to proxy runner SSE → persist + broadcast - go proxyRunnerStream(runnerURL, bodyBytes, sessionName, runID, threadID) + go proxyRunnerStream(runnerURL, bodyBytes, sessionName, runID, threadID, proxySecret) // Return metadata immediately — events arrive via GET /agui/events c.JSON(http.StatusOK, gin.H{ @@ -252,9 +286,9 @@ func HandleAGUIRunProxy(c *gin.Context) { // proxyRunnerStream connects to the runner's SSE endpoint, reads events, // persists them, and publishes them to the live broadcast pipe. Runs in // a background goroutine so the POST /agui/run handler can return immediately. -func proxyRunnerStream(runnerURL string, bodyBytes []byte, sessionName, runID, threadID string) { +func proxyRunnerStream(runnerURL string, bodyBytes []byte, sessionName, runID, threadID, proxySecret string) { log.Printf("AGUI Proxy: connecting to runner at %s", runnerURL) - resp, err := connectToRunner(runnerURL, bodyBytes) + resp, err := connectToRunner(runnerURL, bodyBytes, proxySecret) if err != nil { log.Printf("AGUI Proxy: runner unavailable for %s: %v", sessionName, err) // Publish error events so GET /agui/events subscribers see the failure @@ -418,6 +452,9 @@ func HandleAGUIInterrupt(c *gin.Context) { return } req.Header.Set("Content-Type", "application/json") + if ps := getRunnerProxySecret(projectName, sessionName); ps != "" { + req.Header.Set("Authorization", "Bearer "+ps) + } resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req) if err != nil { @@ -483,6 +520,9 @@ func HandleAGUIFeedback(c *gin.Context) { return } req.Header.Set("Content-Type", "application/json") + if ps := getRunnerProxySecret(projectName, sessionName); ps != "" { + req.Header.Set("Authorization", "Bearer "+ps) + } resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req) if err != nil { @@ -542,6 +582,9 @@ func HandleCapabilities(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"framework": "unknown"}) return } + if ps := getRunnerProxySecret(projectName, sessionName); ps != "" { + req.Header.Set("Authorization", "Bearer "+ps) + } resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req) if err != nil { c.JSON(http.StatusOK, gin.H{ @@ -590,6 +633,9 @@ func HandleMCPStatus(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"servers": []interface{}{}, "totalCount": 0}) return } + if ps := getRunnerProxySecret(projectName, sessionName); ps != "" { + req.Header.Set("Authorization", "Bearer "+ps) + } resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req) if err != nil { c.JSON(http.StatusOK, gin.H{"servers": []interface{}{}, "totalCount": 0}) @@ -629,7 +675,11 @@ var runnerHTTPClient = &http.Client{ // container startup time and K8s Service DNS propagation. Retries on // "connection refused", "no such host", and "dial tcp" errors with // exponential backoff (500ms initial, 1.5x, capped at 5s, 15 attempts). -func connectToRunner(runnerURL string, bodyBytes []byte) (*http.Response, error) { +// +// proxySecret is the RUNNER_PROXY_SECRET shared between the backend and the runner. +// When non-empty it is sent as "Authorization: Bearer {proxySecret}" so the runner +// can reject direct connections that bypass the backend proxy. +func connectToRunner(runnerURL string, bodyBytes []byte, proxySecret string) (*http.Response, error) { maxAttempts := 15 retryDelay := 500 * time.Millisecond maxDelay := 5 * time.Second @@ -641,6 +691,9 @@ func connectToRunner(runnerURL string, bodyBytes []byte) (*http.Response, error) } req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "text/event-stream") + if proxySecret != "" { + req.Header.Set("Authorization", "Bearer "+proxySecret) + } resp, err := runnerHTTPClient.Do(req) if err == nil { diff --git a/components/operator/go.mod b/components/operator/go.mod index 2d87a38107..d704c3826a 100644 --- a/components/operator/go.mod +++ b/components/operator/go.mod @@ -5,6 +5,7 @@ go 1.24.0 toolchain go1.24.7 require ( + github.com/google/uuid v1.6.0 go.opentelemetry.io/otel v1.33.0 go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.33.0 go.opentelemetry.io/otel/metric v1.33.0 @@ -35,7 +36,6 @@ require ( github.com/google/btree v1.1.3 // indirect github.com/google/gnostic-models v0.7.0 // indirect github.com/google/go-cmp v0.7.0 // indirect - github.com/google/uuid v1.6.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.24.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect diff --git a/components/operator/internal/handlers/sessions.go b/components/operator/internal/handlers/sessions.go index 30d229b5de..58680dadcb 100644 --- a/components/operator/internal/handlers/sessions.go +++ b/components/operator/internal/handlers/sessions.go @@ -17,6 +17,7 @@ import ( "ambient-code-operator/internal/config" "ambient-code-operator/internal/types" + "github.com/google/uuid" authnv1 "k8s.io/api/authentication/v1" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" @@ -1025,6 +1026,16 @@ func handleAgenticSessionEvent(obj *unstructured.Unstructured) error { Key: "k8s-token", }}, }) + // RUNNER_PROXY_SECRET: static shared secret for backend→runner proxy authentication. + // Optional so that sessions created before this field was added continue to work. + base = append(base, corev1.EnvVar{ + Name: "RUNNER_PROXY_SECRET", + ValueFrom: &corev1.EnvVarSource{SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{Name: secretName}, + Key: "proxy-secret", + Optional: boolPtr(true), + }}, + }) // Add CR-provided envs last (override base when same key) if spec, ok := currentObj.Object["spec"].(map[string]interface{}); ok { // Inject REPOS_JSON and MAIN_REPO_NAME from spec.repos and spec.mainRepoName if present @@ -2348,6 +2359,11 @@ func regenerateRunnerToken(sessionNamespace, sessionName string, session *unstru // Store token in Secret secretName := fmt.Sprintf("ambient-runner-token-%s", sessionName) refreshedAt := time.Now().UTC().Format(time.RFC3339) + // proxySecret is a static random token shared between the backend proxy and the runner. + // It is generated once at session creation and never rotated, unlike the k8s-token. + // The backend sends it as Authorization: Bearer {proxySecret} when proxying to the runner, + // and the runner validates it to reject direct connections that bypass the proxy. + proxySecret := uuid.New().String() sec := &corev1.Secret{ ObjectMeta: v1.ObjectMeta{ Name: secretName, @@ -2360,7 +2376,8 @@ func regenerateRunnerToken(sessionNamespace, sessionName string, session *unstru }, Type: corev1.SecretTypeOpaque, Data: map[string][]byte{ - "k8s-token": []byte(k8sToken), + "k8s-token": []byte(k8sToken), + "proxy-secret": []byte(proxySecret), }, } @@ -2376,6 +2393,10 @@ func regenerateRunnerToken(sessionNamespace, sessionName string, session *unstru secretCopy.Data = map[string][]byte{} } secretCopy.Data["k8s-token"] = []byte(k8sToken) + // Preserve existing proxy-secret on rotation — only set it if absent (first-time backfill). + if _, hasProxySecret := secretCopy.Data["proxy-secret"]; !hasProxySecret { + secretCopy.Data["proxy-secret"] = []byte(proxySecret) + } if secretCopy.Annotations == nil { secretCopy.Annotations = map[string]string{} } diff --git a/components/runners/claude-code-runner/ambient_runner/app.py b/components/runners/claude-code-runner/ambient_runner/app.py index 56b6243466..e8cadea21d 100644 --- a/components/runners/claude-code-runner/ambient_runner/app.py +++ b/components/runners/claude-code-runner/ambient_runner/app.py @@ -27,7 +27,6 @@ import uuid from contextlib import asynccontextmanager from pathlib import Path -from typing import Optional from urllib.parse import urlparse import aiohttp @@ -146,6 +145,12 @@ async def lifespan(app: FastAPI): app = FastAPI(title=title, version=version, lifespan=lifespan) + # Reject direct AG-UI connections that bypass the backend proxy. + # The middleware is a no-op when RUNNER_PROXY_SECRET is not set (dev/test). + from ambient_runner.middleware.proxy_auth import ProxyAuthMiddleware + + app.add_middleware(ProxyAuthMiddleware) + add_ambient_endpoints( app, bridge, diff --git a/components/runners/claude-code-runner/ambient_runner/middleware/__init__.py b/components/runners/claude-code-runner/ambient_runner/middleware/__init__.py index 917a361519..9d066f2eb1 100644 --- a/components/runners/claude-code-runner/ambient_runner/middleware/__init__.py +++ b/components/runners/claude-code-runner/ambient_runner/middleware/__init__.py @@ -6,6 +6,7 @@ """ from ambient_runner.middleware.developer_events import emit_developer_message +from ambient_runner.middleware.proxy_auth import ProxyAuthMiddleware from ambient_runner.middleware.tracing import tracing_middleware -__all__ = ["tracing_middleware", "emit_developer_message"] +__all__ = ["tracing_middleware", "emit_developer_message", "ProxyAuthMiddleware"] diff --git a/components/runners/claude-code-runner/ambient_runner/middleware/proxy_auth.py b/components/runners/claude-code-runner/ambient_runner/middleware/proxy_auth.py new file mode 100644 index 0000000000..f49d0629ca --- /dev/null +++ b/components/runners/claude-code-runner/ambient_runner/middleware/proxy_auth.py @@ -0,0 +1,75 @@ +""" +Proxy authentication middleware for the Ambient Runner. + +Rejects direct AG-UI connections that bypass the backend proxy by validating +the Authorization header against the RUNNER_PROXY_SECRET environment variable. + +The backend proxy sets ``Authorization: Bearer {RUNNER_PROXY_SECRET}`` on +every request it forwards to the runner. The runner then validates this header +to ensure the request came through the authorised backend proxy rather than +being sent directly by an arbitrary cluster process. + +When RUNNER_PROXY_SECRET is not set (local development, unit tests), the +middleware is disabled and all requests pass through unmodified. + +Protected methods: POST, PUT, PATCH, DELETE (write operations). +Excluded paths: /health (liveness probes must not require auth). +""" + +import logging +import os + +from fastapi import Request +from fastapi.responses import JSONResponse +from starlette.middleware.base import BaseHTTPMiddleware + +logger = logging.getLogger(__name__) + +# Paths that are always public regardless of auth configuration. +_PUBLIC_PATHS = {"/health"} + + +class ProxyAuthMiddleware(BaseHTTPMiddleware): + """Reject write requests that do not carry a valid proxy secret. + + Only active when the ``RUNNER_PROXY_SECRET`` environment variable is set. + When the variable is absent the middleware is a no-op so that local + development and tests work without configuration changes. + """ + + async def dispatch(self, request: Request, call_next): + proxy_secret = os.getenv("RUNNER_PROXY_SECRET", "").strip() + + # Passthrough when no secret is configured (dev / test mode). + if not proxy_secret: + return await call_next(request) + + # Health endpoint is always public (required for K8s liveness probes). + if request.url.path in _PUBLIC_PATHS: + return await call_next(request) + + # Only validate write operations — GET/HEAD/OPTIONS are read-only. + if request.method not in ("POST", "PUT", "PATCH", "DELETE"): + return await call_next(request) + + auth_header = request.headers.get("Authorization", "") + expected = f"Bearer {proxy_secret}" + + if auth_header != expected: + logger.warning( + "Rejected direct runner connection from %s %s " + "(missing or invalid Authorization header)", + request.method, + request.url.path, + ) + return JSONResponse( + status_code=403, + content={ + "detail": ( + "Direct runner connections are not permitted. " + "Route requests through the platform backend proxy." + ) + }, + ) + + return await call_next(request) diff --git a/components/runners/claude-code-runner/tests/test_proxy_auth.py b/components/runners/claude-code-runner/tests/test_proxy_auth.py new file mode 100644 index 0000000000..fa4f0eac93 --- /dev/null +++ b/components/runners/claude-code-runner/tests/test_proxy_auth.py @@ -0,0 +1,168 @@ +""" +Tests for ProxyAuthMiddleware — backend proxy authentication. + +Verifies that the runner rejects direct AG-UI connections that bypass the +backend proxy when RUNNER_PROXY_SECRET is configured, and that it allows +requests that carry the correct Authorization header. +""" + + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from ambient_runner.middleware.proxy_auth import ProxyAuthMiddleware + + +# --------------------------------------------------------------------------- +# Minimal test app +# --------------------------------------------------------------------------- + + +def _make_app() -> FastAPI: + """Create a minimal FastAPI app with ProxyAuthMiddleware and one endpoint.""" + app = FastAPI() + app.add_middleware(ProxyAuthMiddleware) + + @app.post("/") + async def run(): + return {"status": "ok"} + + @app.post("/interrupt") + async def interrupt(): + return {"status": "ok"} + + @app.post("/feedback") + async def feedback(): + return {"status": "ok"} + + @app.get("/health") + async def health(): + return {"status": "healthy"} + + @app.get("/capabilities") + async def capabilities(): + return {"framework": "test"} + + return app + + +# --------------------------------------------------------------------------- +# Fixtures +# --------------------------------------------------------------------------- + + +@pytest.fixture() +def client(monkeypatch): + """Client with RUNNER_PROXY_SECRET not set (passthrough mode).""" + monkeypatch.delenv("RUNNER_PROXY_SECRET", raising=False) + with TestClient(_make_app()) as c: + yield c + + +@pytest.fixture() +def secure_client(monkeypatch): + """Client with RUNNER_PROXY_SECRET=test-secret-xyz.""" + monkeypatch.setenv("RUNNER_PROXY_SECRET", "test-secret-xyz") + with TestClient(_make_app()) as c: + yield c + + +# --------------------------------------------------------------------------- +# Passthrough mode (RUNNER_PROXY_SECRET not set) +# --------------------------------------------------------------------------- + + +class TestPassthroughMode: + """When RUNNER_PROXY_SECRET is absent all requests pass through.""" + + def test_run_allowed_without_auth(self, client): + resp = client.post("/", json={"messages": []}) + assert resp.status_code == 200 + + def test_interrupt_allowed_without_auth(self, client): + resp = client.post("/interrupt") + assert resp.status_code == 200 + + def test_health_allowed_without_auth(self, client): + resp = client.get("/health") + assert resp.status_code == 200 + + def test_get_endpoints_allowed_without_auth(self, client): + resp = client.get("/capabilities") + assert resp.status_code == 200 + + +# --------------------------------------------------------------------------- +# Enforcement mode (RUNNER_PROXY_SECRET set) +# --------------------------------------------------------------------------- + + +class TestEnforcementMode: + """When RUNNER_PROXY_SECRET is set, write endpoints require the correct token.""" + + def test_run_rejected_without_auth(self, secure_client): + resp = secure_client.post("/") + assert resp.status_code == 403 + + def test_run_rejected_with_wrong_token(self, secure_client): + resp = secure_client.post("/", headers={"Authorization": "Bearer wrong-token"}) + assert resp.status_code == 403 + + def test_run_rejected_with_empty_auth(self, secure_client): + resp = secure_client.post("/", headers={"Authorization": ""}) + assert resp.status_code == 403 + + def test_run_allowed_with_correct_token(self, secure_client): + resp = secure_client.post( + "/", headers={"Authorization": "Bearer test-secret-xyz"} + ) + assert resp.status_code == 200 + + def test_interrupt_rejected_without_auth(self, secure_client): + resp = secure_client.post("/interrupt") + assert resp.status_code == 403 + + def test_interrupt_allowed_with_correct_token(self, secure_client): + resp = secure_client.post( + "/interrupt", headers={"Authorization": "Bearer test-secret-xyz"} + ) + assert resp.status_code == 200 + + def test_feedback_rejected_without_auth(self, secure_client): + resp = secure_client.post("/feedback") + assert resp.status_code == 403 + + def test_feedback_allowed_with_correct_token(self, secure_client): + resp = secure_client.post( + "/feedback", headers={"Authorization": "Bearer test-secret-xyz"} + ) + assert resp.status_code == 200 + + def test_health_always_public(self, secure_client): + """Health endpoint must not require auth (K8s liveness probes).""" + resp = secure_client.get("/health") + assert resp.status_code == 200 + + def test_get_endpoints_allowed_without_auth(self, secure_client): + """Read-only GET requests do not require auth.""" + resp = secure_client.get("/capabilities") + assert resp.status_code == 200 + + def test_error_response_has_detail_field(self, secure_client): + """Rejected requests return a JSON body with a 'detail' field.""" + resp = secure_client.post("/") + assert resp.status_code == 403 + body = resp.json() + assert "detail" in body + assert "backend proxy" in body["detail"] + + def test_malformed_auth_scheme_rejected(self, secure_client): + """Token without 'Bearer ' prefix is rejected.""" + resp = secure_client.post("/", headers={"Authorization": "test-secret-xyz"}) + assert resp.status_code == 403 + + def test_basic_auth_rejected(self, secure_client): + """Basic auth is not a valid scheme for proxy auth.""" + resp = secure_client.post("/", headers={"Authorization": "Basic dGVzdA=="}) + assert resp.status_code == 403 From 3dc7a53e65eee7bdd0ed12c23579135ab12ba5ef Mon Sep 17 00:00:00 2001 From: Jeremy Eder Date: Fri, 6 Mar 2026 22:22:52 -0500 Subject: [PATCH 2/2] chore: trigger CI