pipeline

package
v0.4.0-rc.2 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: Apache-2.0 Imports: 25 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package pipeline turns a request into a verdict: it runs the rule evaluator under a per-request deadline and applies the enforcement mode (detect or block) and the failure mode (fail open or closed).

Index

Constants

View Source
const DefaultTimeout = 250 * time.Millisecond

DefaultTimeout is the per-request inspection deadline used when Config does not set one. It is a safety cap, not the expected latency: it is set so that requests within the default argument and body limits finish in time, because in block mode a timeout rejects the request.

Variables

This section is empty.

Functions

func InspectedResponseType added in v0.4.0

func InspectedResponseType(contentType string) bool

InspectedResponseType reports whether the rules read a response body with this Content-Type.

func WebSocketHandshake added in v0.4.0

func WebSocketHandshake(r *request.Request) bool

WebSocketHandshake reports whether r looks like the opening handshake of a WebSocket (RFC 6455 §4.1, or RFC 8441 over HTTP/2): an Upgrade header naming websocket, or a Sec-WebSocket-Key or Sec-WebSocket-Version header. Any one is enough, because proxies drop some: Traefik's ForwardAuth removes Upgrade and Connection (hop-by-hop headers) before asking the engine, and a WebSocket over HTTP/2 has no Sec-WebSocket-Key. A server doesn't upgrade a handshake without Sec-WebSocket-Version, so a real one can't hide from this check; a request that only looks like one gets the policy's WebSocket rules too, which is the safe side.

Types

type Action

type Action uint8

Action is what the proxy should do with the request.

const (
	// ActionAllow forwards the request.
	ActionAllow Action = iota
	// ActionDeny rejects the request with Verdict.Status.
	ActionDeny
	// ActionLog forwards the request but records that it would have been
	// blocked (detect mode).
	ActionLog
)

func (Action) String

func (a Action) String() string

type Admission

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

Admission bounds how many evaluations run at once.

func NewAdmission

func NewAdmission(n int) *Admission

NewAdmission returns an Admission for n concurrent evaluations; n <= 0 means 2 * GOMAXPROCS.

func (*Admission) Capacity

func (a *Admission) Capacity() int

Capacity returns the maximum number of concurrent evaluations.

func (*Admission) InFlight

func (a *Admission) InFlight() int

InFlight returns the number of evaluations running now, including ones that timed out and are still finishing.

type Config

type Config struct {
	Mode        Mode
	FailureMode FailureMode
	// Timeout bounds inspection time per request. Zero means DefaultTimeout.
	Timeout time.Duration
	// MaxConcurrent bounds how many evaluations run at once, including ones
	// that already timed out and are still finishing. When all slots are
	// busy, new requests get the failure mode immediately (ReasonOverload)
	// instead of adding work. Zero means 2 * GOMAXPROCS. Ignored when
	// Admission is set.
	MaxConcurrent int
	// Admission, if set, is shared with other pipelines (one per policy),
	// so the bound holds for the whole engine.
	Admission *Admission
	// Oversize decides what happens to bodies longer than the inspection
	// limit (request.Request.BodyTruncated).
	Oversize OversizeAction
	// Observer, if set, is told about every verdict (metrics).
	Observer Observer
	// Routes decides which paths skip inspection entirely or skip only body
	// inspection (tier T0). Nil inspects everything.
	Routes *router.Table
	// GRPCMessages inspects the text in gRPC calls' messages: protobuf
	// read without its schema (pkg/grpcwire), the text fields given to the
	// rules as form arguments. A call whose messages can't all be read (a
	// message cut at the body limit, compressed other than with gzip, not
	// protobuf) is handled as an oversized body. Off by default: see
	// docs/design/0002 §8.7.
	GRPCMessages bool
	// WebSocket is what a WebSocket handshake must meet (allowed origins,
	// required headers), checked before the rules. Nil: nothing more than
	// any request.
	WebSocket *WebSocketRules
	// Responses configures response inspection; the zero value inspects
	// none.
	Responses ResponseConfig
}

Config configures a Pipeline.

type Exchange added in v0.4.0

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

Exchange is a request's inspection kept for its response, for a policy that inspects responses. CheckResponse inspects the response once; Close releases the evaluation, and may be called from any goroutine, also while CheckResponse runs or after it timed out.

func (*Exchange) BodyLimit added in v0.4.0

func (e *Exchange) BodyLimit() int64

BodyLimit is how much of the response body is inspected: 0 for none.

func (*Exchange) CheckResponse added in v0.4.0

func (e *Exchange) CheckResponse(ctx context.Context, resp *request.Response) Verdict

CheckResponse inspects resp, the response to the exchange's request, with its body cut at BodyLimit by the adapter (a longer one is BodyTruncated). It returns within the pipeline's timeout, under its admission limit, with its failure mode. A body that is truncated or uninspected gets the oversize action once the rules found nothing: OversizeDeny replaces the response in block mode with 502 Bad Gateway. In block mode, a deny replaces the response with the verdict's status.

