Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 57 additions & 4 deletions components/backend/websocket/agui_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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{
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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{
Expand Down Expand Up @@ -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})
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion components/operator/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
23 changes: 22 additions & 1 deletion components/operator/internal/handlers/sessions.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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),
},
}

Expand All @@ -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{}
}
Expand Down
7 changes: 6 additions & 1 deletion components/runners/claude-code-runner/ambient_runner/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Original file line number Diff line number Diff line change
@@ -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)
Loading