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
- func CheckLimitPath(p string) error
- func CheckRateLimits(cfgs []RateLimitConfig) error
- func GRPCContentType(r *request.Request) bool
- func InspectedResponseType(contentType string) bool
- func ResponseContentType(h http.Header) string
- func StreamKind(contentType string) streams.Kind
- func Stricter(a, b Verdict) bool
- func WebSocketHandshake(r *request.Request) bool
- type Action
- type Admission
- type Config
- type DenyResponse
- type Exchange
- func (e *Exchange) BodyLimit() int64
- func (e *Exchange) CheckEvent(ctx context.Context, req *request.Request, stream *request.Response, ...) Verdict
- func (e *Exchange) CheckResponse(ctx context.Context, resp *request.Response) Verdict
- func (e *Exchange) Close()
- func (e *Exchange) FailureMode() FailureMode
- func (e *Exchange) HoldsEvents() bool
- func (e *Exchange) OnVerdict(observe func(Verdict))
- func (e *Exchange) Refused() Verdict
- func (e *Exchange) Streams() bool
- func (e *Exchange) UsageMeter(h http.Header) *UsageMeter
- func (e *Exchange) WantsBody(contentType string) bool
- type ExchangeInspector
- type FailureMode
- type GRPCRead
- type GRPCStream
- type GRPCStreamInspector
- type GeoRules
- type Inspector
- type LLM
- type LLMConfig
- type LLMEndpoint
- type LLMExclusion
- type LLMVerdict
- type Mode
- type Observer
- type OversizeAction
- type Pipeline
- func (p *Pipeline) Admission() *Admission
- func (p *Pipeline) BodyLimit(r *request.Request, max int64) int64
- func (p *Pipeline) Check(ctx context.Context, r *request.Request) Verdict
- func (p *Pipeline) CheckExchange(ctx context.Context, r *request.Request) (Verdict, *Exchange)
- func (p *Pipeline) CheckGRPCMessage(ctx context.Context, call *request.Request, ev streams.Event, n int) Verdict
- func (p *Pipeline) CheckWebSocketMessage(ctx context.Context, handshake *request.Request, text []byte, truncated bool) Verdict
- func (p *Pipeline) GRPCSchema(call *request.Request) (*grpcschema.Schema, *grpcschema.Message)
- func (p *Pipeline) GRPCStream(r *request.Request) GRPCStream
- func (p *Pipeline) GeoBlocks(r *request.Request) bool
- func (p *Pipeline) LLMBodyLimit(r *request.Request) int64
- func (p *Pipeline) Mode() Mode
- func (p *Pipeline) RateLimited(r *request.Request) bool
- type RateLimitConfig
- type RateLimits
- type Reason
- type ResponseConfig
- type UsageMeter
- type Verdict
- type WebSocketConfig
- type WebSocketMessages
- type WebSocketRules
Constants ¶
const DefaultIPv6Prefix = 56
DefaultIPv6Prefix is the prefix IPv6 clients are counted by when a limit doesn't set one: a subscriber holds at least a /64, often a /56 or a /48.
const DefaultLLMBodyBytes = 1 << 20
DefaultLLMBodyBytes is the body read on an LLM endpoint when the policy sets no limit (spec.llm.maxBodyBytes).
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.
const MaxDenyResponseBytes = 8 << 10
MaxDenyResponseBytes bounds a DenyResponse's body, as the CRD does.
const MaxLLMEndpoints = 8
MaxLLMEndpoints is the most endpoints a policy has.
const MaxRateLimits = 8
MaxRateLimits is the most limits a policy has (spec.rateLimits).
const RequestIDToken = "{{request_id}}" // #nosec G101 -- a placeholder, not a credential
RequestIDToken is the one substitution a DenyResponse's body has: each is replaced with the request's ID.
Variables ¶
This section is empty.
Functions ¶
func CheckLimitPath ¶
CheckLimitPath checks one of a limit's path patterns as CompileRateLimits does.
func CheckRateLimits ¶
func CheckRateLimits(cfgs []RateLimitConfig) error
CheckRateLimits checks a policy's limits as CompileRateLimits does, without a store: what it refuses, CompileRateLimits refuses. The operator's webhook and bundle builder check with it, since one limit the engine refuses makes it refuse the whole bundle.
func GRPCContentType ¶ added in v0.5.0
GRPCContentType reports whether r's content type is a gRPC or gRPC-Web one (application/grpc, application/grpc+json, application/grpc-web...), whatever its body: what DenyGRPC refuses.
func InspectedResponseType ¶ added in v0.4.0
InspectedResponseType reports whether the rules read a response body with this Content-Type: rules.ResponseBodyType, so also one with a structured syntax suffix (+json, +xml), one a strict parser rejects, or none.
func ResponseContentType ¶ added in v0.4.3
ResponseContentType is the Content-Type of a response with headers h, as WantsBody takes it: its values joined with ",", so a header sent twice, which isn't one type, reads as text.
func StreamKind ¶ added in v0.6.0
StreamKind is the kind of stream a response with this Content-Type is, split into events when Streams is on.
func Stricter ¶ added in v0.4.3
Stricter reports whether verdict a is stricter than b: deny over log over allow.
func WebSocketHandshake ¶ added in v0.4.0
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 Admission ¶
type Admission struct {
// contains filtered or unexported fields
}
Admission bounds how many evaluations run at once.
func NewAdmission ¶
NewAdmission returns an Admission for n concurrent evaluations; n <= 0 means 2 * GOMAXPROCS.
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
// Policy is the policy the pipeline enforces, in bundle mode
// ("namespace/name"): its verdicts name it (Verdict.Policy), before the
// Observer is told about them. Empty in standalone mode.
Policy string
// 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
// GRPCPerMessage, with GRPCMessages, inspects a gRPC call's messages
// one by one as they come, through the adapters that can stream a
// request body (ext_proc), instead of the buffered body: long client
// streams and bidirectional calls then work (#315, GRPCStream). Other
// adapters inspect the buffered body as without it.
GRPCPerMessage bool
// GRPCSchema, with GRPCMessages, reads the messages of the methods it
// describes with their schema (grpcwire.Fields, design 0013): fields by
// their types, named by their paths. Nil, or a method it doesn't
// describe: without it.
GRPCSchema *grpcschema.Schema
// 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
// RateLimits are the policy's limits (CompileRateLimits), checked after
// the IP lists and the skipped paths, before anything else. Nil: none.
RateLimits *RateLimits
// IPDeny and IPAllow are the policy's IP lists (#358), checked on the
// resolved client IP before anything else: a client in IPDeny is
// denied (logged in detect mode) with ReasonIPDeny, one in IPAllow and
// not in IPDeny is let through uninspected with ReasonIPAllow. Nil:
// none.
IPDeny, IPAllow *iplist.Set
// Geo is the policy's geo blocking (design 0011), checked right after
// the IP lists, on the country the policy set looked up for the
// request (request.Request.Geo). Nil: none.
Geo *GeoRules
// DenyGRPC denies a request with a gRPC or gRPC-Web content type
// (logged in detect mode) with ReasonGRPC, before the rules: for routes
// that serve no gRPC (#367).
DenyGRPC bool
// DenyResponse is the body of the policy's denials, which its verdicts
// carry (Verdict.DenyResponse). Nil: the adapter's own.
DenyResponse *DenyResponse
// LLM is the policy's LLM endpoints (CompileLLM): their requests are
// parsed and checked after the rate limits, before the rules. Nil:
// none.
LLM *LLM
}
Config configures a Pipeline.
type DenyResponse ¶
type DenyResponse struct {
// contains filtered or unexported fields
}
DenyResponse is the body of a policy's denials (WAFPolicy spec.denyResponse, or the InkwallConfig's default), compiled: the verdicts of the policy's pipeline carry it (Verdict.DenyResponse), and the adapters that write a body answer a denial with it instead of their own. It is immutable and safe for concurrent use.
func CompileDenyResponse ¶
func CompileDenyResponse(contentType, body string) (*DenyResponse, error)
CompileDenyResponse checks and compiles a denial's content type and body: one of the allowed media types, with charset=utf-8 or no parameter; a body of at most MaxDenyResponseBytes of UTF-8, not empty. Whether a JSON body is a JSON document is the webhook's to check (CheckJSON): the engine serves it as it is, rather than refuse a bundle for it.
func (*DenyResponse) CheckJSON ¶
func (d *DenyResponse) CheckJSON() error
CheckJSON returns an error when d's content type is JSON and its body, with a request ID in it, isn't a JSON document.
func (*DenyResponse) ContentType ¶
func (d *DenyResponse) ContentType() string
ContentType is the Content-Type the denial is served with.
func (*DenyResponse) Render ¶
func (d *DenyResponse) Render(id string) []byte
Render returns the body for the request ID id, escaped for the content type: HTML-escaped for text/html, as in a JSON string for JSON (the token goes inside a string's quotes), as it is for text/plain. Adapters keep only IDs of [A-Za-z0-9._:-] (httpadapter.RequestID), which no escaping changes; the escaping holds for any ID.
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 JoinExchanges ¶ added in v0.4.3
JoinExchanges returns one Exchange for the exchanges of a request inspected by several policies: the response is inspected by each, each to its own body limit, and gets the strictest verdict. nil for none.
func (*Exchange) BodyLimit ¶ added in v0.4.0
BodyLimit is how much of the response body is inspected: 0 for none.
func (*Exchange) CheckEvent ¶ added in v0.6.0
func (e *Exchange) CheckEvent(ctx context.Context, req *request.Request, stream *request.Response, ev streams.Event, n int) Verdict
CheckEvent inspects one event of a streamed response (#323, 0006 §2): ev, the n-th event (from 1) of stream, the response to req, whose status and headers were inspected with CheckResponse. The event is inspected on its own, as a WebSocket message is: a fresh evaluation of a clean request with req's identity and path (so exclusions and events apply, but the request's score isn't added to every event), whose response has the stream's status and headers and the event's text as a plain-text body. A cut event (ev.Truncated) gets the oversize action. The Exchange may already be closed: only its policy is used.
func (*Exchange) CheckResponse ¶ added in v0.4.0
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) FailureMode ¶ added in v0.6.0
func (e *Exchange) FailureMode() FailureMode
FailureMode is the request's failure mode, resolved for the pipeline's mode: what an adapter that loses the exchange before the response (the SPOE agent's table) does with that response.
func (*Exchange) HoldsEvents ¶ added in v0.6.0
HoldsEvents reports whether an adapter holds each event of a stream until it is inspected: in block mode, so a denied event never goes out. Detect mode forwards at once and inspects a copy.
func (*Exchange) OnVerdict ¶ added in v0.4.0
OnVerdict sets a function told about the response's verdict (a policy's counter).
func (*Exchange) Refused ¶ added in v0.6.0
Refused is the verdict of a response the adapter can't hold for inspection (the bodies it holds are at their bound): the failure mode, as for an evaluation refused a slot (ReasonOverload), reported as a response's verdict. The exchange is spent.
func (*Exchange) Streams ¶ added in v0.6.0
Streams reports whether streamed responses are inspected event by event (ResponseConfig.Streams).
func (*Exchange) UsageMeter ¶
func (e *Exchange) UsageMeter(h http.Header) *UsageMeter
UsageMeter returns the meter that settles the exchange's token limits with the usage of its streamed response, of headers h; nil when there is none to settle: no token limit charged the request, or the response isn't Server-Sent Events, or is encoded (Content-Encoding). Only the first call returns one.
func (*Exchange) WantsBody ¶ added in v0.4.0
WantsBody reports whether a response body with this Content-Type (ResponseContentType of the headers) is inspected: a body limit is set and the rules read its media type (rules.ResponseBodyType). 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 GRPCRead ¶
type GRPCRead struct {
// Described: messages read with the policy's schema; Undescribed:
// without (the policy has none, or it doesn't describe the method).
Described, Undescribed int
// Unknown is how many fields of the described messages the schema
// doesn't describe, read without it: a set older than the application.
Unknown int
}
GRPCRead counts what reading a gRPC call's messages found.
type GRPCStream ¶ added in v0.6.0
type GRPCStream interface {
// CheckGRPCMessage inspects ev, the n-th message (from 1) of call,
// whose headers were inspected (Check or CheckExchange) and let
// through.
CheckGRPCMessage(ctx context.Context, call *request.Request, ev streams.Event, n int) Verdict
// Mode is the policy's mode: block mode holds each message until it is
// inspected.
Mode() Mode
// GRPCSchema returns what call's messages are read with: the policy's
// schema and the input type of call's method, or nils when it has none
// or doesn't describe the method (design 0013 §6.5).
GRPCSchema(call *request.Request) (*grpcschema.Schema, *grpcschema.Message)
}
GRPCStream inspects the messages of one gRPC call's request stream one by one, as they come (#315, docs/design/0006 §2).
type GRPCStreamInspector ¶ added in v0.6.0
type GRPCStreamInspector interface {
// GRPCStream returns how r's messages are inspected one by one, or nil
// when they aren't: r isn't a gRPC call, or its policy inspects the
// buffered body. r carries its headers only.
GRPCStream(r *request.Request) GRPCStream
}
GRPCStreamInspector is an Inspector whose policies may inspect gRPC calls message by message, for the adapters that can stream a request body (ext_proc).
type GeoRules ¶
type GeoRules struct {
// Countries are the listed countries.
Countries geo.Set
// Allow makes Countries an allow list: a client in any other country
// is denied. It doesn't skip inspection, unlike an IP allow list.
Allow bool
// UnknownDeny denies a public address the table has no country for.
UnknownDeny bool
// Detect only logs, on a Block policy too.
Detect bool
}
GeoRules is a policy's geo blocking (design 0011 §2): a deny list, or an allow list, of countries.
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 LLM ¶
type LLM struct {
// contains filtered or unexported fields
}
LLM is a policy's compiled LLM endpoints. It is immutable.
func CompileLLM ¶
CompileLLM compiles a policy's LLM endpoints; nil for none.
type LLMConfig ¶
type LLMConfig struct {
Endpoints []LLMEndpoint
// MaxBodyBytes is the body read on an endpoint; 0: DefaultLLMBodyBytes.
MaxBodyBytes int64
// RuleSetBody gives the rules the endpoints' bodies too, request and
// response, when RulesReadBodies.
RuleSetBody bool
// RulesReadBodies is whether the policy's rules read bodies at all
// (body.inspect): the endpoints' are read for the LLM checks either
// way.
RulesReadBodies bool
// Checks are the request checks.
Checks llm.Config
// Detect logs the requests that fail a check instead of denying them.
Detect bool
// Exclusions turn checks off (by their rule IDs), on a path or all.
Exclusions []LLMExclusion
// Metrics, if set, count the bodies read and the checks failed.
Metrics *llm.Metrics
}
LLMConfig is a policy's LLM endpoints (design 0012): their request bodies are parsed and checked (pkg/llm) before the rules, which skip them unless RuleSetBody.
type LLMEndpoint ¶
type LLMEndpoint struct {
// Paths are exact paths or prefixes ending in "*", as rate limits'.
Paths []string
// Format is the API's; llm.FormatUnknown checks requests as every
// format the engine knows.
Format llm.Format
}
LLMEndpoint is paths that serve one LLM API.
type LLMExclusion ¶
LLMExclusion turns checks off on Path (an exact path or a prefix ending in "*", as exclusions' paths; empty: every path).
type LLMVerdict ¶
type LLMVerdict struct {
Format llm.Format
Check llm.Check
// Model is the model the request named, at most 64 bytes: the client chooses it.
Model string
// MessageIndex is the message or tool the check is about, -1 for the
// request or a top-level field; Role its role.
MessageIndex int
Role llm.Role
// Offset is where in the body the check failed.
Offset int
// EstimatedTokens are the request's tokens as charged at request time.
EstimatedTokens int64
}
LLMVerdict is, with ReasonLLM, the LLM check a request failed, and where: never the prompt's text.
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 (*Pipeline) BodyLimit ¶
BodyLimit implements Inspector: max, or 0 for a path whose body is skipped, so adapters don't buffer bodies that aren't inspected. A request over one of the policy's Block rate limits is decided here, before its body is read, and gets 0: a flood over its limit isn't read.
func (*Pipeline) Check ¶
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
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) CheckGRPCMessage ¶ added in v0.6.0
func (p *Pipeline) CheckGRPCMessage(ctx context.Context, call *request.Request, ev streams.Event, n int) Verdict
CheckGRPCMessage implements GRPCStream. The message is inspected on its own, as a WebSocket message is (CheckWebSocketMessage): a fresh evaluation of a clean gRPC call with call's identity, path and content type, but not its query or other headers (inspected with the call; run again they would add the call's score to every message), whose form arguments are the message's text fields (request.Request.GRPCText), as grpcMessages names them in a buffered body. Each evaluation goes through admission control and the deadline, as a request does: a flood of messages is shed with the failure mode as a flood of requests is. A message cut at the body limit, or compressed in an encoding the engine can't read, gets the oversize action; a stream that isn't gRPC framing is denied whatever the oversize action, since under Allow it would pass uninspected (a JSON body labelled gRPC).
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, on its own (#363): as a request whose form arguments are the message (request.Request.WebSocketText), with the handshake's identity (request ID, client IP, host) and path, for exclusions and path rules, but not its query arguments or headers. Those were inspected with the handshake; run again, they would add the handshake's score to every message and count toward the message's argument limit. 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) GRPCSchema ¶
func (p *Pipeline) GRPCSchema(call *request.Request) (*grpcschema.Schema, *grpcschema.Message)
GRPCSchema implements GRPCStream.
func (*Pipeline) GRPCStream ¶ added in v0.6.0
func (p *Pipeline) GRPCStream(r *request.Request) GRPCStream
GRPCStream implements GRPCStreamInspector: r is a gRPC call (a POST whose one Content-Type is application/grpc or application/grpc+proto), the pipeline inspects messages one by one, and r's route is inspected with its body. gRPC-Web is left buffered: browsers don't stream a request, and its text form is base64.
func (*Pipeline) GeoBlocks ¶
GeoBlocks reports whether the policy's geo decides r on its own, the IP lists not deciding first: a denied country in Block, or a missing table failing closed. A set of policies asks it before any policy's rate limits, which geo comes before (design 0011 §2.3).
func (*Pipeline) LLMBodyLimit ¶
LLMBodyLimit returns the body to read for r on one of the policy's LLM endpoints (spec.llm.maxBodyBytes), 0 for a request on none.
type RateLimitConfig ¶
type RateLimitConfig struct {
// Name names the limit in verdicts, events and logs.
Name string
// Requests per Period, in bursts of at most Burst (0: Requests).
Requests int64
Period time.Duration
Burst int64
// Header counts by this request header's first value (lower case), and
// a request without it by its client IP. Empty: the client IP.
Header string
// IPv6Prefix counts IPv6 clients by this prefix (0: DefaultIPv6Prefix).
IPv6Prefix int
// Paths are exact paths or prefixes ending in "*", as skip paths; empty:
// every path. Methods, upper case; empty: every method.
Paths []string
Methods []string
// Detect logs the requests over the limit instead of denying them.
Detect bool
// Tokens counts LLM tokens, not requests (design 0012 §6): Requests and
// Burst are tokens, and a request on one of the policy's LLM endpoints
// takes its estimate at once, after the LLM checks; other requests
// aren't counted. A key in debt is refused before its body is read.
Tokens bool
}
RateLimitConfig is one of a policy's rate limits (design 0009).
type RateLimits ¶
type RateLimits struct {
// contains filtered or unexported fields
}
RateLimits are a policy's compiled limits, all in one Store.
func CompileRateLimits ¶
func CompileRateLimits(store *ratelimit.Store, live *ratelimit.Live, policy string, cfgs []RateLimitConfig) (*RateLimits, error)
CompileRateLimits compiles a policy's limits into store. Their buckets are named by the policy, each limit's name and its key, so the same limit in a later bundle keeps them. live collects every limit of the bundle, for reusing the entries of limits no longer in it.
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 // ReasonIPDeny means the client IP is in the policy's deny list. ReasonIPDeny // ReasonIPAllow means the client IP is in the policy's allow list, so // the request was not inspected. ReasonIPAllow // ReasonGRPC means a gRPC call on a policy that refuses gRPC // (DenyGRPC). ReasonGRPC // ReasonRateLimit means the client was over one of the policy's rate // limits (Verdict.RateLimit). ReasonRateLimit // ReasonGeoDeny means the client's country is denied by the policy's // geo blocking (Verdict.Country). ReasonGeoDeny // engine doesn't hold, and the policy fails closed. ReasonGeoUnavailable // ReasonLLM means a request on one of the policy's LLM endpoints // failed an LLM check (Verdict.LLM). ReasonLLM )
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
// Streams inspects streamed responses (Server-Sent Events, gRPC server
// streams) event by event (Exchange.CheckEvent); off, their bodies
// pass uninspected (#323).
Streams bool
}
ResponseConfig configures response inspection.
type UsageMeter ¶
type UsageMeter struct {
// contains filtered or unexported fields
}
UsageMeter settles the token limits an exchange's request was charged with the usage its streamed response (Server-Sent Events) reports (llm.StreamUsage): an adapter writes it the stream's bytes as they go out, and closes it when the stream ends. It splits the stream into events, holding at most one event's data, up to the response body limit (responses.maxBytes): a longer event is skipped. When the stream gave its final usage, the estimate is settled by it, a refund or a debt; when it ended before (cut, or a client gone), the usage so far only adds debt. Without usage the estimate stands. It is safe for concurrent use.
func (*UsageMeter) Write ¶
func (m *UsageMeter) Write(b []byte)
Write reads the next part of the stream.
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
// DenyResponse is that policy's denial body (spec.denyResponse, or the
// bundle's default), which adapters answer a deny with; nil: their
// own.
DenyResponse *DenyResponse
// RateLimit is, with ReasonRateLimit, the limit the client was over,
// and RetryAfter how long until a request would be within it (whole
// seconds; the answer's Retry-After).
RateLimit string
RetryAfter time.Duration
// SampledEvent is, with ReasonRateLimit, ReasonGeoDeny or
// ReasonGeoUnavailable, whether the verdict becomes a security event:
// limited requests are sampled per client and capped (pkg/ratelimit),
// geo's per (policy, country), so a flood can't push other events out.
// SampledCount is the requests the event stands for, this one included.
SampledEvent bool
SampledCount uint32
// GeoMatch is set when the policy's geo blocking denied the request or
// would have (in Detect, also when a rule's reason won), and Country
// is the client's country as the metrics label it: the code, or
// "unknown".
GeoMatch bool
Country string
// LLM is, with ReasonLLM, the LLM check the request failed, and where.
LLM *LLMVerdict
// LLMBody: the request's body is an LLM endpoint's, so events keep no
// snippet of what the rules matched in it (design 0012 §9).
LLMBody bool
// 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
// WebSocketMessage reports a verdict on a message a client sent on a
// WebSocket, not on a request.
WebSocketMessage bool
// GRPCRead counts the gRPC messages read for the verdict, and the
// fields their schema doesn't describe (design 0013 §10).
GRPCRead GRPCRead
// StreamEvent, with Response, is the index (from 1) of the event or
// message of a streamed response the verdict is about; without
// Response, of the message of a gRPC call's request stream (#315). 0
// for a whole request or response.
StreamEvent int
}
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.