Files
netbird/proxy/internal/middleware/chain_test.go
Maycon Santos 92a66cdd20 [management,proxy,client] 0.74.0 version (#6563)
* [management,proxy] Agent network: per-account LLM gateway (policy, metering, multi-provider) (#6555)

* [agent-network] Shared proto, OpenAPI schema, and generated types

* [agent-network] Management: store, manager, synthesizer, policy engine, provider catalog, HTTP/gRPC API

Adds the account-scoped agent-network module: provider/policy/budget CRUD and
store, the reverse-proxy service synthesizer, policy selection + limit
enforcement, the provider catalog (incl. Vertex AI and AWS Bedrock entries),
and the management HTTP + proxy gRPC surfaces.

* [management] Fix agent-network proxy-peer fan-out on affected-peer recompute

The affected-peers resolver loaded only persisted reverse-proxy services, but
agent-network services are synthesized on demand and never persisted. As a
result the embedded proxy peer was never folded into the affected set when a
client's group changed, so the proxy received no network-map update for a newly
authorised client and rejected its handshake until a full resync (restart).

loadProxyServices now merges the synthesized agent-network services (injected
via a registration hook to avoid an import cycle), so proxy peers learn newly
authorised clients immediately.

* [proxy] Reverse-proxy middleware framework, chain, and request plumbing

The per-target middleware chain (slots, dispatcher, mutation gate, metadata
merger), body capture, access-log terminal sink, and the proxy wiring that
builds + runs chains for synthesized agent-network services.

* [proxy] LLM parsers, pricing, and builtin middlewares (OpenAI, Anthropic, Vertex AI, AWS Bedrock)

Request/response parsers and SSE/event-stream metering, the embedded pricing
table, and the builtin middleware set: request parser, router, policy
limit-check/record, cost meter, guardrail, identity inject, response parser.
Includes the path-routed providers — Google Vertex AI (keyfile:: service-account
OAuth minting) and AWS Bedrock (bearer auth, invoke/converse/streaming, optional
/bedrock prefix) — plus the Models allowlist and unmeterable-publisher deny.

* [proxy] IPv6 in-place apply and TCP accept-loop hardening on netstack listeners

* [agent-network] End-to-end test suite, module docs, and deployment preset

* [agent-network] Fix codespell typos and exclude false positives

- labelgen word pool: vermillion -> vermilion, racoon -> raccoon.
- codespell ignore list: add flate (Go compress/flate package), recordin
  (a test-local identifier), and unparseable (a valid alternative spelling used
  consistently across identifiers + a metadata-value constant).

* [management] Set LastSeen on injected proxy peer in realstack test (MySQL strict-mode)

The injected embedded proxy peer had a PeerStatus with a zero LastSeen, which
serializes to '0000-00-00' and is rejected by MySQL in strict mode (SQLite
tolerates it). Set LastSeen to a valid time so SaveAccount succeeds on both
engines.

* [agent-network] Remove e2e shell-script suite from this branch

The end-to-end shell scripts under scripts/e2e/ are maintained in a separate
testing suite and are not part of this change set.

* [agent-network] Polish module docs: remove internal review scaffolding, fix links, verify diagrams

Strip PR-review framing, commit references, absolute paths, and stale internal
references from the agent-network module docs; fix broken relative links; verify
all diagrams against the current architecture. Remove the internal AI-reviewer
prompt file.

* [management] Refine session expiration handling to support 3-state encoding for SSO deadlines

* [agent-network] Relocate agentnetwork package to internals/modules

Move management/server/agentnetwork (and its catalog/, labelgen/, types/
subpackages) to management/internals/modules/agentnetwork, alongside the
reverse-proxy module, and rewrite all importers. Pure relocation: package names,
the synthesizer + affectedpeers registration hook, and store access (shared
store.Store) are unchanged, so no import cycle is introduced (affectedpeers
still depends only on the agentnetwork/types leaf).

* [agent-network] Co-locate HTTP handlers in the module (RegisterEndpoints)

Move the agent-network HTTP handlers from server/http/handlers/agentnetwork into
the module at internals/modules/agentnetwork/handlers (package handlers) and
rename the entrypoint AddEndpoints -> RegisterEndpoints, matching the
reverse-proxy module convention. Wiring in http/handler.go updated accordingly.

* Update getting started to point to rc when agent network enabled

* Add a reference to a commercial license

* Fix docs localhost link

* Fix docs localhost link

* Add private services domain note

* [management] Add agent-network telemetry metrics (#6561)

Surface agent-network adoption and usage in the self-hosted metrics
worker: distinct accounts, providers, policies, budget rules, accounts
with log collection enabled, and aggregated input/output tokens plus
cost.

Tokens and cost are summed from agent_network_request_usage (the
always-written per-request ledger) so the figures are accurate
regardless of the log-collection toggle and carry no double-counting.
All values come from a handful of indexed aggregate queries run only on
the worker's periodic tick.

Adds store.AgentNetworkMetrics with GetAgentNetworkMetrics on the Store
interface, the SqlStore implementation, and a zero-valued FileStore stub.

* Update NetBird server and proxy image versions to 0.74.0-rc.2

* [management,proxy] Reduce agent-network cognitive complexity (#6566)

Address the SonarCloud quality-gate findings in new agent-network code
by extracting focused helpers. No behavior change.

- synthesizer.go: split buildIdentityInjectConfigJSON into per-shape
  rule builders; extract mergeGuardrail from mergeGuardrails to cut
  nesting depth.
- llm_identity_inject: extract injectionEmitsAnything validation
  predicate from New.
- llm_response_parser/streaming.go: extract applyOpenAIStreamUsage and
  applyAnthropicStreamUsage (via a named anthropicStreamUsage type) and
  simplify the OpenAI scanner loop.
- reverseproxy.go: decompose ServeHTTP into serveRouteError,
  buildTargetContext, serveDirect, serveWithChain, captureRequestForChain,
  serveDeny, newResponseWriter, observeResponse, and forwardUpstream,
  preserving the defer ordering so response observation still reads the
  captured writer before it is released.

* [management] Move agent-network access-log ingest into the agentnetwork module (#6568)

The agent-network access-log ingest path (metaKey wire contract, flatten,
usage derivation, and the dual-write of the usage ledger + settings-gated
full row) lived in the reverseproxy accesslogs manager, even though the
agentnetwork module already owns the rest of that domain — types, read
(ListAccessLogs / GetUsageOverview), the budget-counter writes, and
retention cleanup.

Move it next to the rest: a stateless agentnetwork.IngestAccessLog(ctx,
store, entry) that the reverseproxy SaveAccessLog delegates to when the
entry is agent-network. Removes the agentNetworkTypes import from the
reverseproxy manager. No behavior change; the write/read table separation
is unchanged.

Adds real-store coverage for the disable->enable log-collection toggle
(usage ledger always written, full row gated) plus the metadata parse and
group-dedup helpers, which previously had no dedicated tests.

* Add session view support in the access log

* [management,proxy] Container-based agent-network e2e harness (#6577)

* [e2e] Add container-based agent-network e2e harness (Pillar 1)

Introduce a self-contained, OIDC-free e2e harness that stands up NetBird
in containers, so suites no longer depend on the hand-maintained Tilt
stack or a real IdP.

- harness brings up the combined server (management + signal + relay +
  STUN + embedded IdP) in a single container built from
  combined/Dockerfile.multistage, and mints an admin PAT through the
  unauthenticated /api/setup bootstrap (NB_SETUP_PAT_ENABLED). API access
  goes through the existing shared/management/client/rest typed client.
- the image is built via the docker CLI (BuildKit) so the Dockerfile's
  cache mounts are honored; testcontainers then runs the tagged image.
- everything is behind the `e2e` build tag so normal builds and unit
  tests never pull in testcontainers.

Adds BuildKit cache mounts to combined/Dockerfile.multistage so source
changes recompile incrementally rather than from scratch.

Pillar 1 proven by TestCombinedBootstrap: server builds, boots, mints a
PAT, and the PAT authenticates a real management API call.

* [e2e] Add management-side agent-network scenarios (Pillar 2)

Port the API-driven agent-network scenarios from the bash suites to Go,
sharing one combined server per package run (TestMain) with each test
owning its resource cleanup. Drives the /api/agent-network/* endpoints
through the shared REST client's NewRequest primitive with the generated
api types.

Scenarios:
- provider lifecycle (create/get/list/delete + 404 after delete)
- provider validation (missing api_key, unknown catalog id → 4xx)
- settings collection-toggle round-trip with cluster/subdomain immutability
- policy window floor (reject <60s enabled limit, accept at 60s)
- consumption read endpoint returns an array

All deterministic and dependency-free (dummy provider keys; no upstream
calls), so they run headless in CI.

* [e2e] Add live chat-through-proxy scenario (Pillar 3)

Stand up the full agent-network data path in containers and drive a real
chat-completion through the gateway:

- harness: a shared docker network (combined server reachable by alias),
  a proxy container built from the published reverse-proxy image
  (NB_PROXY_PRIVATE, NB_PROXY_ALLOW_INSECURE, NB_RELAY_TRANSPORT=ws to match
  the combined server's WS-multiplexed relay) with a generated self-signed
  wildcard cert, and a netbird client container that joins via a setup key.
- the combined image, proxy image, and client image default to the
  published rc.2 releases (overridable via NB_E2E_*_IMAGE; a bare local tag
  is built from source instead). Geolocation download is disabled so the
  server starts without external fetches.
- one shared domain is used for the management exposed address, the proxy
  domain, and the agent-network cluster; the proxy token is minted via the
  server CLI (global) to match the manual install.

TestChatCompletionThroughProxy provisions provider+policy+group+setup key,
runs proxy+client, drives an OpenAI chat-completion through the tunnel, and
asserts a 200 plus the ingested access-log row. Requires OPENAI_TOKEN
(skips otherwise). The provider must be created with enabled=true explicitly
— the create default is false despite the API doc.

* [e2e] Run the live chat scenario across a provider matrix

Replace the single-provider chat test with a data-driven matrix that runs
the same scenario through every provider whose credentials are present in
the environment (keys/URLs sourced from ~/.llm-keys locally, Actions
secrets in CI):

- OpenAI (chat), Anthropic (messages), Vercel, OpenRouter, Cloudflare
  (OpenAI-compatible gateways), and Bedrock (path-routed, bearer, via the
  messages shape) — covering both wire shapes and the gateway routing.
- all providers are created enabled with a unique model string so the
  proxy's connect-time snapshot carries them all and model->provider
  routing is unambiguous (provider toggles after connect don't reconcile
  to a connected proxy).
- the client supports both wire shapes (/v1/chat/completions and
  /v1/messages); Cloudflare gets the openai provider segment appended to
  its gateway URL.

Each provider must return 200 through the tunnel and produce an ingested
access-log row. Vertex is intentionally excluded from the uniform matrix:
it needs a bespoke rawPredict request shape rather than the shared
chat/messages path, so it warrants a dedicated scenario.

* [ci] Add manual workflow for the agent-network e2e suite

The e2e suite (build tag `e2e`) stands up the combined server + proxy +
client in Docker and drives live chat-completions, so it is slow and needs
provider credentials. Gate it out of normal CI (it already is, via the
build tag) and run it on demand via workflow_dispatch. Provider scenarios
skip when their secret is unset, so it degrades gracefully.

* [e2e] Add Vertex to the provider matrix; run e2e on ubuntu-latest

Vertex (Anthropic-on-Vertex) doesn't share the chat/messages wire shapes:
the model travels in a rawPredict path and the proxy mints the service
account's OAuth token. Add a Vertex client method that posts
/v1/projects/<project>/locations/<region>/publishers/anthropic/models/<model>:rawPredict
with the Vertex anthropic_version body, and wire it into the matrix as a
path-routed provider (created without a models array). It is keyed off
GOOGLE_VERTEX_SA_BASE64 + GOOGLE_VERTEX_PROJECT (region defaults to
"global", model to a pinned claude snapshot, both overridable).

Also bump the e2e workflow runner to ubuntu-latest and add the Vertex
secrets.

* Add docker/docker and docker/go-connections as direct dependencies in go.mod

* [ci] Trigger agent-network e2e workflow on push to main and pull requests

* [e2e] Fix proxy cert permission denied on Linux CI runners

The proxy bind-mounts a temp dir of self-signed certs. MkdirTemp creates
it 0700 and the key was 0600, which Docker Desktop on macOS ignores but a
non-root proxy container on Linux runners cannot traverse/read, so the
cert watcher failed with "open /certs/tls.crt: permission denied" and the
container exited. Widen the cert dir to 0755 and write the throwaway key
0644 so the proxy uid can read the bind-mounted material.

* [e2e] Build images from source by default instead of pulling rc.2

The agent-network code under test lives in this branch, so the e2e should
exercise it rather than a frozen published release. Flip the harness
default: combined/proxy/client are now built from their in-repo
Dockerfiles (combined/Dockerfile.multistage, proxy/Dockerfile.multistage,
e2e/harness/Dockerfile.client) under local tags. Pulling a published image
stays available by setting NB_E2E_*_IMAGE to a registry reference.

Builds now go through buildx --load so the Dockerfile cache mounts are
honored and the result is loaded for testcontainers. The CI workflow adds
a container-driver builder and a local layer cache (NB_E2E_BUILDX_CACHE)
persisted via actions/cache, which caches the base/apt/dep-download layers
across runs. The Go compile still re-runs each time, as BuildKit mount
caches cannot be exported to the GitHub cache.

* [e2e] Cover real providers in lifecycle + assert real consumption metering

- TestProviderLifecycle now runs per available real provider (create → get →
  list → delete → 404) instead of a single dummy provider, exercising each
  catalog's create and field round-trip. Create is offline, so it stays fast
  and burns no provider quota; falls back to a synthetic OpenAI provider when
  no keys are set.
- TestProvidersMatrix attaches a token limit (high caps, 60s window) to its
  policy, which switches on usage metering, and asserts consumption rows are
  recorded with positive token counts after the live traffic. Consumption is
  account-scoped (keyed by source group / user and window, not per provider),
  so the assertion is aggregate.
- TestProviderValidation gains invalid-upstream and blank-name cases. Create
  validation is uniform across catalogs (no per-provider required-field rules),
  so per-provider rejection cases would be redundant.

* [e2e] Assert session id propagates per provider

Each matrix request now sends a unique session id as the universal
x-session-id header and asserts it round-trips into that provider's
access-log row. This guards the session-grouping contract end to end for
every provider (header extraction runs in llm_request_parser ahead of the
parser-specific body extraction, so it is provider-agnostic).

* [e2e] Drop accidentally committed sync-phases dashboard

netbird-sync-phases.json was swept into the Pillar 1 commit by a broad
git add; it belongs to the unrelated sync-phases metrics work, not this
e2e harness. Remove it from the branch so the PR diff is scoped to the
e2e changes.

* [e2e] Revert accidentally committed sync-phase ingest spec

The netbird_sync_phase measurement spec in metrics ingest was swept into
the Pillar 1 commit; it belongs to the unrelated sync-phases metrics work,
not this e2e harness. Its emission side never landed here, so the spec was
orphaned anyway. Restore ingest/main.go to its origin/main state.

* Fix golint issues

* Fix sonar

* Add access log session test

* Fix access log tests

---------

Co-authored-by: braginini <bangvalo@gmail.com>
Co-authored-by: Zoltan Papp <zoltan.pmail@gmail.com>
2026-07-01 12:45:14 +02:00

371 lines
14 KiB
Go

package middleware
import (
"context"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// fakeMiddleware is a minimal Middleware for chain composition tests.
// It records the metadata the dispatcher hands to it and emits a
// caller-supplied Output. Tests use the recorded snapshot to assert
// that earlier-in-slot emissions are visible to later middlewares.
type fakeMiddleware struct {
id string
slot Slot
keys []string
emit []KV
decision Decision
mutationsSupported bool
canMutate bool
mutations *Mutations
// seen captures the in.Metadata snapshot the dispatcher passed to
// Invoke, so tests can assert ordering and visibility.
seen []KV
}
func (f *fakeMiddleware) ID() string { return f.id }
func (f *fakeMiddleware) Version() string { return "test" }
func (f *fakeMiddleware) Slot() Slot { return f.slot }
func (f *fakeMiddleware) AcceptedContentTypes() []string { return nil }
func (f *fakeMiddleware) MetadataKeys() []string { return f.keys }
func (f *fakeMiddleware) MutationsSupported() bool { return f.mutationsSupported }
func (f *fakeMiddleware) Close() error { return nil }
func (f *fakeMiddleware) Invoke(_ context.Context, in *Input) (*Output, error) {
f.seen = append([]KV(nil), in.Metadata...)
out := &Output{Decision: f.decision, Metadata: append([]KV(nil), f.emit...)}
if f.mutations != nil {
m := *f.mutations
out.Mutations = &m
}
return out, nil
}
// chainFor builds a Chain over the given middlewares with a noop
// dispatcher.
func chainFor(t *testing.T, mws ...*fakeMiddleware) *Chain {
t.Helper()
bound := make([]boundMiddleware, len(mws))
for i, mw := range mws {
bound[i] = boundMiddleware{
spec: Spec{
ID: mw.id,
Slot: mw.slot,
Enabled: true,
MetadataKeys: mw.keys,
CanMutate: mw.canMutate,
MutationsSupported: mw.mutationsSupported,
},
mw: mw,
}
}
disp := NewDispatcher(nil, nil)
return NewChain("t-1", bound, disp)
}
// TestChain_RunRequest_ThreadsMetadataAcrossMiddlewares locks that
// each on_request middleware sees metadata emitted by earlier
// middlewares in the same slot. Regression cover for the original
// chain.go where every iteration cloned from the same source `in` and
// later middlewares (e.g. llm_guardrail) couldn't read what the first
// (e.g. llm_request_parser) had just emitted.
func TestChain_RunRequest_ThreadsMetadataAcrossMiddlewares(t *testing.T) {
first := &fakeMiddleware{
id: "first",
slot: SlotOnRequest,
keys: []string{"foo.k"},
emit: []KV{{Key: "foo.k", Value: "v"}},
}
second := &fakeMiddleware{
id: "second",
slot: SlotOnRequest,
keys: []string{"bar.k"},
emit: []KV{{Key: "bar.k", Value: "z"}},
}
c := chainFor(t, first, second)
acc := NewAccumulator(0)
denied, merged, rewrite, err := c.RunRequest(context.Background(), nil, &Input{}, acc)
require.NoError(t, err)
assert.Nil(t, denied, "no deny without DecisionDeny")
assert.Nil(t, rewrite, "no rewrite without Mutations.RewriteUpstream")
require.Len(t, second.seen, 1, "the second middleware must observe one prior emission")
assert.Equal(t, "foo.k", second.seen[0].Key, "second middleware must see the first middleware's key")
assert.Equal(t, "v", second.seen[0].Value, "second middleware must see the first middleware's value")
require.Len(t, merged, 2, "merged slice contains both middleware emissions")
}
// TestChain_RunResponse_ThreadsMetadataAcrossMiddlewares does the
// same for the response slot. The response slot iterates in reverse
// registration order, so the middleware registered LAST runs first.
// This test asserts that a middleware running later (in reverse
// order) sees the metadata emitted by the one that ran before it.
func TestChain_RunResponse_ThreadsMetadataAcrossMiddlewares(t *testing.T) {
// Registration order: [outer, inner].
// Reverse iteration runs inner first, outer second.
// outer must see inner's emission.
outer := &fakeMiddleware{
id: "outer",
slot: SlotOnResponse,
keys: []string{"outer.k"},
emit: []KV{{Key: "outer.k", Value: "o"}},
}
inner := &fakeMiddleware{
id: "inner",
slot: SlotOnResponse,
keys: []string{"inner.k"},
emit: []KV{{Key: "inner.k", Value: "i"}},
}
c := chainFor(t, outer, inner)
acc := NewAccumulator(0)
merged := c.RunResponse(context.Background(), &Input{}, acc)
require.Len(t, outer.seen, 1, "outer must observe inner's emission")
assert.Equal(t, "inner.k", outer.seen[0].Key)
require.Len(t, merged, 2, "merged slice contains both response emissions")
}
// TestChain_RunResponse_CostMeterScenario simulates the synth-service
// chain shape (response_parser registered AFTER cost_meter so reverse
// iter runs response_parser first). The cost_meter analogue must see
// the tokens response_parser just emitted — this is the exact
// regression that produced cost.skipped=missing_tokens in the live
// access logs.
func TestChain_RunResponse_CostMeterScenario(t *testing.T) {
// Synthesizer registers cost_meter first, response_parser second.
costMeter := &fakeMiddleware{
id: "cost_meter",
slot: SlotOnResponse,
keys: []string{"cost.usd_total", "cost.skipped"},
}
respParser := &fakeMiddleware{
id: "llm_response_parser",
slot: SlotOnResponse,
keys: []string{"llm.input_tokens", "llm.output_tokens"},
emit: []KV{
{Key: "llm.input_tokens", Value: "13"},
{Key: "llm.output_tokens", Value: "259"},
},
}
c := chainFor(t, costMeter, respParser)
acc := NewAccumulator(0)
_ = c.RunResponse(context.Background(), &Input{}, acc)
require.Len(t, costMeter.seen, 2, "cost_meter must observe both token keys emitted by response_parser")
keys := []string{costMeter.seen[0].Key, costMeter.seen[1].Key}
assert.ElementsMatch(t, []string{"llm.input_tokens", "llm.output_tokens"}, keys,
"cost_meter must see the exact keys response_parser emitted")
values := []string{costMeter.seen[0].Value, costMeter.seen[1].Value}
assert.ElementsMatch(t, []string{"13", "259"}, values, "cost_meter must see the exact token counts")
for _, kv := range costMeter.seen {
_, err := strconv.Atoi(kv.Value)
assert.NoError(t, err, "values handed to cost_meter must be numeric (regression for missing_tokens)")
}
}
// TestChain_RunResponse_DetachedContextStillRecords guards the metering
// fix in reverseproxy.go. The response/terminal phase runs after the body
// is forwarded, so a streaming client has usually disconnected by then,
// cancelling its request context. The dispatcher derives each middleware's
// context from the one passed here and short-circuits to fail-mode the
// instant it's Done, which silently drops token/cost metering. The reverse
// proxy now detaches that phase with context.WithoutCancel; this proves a
// context detached from an already-cancelled parent still lets a response
// middleware emit. (The cancelled-parent direction is intentionally not
// asserted: the dispatcher's select over ctx.Done vs the result channel is
// racy when both are ready, which is exactly why the bug was intermittent.)
func TestChain_RunResponse_DetachedContextStillRecords(t *testing.T) {
resp := &fakeMiddleware{
id: "recorder",
slot: SlotOnResponse,
keys: []string{"llm.input_tokens"},
emit: []KV{{Key: "llm.input_tokens", Value: "42"}},
decision: DecisionPassthrough,
}
c := chainFor(t, resp)
clientCtx, cancel := context.WithCancel(context.Background())
cancel() // client disconnected after the stream completed
require.Error(t, clientCtx.Err(), "client context must be cancelled for the test to be meaningful")
detached := context.WithoutCancel(clientCtx)
require.NoError(t, detached.Err(), "detached context must not inherit the client's cancellation")
acc := NewAccumulator(MaxRequestMetadataBytes)
merged := c.RunResponse(detached, &Input{Slot: SlotOnResponse}, acc)
var got string
for _, kv := range merged {
if kv.Key == "llm.input_tokens" {
got = kv.Value
}
}
assert.Equal(t, "42", got, "response middleware must still emit token metadata under the detached context")
}
// TestChain_RunRequest_LatestRewriteWins asserts that when two
// on_request middlewares both emit an UpstreamRewrite, the chain
// returns the value from the later middleware.
func TestChain_RunRequest_LatestRewriteWins(t *testing.T) {
first := &fakeMiddleware{
id: "first",
slot: SlotOnRequest,
mutationsSupported: true,
canMutate: true,
mutations: &Mutations{RewriteUpstream: &UpstreamRewrite{Scheme: "https", Host: "first.test"}},
}
second := &fakeMiddleware{
id: "second",
slot: SlotOnRequest,
mutationsSupported: true,
canMutate: true,
mutations: &Mutations{RewriteUpstream: &UpstreamRewrite{Scheme: "https", Host: "second.test"}},
}
c := chainFor(t, first, second)
acc := NewAccumulator(0)
denied, _, rewrite, err := c.RunRequest(context.Background(), nil, &Input{}, acc)
require.NoError(t, err)
assert.Nil(t, denied, "neither middleware denies")
require.NotNil(t, rewrite, "chain must surface the rewrite emitted by the on_request slot")
assert.Equal(t, "https", rewrite.Scheme, "rewrite scheme must come from the later middleware")
assert.Equal(t, "second.test", rewrite.Host, "rewrite host must come from the later middleware (last-write-wins)")
}
// TestChain_RunRequest_NoRewrite_NilReturn asserts the chain returns a
// nil rewrite when no middleware emits one.
func TestChain_RunRequest_NoRewrite_NilReturn(t *testing.T) {
first := &fakeMiddleware{id: "first", slot: SlotOnRequest}
second := &fakeMiddleware{id: "second", slot: SlotOnRequest}
c := chainFor(t, first, second)
acc := NewAccumulator(0)
denied, _, rewrite, err := c.RunRequest(context.Background(), nil, &Input{}, acc)
require.NoError(t, err)
assert.Nil(t, denied, "neither middleware denies")
assert.Nil(t, rewrite, "chain must return nil rewrite when no middleware emits one")
}
// TestChain_ApplyMutations_RewriteGatedOnCanMutate asserts that a
// middleware emitting an UpstreamRewrite with CanMutate=false has its
// rewrite filtered out by the chain. The dispatcher's filterOutput
// already clears Mutations when the gates fail; the chain's defensive
// gate inside mutationRewrite mirrors that contract so a stale
// Mutations field cannot leak through.
func TestChain_ApplyMutations_RewriteGatedOnCanMutate(t *testing.T) {
mw := &fakeMiddleware{
id: "first",
slot: SlotOnRequest,
mutationsSupported: true,
canMutate: false,
mutations: &Mutations{RewriteUpstream: &UpstreamRewrite{Scheme: "https", Host: "denied.test"}},
}
c := chainFor(t, mw)
acc := NewAccumulator(0)
denied, _, rewrite, err := c.RunRequest(context.Background(), nil, &Input{}, acc)
require.NoError(t, err)
assert.Nil(t, denied, "middleware does not deny")
assert.Nil(t, rewrite, "rewrite must be filtered when CanMutate=false")
}
// TestChain_RunRequest_PropagatesUserGroups asserts the chain forwards
// Input.UserGroups verbatim through cloneInputFor so policy-aware
// middlewares (e.g. llm_policy_check) can authorise without an extra
// management round-trip.
func TestChain_RunRequest_PropagatesUserGroups(t *testing.T) {
groupCapture := &userGroupCaptureMiddleware{
id: "group-capture",
slot: SlotOnRequest,
}
c := chainFor(t, groupCapture.fake())
groupCapture.bind(c)
acc := NewAccumulator(0)
in := &Input{UserGroups: []string{"g1"}}
denied, _, _, err := c.RunRequest(context.Background(), nil, in, acc)
require.NoError(t, err)
assert.Nil(t, denied, "no deny without DecisionDeny")
require.Len(t, groupCapture.seenGroups, 1, "middleware must observe the caller's UserGroups")
assert.Equal(t, "g1", groupCapture.seenGroups[0], "UserGroups must reach the middleware verbatim")
}
// userGroupCaptureMiddleware is a fakeMiddleware variant that records
// Input.UserGroups during Invoke. It exists so the cloneInputFor
// behaviour for the new field can be asserted without leaking into
// every other chain test.
type userGroupCaptureMiddleware struct {
id string
slot Slot
seenGroups []string
fakeMW *fakeMiddleware
}
func (u *userGroupCaptureMiddleware) fake() *fakeMiddleware {
u.fakeMW = &fakeMiddleware{id: u.id, slot: u.slot}
return u.fakeMW
}
func (u *userGroupCaptureMiddleware) bind(c *Chain) {
for i, bm := range c.all {
if bm.spec.ID != u.id {
continue
}
c.all[i].mw = userGroupRecorder{
fakeMiddleware: u.fakeMW,
parent: u,
}
}
}
type userGroupRecorder struct {
*fakeMiddleware
parent *userGroupCaptureMiddleware
}
func (r userGroupRecorder) Invoke(ctx context.Context, in *Input) (*Output, error) {
r.parent.seenGroups = append([]string(nil), in.UserGroups...)
return r.fakeMiddleware.Invoke(ctx, in)
}
// TestChain_RunTerminal_SeesAccumulatedMetadata locks that terminal
// middlewares observe the full bag (the caller-supplied in.Metadata
// plus any prior terminal emissions).
func TestChain_RunTerminal_SeesAccumulatedMetadata(t *testing.T) {
first := &fakeMiddleware{
id: "term-1",
slot: SlotTerminal,
keys: []string{"term.first"},
emit: []KV{{Key: "term.first", Value: "1"}},
}
second := &fakeMiddleware{
id: "term-2",
slot: SlotTerminal,
keys: []string{"term.second"},
}
c := chainFor(t, first, second)
acc := NewAccumulator(0)
in := &Input{Metadata: []KV{{Key: "ext.k", Value: "ext"}}}
merged := c.RunTerminal(context.Background(), in, acc)
require.Len(t, second.seen, 2, "second terminal must see ext bag + first terminal's emission")
got := map[string]string{}
for _, kv := range second.seen {
got[kv.Key] = kv.Value
}
assert.Equal(t, "ext", got["ext.k"], "external bag carries through")
assert.Equal(t, "1", got["term.first"], "first terminal's emission visible to second terminal")
assert.Len(t, merged, 1, "only first terminal emitted; second emitted nothing")
}