enginetest

package
v0.0.0-...-0573110 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 35 Imported by: 0

Documentation

Overview

Package enginetest is a policy-neutral in-process test harness for the traffic extension request-handling engine. It drives the real extproc.Server.Process loop through a fake Envoy stream and reduces the response sequence to a Verdict. Callers inject an engine.Resolver and the registrations used to evaluate its neutral engine.Unit values.

Where tests live

enginetest is a toolbox, not a home for feature tests:

  • Single-package semantics (matchers, policy evaluation, sorting) stay in the owning package's ordinary _test.go files and do not need this harness.
  • API-specific full-chain scenarios live in the owning API's test package. SecurityProfile fixtures and scenarios live in testing/securityprofile; another policy API can supply its own resolver without changing this package.
  • The _test.go files inside this package only prove the harness itself works.

Only integration boundaries that cannot exist in-process stay in tests/integration/agentio: Envoy-authenticated attributes, egress TLS termination, apiserver/CRD deployment consistency, krt watch propagation, and cross-pod webhook delivery.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BodyGate

func BodyGate() filter.Definition

BodyGate returns a Definition for a fake filter that suspends at request headers, forcing a buffered headers/body exchange in a scenario. The unit's bool config is the deny switch: true stops the body phase with 403, false lets the body through, and a nil config skips the gate entirely.

func DeliverySweep

func DeliverySweep(t *testing.T, body []byte, fn func(t *testing.T, withBody func(*RequestBuilder) *RequestBuilder))

DeliverySweep runs fn once per body-delivery shape Envoy actually produces in BUFFERED mode, handing it a function that attaches the body to a builder. There are exactly two shapes and both carry the complete body: the end-of-stream message, and the trailer flush that leaves EndOfStream clear. A verdict must come out the same either way — keying on EndOfStream releases the trailer-flush body unjudged, because trailer mode is SKIP and no further message follows it.

Envoy never splits a body across messages in BUFFERED mode (it buffers internally and emits the whole body at once), so sweeping split points would exercise a wire shape production never sees; use BodyChunks directly to pin behaviour for that.

func LockMetrics

func LockMetrics(t testing.TB)

LockMetrics acquires the metrics mutex for the duration of the test. Call it first in any test that uses MetricProbe.

Types

type AuditMode

type AuditMode int

AuditMode selects how webhook deliveries execute.

const (
	// AuditSync delivers each webhook inline on the request goroutine,
	// through the same dispatch code the worker pool runs. Deliveries are
	// complete when Harness.Run returns, so absence assertions need no
	// barrier. Default.
	AuditSync AuditMode = iota
	// AuditBuffered uses the production asynchronous dispatcher with a
	// real worker pool.
	AuditBuffered
)

type AuditOptions

type AuditOptions struct {
	Mode AuditMode
	// BufferSize and Workers apply to AuditBuffered; zero means small
	// test-friendly defaults (64 / 1).
	BufferSize  int
	Workers     int
	InsecureTLS bool
}

AuditOptions configures WireAudit.

type AuditReceiver

type AuditReceiver struct {
	// contains filtered or unexported fields
}

AuditReceiver is an in-process HTTP endpoint for audit webhook targets. It records every request (before applying any injected fault response) and supports marker-based waiting, mirroring the E2E audit-receiver pattern without log scraping.

func NewAuditReceiver

func NewAuditReceiver(t testing.TB) *AuditReceiver

NewAuditReceiver starts the receiver and closes it on test cleanup.

func (*AuditReceiver) AssertAbsent

func (a *AuditReceiver) AssertAbsent(t testing.TB, marker string)

AssertAbsent fails when any received request contains marker. Sound in synchronous audit mode, where delivery completes before the request handler returns; in buffered mode drain the dispatcher first.

func (*AuditReceiver) Matching

func (a *AuditReceiver) Matching(marker string) []ReceivedRequest

Matching returns the received requests whose URL, headers, or body contain marker.

func (*AuditReceiver) Requests

func (a *AuditReceiver) Requests() []ReceivedRequest

Requests returns a snapshot of everything received so far.

func (*AuditReceiver) SetResponse

func (a *AuditReceiver) SetResponse(status int, body string)

