* ⚡ build each trusted IP list once instead of once per router
Traefik builds an entry-point middleware once per router, and every
instance parsed forwardedHeadersTrustedIps and clientTrustedIps twice,
in ValidateParams and then for the pool strategy. NewChecker now returns
the Checker already built for the same list. A Checker is read-only once
built, so the bouncers can share it.
The cache is keyed by the comma-joined list. A list with an entry that
contains a comma is never valid, so it skips the cache and still fails
validation. The cache is emptied when it reaches 64 lists, so lists
replaced over many reloads do not pile up.
Fixes#440.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* 🐛 name the invalid entry in the trusted IPs error
net.ParseCIDR returns a nil network on failure, so the error named
<nil> instead of the entry that failed to parse.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* ⚡ keep at most 16 trusted IP lists in the cache
A configuration uses one to three lists, so 16 still leaves room, and
lists replaced over many reloads hold a quarter of the memory.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* 🐛 print the invalid entry once in the trusted IPs error
The error from net.ParseCIDR already names the entry, so naming it
again printed it twice.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* add crowdsecAppsecTimeoutMilliseconds
Lets the AppSec call time out independently from httpTimeoutSeconds, in milliseconds. Defaults to 0 (falls back to httpTimeoutSeconds).
Refs #388
* Update README.md
Co-authored-by: mathieuHa <mathieu@hanotaux.fr>
---------
Co-authored-by: mathieuHa <mathieu@hanotaux.fr>
* 🐛 Use http_status from appsec response
* 🍱 fix test title
* 🍱 fix README
* 🍱 fix test
* 🍱 apply suggestions from code review
Relay an AppSec ban status only between 200 and 599, README wording, e2e README, typo.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* 🍱 keep the e2e Traefik port consistent
The e2e README says 8089, and traefik.yml takes its port from WEB_PORT so the env override works.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
---------
Co-authored-by: ffluegel
Co-authored-by: mhx <mathieu@hanotaux.fr>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
* 🐛 only read the forwarded header from trusted proxies
When forwardedHeadersTrustedIps is set, the forwarded header is now only
read when the peer address is in that list; any other request is checked
against its peer address. Before, a client reaching Traefik directly could
put any IP in the header (e.g. Cf-Connecting-Ip, which Traefik does not
strip) and be checked against that IP instead of its own.
With an empty list the header is still read from any peer, as before:
Traefik's entrypoint already strips X-Forwarded-For and X-Real-Ip from
untrusted peers. A warning is logged at startup when the list is empty
and another header is configured.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 🍱 remove useless test and move warning in configureation.go
* 🍱 revert bouncer.go
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: maxlerebourg <maxlerebourg@gmail.com>
* 🐛 redirect a captcha submitted again after it was solved
With the captcha open in two tabs, solving it in the first tab and then
submitting it in the second sent that second POST on to the backend,
because the IP had already solved it. A backend that only accepts GET
on that page answered 405.
A form POST that carries the provider's response field, from an IP that
has already solved the captcha, is now redirected to the same URL, like
a captcha that was just solved. This covers both the LAPI and the
AppSec captcha. Only bodies with a Content-Length of at most 64 KiB are
read, and the body is restored for the next handler. Any other request
from that IP goes through as before.
Based on the idea in #374 by svmrw.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 🍱 add testing for e2e captcha
* 🍱 fix README
* 🍱 fix README
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: maxlerebourg <maxlerebourg@gmail.com>
Since crowdsecurity/lua-cs-bouncer#163, lua reads the body of an HTTP/2
request without a Content-Length, only treats gRPC bodies as
unreadable, and defaults APPSEC_DROP_UNREADABLE_BODY to false. The
README entry for crowdsecAppsecUnreadableBodyBlock now states that
difference, and the comments no longer claim parity.
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 🐛 say why AppSec is unreachable
appsecQuery:unreachable was logged without its cause, at any log level.
It now carries the transport error, or the 502, 503 or 504 status
returned by a proxy in front of AppSec.
On such a status, the error returned to block the request read
"%!w(<nil>)", and the response body was never closed, so its connection
was not reused. The body is now drained and closed, as on the other
paths.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* ✅ drop the unreachable reason test
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 🐛 let crowdsecAppsecFailureBlock decide on a 401 or any unexpected AppSec status
AppSec returns 401 when it cannot reach the LAPI to check the bouncer key.
A reverse proxy (Traefik for example) in front of a missing AppSec can return 404 or 503.
This can cause the bouncer to ban every visitor on an unexpected failure.
Like lua-cs-bouncer's APPSEC_FAILURE_ACTION, the crowdsecAppsecFailureBlock option now decides for any unexpected status, not only 500.
Its default stays true, so nothing changes for users who did not set it. A 403 whose body cannot be applied still blocks.
lua-cs-bouncer: https://github.com/crowdsecurity/lua-cs-bouncer/blob/4aad1dfa653d9d96fb5c0114ae930eb2353214c8/lib/crowdsec.lua#L688-L760
Assisted-by: Claude Opus 5.5
* 🍱 best handling for appsec reuse 502-503-504, same for crowdsec
* Update bouncer_test.go
* Update bouncer_test.go
---------
Co-authored-by: maxlerebourg <maxlerebourg@gmail.com>
Co-authored-by: mathieuHa <mathieu@hanotaux.fr>
* ✨ skip the AppSec query for excluded locations
Refs #393.
crowdsecAppsecExcludedLocations lists paths (/healthz, any host) or
host/path entries (registry.example.com/v2/) whose requests are not sent
to AppSec. LAPI decisions still apply. An entry matches its exact path or
anything below it on a / boundary; the host is compared like Traefik's
Host matcher (case-insensitive, without port or trailing dot).
A request is only excluded when its path has a single reading: no
percent-encoding left, no dot or empty segment, no ; \ % * or non-ASCII.
Anything else is inspected as before, so ..;, %2F, double encoding and
similar tricks cannot reach another resource uninspected, whatever
sanitizePath is set to. /crowdsec-internal/challenge/ is always sent to
AppSec.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 🍱 authorize just host and host:port
* 🍱 fix last bugz
* 🍱 fix comments
* 🍱 revert readme update
* 🍱 typo
* Update README.md
Co-authored-by: mathieuHa <mathieu@hanotaux.fr>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: maxlerebourg <maxlerebourg@gmail.com>
A single job runs whoami, Traefik and CrowdSec. CrowdSec is a prestart
sidecar in Traefik's group, so it reads Traefik's access log from the
allocation directory, and a prestart task waits for the LAPI before
Traefik starts. Traefik discovers whoami with the Nomad provider through
the task API socket, using the job's workload identity, which also
reads the bouncer key from a Nomad variable. This works with ACLs on.
The acquisition sets force_inotify: CrowdSec can load it before Traefik
has created its log file, and would then never follow it.
Renovate now also bumps the plugin pin and the image tags in the Nomad
example.
Closes#50
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 🐛 keep the 429 of an AppSec RateLimit() block instead of the ban status
Signed-off-by: Ryo Kusnadi <ryokusnadi@gmail.com>
* Say in README that any AppSec ban with http_status 429 keeps the 429
Signed-off-by: Ryo Kusnadi <ryokusnadi@gmail.com>
---------
Signed-off-by: Ryo Kusnadi <ryokusnadi@gmail.com>
The example no longer installs: the CrowdSec image tag v1.8.1-2 does not
exist, the README pins Traefik chart v28.0.0 while the values target
the current chart, and the plugin is still on v1.7.1.
- Pin both charts in the README (crowdsec 0.24.2, traefik 42.2.0) and let
each chart pick its image, instead of overriding image.tag.
- Register the bouncer with BOUNCER_KEY_traefik from a secret and read it
in Traefik with crowdsecLapiKeyFile, as in CrowdSec's own Traefik guide.
- Enable AppSec, stream mode, containerd log parsing, JSON access logs that
keep only User-Agent, and externalTrafficPolicy: Local.
- Move to plugin v1.8.1 and the chart 42 values layout (log, accessLog).
- Drop the unreferenced crowdsec/service.yml and traefik/dashboard.yml.
- Renovate: track the two chart versions in the README instead of the
image tags, whose regex kept the "-2" suffix of v1.6.1-2.
Closes#258
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Fixes#411.
A client reaching Traefik over a link-local IPv6 address has a
RemoteAddr like [fe80::1%eth0]:1234. net.SplitHostPort keeps the zone,
net.ParseIP rejects it, and ServeHTTP bans every such request with
reason TECH before the trusted IP check or any CrowdSec lookup.
GetRemoteIP now drops the zone, both from RemoteAddr and from forwarded
header entries, the same way Traefik's forwarded headers middleware does
for X-Real-Ip. The address used for the trusted IP check, the cache key,
the LAPI query and AppSec is a plain IP again.
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 🐛 do not ban a request whose client aborted the body upload
Fixes#395.
When AppSec buffers the request body and the read fails, appsecQuery
returned an error and handleNextServeHTTP turned it into a ban: a 403
with reason APPSEC, counted in the blocked requests pushed to LAPI.
The usual cause is a client that cancels an upload. CrowdSec never saw
the request, and none of the *Block options applied.
A failed body read now answers 499 when the request context is
cancelled (client gone, as Traefik's own proxy reports it) and 400
otherwise. It is no longer a ban, uses no ban page and is not counted.
The request was never forwarded on the old path either, so this is not
a fail-open and needs no new option. Real AppSec blocks still ban.
The 400 case is not theoretical: an HTTP/3 client that resets only its
upload stream fails the read without cancelling the context. Checking
the context alone would still ban there, and the h2/h3 error types
cannot be matched from the plugin.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* ✅ add a short test for client body read errors
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 🐛 ban LAPI decisions of an unknown type, such as challenge
In stream mode a decision whose type is neither ban nor captcha was
cached as an empty value, which reads back as a cache miss, so the
request was allowed. The challenge protocol says a challenge decision
from the LAPI or a blocklist carries nothing to serve and must fail
closed to ban, and CrowdSec's own bouncer falls back to ban for any
type it does not support.
Unknown types are now cached as a ban in both modes. Live mode already
banned them, but it never cached them, so it queried the LAPI again on
every request.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 🐛 log unexpected AppSec statuses at INFO
A 401 or any other unexpected AppSec status was turned into a ban
and only logged at DEBUG, in handleNextServeHTTP. AppSec answers
401 when it rejects the bouncer key, and also when it cannot reach the
LAPI to validate a key it has not cached yet. With the default INFO
logs, every visitor was then banned with no trace in the plugin logs.
The status is now logged at INFO, as a 500 already is. The behaviour
does not change, and the README now states it: such a status always
blocks, whatever crowdsecAppsecFailureBlock says, and a 502, 503 or
504 counts as unreachable.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 🐛 serve the captcha when AppSec answers with a captcha action
Any AppSec action other than allow or challenge was turned into a
ban, so a captcha remediation from AppSec (set by a rule or a hook)
banned the visitor. The challenge protocol says to apply the action
AppSec returns, and CrowdSec's own bouncer serves the captcha.
A captcha action now uses the configured captcha the same way a LAPI
captcha decision does: an IP that already solved it goes through,
and other requests get the captcha page. The form posts back to the
same URL, so it is validated when AppSec answers that post with a
captcha again. Without a provider, or for a HEAD request, it falls
back to ban as before. The decision handling moves to its own method
so that it does not loop back into the AppSec query.
In crowdsecMode appsec, New returned before setting up the cache and
the captcha client, so the captcha could never be served there. It
now returns after them. Without captchaProvider nothing changes.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 🐛 never forward /crowdsec-internal/challenge/* to the backend
The plugin relied on AppSec to answer the internal challenge paths.
When AppSec did not, the request went on to the backend: AppSec allows
the custom script path when no custom script is configured, and every
path passes when the plugin fails open because AppSec is unreachable
or failing. The challenge protocol requires the remediation component
to terminate these paths and never pass them to the origin.
With AppSec enabled, a request under that prefix that AppSec did not
answer now gets a 404.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 🐛 count a challenge once in the blocked requests, not its assets
Every challenge response counted as a dropped request in the metrics
pushed to the LAPI: the page, the fingerprint and proof-of-work
scripts, and the proof submission, even a successful one. A visitor
who passed the challenge showed up as four blocked requests.
Responses on /crowdsec-internal/challenge/* are part of a challenge
that was already counted, so only the challenge page counts now.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 📝 document that bot detection needs the challenge submission body
The challenge proof is posted to /crowdsec-internal/challenge/submit,
and AppSec only accepts it if it receives the whole form. With
crowdsecAppsecBodyLimit set to 0 the plugin sends no body, and with a
smaller limit the form is cut short. In both cases the proof is
rejected and the visitor is challenged forever, with nothing in the
logs to explain it. The default of 10MB is enough.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 🐛 fail an AppSec challenge without a body closed, and replace its headers
Fixes#397.
A challenge envelope without user_body_content was relayed as its
http_status with an empty body, so the visitor got a blank 200 instead of
being blocked. The challenge protocol requires failing that case closed.
appsecQuery now rejects it, and it ends in the ban response like any
other malformed AppSec answer.
user_headers were added next to any header already on the response, so a
policy set earlier left two Content-Security-Policy values and the
browser enforced both. They now replace headers of the same name, as the
protocol asks, while each user_cookies entry stays its own Set-Cookie.
Traefik's headers middleware sets its CSP as the response is written, so
when it is listed before the bouncer it still overrides the challenge
policy whatever the plugin does. Checked on Traefik 3.7.9. The README now
says to list the bouncer first.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 📝 explain the challenge Content-Security-Policy and the middleware order
The previous paragraph read as if the plugin's header replacement
should win against Traefik's headers middleware, and it did not say
what breaks or how to keep security headers on the challenge page.
It now states what the challenge needs, the symptom when it is
blocked, and why a headers middleware listed before the bouncer
overrides the policy: it applies its headers when the response is
written, after the plugin. The recommended setup keeps the CSP in a
headers middleware after the bouncer and other security headers
before it. Checked on Traefik 3.7.13, where the challenge keeps its
policy and still gets X-Frame-Options. Links CrowdSec's own CSP
guidance and the protocol requirement. The "See examples" line goes
back under the /crowdsec-internal section, where it was on main.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* 🍱 reduce readme modif
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: maxlerebourg <maxlerebourg@gmail.com>
Traefik runs the plugin under yaegi, which shares the case list of a
select statement between every goroutine that runs it. Both ticker
loops ran the same select, so when the tickers fired together one loop
could end up waiting on the other's channel, dropping stream ticks for
up to two metrics intervals.
Range over the ticker channel instead, which yaegi evaluates per
execution. The stop channel was never used.
Fixes#377
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* add the bot detection feature to the crowdsec traefik bouncer
* fix the return value
* add http status normalization
* fix appsec query test return values
* add boundaries for appsec response
* 🎨 satisfy golangci-lint on the appsec response path
gofmt on bouncer_test.go (merge artifact), a doc comment revive requires
on the exported AppSecResponse, and nolint directives for the linters the
new appsecQuery signature trips: tagliatelle on the snake_case json tags
that are Appsec's wire format, and nilnil/gocognit/gocyclo/funlen on
appsecQuery itself, matching how New is already handled.
No feature code changed.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* 🐛 keep serving the configured ban page for appsec bans
An appsec "ban" with a structured body was served straight from appsec,
so an operator with banFilePath configured silently lost their ban page
as soon as Crowdsec 1.8 started returning structured JSON — and got a
blank 403 when appsec sent no user_body_content at all. Route the ban
action back through handleBanServeHTTP, which keeps the template, the
content type, the remediation header value and the trace templating.
Only actions that must carry their own content, challenge among them,
are relayed from appsec. Those now fall back to banTemplateContentType
when appsec sends no Content-Type, instead of letting Go sniff it.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* 🍱 reduce test and logic in appsec query
* 🍱 use same appsec response limit as defined for user
* 🍱 fix lint
* 🐛 fix tests
* 🍱 revert to 1Mo appsec response body
* 📝 examples: add a bot detection example
The PR relays the whole AppSec remediation rather than collapsing it into a
403, which is what makes the bot challenge possible: a ban is a status code,
a challenge is a status code plus a body, cookies and headers. Nothing
demonstrated that, so this adds an example alongside the existing ones.
Verified end to end against CrowdSec 1.8.1: the challenge page is served, the
browser solves the proof of work, the submission is accepted and the request
reaches the backend.
Three things break this setup silently, and all three cost time here, so the
README names them:
- The router must also match /crowdsec-internal. The challenge page loads its
fingerprint script and its proof-of-work worker from there by absolute path,
so a router scoped to the application prefix alone returns 404 and the
challenge can never be solved, with no error logged anywhere.
- The acquisition must load the config that calls SendChallenge(), which is
appsec-bot-challenge-scoring; the -balanced variant only carries the
rejection threshold. Loading the latter alone processes requests and
challenges nothing. The wildcard form from the CrowdSec enable guide is used
instead of a hand-written list, since it also picks up the exclusion configs
the collection ships.
- Referencing an appsec-config that is not installed is fatal rather than
degraded. CrowdSec refuses to start and, because crowdsecAppsecFailureBlock
defaults to true, every request then returns a 403 that reads like a WAF
decision. appsec-default needs appsec-virtual-patching and
appsec-generic-rules, so both are in COLLECTIONS.
The routing requirement is in the main README too, since it applies to anyone
enabling bot detection and not just to this example.
The example runs the plugin from the working tree, as relaying the remediation
is not in a release yet; the catalog lines are present and commented out.
* 🍱 reduce complexity and set the remediationHeader to 'challenge' instead of decision.Action
* 📝 examples: add a bot detection example
The PR relays the whole AppSec remediation rather than collapsing it into a
403, which is what makes the bot challenge possible: a ban is a status code,
a challenge is a status code plus a body, cookies and headers. Nothing
demonstrated that, so this adds an example alongside the existing ones.
Verified end to end against CrowdSec 1.8.1: the challenge page is served, the
browser solves the proof of work, the submission is accepted and the request
reaches the backend.
Two things break this setup silently, and both cost time here, so the README
names them:
- The router must also match /crowdsec-internal. The challenge page loads its
fingerprint script and its proof-of-work worker from there by absolute path,
so a router scoped to the application prefix alone returns 404 and the
challenge can never be solved, with no error logged anywhere.
- The acquisition must load the config that calls SendChallenge(), which is
appsec-bot-challenge-scoring; the -balanced variant only carries the
rejection threshold. Loading the latter alone processes requests and
challenges nothing. The wildcard form from the CrowdSec enable guide is used
instead of a hand-written list, since it also picks up the exclusion configs
the collection ships.
The routing requirement is in the main README too, since it applies to anyone
enabling bot detection and not just to this example, along with the supported
versions stated the same way as the existing Appsec line.
* ✅ tests: drop the challenge Content-Type fallback test
c8d7751 removed the fallback that set Content-Type from banTemplateContentType
when the appsec response carried none, but left the test asserting it, so the
suite has been red since.
Removing the test rather than restoring the fallback, per maxlerebourg.
* 🍱 harmonize appsecServer vs appsec in test
* 🍱 reduce loc and go closer to Lua implementation
* 💄 fix log statusCode 401 -> 403
* 🍱 fix lint
* 🍱 add guard on appsec response
* 🍱 fix lint
---------
Co-authored-by: mhx <mathieu@hanotaux.fr>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: maxlerebourg <maxlerebourg@gmail.com>
* Disable request blocking when CrowdSec is unavailable in live mode.
* 📝 document the live-mode behaviour and cover it with tests
The README said UpdateMaxFailure is "used only in stream and alone mode",
which this branch makes untrue, so the feature was undiscoverable from the
docs. It now also records that -1 is the only value with any effect in live
and none mode, since that path has no failure counter.
Test_handleNoStreamCache had a TODO and no cases, so this path had no
coverage in either direction. Adds four: live blocks at the default and at
any positive value, live lets the request through at -1, and none does the
same. The last two fail without the three-line change in this branch.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: mhx <mathieu@hanotaux.fr>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* 🐛 do not drop bodyless DELETE over HTTP/3
Fix#385.
Over HTTP/3 a bodyless request cannot be told apart from one carrying an
unreadable body. Go's HTTP/2 server can make that distinction -- it only sets
ContentLength to -1 when the client left the stream open for DATA frames, so a
request that ends at the headers keeps ContentLength 0 and isBodyUnreadable
stays false (x/net/http2/server.go, `bodyOpen := !f.StreamEnded()`). quic-go has
no equivalent: http3/server_conn.go assigns req.Body unconditionally and
http3/headers.go defaults ContentLength to -1 whenever the Content-Length header
is absent, so every bodyless HTTP/3 request looks unreadable regardless of
method.
With DELETE in isMethodWithBody, that turns an ordinary
fetch(url, {method: "DELETE"}) into a 403 on HTTP/3 while the same call succeeds
on HTTP/2. dani reported this on #352 before it was merged.
A DELETE body is legal but has no defined semantics (RFC 9110 9.3.5), and the
gRPC streams #323/#332 guard against are always POST, so dropping DELETE from
the list costs no protection there. Note this diverges from lua-cs-bouncer's
METHODS_WITH_BODY, which still lists DELETE; the same false positive likely
applies there.
Adds Test_appsecQuery_unreadableBodyMethods, which pins the behaviour for all
seven methods and fails on the previous code for DELETE. isMethodWithBody had no
direct coverage before.
* 🍱 Mutualize new utils
---------
Co-authored-by: maxlerebourg <maxlerebourg@gmail.com>
* 🐛 keep the stream lease alive when updateIntervalSeconds is 1
handleStreamCache takes a lease so a single node polls LAPI per interval,
and stores it for updateInterval-1 seconds. The e2e stream scenario now
sets updateIntervalSeconds to 1, which makes that a 0 second duration:
golang-ttl-map returns early on a zero ttl (map.go:114) and redis rejects
a non positive EX, so the lease is never stored and the guard silently
does nothing.
Floor the duration at 1 second. At an interval of 1 the lease can survive
a tick that fires slightly early and cost one skipped poll, which is far
better than every node polling every tick against a shared redis.
* Adjust lease duration to prevent cache update conflicts
Updated lease duration logic to ensure a minimum of 1 second.
---------
Co-authored-by: maxlerebourg <maxlerebourg@gmail.com>
* ✨ cicd: bump the version before tagging instead of after
The version reported to the Crowdsec LAPI lives in version.go, so it must
be correct in the very commit the tag points at. Every mechanism so far
updated it *after* the tag existed, which cannot work:
- release.yml ran on `release: published` and force-moved the tag. It also
failed on all four of its runs and was removed in #360.
- The Renovate customManager on version.go uses the github-tags datasource,
so it can only propose vX once vX is already tagged. The bump always lands
after the tag.
Result: v1.7.0 is tagged at a commit reading v1.6.0 (#363), same shape as
the earlier #322.
Replace both with a two-step flow that bumps first and tags last, so the
released source always matches its tag.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* 🍱 reduce loc + remove claude code comment
* 🍱 remove useless spellcheck disable
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: maxlerebourg <maxlerebourg@gmail.com>
* feat: Allow cache reading from replicas
* 🍱 fix logic
* ✨ add testing for redis with mock
* 🍱 fix permission
* 📝 test(e2e/redis): fix swapped IP→verdict comments
The mock returns "f" (not banned) for 1.2.3.4 and "t" (banned) for
1.2.3.5, and the run.sh assertions match that. Both doc comments
described the opposite mapping; correct them to match the code.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* ✅ test(e2e/redis): exercise read-from-replica path
The redis scenario only set redisCacheHost, so it validated the writer
but never the round-robin reader path this feature adds. Split the mock
into two roles: the primary (--redis-addr) now answers every GET with a
miss, while the replica (--redis-read-addr) serves the hardcoded
verdicts. The scenario points redisCacheReadHosts at the replica (twice,
to drive round-robin), so the banned-IP-blocked assertion only passes if
the plugin actually reads decisions from the replica rather than the
primary.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* 📝 docs: note replicas don't fall back to primary on outage
When RedisCacheReadHosts is set, reads are not retried against the
primary if the replicas are unreachable. Document that this, combined
with the default RedisCacheUnreachableBlock=true, means a replica outage
can block traffic while the primary is healthy.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* 🐛 fix(cache): avoid nil-pointer panic on empty redis read
redisCache.get fell through to `switch err.Error()` when Get returned a
nil error with an empty value, panicking on the nil error. simpleredis
never returns that combination today (a miss yields RedisMiss), so it
was unreachable in practice — but the read path is safer treating an
empty, error-free read as a cache miss, which also guarantees err is
non-nil before err.Error() is called.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* 🍱 add test for rotation
* 🐛 readd redis/run.sh
* 🐛 fix redis/run.sh
* 🐛 fix test label; remove log
* 🍱 add tests for roundRobin
* 🐛 fix test
---------
Co-authored-by: maxlerebourg <maxlerebourg@gmail.com>
Co-authored-by: mhx <mathieu@hanotaux.fr>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Do not consider body unreadable when it's http.NoBody
Fix#351
* 🐛 appsec: only drop unreadable bodies for methods that carry one
Gate the crowdsecAppsecUnreadableBodyBlock drop on the request method,
mirroring the reference lua-cs-bouncer METHODS_WITH_BODY list
(POST/PUT/PATCH/DELETE). Browser GETs over HTTP/3 never carry a
Content-Length (quic-go always wraps the stream in a non-nil body with
ContentLength -1), so they were all wrongly dropped; they are now
forwarded to appsec headers-only, while gRPC streams (always POST) stay
droppable.
Fix#351
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* 🍱 add test and remove useless comment
* 🍱 add test for GET with unreadable body
* 🍱 fix log
* 🍱 fix test
---------
Co-authored-by: mhx <mathieu@hanotaux.fr>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: maxlerebourg <maxlerebourg@gmail.com>
The 2026-07-03 runs surfaced two config problems:
- The grouped "renovate/all" branch made Renovate fetch and hold the
changelog of every upgrade instance separately (Traefik v3.0.0->v3.7.6
was fetched ~10x, once per compose file), which blew the default 4GB
V8 heap: "FATAL ERROR: ... JavaScript heap out of memory" (exit 134),
killing the run after the branch was pushed but before the PR was
opened. Disable changelog fetching (release notes were truncated in
the grouped PR body anyway) and raise the Node heap to 8GB as a
safety net.
- No gitAuthor was set, so commits were authored as Mend's
renovate@whitesourcesoftware.com, which GitHub flags "Unverified"
(Vigilant Mode) and Renovate warns about on every run. Use the token
owner's noreply address instead.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* ⬆️ bump example image versions to latest stable
Align every docker-compose and Helm-values example on the same set:
- Traefik v3.0.0 / v3.5.0 → v3.7.1
- Crowdsec v1.6.1-2 / v1.6.8 / latest → v1.7.8
- Plugin pin v1.3.0 / v1.4.5 / v1.5.0 → v1.6.0
No env / volume changes needed: every Crowdsec example already mounts
/var/lib/crowdsec/data, so the v1.7 strict volume check is already
satisfied (CROWDSEC_BYPASS_DB_VOLUME_CHECK is only required when
running without persistence, as in the E2E suite).
* 🤖 chore: adopt Renovate (weekly, self-hosted) to replace manual version bumps
Automate the kind of bump this PR did by hand. Renovate covers what Dependabot
could not reach here:
- example docker-compose image tags (traefik / crowdsec) — native manager;
- the plugin self-pin (`experimental.plugins.bouncer.version=` in compose args
and `version:` in the Traefik Helm values) — customManager, github-tags;
- the Crowdsec/Traefik image tags in the Helm values (no `repository` key, so
matched by file) — customManager, docker;
- the pinned Traefik binary in the e2e mock suite (`TRAEFIK_VERSION`) —
customManager, github-releases;
- go.mod + GitHub Actions — native managers (this is why we drop Dependabot:
running both would open duplicate PRs).
Runs weekly via a self-hosted workflow (Mondays 04:00 UTC, plus manual
dispatch). Needs a RENOVATE_TOKEN secret (documented in the workflow). Renovate
PRs trigger the existing e2e CI, so a Traefik/Crowdsec bump is validated to
actually boot and bounce before merge.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* 🔒 ci: pin Go to 1.22 (yaegi ceiling) and cap Renovate's Go updates
The plugin is interpreted by yaegi, bundled in Traefik. Even the latest Traefik
(v3.7.1) ships yaegi v0.16.1, which only supports Go 1.22 — so the plugin's real
ceiling is Go 1.22 on every current Traefik, regardless of the Go version
Traefik itself is built with.
- main.yml: build/test on Go 1.22 (was 1.23) so `go build`/`go test` reject
newer stdlib early; yaegi v0.16.1 stays the required yaegi_test guard.
- renovate.json: cap the go.mod `go`/`toolchain` directive at `<1.23` so
Renovate keeps deps/actions/toolchain current but never pushes the plugin
past what yaegi supports. Raise the cap when Traefik ships a newer yaegi.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* 🐛 ci(renovate): stop ignoring examples/ and tests/ so custom managers run
config:recommended ships a default ignorePaths that excludes **/examples/**
and **/tests/** (and **/vendor/**). That silently disabled 4 of the 5 custom
managers and all example/helm coverage this PR adds — Renovate only saw the
root docker-compose, go.mod and workflows.
Override ignorePaths to keep only vendor/node_modules. Verified via
`renovate --platform=local --dry-run=full`: package files detected go from
7 -> 32, and every custom manager now extracts its dep (plugin self-pin
across 11 compose files, traefik/crowdsec helm tags, e2e TRAEFIK_VERSION pin).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* ⏪ chore: drop one-time example version bumps, let Renovate own them
The manual version catch-up across the example docker-compose files and the
Helm values is now redundant: Renovate (this PR) covers all of them via its
native docker-compose/docker managers plus the custom managers for the plugin
self-pin and the e2e Traefik binary. Reverting these files to keep the PR a
clean "adopt Renovate" change; Renovate will open the bump PRs itself.
Note: examples/tls-auth uses crowdsecurity/crowdsec:latest again — Renovate
does not pin rolling tags, so that one stays floating unless pinned separately.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* 📌 examples(tls-auth): pin crowdsec to v1.6.8 instead of :latest
Rolling `latest` tags aren't reproducible and Renovate can't manage them.
v1.6.8 is already the crowdsec tag used in the root docker-compose files and,
unlike the `-2` build-suffixed tags, Renovate bumps it (→ v1.7.8).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* 📌 examples: normalize crowdsec v1.6.1-2 -> v1.6.8 so Renovate can manage it
Renovate's docker versioning won't advance a build-suffixed tag (v1.6.1-2) to
a clean release (v1.7.8), so those 8 examples would have stayed frozen. v1.6.8
is already used in the root compose files and Renovate bumps it. Also updated
the captcha README snippet to match its compose.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* 🍱 group all + no dashboard + branch prefix
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: maxlerebourg <maxlerebourg@gmail.com>
* 🐛 fix appsec silently 403-ing gRPC streams with unreadable body
A bidirectional gRPC stream is an HTTP/2 request with no Content-Length
whose body never reaches EOF. Since #321 removed the ContentLength guard,
appsecQuery buffered it with io.ReadAll, which blocked until the request
timed out and was turned into a 403 (issue #323). The backend was never
reached (OriginStatus:0).
Mirror the reference lua-cs-bouncer behaviour: detect an unreadable body
(ProtoMajor >= 2 && ContentLength < 0) and, instead of buffering it,
forward the request to Appsec with headers only. Add a new
CrowdsecAppsecDropUnreadableBody option (default false) that mirrors the
reference APPSEC_DROP_UNREADABLE_BODY: when true, such requests are
blocked outright instead of forwarded without their body.
Readable HTTP/1.1 bodies are still buffered and inspected, so the bypass
closed by #321 stays closed.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* 🚨 appsec: satisfy linters (gocritic ifElseChain, misspell)
Rewrite the body-handling if/else chain in appsecQuery as a switch
(gocritic) and use US spelling "behavior" (misspell).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* 🔇 appsec: drop redundant unreadable-body debug log
Address review on #332: the caller (handleNextServeHTTP) already logs the
returned error with the request IP, so the inner Debug line duplicated it.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* 🍱 increase gocyclo
* 🍱 fix lint
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: maxlerebourg <maxlerebourg@gmail.com>
* Consider 502, 503 and 504 as unavaible for appsec
Fixes#337
* ✨ add test and the function isReverseProxyError
---------
Co-authored-by: maxlerebourg <maxlerebourg@gmail.com>
* Add parameter to configure Ban Response Content-Type
* Add testing for new BanResponseContentType parameter
* Ensure there is a fallback to default Content-Type is user provided empty value
* Set Content-Type even if banTemplate is nil
* Add more edge cases for testing ban response Content-Type
* Add CR/LF validation for BanResponseContentType
* Add CaptchaResponseContentType to allow separate Content-Type configuration for captcha responses
* Add testing for new CaptchaResponseContentType
* Update README
* Split nil and CR/LF response Content-Type value validation into separate function
* Throw error instead of setting the default in case of empty parameter declaration
* Update testing accordingly
* ✨ remove HTML from var name, add tests and infer content type from filePath
* 🍱 fix lint ?
* 🍱 fix lint
* 🍱 fix lint
* 🍱 fix lint + naming
* 🍱 fix lint
* 🍱 fuck lint
---------
Co-authored-by: maxlerebourg <maxlerebourg@gmail.com>
* 🐛 fall back to system trust store when no custom TLS CA is set
Closes#327.
Until now, configuring `crowdsecLapiScheme=https` forced the operator
to either provide `crowdsecLapiTLSCertificateAuthority` (a custom CA)
or set `crowdsecLapiTLSInsecureVerify=true` — there was no way to rely
on the host's system trust store, which is the expected setup when the
LAPI sits behind a reverse proxy with a publicly trusted (e.g. Let's
Encrypt) certificate.
Two contributing bugs:
- `validateParamsTLS` rejected an empty CA up-front.
- `getTLSConfig` always allocated an empty `tls.Config.RootCAs`,
which silently disabled the standard library's fall-back to
`x509.SystemCertPool()`.
Fix: drop the validation error for the empty-CA case and only allocate
`RootCAs` when a custom CA is actually provided. Same change applies
symmetrically to the AppSec path since the helper is shared.
Add unit tests covering the four meaningful states (HTTP, HTTPS with
system CA, HTTPS with custom CA, HTTPS with insecure verify) plus the
malformed-PEM rejection. README updated to document the system trust
store as an explicit option for both LAPI and AppSec HTTPS.
* 📝 fix gofmt alignment in TLS test struct
* ✅ update existing test: https without CA is now accepted
* ♻️ tests: hoist shared validPEM to package level, rename cfgGarbage
Address review on #331:
- the self-signed validPEM block was duplicated in two test funcs; declare it
once at package level and drop both local copies.
- rename cfgGarbage -> cfgInvalidCA (and its test case) for a descriptive name.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* ✅ e2e mock: add tls-system-ca scenario (HTTPS LAPI via system trust store)
CI regression coverage for this PR: with no custom CA configured, the bouncer
must fall back to the OS/system trust store for an HTTPS LAPI.
In the binary suite the "system trust store" is whatever Go's
x509.SystemCertPool() reads, which honours SSL_CERT_FILE on the Traefik process.
The scenario mints a throwaway CA, serves the mock LAPI over HTTPS with a cert
signed by it, and runs the stack twice:
- positive: SSL_CERT_FILE = our CA -> LAPI trusted -> 200
- negative: SSL_CERT_FILE = empty bundle -> not trusted -> 403 (fail-closed)
The negative run proves the patch still VERIFIES (not an insecure skip).
- mocklapi: optional --lapi-tls-cert/--lapi-tls-key to serve the LAPI over TLS.
- common.sh: opt-in LAPI_TLS_CERT/KEY (HTTPS mock) and TRAEFIK_SSL_CERT_FILE
(inject SSL_CERT_FILE into Traefik); both default-empty, other scenarios
unaffected.
- adds openssl as a scenario-only dependency.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>