func (*Exchange) Close added in v0.4.0

func (e *Exchange) Close()

Close releases the evaluation: now, or when the running evaluation of the response finishes.

func (*Exchange) OnVerdict added in v0.4.0

func (e *Exchange) OnVerdict(policy string, observe func(Verdict))

OnVerdict sets the policy the response's verdict names, and a function told about that verdict (a policy's counter).

func (*Exchange) WantsBody added in v0.4.0

func (e *Exchange) WantsBody(contentType string) bool

WantsBody reports whether a response body with this Content-Type is inspected: a body limit is set and the rules read its media type (rules.ResponseBodyTypes). Others, such as images and streams (Server-Sent Events, gRPC), pass without their body inspected and without being counted as oversized.

type ExchangeInspector added in v0.4.0

type ExchangeInspector interface {
	Inspector
	// CheckExchange is Check, and returns the Exchange to inspect r's
	// response with when it is inspected and r was let through (nil
	// otherwise). The caller must Close it.
	CheckExchange(ctx context.Context, r *request.Request) (Verdict, *Exchange)
}

ExchangeInspector is an Inspector that also inspects responses, for the adapters that see them (ext_proc).

type FailureMode

type FailureMode uint8

FailureMode decides what happens when a request cannot be inspected: inspection timed out, failed, or was shed under overload.

const (
	// FailAuto is the default: fail closed in block mode and open in detect
	// mode. A fail-open block mode is bypassable: padding a request until
	// inspection times out gets it forwarded uninspected.
	FailAuto FailureMode = iota
	// FailOpen allows the request, choosing availability over enforcement.
	FailOpen
	// FailClosed rejects the request with 503 Service Unavailable.
	FailClosed
)

func (FailureMode) Resolve

func (f FailureMode) Resolve(m Mode) FailureMode

Resolve returns the effective failure mode for an enforcement mode.

type Inspector

type Inspector interface {
	// Check inspects r and returns the verdict.
	Check(ctx context.Context, r *request.Request) Verdict
	// BodyLimit returns how many body bytes to read for r, which carries
	// no body yet: 0 means the body isn't inspected, so it isn't read. max
	// is the adapter's own limit, used when nothing more specific applies.
	BodyLimit(r *request.Request, max int64) int64
}

Inspector is what adapters inspect requests with: one Pipeline, or a set of policies that picks a pipeline per route.

type Mode

type Mode uint8

Mode is the enforcement mode.

const (
	// ModeDetect reports matches but never blocks. It is the default.
	ModeDetect Mode = iota
	// ModeBlock blocks requests that the rules interrupt.
	ModeBlock
)

type Observer

type Observer interface {
	ObserveVerdict(v Verdict)
}

Observer receives every verdict. Implementations must be fast and safe for concurrent use: they run on the request path.

type OversizeAction

type OversizeAction uint8

OversizeAction decides what happens to a request whose body is longer than the inspection limit.

const (
	// OversizeAuto is the default: deny in block mode, allow in detect mode.
	OversizeAuto OversizeAction = iota
	// OversizeAllow inspects headers and URI only and forwards the body
	// uninspected; the verdict carries ReasonOversize so it is logged and
	// counted. A truncated body is never inspected: a prefix of JSON, XML
	// or multipart cannot be parsed, and inspecting a prefix of any body
	// leaves the rest as a hiding place.
	OversizeAllow
	// OversizeDeny rejects oversized bodies with 413 Content Too Large in
	// block mode (detect mode logs them), so no body escapes inspection.
	OversizeDeny
)

func (OversizeAction) Resolve

func (o OversizeAction) Resolve(m Mode) OversizeAction

Resolve returns the effective oversize action for an enforcement mode.

type Pipeline

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

Pipeline evaluates requests. It is safe for concurrent use.

func New

func New(eval rules.Evaluator, cfg Config) *Pipeline

New returns a pipeline that evaluates requests with eval.

func (*Pipeline) Admission

func (p *Pipeline) Admission() *Admission

Admission returns the pipeline's admission limit.

func (*Pipeline) BodyLimit

func (p *Pipeline) BodyLimit(r *request.Request, max int64) int64

BodyLimit implements Inspector: max, or 0 for a path whose body is skipped, so adapters don't buffer bodies that aren't inspected.

func (*Pipeline) Check

func (p *Pipeline) Check(ctx context.Context, r *request.Request) Verdict

Check inspects r and returns the verdict. It returns within the configured timeout even if the evaluator does not.

func (*Pipeline) CheckExchange added in v0.4.0

func (p *Pipeline) CheckExchange(ctx context.Context, r *request.Request) (Verdict, *Exchange)

CheckExchange is Check, and also returns the Exchange to inspect r's response with when the pipeline inspects responses and the request was let through (nil otherwise). The caller must Close it.

func (*Pipeline) CheckWebSocketMessage added in v0.4.0

func (p *Pipeline) CheckWebSocketMessage(ctx context.Context, handshake *request.Request, text []byte, truncated bool) Verdict