SetResponse makes the receiver answer every subsequent request with the given status and body, while still recording the request. Use it to exercise http_error handling in the dispatcher.

func (*AuditReceiver) URL

func (a *AuditReceiver) URL(path string) string

URL returns the receiver base URL joined with path. The path may contain audit URL template expressions; they are rendered by the webhook sink.

func (*AuditReceiver) WaitFor

func (a *AuditReceiver) WaitFor(t testing.TB, marker string, timeout time.Duration) ReceivedRequest

WaitFor blocks until a request containing marker arrives, without polling: the receiver broadcasts on every captured request.

type AuditWiring

type AuditWiring struct {
	Router *audit.Router
	// contains filtered or unexported fields
}

AuditWiring replicates the production audit wiring — Buffered dispatcher, webhook Sink, Router registration — with a mode switch for synchronous delivery. Pass Router to Options.AuditRouter when building the Harness.

func WireAudit

func WireAudit(t testing.TB, opts AuditOptions) *AuditWiring

WireAudit assembles the audit delivery pipeline, mirroring the traffic extension main wiring. In AuditBuffered mode the worker pool is started and drained on test cleanup.

func (*AuditWiring) Drain

func (w *AuditWiring) Drain(t testing.TB)

Drain blocks until every accepted delivery has completed. It is a no-op in AuditSync mode, where deliveries finish before Harness.Run returns. Call it before absence assertions in AuditBuffered mode.

type CaptureAccessLogger

type CaptureAccessLogger struct {
	// contains filtered or unexported fields
}

CaptureAccessLogger is a synchronous accesslog.Logger that records every submitted entry, replacing the asynchronous production BufferedLogger so tests can assert entries deterministically.

func (*CaptureAccessLogger) Entries

func (c *CaptureAccessLogger) Entries() []accesslog.Entry

Entries returns a snapshot of all recorded entries.

func (*CaptureAccessLogger) Reset

func (c *CaptureAccessLogger) Reset()

Reset clears recorded entries.

func (*CaptureAccessLogger) Submit

func (c *CaptureAccessLogger) Submit(entry accesslog.Entry)

type Harness

type Harness struct {
	Server    *extproc.Server
	AccessLog *CaptureAccessLogger
	// contains filtered or unexported fields
}

Harness wires the real extproc.Server to a caller-supplied resolver and captures observability, mirroring the policy-neutral part of production assembly without the gRPC transport.

func New

func New(t testing.TB, opts Options) *Harness

New builds a policy-neutral Harness around the supplied resolver.

func NewSingleFilter

func NewSingleFilter(t testing.TB, cfg SingleFilter) *Harness

NewSingleFilter builds a Harness around cfg. The payload is projected once, up front — exactly as the collection boundary does in production — so a payload that does not parse fails the test here rather than as a puzzling wire error.

func (*Harness) Probe

func (h *Harness) Probe() *InfoProbe

Probe exposes the harness's info probe (nil when disabled).

func (*Harness) Run

func (h *Harness) Run(t testing.TB, rb *RequestBuilder) *Verdict

Run drives one request through the real Process loop and reduces the response sequence to a Verdict. Process errors land in Verdict.Err.

func (*Harness) RunMessages

func (h *Harness) RunMessages(t testing.TB, msgs []*extProcPb.ProcessingRequest) *Verdict

RunMessages is the escape hatch for hand-crafted message sequences.

func (*Harness) RunParallel

func (h *Harness) RunParallel(t *testing.T, n int, build func(i int) *RequestBuilder) []*Verdict

RunParallel drives n requests through the server concurrently, one stream each, and returns the verdicts in request order. The shared ResolutionProbe cannot attribute resolutions to individual concurrent requests, so Verdict.Resolution is left nil; assert on wire-level facts.

func (*Harness) RunStream

RunStream runs Process against a caller-owned stream, for interactive or fault-injection scenarios.

type HeaderOp

type HeaderOp struct {
	Kind  HeaderOpKind
	Name  string
	Value string
}

HeaderOp records one normalized header operation decoded from an ext_proc response.

type HeaderOpKind

type HeaderOpKind string

