🐛 redirect a captcha submitted again after it was solved (#428)

* 🐛 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>
This commit is contained in:
authored and GitHub committed 2026-11-14 17:21:33 +01:00
1 parent bdaae9cb60
commit f02a678dff
8 files changed
+207 -19

No files matched your search

+9 -1
View File
@@ -503,6 +503,10 @@ func (bouncer *Bouncer) handleRemediationServeHTTP(rw http.ResponseWriter, req *
bouncer.log.Debug(fmt.Sprintf("handleRemediationServeHTTP ip:%s remediation:%s", remoteIP, remediation))
if bouncer.captchaClient.Valid && remediation == cache.CaptchaValue && req.Method != http.MethodHead {
if bouncer.captchaClient.Check(remoteIP) {
if bouncer.captchaClient.HasResponse(req) {
bouncer.captchaClient.ServeSolved(rw, req)
return
}
bouncer.handleNextServeHTTP(rw, req, remoteIP)
return
}
@@ -548,7 +552,11 @@ func (bouncer *Bouncer) handleAppsecDecisionServeHTTP(rw http.ResponseWriter, re
bouncer.handleAppsecResponseServeHTTP(rw, req, decision)
case decision.Action == appsecCaptchaAction && bouncer.captchaClient.Valid && req.Method != http.MethodHead:
if bouncer.captchaClient.Check(remoteIP) {
return false
if !bouncer.captchaClient.HasResponse(req) {
return false
}
bouncer.captchaClient.ServeSolved(rw, req)
return true
}
atomic.AddInt64(&blockedRequests, 1)
bouncer.captchaClient.ServeHTTP(rw, req, remoteIP)
+73
View File
@@ -0,0 +1,73 @@
package crowdsec_bouncer_traefik_plugin //nolint:revive,stylecheck
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
cache "github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/cache"
captcha "github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/captcha"
configuration "github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/configuration"
logger "github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/logger"
)
func TestSolvedCaptchaSubmission(t *testing.T) {
log := logger.New("ERROR", "")
cacheClient := &cache.Client{}
cacheClient.New(log, false, "", nil, "", "")
cacheClient.Set("192.0.2.1_captcha", cache.CaptchaDoneValue, 60)
captchaClient := &captcha.Client{}
if err := captchaClient.New(log, cacheClient, &http.Client{}, configuration.HcaptchaProvider, "", "", "", "", "site", "secret", "", "captcha.html", 60); err != nil {
t.Fatal(err)
}
tests := []struct {
name string
body string
appsec bool
wantCode int
wantNext bool
}{
{name: "lapi captcha submitted again", body: "h-captcha-response=token", wantCode: http.StatusFound},
{name: "lapi other form", body: "name=value", wantCode: http.StatusOK, wantNext: true},
{name: "appsec captcha submitted again", body: "h-captcha-response=token", appsec: true, wantCode: http.StatusFound},
{name: "appsec other form", body: "name=value", appsec: true, wantCode: http.StatusOK, wantNext: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var nextBody string
bouncer := &Bouncer{
next: http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
body, _ := io.ReadAll(req.Body)
nextBody = string(body)
}),
cacheClient: cacheClient,
captchaClient: captchaClient,
log: log,
}
req := httptest.NewRequest(http.MethodPost, "http://example.com/page?a=1", strings.NewReader(tt.body))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rw := httptest.NewRecorder()
if tt.appsec {
if !bouncer.handleAppsecDecisionServeHTTP(rw, req, "192.0.2.1", &AppSecResponse{Action: appsecCaptchaAction}) {
bouncer.next.ServeHTTP(rw, req)
}
} else {
bouncer.handleRemediationServeHTTP(rw, req, "192.0.2.1", cache.CaptchaValue)
}
if rw.Code != tt.wantCode {
t.Errorf("status = %d, want %d", rw.Code, tt.wantCode)
}
if tt.wantCode == http.StatusFound && rw.Header().Get("Location") != "http://example.com/page?a=1" {
t.Errorf("Location = %q", rw.Header().Get("Location"))
}
if tt.wantNext != (nextBody == tt.body) {
t.Errorf("next got body %q, want next called: %v", nextBody, tt.wantNext)
}
})
}
}
+30 -4
View File
@@ -2,8 +2,10 @@
package captcha
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
@@ -37,6 +39,8 @@ type infoProvider struct {
validate string
}
const responseFormLimit = 64 << 10
//nolint:gochecknoglobals
var infoProviders = map[string]*infoProvider{
configuration.HcaptchaProvider: {
@@ -96,10 +100,7 @@ func (c *Client) ServeHTTP(rw http.ResponseWriter, r *http.Request, remoteIP str
if valid {
c.log.Debug("captcha:ServeHTTP captcha:valid")
c.cacheClient.Set(remoteIP+"_captcha", cache.CaptchaDoneValue, c.gracePeriodSeconds)
if c.remediationCustomHeader != "" {
rw.Header().Set(c.remediationCustomHeader, "solved-captcha")
}
http.Redirect(rw, r, r.URL.String(), http.StatusFound)
c.ServeSolved(rw, r)
return
}
rw.Header().Set("Content-Type", c.templateContentType)
@@ -117,6 +118,31 @@ func (c *Client) ServeHTTP(rw http.ResponseWriter, r *http.Request, remoteIP str
}
}
// ServeSolved redirects a request whose captcha is solved to its own URL.
func (c *Client) ServeSolved(rw http.ResponseWriter, r *http.Request) {
if c.remediationCustomHeader != "" {
rw.Header().Set(c.remediationCustomHeader, "solved-captcha")
}
http.Redirect(rw, r, r.URL.String(), http.StatusFound)
}
// HasResponse reports whether the request is a captcha form submission.
func (c *Client) HasResponse(r *http.Request) bool {
if r.Method != http.MethodPost || r.ContentLength <= 0 || r.ContentLength > responseFormLimit {
return false
}
if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/x-www-form-urlencoded") {
return false
}
body, err := io.ReadAll(io.LimitReader(r.Body, r.ContentLength))
r.Body = io.NopCloser(io.MultiReader(bytes.NewReader(body), r.Body))
if err != nil {
return false
}
values, err := url.ParseQuery(string(body))
return err == nil && values.Get(c.infoProvider.response) != ""
}
// Check Verify if the captcha is already done.
func (c *Client) Check(remoteIP string) bool {
value, _ := c.cacheClient.Get(remoteIP + "_captcha")
+46
View File
@@ -0,0 +1,46 @@
package captcha
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestClient_HasResponse(t *testing.T) {
client := &Client{infoProvider: &infoProvider{response: "response-captcha"}}
form := "application/x-www-form-urlencoded"
tests := []struct {
name string
method string
contentType string
body string
length int64
want bool
}{
{name: "captcha form", method: http.MethodPost, contentType: form, body: "response-captcha=token", want: true},
{name: "other form", method: http.MethodPost, contentType: form, body: "name=value"},
{name: "get", method: http.MethodGet, contentType: form, body: "response-captcha=token"},
{name: "json", method: http.MethodPost, contentType: "application/json", body: `{"response-captcha":"token"}`},
{name: "unknown length", method: http.MethodPost, contentType: form, body: "response-captcha=token", length: -1},
{name: "too large", method: http.MethodPost, contentType: form, body: "response-captcha=token&" + strings.Repeat("a", responseFormLimit)},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(tt.method, "http://example.com/page", strings.NewReader(tt.body))
req.Header.Set("Content-Type", tt.contentType)
if tt.length != 0 {
req.ContentLength = tt.length
}
if got := client.HasResponse(req); got != tt.want {
t.Errorf("HasResponse() = %v, want %v", got, tt.want)
}
body, _ := io.ReadAll(req.Body)
if string(body) != tt.body {
t.Errorf("body after HasResponse() = %q, want %q", body, tt.body)
}
})
}
}
+15 -12
View File
@@ -14,28 +14,31 @@ ships in its own PR (#333).
These tests validate the **plugin's own behaviour**: the request flow through
the Traefik middleware, the live / none / stream modes, caching, trusted-IP
bypass, ban / captcha page rendering, and the AppSec request path (header
forwarding + enforcing the engine's allow/block verdict).
bypass, ban / captcha page rendering, the browser's captcha submission, and the
AppSec request path (header forwarding + enforcing the engine's allow/block
verdict).
The mock stands in for Crowdsec, emulating the slice of the LAPI HTTP contract
the plugin consumes — including a single, deterministic AppSec rule (block any
URI containing `rpc2`, the probe from [`examples/appsec-enabled`](../../../examples/appsec-enabled)).
It is not the real WAF engine, so this suite exercises the plugin's AppSec
*wiring* rather than the detection accuracy of OWASP CRS / virtual patching —
that lives upstream in Crowdsec.
the plugin consumes, plus a deterministic AppSec stand-in that decides from
markers in the forwarded request (see the table below). It is not the real WAF
engine, so this suite exercises the plugin's AppSec *wiring* rather than the
detection accuracy of OWASP CRS / virtual patching — that lives upstream in
Crowdsec.
## What runs
| Component | How |
|-----------|-----|
| Traefik | Binary `v3.7.1`, downloaded into `.cache/` (reused across local runs; re-downloaded on fresh CI runners) |
| Traefik | Binary downloaded into `.cache/` (reused across local runs; re-downloaded on fresh CI runners) |
| Plugin | Loaded via `experimental.localPlugins` from the repo root (symlinked into `plugins-local/`) |
| LAPI | `mocklapi` — a stdlib-only Go command (its own nested module), compiled and cached under `.cache/`, driven through `/admin` endpoints instead of `cscli`. Serves plain HTTP, or HTTPS when `--lapi-tls-cert/--lapi-tls-key` are passed (the `tls-system-ca` scenario) |
| AppSec | WAF stand-in built into the mock — blocks URIs containing `rpc2`, allows the rest |
| AppSec | WAF stand-in built into the mock — answers 403/500/502 when the forwarded URI contains `403`/`500`/`502`, and 403 when the forwarded body (within `crowdsecAppsecBodyLimit`) contains `a=0`; anything else is allowed |
| Captcha | Siteverify stub on the mock LAPI (`/captcha/validate`): answers `{"success":true}` only for the token `ok` |
| Redis | Primary and replica stand-ins on plain TCP (inline-command wire format): the replica serves the hardcoded verdicts, the primary always misses on GET, so a scenario can prove reads are offloaded to the replica |
| Backend | A plain HTTP responder built into the mock |
Fixed ports (override with env vars if needed): Traefik `8000`, LAPI `8090`,
backend `8091`, AppSec `8092`.
Fixed ports (override with env vars if needed): Traefik `8000`, LAPI `8090`, backend `8091`, AppSec
`8092`, Redis primary `8093`, Redis replica `8094`.
## Running locally
@@ -69,7 +72,7 @@ mock/
traefik.yml # static Traefik config (shared by all scenarios)
mocklapi/
go.mod # nested module — kept out of the plugin's build/lint/vendor
main.go # mock LAPI + AppSec stand-in + backend
main.go # mock LAPI + AppSec stand-in + captcha validator + Redis stubs + backend
scenarios/
<name>/
dynamic.yml # Traefik dynamic config (router + bouncer middleware + backend)
+7
View File
@@ -183,6 +183,13 @@ func main() {
w.WriteHeader(http.StatusCreated)
})
// captcha siteverify stand-in: the plugin posts the browser's token back to
// the "provider"; only the known-good token solves the challenge.
mux.HandleFunc("/captcha/validate", func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
writeJSON(w, map[string]bool{"success": r.FormValue("response") == "ok"})
})
// Test control plane: add / remove decisions instead of cscli.
mux.HandleFunc("/admin/decisions", func(_ http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
+6 -2
View File
@@ -24,10 +24,14 @@ http:
crowdsecLapiKey: "@@APIKEY@@"
forwardedHeadersTrustedIps:
- "127.0.0.1/32"
captchaProvider: turnstile
captchaProvider: custom
captchaCustomJsUrl: "http://test.com"
captchaCustomKey: "captcha-response"
captchaCustomResponse: "response-captcha"
captchaCustomValidateUrl: "http://@@LAPI_HOST@@/captcha/validate"
# Cloudflare Turnstile public test keys: render a valid widget without
# contacting a real API key.
captchaSiteKey: "1x00000000000000000000AA"
captchaSecretKey: "1x0000000000000000000000000000000AA"
captchaHtmlFilePath: "@@SCENARIO_DIR@@/captcha.html"
captchaFilePath: "@@SCENARIO_DIR@@/captcha.html"
captchaGracePeriodSeconds: "10"
+21
View File
@@ -10,6 +10,7 @@ SCENARIO=captcha
body() {
echo "[$SCENARIO] adding captcha decision for 1.2.3.4"
lapi_add_decision 1.2.3.4 captcha 5m
lapi_add_decision 1.2.3.5 captcha 5m
# Status stays 200 before/after (captcha page vs backend), so gate on the body
# marker appearing once the captcha decision has been polled.
@@ -19,11 +20,31 @@ body() {
echo "[$SCENARIO] captcha response Content-Type is HTML"
assert_header "http://127.0.0.1:${WEB_PORT}/foo" Content-Type "text/html; charset=utf-8" -H "X-Forwarded-For: 1.2.3.4"
echo "[$SCENARIO] captcha page is rendered with the configured custom provider"
assert_body_contains "http://127.0.0.1:${WEB_PORT}/foo" "http://test.com" -H "X-Forwarded-For: 1.2.3.4"
assert_body_contains "http://127.0.0.1:${WEB_PORT}/foo" 'class="captcha-response"' -H "X-Forwarded-For: 1.2.3.4"
assert_body_contains "http://127.0.0.1:${WEB_PORT}/foo" 'data-sitekey="1x00000000000000000000AA"' -H "X-Forwarded-For: 1.2.3.4"
echo "[$SCENARIO] captcha response is HTTP 200 (the captcha page itself, not a 403)"
assert_status "http://127.0.0.1:${WEB_PORT}/foo" 200 -H "X-Forwarded-For: 1.2.3.4"
echo "[$SCENARIO] non-flagged IP must still pass through to the backend"
assert_status "http://127.0.0.1:${WEB_PORT}/foo" 200 -H "X-Forwarded-For: 5.6.7.8"
echo "[$SCENARIO] rejected captcha response must re-serve the page (200 + marker)"
assert_body_contains "http://127.0.0.1:${WEB_PORT}/foo" "E2E_CAPTCHA_PAGE_MARKER" -H "X-Forwarded-For: 1.2.3.4" -X POST -d "response-captcha=ko"
echo "[$SCENARIO] valid captcha response must solve the challenge (302 to the same URL)"
assert_status "http://127.0.0.1:${WEB_PORT}/foo" 302 -H "X-Forwarded-For: 1.2.3.4" -X POST -d "response-captcha=ok"
echo "[$SCENARIO] captcha submitted again after being solved must still redirect even if wrong"
assert_header "http://127.0.0.1:${WEB_PORT}/foo" Location "/foo" -H "X-Forwarded-For: 1.2.3.4" -X POST -d "response-captcha=ko"
echo "[$SCENARIO] solved captcha must pass through to the backend"
assert_body_contains "http://127.0.0.1:${WEB_PORT}/foo" "E2E_BACKEND_OK" -H "X-Forwarded-For: 1.2.3.4"
echo "[$SCENARIO] solved captcha for user must not pass through for another user"
assert_body_contains "http://127.0.0.1:${WEB_PORT}/foo" "E2E_CAPTCHA_PAGE_MARKER" -H "X-Forwarded-For: 1.2.3.5"
}
run_scenario "$SCENARIO" "$HERE" body