GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix: harden engine, relay, gateway, and test infrastructure · majorcontext/keep@778a219

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • internal
    • gateway
      • proxy.go
      • proxy_test.go
    • rate
      • counter.go
      • counter_test.go
    • relay
      • handler_test.go
      • mcp
        • client.go
        • server.go
        • stdio_client.go
        • types.go
      • router.go
    • sse
      • reader.go
  • keep_bench_test.go
  • keep_test.go
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎internal/gateway/proxy.go‎

Copy file name to clipboardExpand all lines: internal/gateway/proxy.go
+63-27Lines changed: 63 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,31 @@ func writeInternalError(w http.ResponseWriter, msg string) {
139139

140140
// handleMessages processes /v1/messages requests with bidirectional policy evaluation.
141141
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) {
143167
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxRequestBodySize))
144168
if err != nil {
145169
var maxErr *http.MaxBytesError
@@ -153,22 +177,21 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) {
153177
Message: fmt.Sprintf("Request body exceeds maximum allowed size of %d bytes", maxRequestBodySize),
154178
},
155179
})
156-
return
180+
return nil, nil, err
157181
}
158182
writeInternalError(w, "failed to read request body")
159-
return
183+
return nil, nil, err
160184
}
161185

162186
// Verbose: log raw request.
163187
if p.verbose != nil {
164188
p.verbose.RequestRaw(body)
165189
}
166190

167-
// 2. Parse as MessagesRequest.
168191
var req anthropic.MessagesRequest
169192
if err := json.Unmarshal(body, &req); err != nil {
170193
writeInternalError(w, "failed to parse request body")
171-
return
194+
return nil, nil, err
172195
}
173196

174197
mode := "non-streaming"
@@ -181,10 +204,22 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) {
181204
"messages", len(req.Messages),
182205
)
183206

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+
}
186214

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.
188223
// DecomposeRequest emits: optional summary call, then one call per content block.
189224
// We need to map the content-block calls back to (MessageIndex, BlockIndex).
190225
summaryOffset := 0
@@ -193,7 +228,7 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) {
193228
}
194229

195230
// 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)
197232

198233
hasRedaction := false
199234
blockResults := make([]anthropic.BlockResult, len(blockMap))
@@ -203,7 +238,7 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) {
203238
result, evalErr := p.engine.Evaluate(call, p.scope)
204239
if evalErr != nil {
205240
writeInternalError(w, "policy evaluation error")
206-
return
241+
return nil, evalErr
207242
}
208243

209244
// Log audit entry.
@@ -218,7 +253,7 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) {
218253
p.verbose.RequestDenied(result.Rule, result.Message)
219254
}
220255
writePolicyDeny(w, result.Rule, result.Message)
221-
return
256+
return nil, fmt.Errorf("policy denied: %s", result.Rule)
222257
}
223258

224259
// Track redactions for content blocks (skip the summary call).
@@ -242,14 +277,15 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) {
242277
"redacted_rules", strings.Join(redactedRules, ","),
243278
)
244279

245-
// 6. Reassemble if redacted.
280+
// Reassemble if redacted.
246281
forwardBody := body
247282
if hasRedaction {
248-
patched := anthropic.ReassembleRequest(&req, blockResults)
283+
patched := anthropic.ReassembleRequest(req, blockResults)
284+
var err error
249285
forwardBody, err = json.Marshal(patched)
250286
if err != nil {
251287
writeInternalError(w, "failed to marshal patched request")
252-
return
288+
return nil, err
253289
}
254290
}
255291

@@ -262,13 +298,13 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) {
262298
}
263299
}
264300

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+
}
270303

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.
272308
upstreamBase := strings.TrimRight(p.upstream.String(), "/")
273309
upstreamURL := upstreamBase + "/v1/messages"
274310
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) {
286322
}
287323
defer func() { _ = upstreamResp.Body.Close() }()
288324

289-
// 8. Read response body.
325+
// Read response body.
290326
respBody, err := io.ReadAll(io.LimitReader(upstreamResp.Body, maxResponseBodySize))
291327
if err != nil {
292328
writeInternalError(w, "failed to read upstream response")
@@ -306,7 +342,7 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) {
306342
p.verbose.ResponseRaw(respBody)
307343
}
308344

309-
// 9. Parse as MessagesResponse.
345+
// Parse as MessagesResponse.
310346
var resp anthropic.MessagesResponse
311347
if err := json.Unmarshal(respBody, &resp); err != nil {
312348
// Can't parse response; pass through as-is.
@@ -316,10 +352,10 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) {
316352
return
317353
}
318354

319-
// 10. Decompose response.
355+
// Decompose response.
320356
respCalls := anthropic.DecomposeResponse(&resp, p.scope, p.decompose)
321357

322-
// 11. Evaluate response calls.
358+
// Evaluate response calls.
323359
respSummaryOffset := 0
324360
if p.decompose.ResponseSummaryEnabled() && len(respCalls) > 0 {
325361
respSummaryOffset = 1
@@ -342,7 +378,7 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) {
342378
p.logger.Log(result.Audit)
343379
}
344380

345-
// 12. Check for deny.
381+
// Check for deny.
346382
if result.Decision == keep.Deny {
347383
p.logDebug("response denied", "rule", result.Rule, "message", result.Message)
348384
if p.verbose != nil {
@@ -368,7 +404,7 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) {
368404

369405
p.logDebug("response policy", "status", upstreamResp.StatusCode, "calls", len(respCalls), "redacted", respHasRedaction)
370406

371-
// 13. Reassemble if redacted.
407+
// Reassemble if redacted.
372408
finalBody := respBody
373409
if respHasRedaction {
374410
patched := anthropic.ReassembleResponse(&resp, respBlockResults)
@@ -388,7 +424,7 @@ func (p *Proxy) handleMessages(w http.ResponseWriter, r *http.Request) {
388424
}
389425
}
390426

391-
// 14. Return response to agent.
427+
// Return response to agent.
392428
copyResponseHeaders(w, upstreamResp)
393429
w.WriteHeader(upstreamResp.StatusCode)
394430
_, _ = w.Write(finalBody)

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.