CheckWebSocketMessage inspects the text of a message a client sent on the WebSocket that handshake opened, with the policy's rules: as a request with the handshake's URL and headers whose form arguments are the message (request.Request.WebSocketText). A message cut at the body limit (truncated) is handled as an oversized body. A route the policy skips, or whose body it skips, isn't inspected.

func (*Pipeline) Mode added in v0.4.0

func (p *Pipeline) Mode() Mode

Mode returns the pipeline's mode: the engine's proxy holds each message until it is inspected in block mode, and forwards it at once in detect mode.

type Reason

type Reason uint8

Reason explains a verdict.

const (
	// ReasonNone means no rule interrupted the request.
	ReasonNone Reason = iota
	// ReasonRule means a rule interrupted the request.
	ReasonRule
	// ReasonTimeout means inspection exceeded the deadline.
	ReasonTimeout
	// ReasonError means the evaluator failed.
	ReasonError
	// ReasonCanceled means the caller canceled the request.
	ReasonCanceled
	// ReasonOverload means all evaluation slots were busy, so the request
	// was not inspected.
	ReasonOverload
	// ReasonOversize means the body was longer than the inspection limit
	// and the policy rejects oversized bodies.
	ReasonOversize
	// ReasonSkipped means the route is configured to skip inspection.
	ReasonSkipped
	// ReasonNoPolicy means no policy covers the request's route, so it was
	// not inspected.
	ReasonNoPolicy
	// ReasonSuspended means inspection is suspended (the emergency switch).
	ReasonSuspended
	// ReasonWebSocket means a WebSocket handshake didn't meet the policy's
	// WebSocket rules: an origin not allowed, a required header missing.
	ReasonWebSocket
)

func (Reason) String

func (r Reason) String() string

type ResponseConfig added in v0.4.0

type ResponseConfig struct {
	// Inspect turns response inspection on: CheckExchange keeps each
	// request's evaluation for its response.
	Inspect bool
	// MaxBytes is how much of a response body is inspected; 0 inspects
	// the status and headers only.
	MaxBytes int64
	// Oversize decides what happens to a response whose body is longer
	// than MaxBytes (its prefix is inspected) or couldn't be inspected
	// (request.Response.BodyUninspected). OversizeDeny replaces it in
	// block mode with 502.
	Oversize OversizeAction
}

ResponseConfig configures response inspection.

type Verdict

type Verdict struct {
	Action Action
	// Status is the HTTP status to return when Action is ActionDeny.
	Status int
	Reason Reason
	// InterruptingRuleID is the rule that interrupted the request, if any.
	InterruptingRuleID int
	// RuleIDs lists every rule that matched, including score-only matches.
	RuleIDs []int
	// Matches says where they matched (unredacted), and AnomalyScore is the
	// CRS inbound anomaly score.
	Matches      []rules.Match
	AnomalyScore int
	// Duration is the time spent inspecting.
	Duration time.Duration
	// Policy is the policy that decided, in bundle mode ("namespace/name").
	Policy string
	// Response reports a verdict on the upstream's response, not on the
	// request: a deny replaces the response, and AnomalyScore is the CRS
	// outbound score.
	Response bool
}

Verdict is the pipeline's decision for one request.

type WebSocketConfig added in v0.4.0

type WebSocketConfig struct {
	// AllowedOrigins are the origins a handshake may come from, as
	// "scheme://host" or "scheme://host:port" (http or https). A host may
	// start with "*.": it then matches any subdomain of the rest, at any
	// depth, not the rest itself. Empty: any origin.
	AllowedOrigins []string
	// AllowMissingOrigin lets a handshake without an Origin header through
	// the origin check. Browsers always send one; other clients may not.
	AllowMissingOrigin bool
	// RequiredHeaders are headers a handshake must have, not empty.
	RequiredHeaders []string
}

WebSocketConfig is what a policy requires of a WebSocket handshake. A handshake that doesn't meet it is denied with 403 in block mode (logged in detect mode), with ReasonWebSocket, before the rules run. Requests that aren't handshakes aren't affected.

type WebSocketMessages added in v0.4.0

type WebSocketMessages int

WebSocketMessages is what the engine's reverse proxy does with the messages of a WebSocket it forwards (#276). Only the proxy sees them: ext_proc and forward-auth see the handshake alone (docs/design/0002 §6).

const (
	// MessagesOff forwards messages uninspected.
	MessagesOff WebSocketMessages = iota
	// MessagesInspect inspects text messages; binary ones pass uninspected.
	MessagesInspect
	// MessagesTextOnly inspects text messages and refuses binary ones,
	// which the rules can't read.
	MessagesTextOnly
)

type WebSocketRules added in v0.4.0

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

WebSocketRules is a compiled WebSocketConfig, for Config.WebSocket.

func CompileWebSocket added in v0.4.0

func CompileWebSocket(cfg WebSocketConfig) (*WebSocketRules, error)

CompileWebSocket checks and compiles cfg. It returns nil when cfg requires nothing.

Jump to

Keyboard shortcuts

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