@@ -139,7 +139,31 @@ func writeInternalError(w http.ResponseWriter, msg string) { |
139 | 139 |
|
140 | 140 | // handleMessages processes /v1/messages requests with bidirectional policy evaluation. |
141 | 141 | func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) { |
142 | | - // 1. Read request body (with size limit to prevent memory exhaustion). |
| 142 | + // 1. Read and parse request. |
| 143 | + body, req, err := p.readRequest(w, r) |
| 144 | + if err != nil { |
| 145 | + return // error already written to w |
| 146 | + } |
| 147 | + |
| 148 | + // 2. Evaluate request policy. |
| 149 | + evalResult, err := p.evaluateRequestPolicy(w, req, body) |
| 150 | + if err != nil { |
| 151 | + return // error (or deny) already written to w |
| 152 | + } |
| 153 | + |
| 154 | + // 3. Streaming: buffer, evaluate, replay/synthesize. |
| 155 | + if req.Stream { |
| 156 | + p.handleStreamingResponse(w, r, evalResult.forwardBody) |
| 157 | + return |
| 158 | + } |
| 159 | + |
| 160 | + // 4. Non-streaming: forward, evaluate response, return. |
| 161 | + p.handleNonStreamingResponse(w, r, evalResult.forwardBody) |
| 162 | +} |
| 163 | + |
| 164 | +// readRequest reads the request body (with size limits) and parses it as a MessagesRequest. |
| 165 | +// On error, it writes the appropriate error response to w and returns a non-nil error. |
| 166 | +func (p *Proxy) readRequest(w http.ResponseWriter, r *http.Request) ([]byte, *anthropic.MessagesRequest, error) { |
143 | 167 | body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxRequestBodySize)) |
144 | 168 | if err != nil { |
145 | 169 | var maxErr *http.MaxBytesError |
@@ -153,22 +177,21 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) { |
153 | 177 | Message: fmt.Sprintf("Request body exceeds maximum allowed size of %d bytes", maxRequestBodySize), |
154 | 178 | }, |
155 | 179 | }) |
156 | | - return |
| 180 | + return nil, nil, err |
157 | 181 | } |
158 | 182 | writeInternalError(w, "failed to read request body") |
159 | | - return |
| 183 | + return nil, nil, err |
160 | 184 | } |
161 | 185 |
|
162 | 186 | // Verbose: log raw request. |
163 | 187 | if p.verbose != nil { |
164 | 188 | p.verbose.RequestRaw(body) |
165 | 189 | } |
166 | 190 |
|
167 | | - // 2. Parse as MessagesRequest. |
168 | 191 | var req anthropic.MessagesRequest |
169 | 192 | if err := json.Unmarshal(body, &req); err != nil { |
170 | 193 | writeInternalError(w, "failed to parse request body") |
171 | | - return |
| 194 | + return nil, nil, err |
172 | 195 | } |
173 | 196 |
|
174 | 197 | mode := "non-streaming" |
@@ -181,10 +204,22 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) { |
181 | 204 | "messages", len(req.Messages), |
182 | 205 | ) |
183 | 206 |
|
184 | | - // 3. Decompose request into calls. |
185 | | - calls := anthropic.DecomposeRequest(&req, p.scope, p.decompose) |
| 207 | + return body, &req, nil |
| 208 | +} |
| 209 | + |
| 210 | +// requestPolicyResult holds the output of request policy evaluation. |
| 211 | +type requestPolicyResult struct { |
| 212 | + forwardBody []byte |
| 213 | +} |
186 | 214 |
|
187 | | - // 4. Evaluate each call. Track block results for reassembly. |
| 215 | +// evaluateRequestPolicy decomposes the request, evaluates each call against policy, |
| 216 | +// and reassembles the request body if any redactions were applied. |
| 217 | +// On deny or error, it writes the appropriate response to w and returns a non-nil error. |
| 218 | +func (p *Proxy) evaluateRequestPolicy(w http.ResponseWriter, req *anthropic.MessagesRequest, body []byte) (*requestPolicyResult, error) { |
| 219 | + // Decompose request into calls. |
| 220 | + calls := anthropic.DecomposeRequest(req, p.scope, p.decompose) |
| 221 | + |
| 222 | + // Evaluate each call. Track block results for reassembly. |
188 | 223 | // DecomposeRequest emits: optional summary call, then one call per content block. |
189 | 224 | // We need to map the content-block calls back to (MessageIndex, BlockIndex). |
190 | 225 | summaryOffset := 0 |
@@ -193,7 +228,7 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) { |
193 | 228 | } |
194 | 229 |
|
195 | 230 | // Build the block index mapping by re-walking messages (same order as DecomposeRequest). |
196 | | - blockMap := buildRequestBlockMap(&req, p.decompose) |
| 231 | + blockMap := buildRequestBlockMap(req, p.decompose) |
197 | 232 |
|
198 | 233 | hasRedaction := false |
199 | 234 | blockResults := make([]anthropic.BlockResult, len(blockMap)) |
@@ -203,7 +238,7 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) { |
203 | 238 | result, evalErr := p.engine.Evaluate(call, p.scope) |
204 | 239 | if evalErr != nil { |
205 | 240 | writeInternalError(w, "policy evaluation error") |
206 | | - return |
| 241 | + return nil, evalErr |
207 | 242 | } |
208 | 243 |
|
209 | 244 | // Log audit entry. |
@@ -218,7 +253,7 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) { |
218 | 253 | p.verbose.RequestDenied(result.Rule, result.Message) |
219 | 254 | } |
220 | 255 | writePolicyDeny(w, result.Rule, result.Message) |
221 | | - return |
| 256 | + return nil, fmt.Errorf("policy denied: %s", result.Rule) |
222 | 257 | } |
223 | 258 |
|
224 | 259 | // Track redactions for content blocks (skip the summary call). |
@@ -242,14 +277,15 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) { |
242 | 277 | "redacted_rules", strings.Join(redactedRules, ","), |
243 | 278 | ) |
244 | 279 |
|
245 | | - // 6. Reassemble if redacted. |
| 280 | + // Reassemble if redacted. |
246 | 281 | forwardBody := body |
247 | 282 | if hasRedaction { |
248 | | - patched := anthropic.ReassembleRequest(&req, blockResults) |
| 283 | + patched := anthropic.ReassembleRequest(req, blockResults) |
| 284 | + var err error |
249 | 285 | forwardBody, err = json.Marshal(patched) |
250 | 286 | if err != nil { |
251 | 287 | writeInternalError(w, "failed to marshal patched request") |
252 | | - return |
| 288 | + return nil, err |
253 | 289 | } |
254 | 290 | } |
255 | 291 |
|
@@ -262,13 +298,13 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) { |
262 | 298 | } |
263 | 299 | } |
264 | 300 |
|
265 | | - // 7. Streaming: buffer, evaluate, replay/synthesize. |
266 | | - if req.Stream { |
267 | | - p.handleStreamingResponse(w, r, forwardBody) |
268 | | - return |
269 | | - } |
| 301 | + return &requestPolicyResult{forwardBody: forwardBody}, nil |
| 302 | +} |
270 | 303 |
|
271 | | - // 8. Forward to upstream. |
| 304 | +// handleNonStreamingResponse forwards the request to upstream, reads the response, |
| 305 | +// evaluates response policy, and writes the (possibly redacted) response back to the client. |
| 306 | +func (p *Proxy) handleNonStreamingResponse(w http.ResponseWriter, r *http.Request, forwardBody []byte) { |
| 307 | + // Forward to upstream. |
272 | 308 | upstreamBase := strings.TrimRight(p.upstream.String(), "/") |
273 | 309 | upstreamURL := upstreamBase + "/v1/messages" |
274 | 310 | upstreamReq, err := http.NewRequestWithContext(r.Context(), "POST", upstreamURL, bytes.NewReader(forwardBody)) |
@@ -286,7 +322,7 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) { |
286 | 322 | } |
287 | 323 | defer func() { _ = upstreamResp.Body.Close() }() |
288 | 324 |
|
289 | | - // 8. Read response body. |
| 325 | + // Read response body. |
290 | 326 | respBody, err := io.ReadAll(io.LimitReader(upstreamResp.Body, maxResponseBodySize)) |
291 | 327 | if err != nil { |
292 | 328 | writeInternalError(w, "failed to read upstream response") |
@@ -306,7 +342,7 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) { |
306 | 342 | p.verbose.ResponseRaw(respBody) |
307 | 343 | } |
308 | 344 |
|
309 | | - // 9. Parse as MessagesResponse. |
| 345 | + // Parse as MessagesResponse. |
310 | 346 | var resp anthropic.MessagesResponse |
311 | 347 | if err := json.Unmarshal(respBody, &resp); err != nil { |
312 | 348 | // Can't parse response; pass through as-is. |
@@ -316,10 +352,10 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) { |
316 | 352 | return |
317 | 353 | } |
318 | 354 |
|
319 | | - // 10. Decompose response. |
| 355 | + // Decompose response. |
320 | 356 | respCalls := anthropic.DecomposeResponse(&resp, p.scope, p.decompose) |
321 | 357 |
|
322 | | - // 11. Evaluate response calls. |
| 358 | + // Evaluate response calls. |
323 | 359 | respSummaryOffset := 0 |
324 | 360 | if p.decompose.ResponseSummaryEnabled() && len(respCalls) > 0 { |
325 | 361 | respSummaryOffset = 1 |
@@ -342,7 +378,7 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) { |
342 | 378 | p.logger.Log(result.Audit) |
343 | 379 | } |
344 | 380 |
|
345 | | - // 12. Check for deny. |
| 381 | + // Check for deny. |
346 | 382 | if result.Decision == keep.Deny { |
347 | 383 | p.logDebug("response denied", "rule", result.Rule, "message", result.Message) |
348 | 384 | if p.verbose != nil { |
@@ -368,7 +404,7 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) { |
368 | 404 |
|
369 | 405 | p.logDebug("response policy", "status", upstreamResp.StatusCode, "calls", len(respCalls), "redacted", respHasRedaction) |
370 | 406 |
|
371 | | - // 13. Reassemble if redacted. |
| 407 | + // Reassemble if redacted. |
372 | 408 | finalBody := respBody |
373 | 409 | if respHasRedaction { |
374 | 410 | patched := anthropic.ReassembleResponse(&resp, respBlockResults) |
@@ -388,7 +424,7 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) { |
388 | 424 | } |
389 | 425 | } |
390 | 426 |
|
391 | | - // 14. Return response to agent. |
| 427 | + // Return response to agent. |
392 | 428 | copyResponseHeaders(w, upstreamResp) |
393 | 429 | w.WriteHeader(upstreamResp.StatusCode) |
394 | 430 | _, _ = w.Write(finalBody) |
|