NexusLinkNexusLink Docs

proxy/middleware-framework — generic plugin system

Risk level: High — every proxied request transits this chain. Budget exhaustion, panic recovery, or chain-close bugs hit the hot path for all targets, not just agent-network ones. Backward-compat impact: Additive at the proxy. The middleware and bodytap packages are new (proxy/internal/middleware/middleware.go:1, proxy/internal/middleware/bodytap/request.go:13); existing proxy targets keep working until a chain is bound to them via Manager.Rebuild.

This module is the framework only — no LLM/agent-network domain knowledge is required, since every example built into it is generic.

Module boundary

This module is the framework only: slots, chains, registry, dispatcher, accumulator, body-tap, output filters. No middleware implementation lives here — those land in proxy/internal/middleware/builtin/* (covered in module 31). The package contract is:

  1. The proxy hands a Manager to its config-apply path. The synth pushes per-path PathTargetBinding lists (proxy/internal/middleware/manager.go:26) into Manager.Rebuild, which resolves each spec via the Registry/Resolver (proxy/internal/middleware/registry.go:81-121) and produces an immutable Chain keyed by serviceID|pathID (proxy/internal/middleware/manager.go:410-412).
  2. The reverse-proxy handler captures the request body via bodytap.CaptureRequest, calls Chain.RunRequest, applies returned mutations (already filtered by chain.applyMutations), forwards to the upstream behind a bodytap.CapturingResponseWriter, then calls Chain.RunResponse and Chain.RunTerminal.
  3. Middlewares are inert plugins that receive a deep-cloned Input and return an Output whose decision/mutations are clamped by the dispatcher's filterOutput (proxy/internal/middleware/dispatcher.go:149-172).

Everything that crosses the framework boundary in either direction is value-typed and deep-copied — middlewares cannot mutate the live request directly, and the framework cannot inadvertently leak middleware-owned slices into the request hot path.

Files

Path Role
proxy/internal/middleware/middleware.go Middleware + Factory interfaces.
proxy/internal/middleware/types.go Slot, FailMode, Decision, all limit constants, Input/Output/Mutations/UpstreamRewrite/AuthHeader value types.
proxy/internal/middleware/spec.go Apply-time Spec (validated wire shape + runtime-injected fields) and Clone.
proxy/internal/middleware/registry.go Registry (factory map, RWMutex) and Resolver (Spec → bound Middleware).
proxy/internal/middleware/manager.go Manager, chainTable reverse index, Rebuild/Invalidate*, async chain close.
proxy/internal/middleware/chain.go Chain.RunRequest/RunResponse/RunTerminal, mutation gating, cloneInputFor.
proxy/internal/middleware/chain_test.go Metadata threading, LIFO response order, rewrite gating, UserGroups propagation, terminal accumulation.
proxy/internal/middleware/dispatcher.go Timeout/panic recovery, fail-mode, error classification, filterOutput.
proxy/internal/middleware/decision.go RenderDenyResponse, deny-code regex, status clamp.
proxy/internal/middleware/headerpolicy.go Compile-in header denylist + FilterHeaderMutations.
proxy/internal/middleware/bodypolicy.go ValidateBodyReplace / ApplyBodyReplace smuggling guards.
proxy/internal/middleware/keys.go Metadata key namespace constants.
proxy/internal/middleware/metadata.go Accumulator — allowlist, per-mw/per-request byte caps, redaction.
proxy/internal/middleware/metrics.go OTel instrument bundle (proxy.middleware.*).
proxy/internal/middleware/redaction.go Scan — PEM/JWT/AWS/bearer/Luhn-validated CC patterns.
proxy/internal/middleware/bodytap/request.go Capture + replay reader, Budget semaphore, bypass reason codes.
proxy/internal/middleware/bodytap/response.go CapturingResponseWriter (tee with PassthroughWriter for Flusher/Hijacker preservation).

Slot model

Three slots, declared per-middleware exactly once (proxy/internal/middleware/types.go:27-41):

Splitting a feature across slots (e.g. "parse on the way out, ship on terminal") is the explicit architectural choice — types.go:7-15 and types.go:22-25 make it clear no middleware participates in more than one slot.

Architecture & flow

Chain dispatch

sequenceDiagram
    autonumber
    participant H as proxy HTTP handler
    participant BT as bodytap.CaptureRequest
    participant CH as Chain
    participant DI as Dispatcher
    participant MW as Middleware (per slot)
    participant US as Upstream
    participant CW as CapturingResponseWriter

    H->>BT: CaptureRequest(r, cfg, budget)
    BT-->>H: body[], truncated, release()
    H->>CH: RunRequest(ctx, r, Input, Accumulator)
    loop on_request, registration order
        CH->>CH: cloneInputFor(in, OnRequest)
        CH->>DI: Invoke(ctx, spec, mw, call)
        DI->>MW: mw.Invoke(callCtx, in)
        MW-->>DI: Output{decision, metadata, mutations?}
        DI->>DI: filterOutput (clamp deny, gate mutations)
        DI-->>CH: filtered Output
        CH->>CH: Accumulator.Emit (allowlist + caps + redact)
        alt DecisionDeny
            CH-->>H: denied, merged, rewrite
        else allow
            CH->>CH: applyMutations(r, m) and capture rewrite
        end
    end
    CH-->>H: nil, merged, rewrite
    H->>US: ProxyRequest (with rewrite/mutations applied)
    US-->>CW: bytes (streamed, tee'd into cap-bounded buf)
    CW-->>H: passthrough complete
    H->>CH: RunResponse(ctx, Input{RespBody:CW.Body(),...}, acc)
    loop on_response, REVERSE order (LIFO)
        CH->>DI: Invoke (same wrappers)
    end
    H->>CH: RunTerminal(ctx, Input{Metadata:full bag}, acc)
    H->>BT: release() + CW.Release()

Body-tap mechanics (request + response)

flowchart LR
    subgraph req[Request capture — bodytap.CaptureRequest]
        R0[r.Body] --> R1{cfg.MaxRequestBytes > 0?\nUpgrade absent?\nContent-Type allowed?\nCL <= cap?}
        R1 -- no --> R2[bypass = reason\nbody = nil\nr.Body untouched]
        R1 -- yes --> R3[Budget.Acquire(cap)]
        R3 -- denied --> R4[bypass=BypassBudget]
        R3 -- ok --> R5[io.LimitReader(r.Body, cap+1)\nio.ReadAll]
        R5 --> R6{len > cap?}
        R6 -- truncated --> R7[viewable = buf[:cap]\nr.Body = replayReadCloser{buf, tail}]
        R6 -- whole --> R8[r.Body = NopCloser(bytes.Reader(buf))\nclose original]
        R7 --> R9[(release captured\nbudget on req end)]
        R8 --> R9
    end

    subgraph resp[Response capture — CapturingResponseWriter]
        W0[client] -.-> CW[Write(p)]
        CW --> P1[PassthroughWriter.Write(p)\n— bytes leave to client first]
        P1 --> P2{!stopped?}
        P2 -- yes --> P3{remaining = cap - buf.Len()}
        P3 --> P4[buf.Write(p[:take])\nset truncated if take<n]
        P2 -- no --> P5[silent drop into the tee\n(client write already done)]
    end

The body-tap is the highest-leak-risk surface in this module; three details matter:

  1. Request capture is "read-and-replay", not "read-and-forward". CaptureRequest always swaps r.Body for either a bytes.Reader (whole body fit) or a replayReadCloser that replays the captured prefix then drains the remaining stream from the original body (bodytap/request.go:178-201). This means the upstream still sees the full body even when the tap truncates. The original r.Body is not closed in the truncated branch — replayReadCloser.Close() only closes the tail (bodytap/request.go:199-201), which is the same reader, so close once on request end is correct, but reviewers should confirm the upstream proxy always reads to EOF (otherwise the tail is leaked).
  2. Response capture is a write-through tee. CapturingResponseWriter.Write forwards to the underlying writer first (bodytap/response.go:116-117), then tees into buf under its own mutex. Client never blocks on the tee. Flusher/Hijacker are preserved via the embedded responsewriter.PassthroughWriter. SSE/chunked streams flow through untouched; middlewares only see the bounded prefix.
  3. Budget is a single shared semaphore. Manager constructs one bodytap.Budget at startup (manager.go:138-144, default 256 MiB from bodytap/request.go:39). Every capture pre-acquires its full MaxRequestBytes / MaxResponseBytes from the budget regardless of actual body size; that prevents a flood of small captures from collectively exceeding the cap, but it also means a misconfigured MaxRequestBytes = 1 MiB with 256 concurrent requests already exhausts the default budget. Reviewers should sanity-check the operator-facing defaults that ship with synth-service.

The framework explicitly aborts capture (and increments proxy.middleware.capture_bypass_total) before reading the first byte when Upgrade/Connection: upgrade is set (bodytap/request.go:120-125), when the content-type isn't in the allowlist (bodytap/request.go:126-128), or when the advertised Content-Length already exceeds the cap (bodytap/request.go:131-133). This is the right place to make sure WebSocket upgrades and large file uploads never reach the buffer.

Public contracts

Invariants

Things to scrutinize

Correctness

Security

Concurrency

Performance

Observability

Test coverage

Test file Locks down
proxy/internal/middleware/chain_test.go:77 RunRequest threads metadata across on_request middlewares (regression for the "later mw can't see earlier mw's emissions" bug).
chain_test.go:110 RunResponse reverse-order threading.
chain_test.go:142 cost_meter-shaped scenario: response_parser registered after cost_meter still emits before cost_meter sees the bag (guards the cost.skipped=missing_tokens regression).
chain_test.go:178 UpstreamRewrite last-write-wins.
chain_test.go:206 No middleware emits → nil rewrite.
chain_test.go:224 Rewrite filtered when CanMutate=false.
chain_test.go:245 Input.UserGroups propagates verbatim through cloneInputFor.
chain_test.go:304 Terminal middlewares see the full accumulated bag + prior terminal emissions.

Gaps worth raising with the author: - No direct test for Dispatcher.Invoke timeout / panic / fail-mode behaviour at the framework level (covered indirectly by built-in tests, but a unit test pinning errors_total{kind=...} labels would be cheap insurance). - No test for bodytap.CaptureRequest truncated replay (the upstream-sees-full-body invariant is exactly the kind of thing a regression would silently break). - No test for Budget exhaustion behaviour under concurrency. - No test for Manager.InvalidateMiddleware + LiveServiceCheck race (the auth-revocation race the comment at manager.go:33-38 calls out is the load-bearing reason for LiveServiceCheck).

Known limitations / explicit non-goals

Cross-references