mirror of
https://github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin.git
synced 2026-09-02 20:28:50 +02:00
* ♻️ cidr: build keys through net.IPNet instead of hand-masking bytes CIDRKeys masked the address byte by byte and formatted the result with string concatenation, while SetCIDR/DeleteCIDR format their keys with net.IPNet.String() via NormalizeCIDR. The two agreed only by coincidence: any divergence in formatting silently stops every range decision from matching, with no test covering the invariant. Mask with net.IP.Mask and format through net.IPNet.String() so both sides go through the same formatter. Output is byte for byte identical to the previous implementation (checked against a golden dump of both IPv4 and IPv6 keys, including ::ffff: forms). Dropping the inner byte loops also removes the only intrange violation in the tree, so the linter exclusion added for them is no longer needed, and the redundant import alias on pkg/ip goes away with it. * ⚡ cidr: only probe the prefix lengths that have a decision In stream mode nothing caches a negative result per IP, so the exact IP lookup misses on every legitimate request and each one fell through to GetCIDR, which probed every possible prefix length: 33 cache reads for an IPv4 client, 129 for an IPv6 one, even when no range decision existed at all. On the local cache that is wasted work on the request path; with redis it is 33 to 129 sequential round trips per request. Keep the set of prefix lengths that have at least one decision under a single key, written before the decision itself, and probe only those. Measured cache reads per request: 1 with no range decision (was 33 / 129), 2 with a single /24 in use, 4 with four prefix lengths in use. The set only grows, so a deleted or expired decision leaves a length behind that costs one extra read rather than risking an unmatched decision, and it is written with an effectively infinite duration since it has to outlive every decision it describes. If it is ever missing while decisions live (a redis eviction under maxmemory), range decisions stop matching until the next one arrives; it is the hottest key of the namespace, so an LRU policy evicts it last. * 🔊 cidr: log the decisions dropped for an unparsable CIDR SetCIDR and DeleteCIDR returned silently when NormalizeCIDR rejected the value, so a range decision the plugin does not understand is not enforced and nothing says why. Every other operation of the package logs, and this one fails open, which is the direction worth shouting about. Log at Error with the raw value and what the consequence is, so an unexpected decision format shows up in the logs instead of looking like a decision that was applied. * ✅ cidr: cover the invariant the range matching rests on The helpers were tested in isolation but nothing tied them together, and what actually has to hold is that the key SetCIDR writes for a decision is one of the keys GetCIDR looks up for an IP that decision covers. A formatting change on either side would have silently stopped every range decision from matching with all tests green. TestCIDRKeys_MatchNormalizeCIDR pins that both ways, including the cases worth being explicit about: a decision that is not on a network address, IPv4 mapped clients against an IPv4 range, and that the two families do not mix. Dropping the mask in cidrKey fails 9 of its cases. Also covers CIDRLookupKeys against CIDRKeys length by length, the IPv6 side of the network address test, and CIDRPrefixLen. * ✅ cache: cover the CIDR operations and what a lookup costs pkg/cache had tests for Get, Set and Delete but none for their CIDR counterparts, so the range keyspace was only exercised end to end by the e2e scenario. Test_GetCIDR covers hits, the boundaries of a range, IPv6, IPv4 mapped clients and invalid input. Test_GetCIDR_MostSpecific pins the precedence between overlapping decisions, which is deliberate behaviour that nothing was holding in place: a captcha on a /24 is not overruled by a ban on its /8. Test_DeleteCIDR checks the wider decision survives a narrower one being removed, and Test_SetCIDR_InvalidIsNotStored that a rejected value stores nothing at all. Test_GetCIDR_Reads counts cache reads through an isolated cacheInterface, so the cost of a lookup is part of the contract: probing every prefix length again turns it into 34 reads for IPv4 and 130 for IPv6 and fails. * 🐛 e2e: stop racing the deadline in the stream failure check handleStreamTicker compares updateFailure to updateMaxFailure before incrementing it, so with updateMaxFailure 2 and a 1s interval the bouncer gives up on the third consecutive failed poll, roughly 3s after the endpoint starts failing. The check slept 2s and then polled for a 200 for up to 15s, leaving about a second of margin, and once that window closes it never reopens: a runner under load turns this into a 15s wait followed by a failure. Assert the 200 immediately after the endpoint starts failing, which is always inside the window, and keep polling for the 403 that follows. * 🐛 e2e: do not fail a scenario on a single slow response The new -m 1 is right for the polling helpers, where a timed out request is just another attempt, but the assertions and the mock control plane have no retry: one request that takes over a second on a loaded runner fails the scenario, and since common.sh runs under set -euo pipefail a timed out lapi_add_decision aborts it before the decision even exists. Bound the connect at 1s instead and give the whole request 5s in the seven places that get a single attempt. Nothing waits longer on the happy path. * ⏪ e2e: restore the stream-mode failure check Revert99673b1. The check is not ours to change: it must stay as it was. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * 🔥 e2e: drop the comment above wait_for_status The timeout change in3f78887stands; only the comment goes. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
1ba556e918
commit
955391671c
+60
-23
@@ -2,38 +2,45 @@ package ip
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
maxIPv4PrefixLen = 32
|
||||
maxIPv6PrefixLen = 128
|
||||
)
|
||||
|
||||
// CIDRKeys returns all possible CIDR prefixes of an IP, from the most specific (/32 for IPv4, /128 for IPv6) to the least specific (/0).
|
||||
func CIDRKeys(ipStr string) []string {
|
||||
ip := net.ParseIP(ipStr)
|
||||
if ip == nil {
|
||||
parsed, maxBits := parseForPrefix(ipStr)
|
||||
if parsed == nil {
|
||||
return nil
|
||||
}
|
||||
ip4 := ip.To4()
|
||||
if ip4 != nil {
|
||||
keys := make([]string, 0, 33)
|
||||
for bits := 32; bits >= 0; bits-- {
|
||||
mask := net.CIDRMask(bits, 32)
|
||||
n := make(net.IP, 4)
|
||||
for i := 0; i < 4; i++ {
|
||||
n[i] = ip4[i] & mask[i]
|
||||
}
|
||||
keys = append(keys, n.String()+"/"+strconv.Itoa(bits))
|
||||
}
|
||||
return keys
|
||||
keys := make([]string, 0, maxBits+1)
|
||||
for bits := maxBits; bits >= 0; bits-- {
|
||||
keys = append(keys, cidrKey(parsed, bits, maxBits))
|
||||
}
|
||||
ip16 := ip.To16()
|
||||
keys := make([]string, 0, 129)
|
||||
for bits := 128; bits >= 0; bits-- {
|
||||
mask := net.CIDRMask(bits, 128)
|
||||
n := make(net.IP, 16)
|
||||
for i := 0; i < 16; i++ {
|
||||
n[i] = ip16[i] & mask[i]
|
||||
return keys
|
||||
}
|
||||
|
||||
// CIDRLookupKeys returns the keys of the CIDRs containing an IP for the given prefix lengths
|
||||
// only, most specific first. Duplicates and lengths of the other family are skipped.
|
||||
func CIDRLookupKeys(ipStr string, prefixLens []int) []string {
|
||||
parsed, maxBits := parseForPrefix(ipStr)
|
||||
if parsed == nil {
|
||||
return nil
|
||||
}
|
||||
var wanted [maxIPv6PrefixLen + 1]bool
|
||||
for _, bits := range prefixLens {
|
||||
if bits >= 0 && bits <= maxBits {
|
||||
wanted[bits] = true
|
||||
}
|
||||
}
|
||||
keys := make([]string, 0, len(prefixLens))
|
||||
for bits := maxBits; bits >= 0; bits-- {
|
||||
if wanted[bits] {
|
||||
keys = append(keys, cidrKey(parsed, bits, maxBits))
|
||||
}
|
||||
keys = append(keys, n.String()+"/"+strconv.Itoa(bits))
|
||||
}
|
||||
return keys
|
||||
}
|
||||
@@ -46,3 +53,33 @@ func NormalizeCIDR(cidrStr string) string {
|
||||
}
|
||||
return ipNet.String()
|
||||
}
|
||||
|
||||
// CIDRPrefixLen returns the prefix length of a CIDR, or -1 if it is not a valid CIDR.
|
||||
func CIDRPrefixLen(cidrStr string) int {
|
||||
_, ipNet, err := net.ParseCIDR(strings.TrimSpace(cidrStr))
|
||||
if err != nil {
|
||||
return -1
|
||||
}
|
||||
prefixLen, _ := ipNet.Mask.Size()
|
||||
return prefixLen
|
||||
}
|
||||
|
||||
// parseForPrefix returns the IP in the native form of its family, and that family's bit length.
|
||||
func parseForPrefix(ipStr string) (net.IP, int) {
|
||||
parsed := net.ParseIP(ipStr)
|
||||
if parsed == nil {
|
||||
return nil, 0
|
||||
}
|
||||
if parsed4 := parsed.To4(); parsed4 != nil {
|
||||
return parsed4, maxIPv4PrefixLen
|
||||
}
|
||||
return parsed.To16(), maxIPv6PrefixLen
|
||||
}
|
||||
|
||||
// cidrKey builds the key of the CIDR of bits length containing the IP.
|
||||
// It formats through net.IPNet like NormalizeCIDR, so writes and lookups agree.
|
||||
func cidrKey(parsed net.IP, bits, maxBits int) string {
|
||||
mask := net.CIDRMask(bits, maxBits)
|
||||
ipNet := net.IPNet{IP: parsed.Mask(mask), Mask: mask}
|
||||
return ipNet.String()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user