Documentation
¶
Overview ¶
Package admission owns IP filtering and per-IP local/distributed rate limits.
NewIPFilter and NewRateLimiter construct independent owners and start no goroutines. Callers own configuration persistence, Cleanup scheduling, cancellation and transport. Remote maps passed to ApplyRemoteCounts transfer ownership and must not subsequently be mutated. Configuration/enablement changes retain local and remote history.
A zero filter supports reads and mode/CIDR operations as before; use NewIPFilter before adding individual addresses. A zero limiter supports disabled admission, configuration and distributed-state diagnostics; active local admission requires NewRateLimiter to initialize its shard maps.
ClusterFreshness derives the verdict from the current window and receipt stamp. ObserveClusterFreshness additionally owns diagnostic episode accounting; callers render its result and serialize observation/logging in their loop.
Index ¶
- Constants
- func PrefixFromIPNet(n *net.IPNet) (netip.Prefix, bool)
- type ClusterRateLimitStatus
- type FreshnessObservation
- type FreshnessTransition
- type HotCount
- type IPFilter
- func (f *IPFilter) Add(entry string) error
- func (f *IPFilter) AddAll(entries []string) []InvalidIPEntry
- func (f *IPFilter) Allowed(ipStr string) bool
- func (f *IPFilter) ClearAll()
- func (f *IPFilter) List() []string
- func (f *IPFilter) Mode() string
- func (f *IPFilter) Remove(entry string)
- func (f *IPFilter) Replace(mode string, entries []string) []InvalidIPEntry
- func (f *IPFilter) SetMode(mode string)
- type InvalidIPEntry
- type RateLimiter
- func (r *RateLimiter) AddExemption(entry string) error
- func (r *RateLimiter) AddExemptions(entries []string) []InvalidIPEntry
- func (r *RateLimiter) Allow(ip string) bool
- func (r *RateLimiter) AllowAuto(ip string) bool
- func (r *RateLimiter) AllowClusterAware(ip string) bool
- func (r *RateLimiter) ApplyRemoteCounts(remote map[string]int)
- func (r *RateLimiter) Cleanup()
- func (r *RateLimiter) ClusterEnabled() bool
- func (r *RateLimiter) ClusterFreshness() ClusterRateLimitStatus
- func (r *RateLimiter) Configure(limit int, window time.Duration)
- func (r *RateLimiter) Enabled() bool
- func (r *RateLimiter) ExportHotDeltas() []HotCount
- func (r *RateLimiter) IsExempt(ip string) bool
- func (r *RateLimiter) Limit() int
- func (r *RateLimiter) ListExemptions() []string
- func (r *RateLimiter) ObserveClusterFreshness() FreshnessObservation
- func (r *RateLimiter) RemoteIPCount() int
- func (r *RateLimiter) RemoveExemption(entry string)
- func (r *RateLimiter) ReplaceExemptions(entries []string)
- func (r *RateLimiter) SetClusterEnabled(enabled bool)
- func (r *RateLimiter) Window() time.Duration
Constants ¶
const HotThresholdPercent = 50
HotThresholdPercent is the percentage of the rate limit an IP must reach before its counts are synced to the Control Plane. Keeps gossip traffic minimal.
Variables ¶
This section is empty.
Functions ¶
func PrefixFromIPNet ¶
PrefixFromIPNet converts a *net.IPNet into its canonical netip.Prefix. ok=false for a non-contiguous mask or a width combination net itself rejects — see ipFilterView.oddNets.
The family normalisation here MIRRORS net.networkNumberAndMask, which is what net.IPNet.Contains uses, and it is not obvious: a network address that To4() accepts is an IPv4 network however many bytes it is STORED in, and a 16-byte mask is then re-read as its low four bytes. That makes "::ffff:10.0.0.0/104" behave exactly like "10.0.0.0/8" — including matching the plain IPv4 address 10.0.0.1 — which a naive "16 bytes means IPv6" reading gets wrong in the fail-open direction for a blocklist. Pinned by TestIPFilterView_DifferentialAgainstLegacy, which caught precisely this.
A genuinely-IPv6 prefix keeps its 128-bit width, so it goes on failing to match IPv4 probes exactly as it does today.
Types ¶
type ClusterRateLimitStatus ¶
type ClusterRateLimitStatus struct {
// Armed is true only when this node's allow/deny decisions ACTUALLY consult
// remote counts. That needs BOTH halves of the condition AllowAuto →
// AllowClusterAware requires: the DP gossip loop is running (so AllowAuto
// dispatches to the cluster-aware path) AND the rate limiter itself is
// enabled (AllowClusterAware returns true immediately when it is not,
// before FreshCount is ever reached).
//
// Both halves are load-bearing, and the second one was missed in the first
// version of this file. rateLimitGossipLoop enables distributed admission
// unconditionally when it starts, but skips every RPC while rl.Enabled() is
// false — which is the DEFAULT posture, since Configure only enables the
// limiter for a limit > 0. On such a node no broadcast can ever be applied,
// so a cluster-flag-only Armed reported a permanent, un-clearable
// degradation — gauge pinned at 1, an episode counted, a warning logged, a
// banner shown — on a node that is not rate limiting at all and for which
// no remote count is ever consulted. That is precisely the failure this
// file's own emission rule exists to prevent (a 0/1 gauge on a node that
// never had the feature is indistinguishable from a broken one), applied to
// "is gossip running" but not to "is anything being decided". Found by
// Codex review on PR #1346.
Armed bool
// Applied is true once any broadcast has been received. False on a node
// that has never reached its Control Plane. Reported honestly regardless of
// Armed — it is a fact about what arrived, not about what is enforced.
Applied bool
// Age is how long ago the last broadcast landed (0 when none has).
Age time.Duration
// MaxAge is the window past which a broadcast can no longer describe the
// current window — the rate limiter's own window.
MaxAge time.Duration
// Stale is true when the remote half of a decision this node is ACTUALLY
// MAKING is not being applied: it is armed, and either no broadcast has ever
// landed or the last one is at least MaxAge old. An un-armed node is never
// stale — there is no decision for an expired broadcast to degrade, so
// reporting one would be a false alarm on every surface at once.
Stale bool
// Episodes counts fresh→stale transitions observed by the gossip loop since
// startup. It is the operator's "has this happened before" signal; the
// gauge alone cannot distinguish one long outage from six short ones.
Episodes int64
}
ClusterRateLimitStatus is the read-side snapshot of the cluster rate-limit broadcast's freshness. Every field is derived at read time.
type FreshnessObservation ¶
type FreshnessObservation struct {
Status ClusterRateLimitStatus
Transition FreshnessTransition
}
FreshnessObservation is the engine's observation and transition, for rendering by its caller. Episodes includes this observation; admission never uses it.
type FreshnessTransition ¶
type FreshnessTransition uint8
FreshnessTransition describes an observed diagnostic transition.
const ( FreshnessUnchanged FreshnessTransition = iota FreshnessStale FreshnessRecovered )
Observation transitions; an unchanged observation requires no log message.
type IPFilter ¶
type IPFilter struct {
// contains filtered or unexported fields
}
IPFilter supports allowlist and blocklist mode with CIDR ranges. Mode "allow" → only IPs in the list are permitted (default: allow all). Mode "block" → IPs in the list are denied.
Allowed() runs on EVERY proxied request (handleRequest, and the SOCKS5 handler) before any other work, so the read path is LOCK-FREE: it loads an immutable *ipFilterView through an atomic.Pointer and never touches mu. The mu-guarded fields below stay the authoritative write-side state — Add, Remove, ClearAll, List and Mode keep their exact previous semantics — and every mutator republishes a freshly derived view before releasing the lock. Same contract, and the same reason, as internal/threatfeed's read view.
A mutator added WITHOUT a publishView() call is a silent SECURITY failure, not a performance one: a revoked allowlist entry that keeps admitting, or a removed blocklist entry that keeps denying. It is pinned per mutator by TestIPFilterView_EveryMutatorRepublishes.
func NewIPFilter ¶
func NewIPFilter() *IPFilter
NewIPFilter constructs a filter ready for address and CIDR mutations.
func (*IPFilter) Add ¶
Add accepts plain IPs ("1.2.3.4") or CIDR ("10.0.0.0/8").
Use AddAll to load a LIST — Add publishes the derived view on every call (it must: a single admin edit has to take effect immediately), and publishView rebuilds that view from the whole entry set, so Add in a loop is quadratic. See AddAll.
func (*IPFilter) AddAll ¶
func (f *IPFilter) AddAll(entries []string) []InvalidIPEntry
AddAll appends every valid entry in ONE pass, under ONE lock, publishing the derived view ONCE at the end. Invalid entries are skipped and returned; a nil result means every entry was accepted.
This is the bulk-load primitive every list-restoring caller must use — startup (connlimit_startup.go), admin_settings restore, config-version rollback, config import, and the CP→DP snapshot apply. Publishing per entry instead makes a bulk load O(N²) in the entry count: measured on a 4-core Xeon, an Add loop costs 46 ms at 1k entries, 857 ms at 4k and 3.27 s at 8k (each doubling ~4x), which extrapolates to minutes at 100k — and the ConfigSnapshot cap for this list is maxSnapIPList (2,000,000). That would stall a boot or a snapshot apply on a legitimate enterprise allowlist. AddAll is linear. Pinned by TestIPFilterView_BulkLoadPublishesOnce (exactly one publish per AddAll, at any entry count).
func (*IPFilter) Allowed ¶
Allowed returns true when the IP should be allowed through.
Mode semantics: "allow" = allowlist (only listed IPs pass), "block" = blocklist (listed IPs are denied), "" = disabled (filter off, all pass). ANY OTHER value is treated as corruption and DENIES ALL traffic (fail closed). Coercing a corrupt mode to "block" instead would be unsafe: a corrupted *allowlist* deployment (mode was "allow" with a list of the only trusted IPs) would become a blocklist that admits every IP not on the list — fail open. When we cannot trust the mode, we cannot reason about the list, so we deny everything until an operator restores a valid config.
Reads ONE atomic pointer and takes no lock: this runs on every proxied request, and an RWMutex.RLock is an atomic read-modify-write on a single shared word, so the previous shape made every request in the process contend on one cache line — including the default posture, where the filter is disabled and the lock guarded a decision that never changes. The mode and the entry set are read from ONE view, so a concurrent mutation can no longer be observed half-applied either.
func (*IPFilter) ClearAll ¶
func (f *IPFilter) ClearAll()
ClearAll removes all IP filter entries. Used by config import "replace" mode.
func (*IPFilter) Replace ¶ added in v1.0.263
func (f *IPFilter) Replace(mode string, entries []string) []InvalidIPEntry
Replace installs mode and entries as the filter's ENTIRE configuration in one pass, under ONE writer lock, publishing the derived view ONCE. Every previous entry is discarded; a nil or empty entries slice leaves the filter with the given mode and no entries. Invalid entries are skipped and returned, as AddAll reports them, for logging after the lock is released.
This is the wholesale-replacement primitive for a caller that previously built a fresh filter and swapped the pointer it enforces with (the CP→DP snapshot apply). Replacing a live filter's pointer is a data race against the lock-free Allowed readers in the request path; replacing its contents here is not: readers observe either the previous view or the new one, never an intermediate (a SetMode / ClearAll / AddAll sequence publishes three views, and the middle one is an empty allowlist that denies everything or an empty blocklist that admits everything). Linear in the entry count, like AddAll. The owner's identity, and any observer installed on it, are kept.
func (*IPFilter) SetMode ¶
SetMode sets the IP-filter mode. Valid values are "allow" (allowlist), "block" (blocklist), and "" (disabled). The mode is stored verbatim — the fail-closed handling lives in Allowed(), which denies ALL traffic for any unrecognized (corrupt) mode. This is safer than coercing a corrupt value to "block" here, which would silently convert a corrupted *allowlist* deployment into a permissive blocklist (admitting every non-listed IP). The validated admin API path only ever passes "allow"/"block"; the raw persistence/snapshot paths (config reload, admin_settings restore, config-version rollback, cluster ConfigSnapshot) may carry corruption, and Allowed() fails closed on it.
type InvalidIPEntry ¶
InvalidIPEntry names one entry AddAll could not parse, so the caller can log it exactly as its previous per-entry Add loop did — after the lock is released, never underneath it.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter is a per-IP sliding-window rate limiter.
func NewRateLimiter ¶
func NewRateLimiter() *RateLimiter
NewRateLimiter initializes independent local shards without starting goroutines.
func (*RateLimiter) AddExemption ¶
func (r *RateLimiter) AddExemption(entry string) error
AddExemption adds an IP or CIDR to the rate-limit exempt list.
Use AddExemptions to load a LIST — AddExemption publishes the derived view on every call (it must: a single admin edit has to take effect immediately), and publishing rebuilds that view from the whole entry set, so AddExemption in a loop is quadratic. See AddExemptions.
func (*RateLimiter) AddExemptions ¶
func (r *RateLimiter) AddExemptions(entries []string) []InvalidIPEntry
AddExemptions appends every valid entry in ONE pass, under ONE lock, publishing the derived view ONCE at the end. Invalid entries are skipped and returned; a nil result means every entry was accepted.
This is the bulk-load primitive every list-restoring caller must use — the admin_settings restore at boot and config import. Publishing per entry instead makes a bulk load O(N²) in the entry count, and the ConfigSnapshot cap for this list is maxSnapRateLimitExempt (10,000). Same trap, same shape and same reason as IPFilter.AddAll; pinned by TestRLExemptView_BulkLoadPublishesOnce.
func (*RateLimiter) Allow ¶
func (r *RateLimiter) Allow(ip string) bool
Allow returns true if the IP is within its rate limit or is exempt.
func (*RateLimiter) AllowAuto ¶
func (r *RateLimiter) AllowAuto(ip string) bool
AllowAuto dispatches to AllowClusterAware when cluster rate limiting is active, or plain Allow when running standalone. This is the method that proxy.go and socks5.go should call.
func (*RateLimiter) AllowClusterAware ¶
func (r *RateLimiter) AllowClusterAware(ip string) bool
AllowClusterAware is like Allow but also considers cluster-remote counts. Used when the node is operating as a Data Plane in a cluster.
func (*RateLimiter) ApplyRemoteCounts ¶
func (r *RateLimiter) ApplyRemoteCounts(remote map[string]int)
ApplyRemoteCounts publishes a decoded broadcast. Ownership of the map is transferred to the limiter: the caller must not mutate it after this call.
func (*RateLimiter) Cleanup ¶
func (r *RateLimiter) Cleanup()
Cleanup removes stale client entries (call periodically).
func (*RateLimiter) ClusterEnabled ¶
func (r *RateLimiter) ClusterEnabled() bool
ClusterEnabled reports whether gossip has enabled distributed admission.
func (*RateLimiter) ClusterFreshness ¶
func (r *RateLimiter) ClusterFreshness() ClusterRateLimitStatus
ClusterFreshness computes the current freshness state. Safe to call from any goroutine and from a scrape handler.
func (*RateLimiter) Configure ¶
func (r *RateLimiter) Configure(limit int, window time.Duration)
Configure updates limit and window without clearing retained counts.
func (*RateLimiter) Enabled ¶
func (r *RateLimiter) Enabled() bool
Enabled reports whether local rate limiting is configured.
func (*RateLimiter) ExportHotDeltas ¶
func (r *RateLimiter) ExportHotDeltas() []HotCount
ExportHotDeltas returns current in-window counts for IPs at or above HotThresholdPercent of the configured limit. It expires old timestamps but does not reset counts: repeated exports without new requests return the same count.
func (*RateLimiter) IsExempt ¶
func (r *RateLimiter) IsExempt(ip string) bool
IsExempt returns true if the IP is in the rate-limit exempt list.
Reads ONE atomic pointer and takes no lock: this is the first decision on every proxied request once a rate limit is configured, and an RWMutex.RLock is an atomic read-modify-write on a single shared word, so the previous shape made every request in the process contend on one cache line. The CIDR half is answered by prefixSet, so its cost no longer scales with the length of the operator's exempt list — measured on a 4-core Xeon, the linear scan it replaces cost 3.6 µs per request at 256 exempt CIDRs, which was ~74% of the entire rate-limit gate.
An entirely empty exempt list — the common posture for a deployment that rate-limits but exempts nothing — short-circuits before the probe address is parsed at all. The pre-view shape parsed it unconditionally and then ran an empty loop, so the parse was pure waste.
func (*RateLimiter) Limit ¶
func (r *RateLimiter) Limit() int
Limit returns the configured request limit.
func (*RateLimiter) ListExemptions ¶
func (r *RateLimiter) ListExemptions() []string
ListExemptions returns all rate-limit exempt list entries.
func (*RateLimiter) ObserveClusterFreshness ¶
func (r *RateLimiter) ObserveClusterFreshness() FreshnessObservation
ObserveClusterFreshness records a transition once per stale episode. The caller owns logging and must serialize observation/rendering as the gossip loop does. No clock, logger, transport or background worker is installed.
func (*RateLimiter) RemoteIPCount ¶
func (r *RateLimiter) RemoteIPCount() int
RemoteIPCount reports the last broadcast's size, even when it is stale.
func (*RateLimiter) RemoveExemption ¶
func (r *RateLimiter) RemoveExemption(entry string)
RemoveExemption removes an IP or CIDR from the rate-limit exempt list.
func (*RateLimiter) ReplaceExemptions ¶
func (r *RateLimiter) ReplaceExemptions(entries []string)
ReplaceExemptions atomically replaces the entire rate-limit exempt list. Invalid entries are skipped; a nil or empty slice clears the exempt list. The new IP/CIDR structures are built OUTSIDE the lock and swapped under a single Lock, so a concurrent IsExempt reader never observes a partial or stale-mixed state. Used by applyConfigBackup for config-version rollback (the missing clear/replace primitive for the RateLimitExempt surface).
func (*RateLimiter) SetClusterEnabled ¶
func (r *RateLimiter) SetClusterEnabled(enabled bool)
SetClusterEnabled selects distributed admission without clearing local history, the last broadcast or diagnostic history. The gossip loop owns this switch.
func (*RateLimiter) Window ¶
func (r *RateLimiter) Window() time.Duration
Window returns the configured sliding-window duration.