From d58c86cab1e30a8b6ca6253d4791ec0eba35ea48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Banaszewski?= Date: Tue, 24 Nov 2026 18:27:57 +0100 Subject: [PATCH] feat(aibridge): add request extractor for Anthropic messages in proxy mode (#32470) Adds `aibridge/extractors` and a request extractor for Anthropic `/v1/messages` in proxy mode. `Extractor` will extract facts from request and response bodies needed for recording. This PR only adds `Extractor` for `/messages` shape requests. Response processing will follow. In proxy mode, the forwarding handler now reads the full request body before it records the interception start. It then runs the extractor and sets `ClientSessionID` for every route. If extraction fails, the request is still forwarded unchanged. > Generated with Coder Agents. --- aibridge/extractors/extractors.go | 13 ++ aibridge/extractors/messages.go | 43 ++++++ aibridge/extractors/messages_internal_test.go | 71 +++++++++ .../integrationtest/bridge_internal_test.go | 20 ++- .../internal/integrationtest/setupbridge.go | 59 +++++++- .../testutil/mockprovider/mockprovider.go | 4 + aibridge/provider/anthropic.go | 9 ++ aibridge/provider/bedrock_provider.go | 4 + aibridge/provider/copilot.go | 4 + aibridge/provider/disabled.go | 4 + aibridge/provider/openai.go | 5 + aibridge/provider/provider.go | 7 + aibridge/x/proxy/handler.go | 96 ++++++++++--- aibridge/x/proxy/handler_internal_test.go | 136 +++++++++++++++--- aibridge/x/proxy/outcomes_internal_test.go | 98 ++++++++++--- 15 files changed, 497 insertions(+), 76 deletions(-) create mode 100644 aibridge/extractors/extractors.go create mode 100644 aibridge/extractors/messages.go create mode 100644 aibridge/extractors/messages_internal_test.go diff --git a/aibridge/extractors/extractors.go b/aibridge/extractors/extractors.go new file mode 100644 index 00000000000..5ae27e9dec2 --- /dev/null +++ b/aibridge/extractors/extractors.go @@ -0,0 +1,13 @@ +// Package extractors derives recording facts from the bytes proxy mode +// forwards, without changing them. +package extractors + +import ( + "github.com/coder/coder/v2/aibridge/recorder" +) + +// Extractor provides a way to extract facts from a request and response body. +type Extractor interface { + // ExtractRequest adds Model and CorrelatingToolCallID to the start record. + ExtractRequest(reqBody []byte, start *recorder.InterceptionRecord) error +} diff --git a/aibridge/extractors/messages.go b/aibridge/extractors/messages.go new file mode 100644 index 00000000000..ce20650cc96 --- /dev/null +++ b/aibridge/extractors/messages.go @@ -0,0 +1,43 @@ +package extractors + +import ( + "golang.org/x/xerrors" + + "github.com/coder/coder/v2/aibridge/intercept/messages" + "github.com/coder/coder/v2/aibridge/recorder" +) + +// messagesExtractor extracts recording facts from Anthropic Messages API +// traffic. +type messagesExtractor struct { + // prompt is the last user prompt in the request, nil when absent. It is + // recorded once response message ID is known (PromptUsageRecord.MsgID). + prompt *string + // streaming reports whether the request asked for a streamed response. + // Used as fallback, response metadata has priority. + streaming bool +} + +// NewMessages returns an [Extractor] for one Anthropic Messages API request. +func NewMessages() Extractor { + return &messagesExtractor{} +} + +func (e *messagesExtractor) ExtractRequest(reqBody []byte, start *recorder.InterceptionRecord) error { + payload, err := messages.NewRequestPayload(reqBody) + if err != nil { + return xerrors.Errorf("parse messages request: %w", err) + } + start.Model = payload.Model() + start.CorrelatingToolCallID = payload.CorrelatingToolCallID() + e.streaming = payload.Stream() + + prompt, found, err := payload.LastUserPrompt() + if err != nil { + return xerrors.Errorf("read last user prompt: %w", err) + } + if found { + e.prompt = &prompt + } + return nil +} diff --git a/aibridge/extractors/messages_internal_test.go b/aibridge/extractors/messages_internal_test.go new file mode 100644 index 00000000000..f9dc194b32c --- /dev/null +++ b/aibridge/extractors/messages_internal_test.go @@ -0,0 +1,71 @@ +package extractors + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/coder/coder/v2/aibridge/recorder" +) + +func TestMessagesExtractRequest(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + body string + wantErr string + wantModel string + wantToolCallID *string + wantPrompt *string + wantStreaming bool + }{ + { + name: "AllFields", + body: `{"model":"claude-test","stream":true,"messages":[{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"ok"},{"type":"text","text":"hi"}]}]}`, + wantModel: "claude-test", + wantToolCallID: new("toolu_1"), + wantPrompt: new("hi"), + wantStreaming: true, + }, + { + name: "NoPrompt", + body: `{"model":"claude-test","messages":[]}`, + wantModel: "claude-test", + }, + { + name: "EmptyPrompt", + body: `{"model":"claude-test","messages":[{"role":"user","content":""}]}`, + wantModel: "claude-test", + wantPrompt: new(""), + }, + { + name: "PromptError", + body: `{"model":"claude-test","messages":{}}`, + wantErr: "read last user prompt", + wantModel: "claude-test", + }, + { + name: "InvalidBody", + body: `not JSON`, + wantErr: "parse messages request", + }, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + start := &recorder.InterceptionRecord{} + e, ok := NewMessages().(*messagesExtractor) + require.True(t, ok) + + err := e.ExtractRequest([]byte(tc.body), start) + if tc.wantErr != "" { + require.ErrorContains(t, err, tc.wantErr) + } else { + require.NoError(t, err) + } + require.Equal(t, tc.wantModel, start.Model) + require.Equal(t, tc.wantToolCallID, start.CorrelatingToolCallID) + require.Equal(t, tc.wantPrompt, e.prompt) + require.Equal(t, tc.wantStreaming, e.streaming) + }) + } +} diff --git a/aibridge/internal/integrationtest/bridge_internal_test.go b/aibridge/internal/integrationtest/bridge_internal_test.go index c650375247e..80bdc5e82cf 100644 --- a/aibridge/internal/integrationtest/bridge_internal_test.go +++ b/aibridge/internal/integrationtest/bridge_internal_test.go @@ -1730,6 +1730,7 @@ func TestSessionIDTracking(t *testing.T) { testCases := []struct { name string + proxyMode bool fixture []byte header http.Header metadataSessionID string @@ -1758,6 +1759,18 @@ func TestSessionIDTracking(t *testing.T) { }, metadataSessionID: "user_abc123_account_456_session_f47ac10b-58cc-4372-a567-0e02b2c3d479", }, + // Session in body, proxy mode. + { + name: "claude_code_proxy", + proxyMode: true, + fixture: fixtures.AntSimple, + expectedClient: aibclient.ClaudeCode, + expectSessionID: "f47ac10b-58cc-4372-a567-0e02b2c3d479", + header: http.Header{ + "User-Agent": []string{"claude-cli/2.0.67 (external, cli)"}, + }, + metadataSessionID: "user_abc123_account_456_session_f47ac10b-58cc-4372-a567-0e02b2c3d479", + }, // No session. { name: "zed", @@ -1788,7 +1801,11 @@ func TestSessionIDTracking(t *testing.T) { fix := fixtures.Parse(t, tc.fixture) upstream := testutil.NewMockUpstream(ctx, t, testutil.NewFixtureResponse(fix)) - bridgeServer := newBridgeTestServer(ctx, t, upstream.URL, withProvider(config.ProviderAnthropic)) + opts := []bridgeOption{withProvider(config.ProviderAnthropic)} + if tc.proxyMode { + opts = append(opts, withProxyMode()) + } + bridgeServer := newBridgeTestServer(ctx, t, upstream.URL, opts...) reqBody := fix.Request() if tc.metadataSessionID != "" { @@ -1805,6 +1822,7 @@ func TestSessionIDTracking(t *testing.T) { // Drain the body to let the stream complete. _, err = io.ReadAll(resp.Body) require.NoError(t, err) + bridgeServer.awaitRecordings(t) interceptions := bridgeServer.Recorder.RecordedInterceptions() require.Len(t, interceptions, 1, "expected exactly one interception") diff --git a/aibridge/internal/integrationtest/setupbridge.go b/aibridge/internal/integrationtest/setupbridge.go index f6148b773f3..b6a549d0d06 100644 --- a/aibridge/internal/integrationtest/setupbridge.go +++ b/aibridge/internal/integrationtest/setupbridge.go @@ -26,6 +26,7 @@ import ( "github.com/coder/coder/v2/aibridge/metrics" "github.com/coder/coder/v2/aibridge/provider" "github.com/coder/coder/v2/aibridge/recorder" + "github.com/coder/coder/v2/aibridge/x/proxy" ) const ( @@ -53,6 +54,11 @@ var ( ) type bridgeConfig struct { + // proxyMode serves [proxy.NewRouter], which executes requests through + // ReverseProxy. + // Default remains interception mode that uses [aibridge.NewRequestBridge], + // which executes requests through interceptors. + proxyMode bool providerBuilders []func(t *testing.T, upstreamURL string) aibridge.Provider metrics *metrics.Metrics tracer trace.Tracer @@ -74,11 +80,26 @@ type bridgeConfig struct { recorderMiddleware []recorder.Middleware } -// bridgeTestServer wraps an httptest.Server running a RequestBridge. +// bridgeTestServer wraps an httptest.Server running a RequestBridge or, in +// proxy mode, a proxy Router. type bridgeTestServer struct { *httptest.Server Recorder *testutil.MockRecorder - Bridge *aibridge.RequestBridge + // Bridge is nil in proxy mode. + Bridge *aibridge.RequestBridge + // gate admits every request the server handles. + gate *aibridge.InflightGate +} + +// awaitRecordings stops admission and waits until every admitted request has +// finished recording. Call it after the case's final request and before +// asserting records: proxy mode records after the response completes, so +// reading the response to EOF does not order the records. +func (s *bridgeTestServer) awaitRecordings(t *testing.T) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong) + defer cancel() + require.NoError(t, s.gate.Shutdown(ctx), "recording did not finish") } // makeRequest builds and executes an HTTP request against this server. @@ -124,6 +145,12 @@ func withCustomProvider(p aibridge.Provider) bridgeOption { } } +// withProxyMode serves [proxy.NewRouter] instead of the default +// [aibridge.NewRequestBridge]. +func withProxyMode() bridgeOption { + return func(c *bridgeConfig) { c.proxyMode = true } +} + // withMetrics sets the Prometheus metrics for the bridge. func withMetrics(m *metrics.Metrics) bridgeOption { return func(c *bridgeConfig) { c.metrics = m } @@ -146,6 +173,7 @@ func withActor(id uuid.UUID, username string) bridgeOption { // newBridgeTestServer creates a fully configured test server running // a RequestBridge with sensible defaults: +// - interception mode (unless withProxyMode) // - All standard providers (unless withProvider / withCustomProvider) // - NoopMCPManager (unless withMCP) // - slogtest debug logger @@ -194,18 +222,34 @@ func newBridgeTestServer( mockRec := &testutil.MockRecorder{} rec := aibridge.NewRecorder(cfg.logger, cfg.tracer, cfg.structuredLogging, mockRec, cfg.recorderMiddleware...) - bridge, err := aibridge.NewRequestBridge( - ctx, providers, rec, cfg.mcpProxy, - cfg.logger, cfg.metrics, cfg.tracer, + // gate admits every request, so shutting it down waits for interception + // handlers to return and for proxy recording to finish. + gate := aibridge.NewInflightGate(cfg.logger) + t.Cleanup(gate.Close) + var ( + handler http.Handler + bridge *aibridge.RequestBridge ) - require.NoError(t, err) + if cfg.proxyMode { + router, err := proxy.NewRouter(ctx, providers, cfg.logger, cfg.metrics, cfg.tracer, gate, rec) + require.NoError(t, err) + handler = router + } else { + var err error + bridge, err = aibridge.NewRequestBridge( + ctx, providers, rec, cfg.mcpProxy, + cfg.logger, cfg.metrics, cfg.tracer, + ) + require.NoError(t, err) + handler = gate.Middleware(bridge) + } actor := aibcontext.Actor{ ID: cfg.actorID, APIKeyID: cfg.apiKeyID, Username: cfg.actorUsername, } - srv := httptest.NewUnstartedServer(bridge) + srv := httptest.NewUnstartedServer(handler) srv.Config.BaseContext = func(_ net.Listener) context.Context { return aibcontext.AsActor(ctx, actor) } @@ -216,6 +260,7 @@ func newBridgeTestServer( Server: srv, Recorder: mockRec, Bridge: bridge, + gate: gate, } } diff --git a/aibridge/internal/testutil/mockprovider/mockprovider.go b/aibridge/internal/testutil/mockprovider/mockprovider.go index 95309ce07e9..30b55afbf7e 100644 --- a/aibridge/internal/testutil/mockprovider/mockprovider.go +++ b/aibridge/internal/testutil/mockprovider/mockprovider.go @@ -12,6 +12,7 @@ import ( "cdr.dev/slog/v3" "github.com/coder/coder/v2/aibridge/config" "github.com/coder/coder/v2/aibridge/credential" + "github.com/coder/coder/v2/aibridge/extractors" aibheaders "github.com/coder/coder/v2/aibridge/headers" "github.com/coder/coder/v2/aibridge/intercept" "github.com/coder/coder/v2/aibridge/keypool" @@ -55,3 +56,6 @@ func (m *MockProvider) CreateInterceptor(w http.ResponseWriter, r *http.Request, } return nil, nil //nolint:nilnil // mock: no interceptor configured is not an error } + +// CreateExtractor returns nil, so proxied requests forward without extraction. +func (*MockProvider) CreateExtractor(string) extractors.Extractor { return nil } diff --git a/aibridge/provider/anthropic.go b/aibridge/provider/anthropic.go index f592f5349e9..33dc94a34bc 100644 --- a/aibridge/provider/anthropic.go +++ b/aibridge/provider/anthropic.go @@ -17,6 +17,7 @@ import ( "github.com/coder/coder/v2/aibridge/circuitbreaker" "github.com/coder/coder/v2/aibridge/config" "github.com/coder/coder/v2/aibridge/credential" + "github.com/coder/coder/v2/aibridge/extractors" aibheaders "github.com/coder/coder/v2/aibridge/headers" "github.com/coder/coder/v2/aibridge/intercept" "github.com/coder/coder/v2/aibridge/intercept/messages" @@ -190,6 +191,14 @@ func (p *Anthropic) CreateInterceptor(_ http.ResponseWriter, r *http.Request, tr return interceptor, nil } +// CreateExtractor serves the messages route. +func (p *Anthropic) CreateExtractor(path string) extractors.Extractor { + if path == p.RoutePrefix()+routeMessages { + return extractors.NewMessages() + } + return nil +} + // ResolveCredential determines the upstream credential for a request. // Coder authentication credentials must already have been removed from it. // Remaining provider authentication headers are interpreted as BYOK credentials. diff --git a/aibridge/provider/bedrock_provider.go b/aibridge/provider/bedrock_provider.go index 0bfa586ebe2..764ec3775ae 100644 --- a/aibridge/provider/bedrock_provider.go +++ b/aibridge/provider/bedrock_provider.go @@ -16,6 +16,7 @@ import ( "cdr.dev/slog/v3" "github.com/coder/coder/v2/aibridge/config" "github.com/coder/coder/v2/aibridge/credential" + "github.com/coder/coder/v2/aibridge/extractors" aibheaders "github.com/coder/coder/v2/aibridge/headers" "github.com/coder/coder/v2/aibridge/intercept" "github.com/coder/coder/v2/aibridge/intercept/awssig" @@ -156,6 +157,9 @@ func (p *Bedrock) CreateInterceptor(_ http.ResponseWriter, r *http.Request, trac return intr, outErr } +// CreateExtractor returns nil. No Bedrock route has an extractor yet. +func (*Bedrock) CreateExtractor(string) extractors.Extractor { return nil } + // createMessagesInterceptor builds a messages interceptor wired to the full // Bedrock runtime. The runtime carries the InvokeModel remap config and the // SigV4 signing credentials. diff --git a/aibridge/provider/copilot.go b/aibridge/provider/copilot.go index d2fde331216..6ec8ac5c3a5 100644 --- a/aibridge/provider/copilot.go +++ b/aibridge/provider/copilot.go @@ -15,6 +15,7 @@ import ( "cdr.dev/slog/v3" "github.com/coder/coder/v2/aibridge/config" "github.com/coder/coder/v2/aibridge/credential" + "github.com/coder/coder/v2/aibridge/extractors" aibheaders "github.com/coder/coder/v2/aibridge/headers" "github.com/coder/coder/v2/aibridge/intercept" "github.com/coder/coder/v2/aibridge/intercept/chatcompletions" @@ -206,6 +207,9 @@ func (p *Copilot) CreateInterceptor(_ http.ResponseWriter, r *http.Request, trac return interceptor, nil } +// CreateExtractor returns nil. No Copilot route has an extractor yet. +func (*Copilot) CreateExtractor(string) extractors.Extractor { return nil } + // ResolveCredential resolves Copilot's per-request BYOK token. // Coder authentication credentials must already have been removed from the // request. diff --git a/aibridge/provider/disabled.go b/aibridge/provider/disabled.go index 26fbaefec84..87aefa36db2 100644 --- a/aibridge/provider/disabled.go +++ b/aibridge/provider/disabled.go @@ -9,6 +9,7 @@ import ( "cdr.dev/slog/v3" "github.com/coder/coder/v2/aibridge/config" "github.com/coder/coder/v2/aibridge/credential" + "github.com/coder/coder/v2/aibridge/extractors" "github.com/coder/coder/v2/aibridge/intercept" "github.com/coder/coder/v2/aibridge/keypool" "github.com/coder/coder/v2/aibridge/recorder" @@ -55,3 +56,6 @@ func (*DisabledStub) CreateInterceptor(_ http.ResponseWriter, _ *http.Request, _ //nolint:nilnil // disabled providers never reach the interceptor. return nil, nil } + +// CreateExtractor returns nil. Disabled providers serve no routes. +func (*DisabledStub) CreateExtractor(string) extractors.Extractor { return nil } diff --git a/aibridge/provider/openai.go b/aibridge/provider/openai.go index c6d916d48cf..74d89281c13 100644 --- a/aibridge/provider/openai.go +++ b/aibridge/provider/openai.go @@ -16,6 +16,7 @@ import ( "cdr.dev/slog/v3" "github.com/coder/coder/v2/aibridge/config" "github.com/coder/coder/v2/aibridge/credential" + "github.com/coder/coder/v2/aibridge/extractors" aibheaders "github.com/coder/coder/v2/aibridge/headers" "github.com/coder/coder/v2/aibridge/intercept" "github.com/coder/coder/v2/aibridge/intercept/chatcompletions" @@ -155,6 +156,10 @@ func (p *OpenAI) CreateInterceptor(_ http.ResponseWriter, r *http.Request, trace return interceptor, nil } +// CreateExtractor returns nil. The chat completions and responses routes have +// no extractor yet. +func (*OpenAI) CreateExtractor(string) extractors.Extractor { return nil } + // ResolveCredential determines the upstream credential for a request. // Coder authentication credentials must already have been removed from it. // A remaining Authorization header is interpreted as a BYOK token. Otherwise diff --git a/aibridge/provider/provider.go b/aibridge/provider/provider.go index 07ef8bd7da0..b538b0c766d 100644 --- a/aibridge/provider/provider.go +++ b/aibridge/provider/provider.go @@ -10,6 +10,7 @@ import ( "cdr.dev/slog/v3" "github.com/coder/coder/v2/aibridge/config" "github.com/coder/coder/v2/aibridge/credential" + "github.com/coder/coder/v2/aibridge/extractors" "github.com/coder/coder/v2/aibridge/intercept" "github.com/coder/coder/v2/aibridge/keypool" "github.com/coder/coder/v2/aibridge/recorder" @@ -83,6 +84,12 @@ type Provider interface { // communicating with the upstream provider and formulating a response to be sent to the requesting client. CreateInterceptor(http.ResponseWriter, *http.Request, trace.Tracer) (intercept.Interceptor, error) + // CreateExtractor returns a request-scoped [extractors.Extractor] for a + // proxied request. path is the full request path, including RoutePrefix(). + // nil means extraction is not implemented for the path, not that forwarding + // is rejected. + CreateExtractor(path string) extractors.Extractor + // ResolveCredential determines the upstream credential for a request. // Coder authentication credentials must already have been removed from it. // Remaining provider authentication headers are interpreted as BYOK credentials. diff --git a/aibridge/x/proxy/handler.go b/aibridge/x/proxy/handler.go index 85384c2fc1c..214be71a876 100644 --- a/aibridge/x/proxy/handler.go +++ b/aibridge/x/proxy/handler.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "io" "log" "net/http" "net/http/httputil" @@ -22,6 +23,7 @@ import ( aibclient "github.com/coder/coder/v2/aibridge/client" aibcontext "github.com/coder/coder/v2/aibridge/context" "github.com/coder/coder/v2/aibridge/credential" + "github.com/coder/coder/v2/aibridge/extractors" "github.com/coder/coder/v2/aibridge/headers" "github.com/coder/coder/v2/aibridge/intercept/apidump" "github.com/coder/coder/v2/aibridge/interceptionerror" @@ -65,9 +67,12 @@ type forwardedRequest struct { logger slog.Logger cred credential.Credential record *recorder.InterceptionRecord + // extractor derives recording facts for the route, set by start. Nil when + // the route has no extractor yet. + extractor extractors.Extractor - // outbound is the request passed to the reverse proxy. Set when the circuit - // breaker admits the request, nil otherwise. + // outbound is the request passed to the reverse proxy, set by start once + // the request body has been read. Nil otherwise. outbound *http.Request // requestBody captures the outbound request body for replay. Set with // outbound. @@ -165,35 +170,46 @@ func (fr *forwardedRequest) serve(w http.ResponseWriter, r *http.Request) { defer cleanup() // finish needs to run before cleanup cancels the ctx. defer fr.finish(ctx, release) + defer func() { + if fr.requestBody != nil { + _ = fr.requestBody.Close() + } + }() r = r.WithContext(ctx) if !fr.start(ctx, w, r) { return } route := strings.TrimPrefix(r.URL.Path, "/"+fr.handler.provider.Name()) - fr.err = fr.handler.breaker.Execute(route, "", w, func(rw http.ResponseWriter) error { - fr.outbound, fr.requestBody = replaybody.NewRequest(r) - defer func() { _ = fr.requestBody.Close() }() - return fr.forward(rw) - }) + fr.err = fr.handler.breaker.Execute(route, "", w, fr.forward) if fr.err != nil { span.SetStatus(codes.Error, "forwarding failed") } } -// start validates the request and records its start before forwarding. On -// rejection it writes the response and reports false. +// start validates and reads the request, extracts its facts, and records its +// start before forwarding. On rejection it writes the response and reports +// false. func (fr *forwardedRequest) start(ctx context.Context, w http.ResponseWriter, r *http.Request) bool { logger, record, cred := fr.handler.checkRequest(w, r) fr.logger = logger if record == nil { return false } - // Forwarding captures the request body as it streams upstream. Without full - // duplex, the HTTP/1 server drains the original body past the capture before - // writing an early reply. Writers that cannot enable it keep the default drain. - if err := http.NewResponseController(w).EnableFullDuplex(); err != nil { - logger.Debug(ctx, "full duplex unavailable, early replies drain the request body first", slog.Error(err)) + + if !fr.readRequest(ctx, w, r) { + return false + } + record.ClientSessionID = aibclient.GuessSessionIDFromPayload(aibclient.Type(record.Client), r, fr.requestBody.Bytes()) + // Routes without an extractor yet are forwarded and recorded without the + // facts it would add. + if extractor := fr.handler.provider.CreateExtractor(r.URL.Path); extractor != nil { + // Extraction failures only lose recording facts, the request is still + // forwarded unchanged. + if err := extractor.ExtractRequest(fr.requestBody.Bytes(), record); err != nil { + logger.Warn(ctx, "failed to extract request facts", slog.Error(err)) + } + fr.extractor = extractor } // The start record must exist before forwarding or recording its end. @@ -208,6 +224,48 @@ func (fr *forwardedRequest) start(ctx context.Context, w http.ResponseWriter, r return true } +// readRequest reads the complete request body through a replay capture, then +// rewinds the outbound request so forwarding sends the same bytes. It sets +// fr.outbound and fr.requestBody. On failure it writes the rejection and +// reports false. +func (fr *forwardedRequest) readRequest(ctx context.Context, w http.ResponseWriter, r *http.Request) bool { + outbound, capture := replaybody.NewRequest(r) + // Closing the capture unblocks a stalled body read, so cancellation, + // including inflight gate shutdown, releases the request. + stop := context.AfterFunc(ctx, func() { _ = capture.Close() }) + _, err := io.Copy(io.Discard, outbound.Body) + stop() + var replay io.ReadCloser + if err == nil { + // Rewind so forwarding sends the captured bytes. + replay, err = outbound.GetBody() + } + if err != nil { + _ = capture.Close() + trace.SpanFromContext(ctx).SetStatus(codes.Error, "failed to read request body") + if ctx.Err() != nil { + fr.logger.Debug(ctx, "request canceled while reading its body", slog.Error(context.Cause(ctx))) + // TODO: Return this error in the provider's JSON format. https://linear.app/codercom/issue/AIGOV-810 + http.Error(w, "request canceled", http.StatusServiceUnavailable) + return false + } + //nolint:errcheck // AsType returns the match; only its presence matters. + if _, ok := errors.AsType[*http.MaxBytesError](err); ok { + fr.logger.Debug(ctx, "rejecting oversized request body", slog.Error(err)) + routing.WriteRequestBodyTooLarge(ctx, w) + return false + } + fr.logger.Warn(ctx, "failed to read request body", slog.Error(err)) + // TODO: Return this error in the provider's JSON format. https://linear.app/codercom/issue/AIGOV-810 + http.Error(w, "failed to read request body", http.StatusBadRequest) + return false + } + _ = outbound.Body.Close() + outbound.Body = replay + fr.outbound, fr.requestBody = outbound, capture + return true +} + // finish records how the interception ended, then releases in-flight // admission. It must run before cleanup cancels ctx. func (fr *forwardedRequest) finish(ctx context.Context, release func()) { @@ -368,10 +426,7 @@ func (h *forwardingHandler) checkRequest(w http.ResponseWriter, r *http.Request) AgentFirewallSequenceNumber: firewallSequence, CredentialKind: cred.Kind(), CredentialHint: cred.Hint(), - // Model: TODO, depends on extractor - // ClientSessionID: TODO, depends on request buffering - // CorrelatingToolCallID: TODO, depends on extractor - // TODO https://linear.app/codercom/issue/AIGOV-613 + // forwardedRequest.start sets ClientSessionID, Model and CorrelatingToolCallID. } return logger, ir, cred @@ -419,11 +474,6 @@ func (fr *forwardedRequest) forward(w http.ResponseWriter) (err error) { ErrorHandler: func(w http.ResponseWriter, r *http.Request, proxyErr error) { err = proxyErr ctx := r.Context() - //nolint:errcheck // AsType returns the match; only its presence matters. - if _, ok := errors.AsType[*http.MaxBytesError](proxyErr); ok { - routing.WriteRequestBodyTooLarge(ctx, w) - return - } fr.logger.Warn(ctx, "upstream proxy error", slog.Error(proxyErr)) // TODO: Return this error in the provider's JSON format. https://linear.app/codercom/issue/AIGOV-810 http.Error(w, "upstream proxy error", http.StatusBadGateway) diff --git a/aibridge/x/proxy/handler_internal_test.go b/aibridge/x/proxy/handler_internal_test.go index 6492c881a4d..6fb27144c97 100644 --- a/aibridge/x/proxy/handler_internal_test.go +++ b/aibridge/x/proxy/handler_internal_test.go @@ -40,7 +40,6 @@ import ( "github.com/coder/coder/v2/aibridge/recorder" "github.com/coder/coder/v2/aibridge/routing" "github.com/coder/coder/v2/aibridge/utils" - "github.com/coder/coder/v2/aibridge/x/proxy/replaybody" codertestutil "github.com/coder/coder/v2/testutil" "github.com/coder/quartz" ) @@ -168,20 +167,17 @@ func newTestPool(t *testing.T, keys ...string) *keypool.Pool { return pool } -// prepareAndProxy validates r, captures its body for replay, and forwards it -// outside the circuit breaker. +// prepareAndProxy validates and reads r as start does, then forwards it outside +// the circuit breaker. func prepareAndProxy(t *testing.T, h *forwardingHandler, w http.ResponseWriter, r *http.Request) { t.Helper() fr := &forwardedRequest{handler: h} var record *recorder.InterceptionRecord fr.logger, record, fr.cred = h.checkRequest(w, r) require.NotNil(t, record, "request must pass validation") - fr.outbound, fr.requestBody = replaybody.NewRequest(r) + require.True(t, fr.readRequest(r.Context(), w, r), "request body must be readable") t.Cleanup(func() { _ = fr.requestBody.Close() }) _ = fr.forward(w) - require.NoError(t, fr.requestBody.Close()) - _, err := fr.requestBody.Wait(codertestutil.Context(t, codertestutil.WaitLong)) - require.NoError(t, err) } func TestForwardingHandlerRejects(t *testing.T) { @@ -523,8 +519,7 @@ func TestForwardingHandlerOpenCircuit(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { t.Parallel() - body := &unreadBody{} - req := httptest.NewRequest(http.MethodPost, prov.RoutePrefix()+"/responses", body) + req := httptest.NewRequest(http.MethodPost, prov.RoutePrefix()+"/responses", strings.NewReader("{}")) req = req.WithContext(aibridge.AsActor(t.Context(), aibridge.Actor{ID: uuid.New(), APIKeyID: uuid.NewString()})) req.Header.Set("Authorization", "Bearer user-key") if tc.noCredential { @@ -538,8 +533,6 @@ func TestForwardingHandlerOpenCircuit(t *testing.T) { response := httptest.NewRecorder() handler.ServeHTTP(response, req) require.Equal(t, tc.status, response.Code) - require.False(t, body.read) - require.False(t, body.closed) if tc.status == http.StatusServiceUnavailable { require.Contains(t, response.Body.String(), circuitbreaker.ErrCircuitOpen.Error()) } @@ -744,10 +737,10 @@ func TestForwardingReusesUpstreamConnection(t *testing.T) { require.Equal(t, first, send("second-key"), "per-request proxies must reuse the upstream connection") } -// Centralized requests move to the next key after a key failure. The first -// attempt forwards the body as it is read, so the retry replays the consumed -// prefix and then continues reading the input. The rejected response is -// drained and closed without reaching the client. +// Centralized requests move to the next key after a key failure. The retry +// replays the whole captured body even when the first attempt read only part +// of it. The rejected response is drained and closed without reaching the +// client. func TestForwardingFailoverRetry(t *testing.T) { t.Parallel() const prefix = `{"metadata":{"user_id":` @@ -764,12 +757,11 @@ func TestForwardingFailoverRetry(t *testing.T) { _, err := io.ReadFull(r.Body, chunk) assert.NoError(t, err) assert.Equal(t, prefix, string(chunk)) - assert.Equal(t, len(suffix), input.Len(), "the first attempt must forward the prefix before the input is read") return &http.Response{StatusCode: http.StatusUnauthorized, Header: http.Header{}, Body: rejected}, nil } payload, err := io.ReadAll(r.Body) assert.NoError(t, err) - assert.Equal(t, prefix+suffix, string(payload), "the retry must replay the prefix and read the remaining input") + assert.Equal(t, prefix+suffix, string(payload), "the retry must replay the whole body") return &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("ok"))}, nil }) req := requestWithAuth(t, input) @@ -784,6 +776,67 @@ func TestForwardingFailoverRetry(t *testing.T) { require.EqualValues(t, 1, rejected.closes.Load(), "rejected responses must be closed") } +// newMessagesRequest returns a centralized-key Anthropic Messages request, +// which the provider routes to its extractor. +func newMessagesRequest(t *testing.T, prov provider.Provider, body io.Reader) *http.Request { + t.Helper() + req := requestWithAuth(t, body) + req.URL.Path = prov.RoutePrefix() + "/v1/messages" + req.Header.Del("Authorization") + return req +} + +// Routes with an extractor read the request before recording its start, then +// forward the same bytes. Extraction failures only lose facts. +func TestForwardingExtractsRequest(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + body string + wantModel string + }{ + { + name: "Messages", + body: `{"model":"claude-test","stream":true,"messages":[{"role":"user","content":"hi"}]}`, + wantModel: "claude-test", + }, + { + name: "InvalidJSON", + body: `not JSON`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + prov, err := provider.NewAnthropic(t.Context(), config.Anthropic{BaseURL: "https://upstream.example.test", KeyPool: newTestPool(t, "centralized-key")}, nil, nil) + require.NoError(t, err) + h := newTestForwardingHandler(t, prov, nil) + rec := &testutil.MockRecorder{} + h.recorder = rec + var forwarded []string + h.transport = roundTripFunc(func(r *http.Request) (*http.Response, error) { + assert.Len(t, rec.RecordedInterceptions(), 1, "the start must be recorded before contacting upstream") + payload, err := io.ReadAll(r.Body) + assert.NoError(t, err) + forwarded = append(forwarded, string(payload)) + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: http.NoBody}, nil + }) + req := newMessagesRequest(t, prov, strings.NewReader(tc.body)) + response := httptest.NewRecorder() + h.ServeHTTP(response, req) + require.NoError(t, h.inflight.Shutdown(codertestutil.Context(t, codertestutil.WaitLong))) + + require.Equal(t, http.StatusOK, response.Code) + require.Equal(t, []string{tc.body}, forwarded, "extraction must not alter the forwarded bytes") + starts := rec.RecordedInterceptions() + require.Len(t, starts, 1) + require.Equal(t, tc.wantModel, starts[0].Model) + end := rec.RecordedInterceptionEnd(starts[0].ID) + require.NotNil(t, end) + require.Empty(t, end.ErrorType) + }) + } +} + func TestForwardingRecordingDoesNotBlockResponse(t *testing.T) { t.Parallel() h := newTestForwardingHandler(t, provider.NewOpenAI(config.OpenAI{BaseURL: "https://upstream.example.test"}), nil) @@ -825,9 +878,13 @@ func TestForwardingRecordingDoesNotBlockResponse(t *testing.T) { } // Forwarding records the interception start before contacting upstream and its -// end before releasing admission. +// end before releasing admission. Both records are compared in full. func TestForwardingRecordsInterception(t *testing.T) { t.Parallel() + const ( + userAgent = "codex_cli_rs/0.87.0 (Mac OS 26.2.0; arm64)" + firewallID = "e5f6a7b8-1234-5678-9abc-def012345678" + ) for _, tc := range []struct { name string pooled bool @@ -990,6 +1047,10 @@ func TestForwardingRecordsInterception(t *testing.T) { h.transport = roundTripFunc(func(*http.Request) (*http.Response, error) { return nil, io.ErrClosedPipe }) } req := requestWithAuth(t, strings.NewReader("{}")) + req.Header.Set("User-Agent", userAgent) + req.Header.Set("session-id", "session-1") + req.Header.Set("X-Coder-Agent-Firewall-Session-Id", firewallID) + req.Header.Set("X-Coder-Agent-Firewall-Sequence-Number", "42") if tc.pooled { req.Header.Del("Authorization") } @@ -1002,6 +1063,7 @@ func TestForwardingRecordsInterception(t *testing.T) { req = req.WithContext(ctx) w = cancelOnWrite{ResponseRecorder: response, cancel: cancel} } + before := time.Now() if tc.abort { // Set ServerContextKey so ReverseProxy panics with ErrAbortHandler // when copying the upstream body fails. @@ -1018,11 +1080,41 @@ func TestForwardingRecordsInterception(t *testing.T) { } starts := rec.RecordedInterceptions() require.Len(t, starts, 1) - end := rec.RecordedInterceptionEnd(starts[0].ID) + start := starts[0] + id, err := uuid.Parse(start.ID) + require.NoError(t, err) + require.NotEqual(t, uuid.Nil, id) + require.WithinRange(t, start.StartedAt, before, time.Now()) + wantKind, wantStartHint := credential.KindBYOK, utils.MaskSecret(userSecretKey) + if tc.pooled { + wantKind, wantStartHint = credential.KindCentralized, credential.HintFailoverKey + } + require.Equal(t, &recorder.InterceptionRecord{ + ID: start.ID, + InitiatorID: aibcontext.ActorIDFromContext(req.Context()), + Metadata: recorder.Metadata{"Username": t.Name()}, + Provider: config.ProviderOpenAI, + ProviderName: "openai", + StartedAt: start.StartedAt, + ClientSessionID: new("session-1"), + Client: string(client.Codex), + UserAgent: userAgent, + AgentFirewallSessionID: new(firewallID), + AgentFirewallSequenceNumber: new(int32(42)), + CredentialKind: wantKind, + CredentialHint: wantStartHint, + }, start) + + end := rec.RecordedInterceptionEnd(start.ID) require.NotNil(t, end) - require.Equal(t, tc.wantError, end.ErrorType) - require.Equal(t, tc.wantMessage, end.ErrorMessage) - require.Equal(t, tc.wantHint, end.CredentialHint) + require.WithinRange(t, end.EndedAt, start.StartedAt, time.Now()) + require.Equal(t, &recorder.InterceptionRecordEnded{ + ID: start.ID, + EndedAt: end.EndedAt, + CredentialHint: tc.wantHint, + ErrorType: tc.wantError, + ErrorMessage: tc.wantMessage, + }, end) }) } } diff --git a/aibridge/x/proxy/outcomes_internal_test.go b/aibridge/x/proxy/outcomes_internal_test.go index a0958a41839..6e87efc6e61 100644 --- a/aibridge/x/proxy/outcomes_internal_test.go +++ b/aibridge/x/proxy/outcomes_internal_test.go @@ -7,6 +7,7 @@ import ( "net/http" "net/http/httptest" "strings" + "sync" "sync/atomic" "testing" "time" @@ -19,6 +20,7 @@ import ( "github.com/coder/coder/v2/aibridge/circuitbreaker" "github.com/coder/coder/v2/aibridge/config" aibcontext "github.com/coder/coder/v2/aibridge/context" + "github.com/coder/coder/v2/aibridge/internal/testutil" "github.com/coder/coder/v2/aibridge/keypool" "github.com/coder/coder/v2/aibridge/metrics" "github.com/coder/coder/v2/aibridge/provider" @@ -192,14 +194,14 @@ func TestForwardingTransportOutcomes(t *testing.T) { } } +// Request body read failures reject the request before recording or forwarding +// it. func TestForwardingBodyFailures(t *testing.T) { t.Parallel() for _, tc := range []struct { name string // source returns the request body. read counts what it produces. - source func(read *atomic.Int64) io.Reader - // isWantErr reports whether forwarding and replay failed as expected. - isWantErr func(error) bool + source func(read *atomic.Int64) io.Reader wantStatus int maxRead int64 }{ @@ -208,10 +210,6 @@ func TestForwardingBodyFailures(t *testing.T) { source: func(read *atomic.Int64) io.Reader { return readerFunc(func(p []byte) (int, error) { clear(p); read.Add(int64(len(p))); return len(p), nil }) }, - isWantErr: func(err error) bool { - _, ok := errors.AsType[*http.MaxBytesError](err) - return ok - }, wantStatus: http.StatusRequestEntityTooLarge, maxRead: routing.MaxRequestBodyBytes + 1, }, @@ -220,8 +218,7 @@ func TestForwardingBodyFailures(t *testing.T) { source: func(read *atomic.Int64) io.Reader { return readerFunc(func([]byte) (int, error) { read.Add(1); return 0, io.ErrUnexpectedEOF }) }, - isWantErr: func(err error) bool { return errors.Is(err, io.ErrUnexpectedEOF) }, - wantStatus: http.StatusBadGateway, + wantStatus: http.StatusBadRequest, maxRead: 1, }, } { @@ -230,31 +227,87 @@ func TestForwardingBodyFailures(t *testing.T) { var read atomic.Int64 response := httptest.NewRecorder() req := requestWithAuth(t, nil) - // Trigger a body limit error mid-stream to check how the handler reports it. req.Body = http.MaxBytesReader(response, io.NopCloser(tc.source(&read)), routing.MaxRequestBodyBytes) req.ContentLength = -1 h := newTestForwardingHandler(t, provider.NewOpenAI(config.OpenAI{BaseURL: "https://upstream.example.test"}), nil) - calls := 0 - h.transport = roundTripFunc(func(r *http.Request) (*http.Response, error) { - calls++ - _, err := io.Copy(io.Discard, r.Body) - return nil, err + rec := &testutil.MockRecorder{} + h.recorder = rec + h.transport = roundTripFunc(func(*http.Request) (*http.Response, error) { + t.Error("rejected requests must not call upstream") + return nil, io.ErrUnexpectedEOF }) call := &forwardedRequest{handler: h} call.serve(response, req) + require.NoError(t, h.inflight.Shutdown(codertestutil.Context(t, codertestutil.WaitLong))) + require.Equal(t, tc.wantStatus, response.Code) - require.Equal(t, 1, calls) - require.Nil(t, call.responseBody) - require.True(t, tc.isWantErr(call.err), "unexpected forwarding error: %v", call.err) - readBefore := read.Load() - _, replayErr := call.requestBody.Wait(codertestutil.Context(t, codertestutil.WaitLong)) - require.Equal(t, readBefore, read.Load(), "replay must not read failed input again") - require.True(t, tc.isWantErr(replayErr), "unexpected replay error: %v", replayErr) + require.Empty(t, rec.RecordedInterceptions(), "rejected requests must not record a start") + require.Nil(t, call.requestBody, "rejected requests must not keep the capture") require.LessOrEqual(t, read.Load(), tc.maxRead, "failure must stop reading input") }) } } +// signalReadBody closes read once the first bytes arrive from the client. +type signalReadBody struct { + io.ReadCloser + read chan struct{} + once sync.Once +} + +func (b *signalReadBody) Read(p []byte) (int, error) { + n, err := b.ReadCloser.Read(p) + if n > 0 { + b.once.Do(func() { close(b.read) }) + } + return n, err +} + +// Closing the inflight gate unblocks a request whose body stalls mid-read, so +// shutdown does not wait for the client to finish sending. +func TestForwardingStalledBodyShutdown(t *testing.T) { + t.Parallel() + h := newTestForwardingHandler(t, provider.NewOpenAI(config.OpenAI{BaseURL: "https://upstream.example.test"}), nil) + rec := &testutil.MockRecorder{} + h.recorder = rec + h.transport = roundTripFunc(func(*http.Request) (*http.Response, error) { + t.Error("stalled requests must not call upstream") + return nil, io.ErrUnexpectedEOF + }) + reading, served := make(chan struct{}), make(chan struct{}) + // The handler response is recorded here, the stalled client cannot read it. + response := httptest.NewRecorder() + gateway := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + defer close(served) + r.Body = &signalReadBody{ReadCloser: r.Body, read: reading} + ctx := aibcontext.AsActor(r.Context(), aibcontext.Actor{ID: uuid.New(), APIKeyID: uuid.NewString()}) + h.ServeHTTP(response, r.WithContext(ctx)) + })) + t.Cleanup(gateway.Close) + // The client sends one byte, then stalls until cleanup ends the body. + body, stall := io.Pipe() + t.Cleanup(func() { _ = stall.Close() }) + req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, gateway.URL+"/openai/v1/chat/completions", body) + require.NoError(t, err) + req.Header.Set("Authorization", "Bearer "+userSecretKey) + go func() { + resp, err := gateway.Client().Do(req) + if err == nil { + _ = resp.Body.Close() + } + }() + _, err = stall.Write([]byte("{")) + require.NoError(t, err) + + ctx := codertestutil.Context(t, codertestutil.WaitShort) + codertestutil.TryReceive(ctx, t, reading) + h.inflight.Close() + require.NoError(t, h.inflight.Shutdown(ctx), "a stalled body must not hold admission after close") + codertestutil.TryReceive(ctx, t, served) + require.Equal(t, http.StatusServiceUnavailable, response.Code, "cancellation is not a client error") + require.Empty(t, rec.RecordedInterceptions(), "canceled requests must not record a start") +} + // Key failover retries with the next pooled key, and an exhausted pool returns // its error response. func TestForwardingKeyOutcomes(t *testing.T) { @@ -455,7 +508,6 @@ func TestForwardingCircuitBreaker(t *testing.T) { require.Equal(t, http.StatusServiceUnavailable, response.Code) require.ErrorIs(t, rejected.err, circuitbreaker.ErrCircuitOpen) require.Nil(t, rejected.responseBody) - require.Nil(t, rejected.requestBody, "open circuit must skip request preparation") require.EqualValues(t, 1, calls.Load(), "the 503 must trip the breaker") }