HeaderOpKind names what a header operation does. It mirrors filter.HeaderOp's kinds but is a distinct type because it is derived from the wire proto: a verdict assertion therefore cannot be satisfied by an engine result that never reached a ProcessingResponse.

const (
	// HeaderSet is OVERWRITE_IF_EXISTS_OR_ADD: it replaces every existing line
	// for the name.
	HeaderSet HeaderOpKind = "set"
	// HeaderAdd is APPEND_IF_EXISTS_OR_ADD: it adds one more line, which is
	// the only way to emit several set-cookie headers.
	HeaderAdd HeaderOpKind = "add"
	// HeaderRemove is a remove_headers entry.
	HeaderRemove HeaderOpKind = "remove"
)

type InfoProbe

type InfoProbe struct {
	// contains filtered or unexported fields
}

InfoProbe is appended to the harness's stream loggers to capture the authoritative StreamInfo of each stream: the matched units and the recorded error, neither of which appears on the wire.

It is not how a test should read the audit outcome — Verdict.AccessLog is EPE's real output, and Verdict.outcome reads it. The probe does see Info.Outcome after derivation, because finishStream derives it before running the logger loop, so the few tests that assert Info.Outcome are reading the same derived value the accesslog carries.

func (*InfoProbe) Last

func (p *InfoProbe) Last() *filter.StreamInfo

Last returns the most recent StreamInfo, or nil when none was captured.

func (*InfoProbe) LastStream

func (p *InfoProbe) LastStream() *filter.Stream

LastStream returns the most recent stream view, or nil.

func (*InfoProbe) Log

func (p *InfoProbe) Log(_ context.Context, st *filter.Stream, info *filter.StreamInfo)

Log implements filter.StreamLogger.

func (*InfoProbe) Reset

func (p *InfoProbe) Reset()

Reset clears captured infos.

type MetricProbe

type MetricProbe struct {
	// contains filtered or unexported fields
}

MetricProbe records a baseline value of one counter series so tests can assert deltas despite cross-test accumulation on package-level metrics.

func ProbeMetric

func ProbeMetric(t testing.TB, name string, labels map[string]string) *MetricProbe

ProbeMetric snapshots the current value of the named counter series in the EPE registry. A series that has not been written yet reads as 0.

func (*MetricProbe) Delta

func (p *MetricProbe) Delta(t testing.TB) float64

Delta returns the change since the probe was created.

func (*MetricProbe) RequireDelta

func (p *MetricProbe) RequireDelta(t testing.TB, want float64)

RequireDelta asserts the change since the probe was created.

type Options

type Options struct {
	// Resolve supplies the policy-neutral units for each request. Required.
	Resolve engine.Resolver
	// AuthorizeRequest is the independent final request authorization step.
	AuthorizeRequest engine.RequestAuthorizer
	// Registrations is the action order used to evaluate resolved units.
	Registrations []filter.Registration
	// StreamLoggers are extra statically registered stream loggers. The
	// resolver may also return one policy-owned logger per stream.
	StreamLoggers []filter.StreamLogger
	// DisableResolutionProbe skips appending the info probe, for tests
	// that assert the exact logger composition.
	DisableResolutionProbe bool
}

Options configures a Harness.

type ReceivedRequest

type ReceivedRequest struct {
	Method string
	// URL is the request URI as received (path + query).
	URL    string
	Header http.Header
	Body   []byte
}

ReceivedRequest is one HTTP request captured by the AuditReceiver.

type RequestBuilder

type RequestBuilder struct {
	// contains filtered or unexported fields
}

RequestBuilder assembles the ProcessingRequest sequence Envoy would send for one HTTP request, including the ext_proc filter_state attributes that carry the caller's Workload/Sandbox identity.

func NewRequest

func NewRequest(method, host, path string) *RequestBuilder

NewRequest starts a builder with GET semantics and no identity. Call Workload to attach workload metadata; missing identity follows the server configuration.

func (*RequestBuilder) Attrs

func (b *RequestBuilder) Attrs() map[string]*structpb.Struct

Attrs returns the ext_proc attribute map, for tests that call HandleRequestHeaders directly.

func (*RequestBuilder) Body

func (b *RequestBuilder) Body(body []byte) *RequestBuilder

