Documentation
¶
Overview ¶
Package middleware holds the framework-agnostic half of a web middleware: resolve a client address, classify it, and decide whether to block.
A framework adapter - sdk-go-nethttp, sdk-go-gin - keeps only the parts that are genuinely framework-shaped and shares everything here, so the shared conformance corpus is asserted once for Go rather than once per framework.
Index ¶
- Constants
- func AnyOf(values ...any) anyOf
- func ConstraintCount(condition any) int
- func Matches(conditions Conditions, result *internetdata.Result) bool
- func MissingMembers(conditions Conditions, result *internetdata.Result) []string
- func Validate(conditions Conditions) error
- type BlockCondition
- type Bound
- type Conditions
- type Core
- type IPSelector
- type Lookup
- type MissingFieldAction
- type Options
- type RequestView
- type Selectors
Constants ¶
const ( DefaultTimeout = 2500 * time.Millisecond DefaultRetries = 0 )
Defaults set for a request path rather than for a script: failing open quickly beats holding a visitor while we try again.
Variables ¶
This section is empty.
Functions ¶
func AnyOf ¶
func AnyOf(values ...any) anyOf
AnyOf matches a member equal to any one of these, for an enum-like field.
func ConstraintCount ¶
ConstraintCount reports how many leaf constraints a condition carries.
func Matches ¶
func Matches(conditions Conditions, result *internetdata.Result) bool
Matches reports whether an answer satisfies the condition and should therefore be blocked.
func MissingMembers ¶
func MissingMembers(conditions Conditions, result *internetdata.Result) []string
MissingMembers names the members a condition asks about that this answer did not carry: a top-level member, or a paid one inside an object every plan gets, by its path (location.city).
A field your plan does not include is absent rather than false, so a condition naming one can never match and the block would silently never fire. An empty object is a real answer, meaning the flag above it is false, so nothing inside one is reported: vpn present but {} is not a plan gap. A populated object carries every member the plan includes, so a member missing there is one.
A member the answer left out is absent whatever its Go type reads: is_bot and the seven service flags, and asn.type, keep a bool and a string, and read false and empty on Unlimited.
A locally answered bogon needs no special case: it is synthesized in the widest shape, so every member is present and nothing reads as missing.
func Validate ¶
func Validate(conditions Conditions) error
Validate refuses a condition that constrains nothing.
Ignoring false means BlockCondition{"is_vpn": false} and an empty one have no terms left to satisfy, so they would match every answer and block all traffic. Nobody writes that on purpose, and failing when the middleware is built beats discovering it in production.
Types ¶
type BlockCondition ¶
BlockCondition is what makes a request worth blocking, written in the shape of a Result and keyed by the wire's own names.
Only the members you name are considered, and they must all hold. A member set to false or nil is ignored entirely - a condition states the positive signals you act on, so there is no way to write "block when this is false", which would otherwise read as blocking everybody.
middleware.BlockCondition{"location": middleware.BlockCondition{"country": middleware.AnyOf("CU", "IR", "KP")}}
middleware.BlockCondition{"asn": middleware.BlockCondition{"type": "hosting"}}
middleware.BlockCondition{"is_vpn": true, "vpn": middleware.BlockCondition{"provider": "nordvpn"}}
middleware.BlockCondition{"resproxy": middleware.BlockCondition{"hits": middleware.Gte(5)}}
A value may be a scalar (equality, strings without regard to case), an AnyOf, a Bound, or a nested BlockCondition. Against a member the answer holds as a list, it matches when any one element does:
middleware.BlockCondition{"pubproxy": middleware.BlockCondition{"protocols": "socks5"}}
middleware.BlockCondition{"web": middleware.BlockCondition{"port": 443, "server": "nginx"}}
type Bound ¶
Bound compares a numeric member. Every field set must hold, so two of them are a range: Gte(5).Lt(100).
type Conditions ¶
type Conditions []BlockCondition
Conditions is a list of conditions, any one of which blocking is enough.
type Core ¶
type Core[Req any] struct { // contains filtered or unexported fields }
Core is the framework-agnostic half of a middleware.
func New ¶
func New[Req any](options Options[Req], defaultIPSelector IPSelector[Req]) (*Core[Req], error)
New builds a Core, or refuses a condition that could never be what anyone meant.
defaultIPSelector is the framework's own accessor, supplied by the adapter and used when the caller named none.
func (*Core[Req]) Evaluate ¶
Evaluate classifies one request. It answers nil when Skip claimed it.
The error return is a MISCONFIGURATION - a condition naming a member the plan does not serve, with OnMissingField set to error. A failed LOOKUP is not an error here: it lands on Lookup.Err and the request is let through.
func (*Core[Req]) EvaluateAgent ¶ added in v2.18.0
func (c *Core[Req]) EvaluateAgent(ctx context.Context, request Req, userAgent string) (*Lookup, error)
EvaluateAgent is Evaluate for an adapter that reads the request's own User-Agent header, which AllowBots sends with the lookup. Off, the agent is never sent.
type IPSelector ¶
IPSelector decides the client address.
There is no portable answer: a framework's own accessor may return the socket peer, or may already have walked a proxy chain, depending on the framework and on how the application configured it. You know your framework and your edge, so this is yours to choose.
type Lookup ¶
type Lookup struct {
// IP is the address that was classified, as the selector resolved it.
IP string
// Result is the answer. Nil when the lookup failed.
Result *internetdata.Result
// Err is why the lookup failed. Nil when it succeeded.
Err error
// Blocked reports whether the condition matched. Always false when no
// condition was configured.
Blocked bool
}
Lookup is what a middleware attached to the request, whether or not it succeeded.
type MissingFieldAction ¶
type MissingFieldAction string
MissingFieldAction says what to do when a condition names a member the plan does not serve.
const ( MissingFieldWarn MissingFieldAction = "warn" MissingFieldError MissingFieldAction = "error" MissingFieldIgnore MissingFieldAction = "ignore" )
type Options ¶
type Options[Req any] struct { // Client is an existing client to use. Prefer this if you already hold // one: two clients mean two caches, and a cache is per instance because // two keys can be on different plans and entitled to different fields. Client *internetdata.Client // APIKey is ignored when Client is set. APIKey string // BaseURL is ignored when Client is set. Defaults to // internetdata.DefaultBaseURL. BaseURL string // Timeout is how long a lookup may hold the request. Defaults to 2500ms, // a much tighter bound than the client's own 30s. Timeout time.Duration // Retries for a transient failure. Defaults to 0, unlike the client's 2. // New refuses a negative count. Retries *int // IPSelector decides the client address. Defaults to the framework's own // accessor. IPSelector IPSelector[Req] // BlockCondition is what to block on. Leave it empty to only enrich the // request and leave the decision to your own code. BlockCondition Conditions // FailClosed blocks when the lookup itself fails. Defaults to false, so // our outage does not become yours. FailClosed bool // OnMissingField says what to do when the condition names a member your // plan does not serve. Defaults to warning once. OnMissingField MissingFieldAction // Skip claims a request, so it is never classified. Skip func(request Req) bool // Logger receives the warnings. Defaults to slog.Default(). Logger *slog.Logger // AllowBots sends the request's own User-Agent header with its lookup, // and never refuses a request whose answer's UserAgent verdict is // verified, whatever BlockCondition matches; the answer is still // attached. An absent or empty header sends none. A keyless client, or a // free key past its trial, is never answered a verdict, so nothing is let // through and OnMissingField says so once. Off by default, so the cache // holds one answer per address rather than one per agent. AllowBots bool }
Options configure a middleware. Everything is optional.
type RequestView ¶
type RequestView struct {
// Header returns a request header by name, case-insensitively.
Header func(name string) string
// FrameworkIP returns the framework's own client-address accessor,
// whatever that resolves to here.
FrameworkIP func() string
}
RequestView is enough of an incoming request for a selector to work with, whatever framework it came from. An adapter supplies one of these per request.
type Selectors ¶
type Selectors[Req any] struct { // Default is the framework's own client-address accessor. What that // resolves to depends on the framework and on how you configured it. Default IPSelector[Req] // XFF reads X-Forwarded-For. // // The LEFT-MOST entry is whatever the caller sent, because proxies append, // so a visitor who sets the header themselves appears first and this // returns their forgery. It is only trustworthy when an edge you control // overwrites the header. When you know how many proxies sit in front, // count from the right with depth: 1 is the address your nearest proxy saw. XFF func(depth int) IPSelector[Req] // Header reads a single-value header by name, for an edge that writes one // - Header("CF-Connecting-IP") behind Cloudflare. Falls back to the // framework's accessor when the header is absent. Header func(name string) IPSelector[Req] }
Selectors are the shared implementations, bound to one framework's request type so a caller writing a custom selector still works with the object they know.
func BindSelectors ¶
func BindSelectors[Req any](view func(Req) RequestView) Selectors[Req]
BindSelectors gives an adapter the shared selectors under its own request type. The adapter passes a function exposing its request once.