Body attaches a complete request body delivered as a single chunk with EndOfStream=true (Envoy's BUFFERED shape).

func (*RequestBuilder) BodyChunks

func (b *RequestBuilder) BodyChunks(chunks ...[]byte) *RequestBuilder

BodyChunks attaches a body split across several messages, only the last of which carries EndOfStream=true. Envoy never produces this in BUFFERED mode — it buffers internally and emits the whole body at once — so this models the STREAMED family and exists only to pin the extension's behaviour if a short message ever appears.

func (*RequestBuilder) Build

Build assembles the full ProcessingRequest sequence.

func (*RequestBuilder) DestinationAddress

func (b *RequestBuilder) DestinationAddress(address string) *RequestBuilder

DestinationAddress sets Envoy's restored downstream destination.address.

func (*RequestBuilder) DestinationPort

func (b *RequestBuilder) DestinationPort(port int32) *RequestBuilder

DestinationPort simulates the Envoy-authenticated TCP destination port. It is delivered as a NUMBER value — attributes.Extract ignores strings — and overrides the authority port for ordinary requests. CONNECT retains its authority port because that is the tunnel target and destination.port is the explicit proxy listener.

func (*RequestBuilder) Header

func (b *RequestBuilder) Header(key, value string) *RequestBuilder

func (*RequestBuilder) HeadersMsg

func (b *RequestBuilder) HeadersMsg() *extProcPb.HttpHeaders

HeadersMsg returns just the HttpHeaders message, for tests that call HandleRequestHeaders directly.

func (*RequestBuilder) RequestID

func (b *RequestBuilder) RequestID(id string) *RequestBuilder

func (*RequestBuilder) ResponseBody

func (b *RequestBuilder) ResponseBody(body []byte) *RequestBuilder

ResponseBody attaches one complete BUFFERED response-body message. Presence is tracked separately so an explicit empty replacement still emits a body.

func (*RequestBuilder) ResponseHeader

func (b *RequestBuilder) ResponseHeader(key, value string) *RequestBuilder

ResponseHeader adds one upstream response header.

func (*RequestBuilder) ResponseHeaders

func (b *RequestBuilder) ResponseHeaders(status int) *RequestBuilder

ResponseHeaders attaches the upstream response-headers message with status.

func (*RequestBuilder) SandboxMetadata

func (b *RequestBuilder) SandboxMetadata(accessToken, clientID string) *RequestBuilder

SandboxMetadata sets the identity fields carried by current ztunnels.

func (*RequestBuilder) SandboxToken

func (b *RequestBuilder) SandboxToken(requestID, accessToken, clientID string) *RequestBuilder

SandboxToken sets filter_state['sandbox.token'] as base64(JSON).

func (*RequestBuilder) Scheme

func (b *RequestBuilder) Scheme(scheme string) *RequestBuilder

func (*RequestBuilder) SourceAddress

func (b *RequestBuilder) SourceAddress(addr string) *RequestBuilder

SourceAddress sets Envoy's source.address attribute ("<ip>:<port>").

func (*RequestBuilder) StreamingHeaders

func (b *RequestBuilder) StreamingHeaders() *RequestBuilder

StreamingHeaders forces EndOfStream=false on the headers message without any body messages — the full-duplex "headers first, body later" shape.

func (*RequestBuilder) Subject

func (b *RequestBuilder) Subject(subject subject.Subject) *RequestBuilder

Subject supplies independent Workload and Sandbox identities.

func (*RequestBuilder) TrailerFlushedBody

func (b *RequestBuilder) TrailerFlushedBody(body []byte) *RequestBuilder

TrailerFlushedBody attaches a complete request body delivered the way Envoy delivers it in BUFFERED mode when the request carries HTTP trailers: one message with the whole body and EndOfStream=false, emitted from onTrailers ("sending data left over in the buffer"). Because request_trailer_mode defaults to SKIP, no RequestTrailers message follows and no further body message ever arrives — so this is the last chance to render a verdict.

func (*RequestBuilder) Workload

func (b *RequestBuilder) Workload(namespace, name string, labels map[string]string) *RequestBuilder

Workload sets the source workload metadata carried by gateway filter state.

type ScriptedStream

type ScriptedStream struct {
	grpc.ServerStream

	// StopOnImmediate mimics Envoy: after an ImmediateResponse has been
	// sent, Recv returns io.EOF even if scripted messages remain. Enabled
	// by NewScriptedStream.
	StopOnImmediate bool
	// RecvErr, when set, is returned by Recv once the script is exhausted,
	// instead of io.EOF (exercises the codes.Unknown receive path).
	RecvErr error
	// SendErr, when set, is returned by the next Send call.
	SendErr error
	// contains filtered or unexported fields
}

ScriptedStream implements extProcPb.ExternalProcessor_ProcessServer over a pre-built message script. Recv pops messages in order and returns io.EOF when the script is exhausted; Send records responses. Because Process is a single synchronous loop, tests call Server.Process(stream) directly on the test goroutine — no goroutines, no channels, fully deterministic.

grpc.ServerStream is embedded as a nil interface on purpose: Process only uses Recv, Send, and Context. Any other stream method panics.

func NewScriptedStream

func NewScriptedStream(ctx context.Context, msgs ...*extProcPb.ProcessingRequest) *ScriptedStream

NewScriptedStream builds a stream that will replay msgs in order.

func (*ScriptedStream) Context

func (s *ScriptedStream) Context() context.Context

func (*ScriptedStream) Recv

func (*ScriptedStream) Responses

func (s *ScriptedStream) Responses() []*extProcPb.ProcessingResponse

Responses returns a snapshot of every response sent so far.

func (*ScriptedStream) Send

type SingleFilter

type SingleFilter struct {
	// Definition is the filter under test, with whatever deps the scenario
	// injects (fake clientsets, in-process endpoints).
	Definition filter.Definition
	// Payload is the filter's own configuration document.
	Payload string

	// Profile and Rule name the unit's attribution and evaluation scope.
	// Zero values default to profile "profile" in namespace "default" and
	// rule "rule"; scenarios asserting on rendered identity set their own.
	Profile inputs.Profile
	Rule    inputs.Rule
	// Inputs is the profile-scoped inputs snapshot visible to CEL/templates.
	Inputs map[string]any
	// InputsError marks the inputs as unavailable, mirroring a profile whose
	// ConfigMap-backed inputs did not resolve; evaluations that read inputs
	// fail with it.
	InputsError string
}

SingleFilter configures a one-filter, one-rule wire harness: the given payload — in the filter's own schema, never a policy CRD's — is projected once, and every request resolves to exactly one unit carrying it. It is the standard shape of a filter-local engine scenario (see doc.go): everything between the scripted Envoy stream and the filter is real, and no policy API is involved.

type Verdict

type Verdict struct {
	Kind VerdictKind

	// ImmediateStatus and ImmediateBody are set when Kind is VerdictBlocked.
	ImmediateStatus int
	ImmediateBody   string
	// ImmediateDetails is the block's RESPONSE_CODE_DETAILS. It is the operator's
	// channel rather than the client's — the body reaches the caller, this reaches
	// the access log — so it is the only place a reason for the block, or the
	// framework's own fail-closed marker, is observable.
	ImmediateDetails string

	// RequestHeaderOps and ResponseHeaderOps record decoded wire operations by
	// direction and in protobuf order. RequestHeaderOps includes mutations from
	// both request-header and request-body responses.
	RequestHeaderOps    []HeaderOp
	ResponseHeaderOps   []HeaderOp
	RequestBodyChanged  bool
	RequestBody         []byte
	ResponseBodyChanged bool
	ResponseBody        []byte
	ResponseStatus      *int

	// ModeOverride is the ProcessingMode set on the first headers-phase
	// response; non-nil proves the NeedsBody signalling fired.
	ModeOverride *extProcV3.ProcessingMode
	// ResponseModeOverride is the dynamic override emitted from response
	// headers when a filter requests the buffered response body.
	ResponseModeOverride *extProcV3.ProcessingMode

	// Info is the authoritative StreamInfo observed by the harness
	// InfoProbe; nil when the probe was disabled or never invoked.
	Info *filter.StreamInfo

	// AccessLog holds the entries the harness audit logger captured for this
	// run alone; RunMessages resets the logger first, so earlier requests in
	// the same test do not leak in.
	AccessLog []accesslog.Entry

	// Raw preserves the full ordered response sequence (read-only: some
	// responses are shared package singletons).
	Raw []*extProcPb.ProcessingResponse

	// Err is the error returned by Process; nil on clean EOF shutdown.
	Err error
}

Verdict reduces the response sequence of one request to assertable facts.

func ParseVerdict

func ParseVerdict(responses []*extProcPb.ProcessingResponse, procErr error) *Verdict

ParseVerdict classifies a response sequence.

func (*Verdict) RequestHeaderValues

func (v *Verdict) RequestHeaderValues(name string) []string

RequestHeaderValues returns every value the request direction set or added for name, in wire order. Several values mean several header lines.

func (*Verdict) RequireAction

func (v *Verdict) RequireAction(t *testing.T, want string)

RequireAction asserts some audited action contains want, e.g. ":bypass:" for an explicit exemption or "mcpacl:block:" for a named filter's verdict.

func (*Verdict) RequireBlocked

func (v *Verdict) RequireBlocked(t *testing.T, wantStatus int)

RequireBlocked asserts an ImmediateResponse with the given status.

func (*Verdict) RequireBlockedBody

func (v *Verdict) RequireBlockedBody(t *testing.T, wantStatus int, wantBodyContains string)

RequireBlockedBody additionally asserts the immediate response body.

func (*Verdict) RequireBypassed

func (v *Verdict) RequireBypassed(t *testing.T)

RequireBypassed asserts the wire shape changed nothing while at least one policy unit matched. Note this no longer implies a bypass rule fired: under the derived outcome, "bypassed" means matched-but-unmodified. Assert RequireAction(t, ":bypass:") when the exemption itself is the subject.

func (*Verdict) RequireGRPCCode

func (v *Verdict) RequireGRPCCode(t *testing.T, want codes.Code)

RequireGRPCCode asserts Process returned an error with the given code.

func (*Verdict) RequireHeader

func (v *Verdict) RequireHeader(t *testing.T, name, want string)

RequireHeader asserts the request direction produced exactly one value for name, equal to want.

func (*Verdict) RequireHeaderRemoved

func (v *Verdict) RequireHeaderRemoved(t *testing.T, name string)

RequireHeaderRemoved asserts the request direction removed name.

func (*Verdict) RequireNoUpstream

func (v *Verdict) RequireNoUpstream(t *testing.T)

RequireNoUpstream checks every response, including responses preceding a deny.

func (*Verdict) RequireOutcome

func (v *Verdict) RequireOutcome(t *testing.T, want string)

RequireOutcome asserts the logged outcome string.

func (*Verdict) RequirePassthrough

func (v *Verdict) RequirePassthrough(t *testing.T)

RequirePassthrough asserts the request passed through unmodified and that no policy unit matched it — which is what passthrough now means.

func (*Verdict) RequireResponseHeader

func (v *Verdict) RequireResponseHeader(t *testing.T, name, want string)

RequireResponseHeader asserts the response phase produced exactly one value for name, equal to want.

func (*Verdict) RequireResponseHeaderRemoved

func (v *Verdict) RequireResponseHeaderRemoved(t *testing.T, name string)

RequireResponseHeaderRemoved asserts the response phase removed name.

func (*Verdict) RequireUpstream

func (v *Verdict) RequireUpstream(t *testing.T, want string) *extProcPb.ProcessingResponse

RequireUpstream checks the target actually emitted on the ext_proc wire, including the separate address, IP and port fields consumed by the proxy. It returns the sole response carrying that target for phase-specific checks.

func (*Verdict) ResponseHeaderValues

func (v *Verdict) ResponseHeaderValues(name string) []string

ResponseHeaderValues returns every value the response phase set or added for name, in wire order. Several values mean several header lines, which is how multi-valued set-cookie is expressed.

type VerdictKind

type VerdictKind string

VerdictKind is the wire-level classification of a response sequence. Bypass and passthrough are indistinguishable on the wire; use Verdict.AccessLog's outcome (see Verdict.outcome) to tell them apart.

const (
	VerdictBlocked     VerdictKind = "blocked"
	VerdictMutated     VerdictKind = "mutated"
	VerdictPassthrough VerdictKind = "passthrough"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址