✨ add crowdsecAppsecTimeoutMilliseconds (#419)

* 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>
This commit is contained in:
solvikandmathieuHa authored and GitHub committed 2026-11-29 13:50:15 +01:00
1 parent b0431e2e53
commit d47336857a
5 files changed
+105 -4

No files matched your search

+6 -1
View File
@@ -385,6 +385,10 @@ make run
- int64
- default: 10485760 (= 10MB)
- Transmit only the first number of bytes to Crowdsec Appsec Server. If the body cannot be read while it is buffered (typically the client aborted the upload), the request is answered with `499` when the client is gone or `400` otherwise, and is neither banned nor counted as a blocked request.
- CrowdsecAppsecTimeoutMilliseconds
- int64
- default: 0 (= use `HTTPTimeoutSeconds`)
- Timeout in milliseconds for the whole Appsec call (connecting, sending the body, and waiting while Appsec queues and evaluates the request), independent from `HTTPTimeoutSeconds` which keeps governing the LAPI. A request that exceeds it counts as unreachable: it is blocked with the default `crowdsecAppsecUnreachableBlock: true`, and let through uninspected with `false`. Size it for Appsec under load, not for its usual few milliseconds: with Appsec's default single routine, a few concurrent uploads near `crowdsecAppsecBodyLimit` delay every other request by hundreds of milliseconds.
- CrowdsecAppsecUnreadableBodyBlock
- bool
- default: true
@@ -474,7 +478,7 @@ make run
- HTTPTimeoutSeconds
- int64
- default: 10
- Default timeout in seconds for contacting Crowdsec LAPI
- Default timeout in seconds for contacting Crowdsec LAPI (and Crowdsec Appsec Server unless `CrowdsecAppsecTimeoutMilliseconds` is set)
- UpdateIntervalSeconds
- int64
- default: 60
@@ -636,6 +640,7 @@ http:
crowdsecAppsecPath: "/"
crowdsecAppsecFailureBlock: true
crowdsecAppsecUnreachableBlock: true
crowdsecAppsecTimeoutMilliseconds: 0
crowdsecAppsecBodyLimit: 10485760
crowdsecAppsecUnreadableBodyBlock: false
crowdsecAppsecExcludedLocations:
+1 -1
View File
@@ -279,7 +279,7 @@ func New(_ context.Context, next http.Handler, config *configuration.Config, nam
IdleConnTimeout: 30 * time.Second,
TLSClientConfig: tlsAppsecConfig,
},
Timeout: time.Duration(config.HTTPTimeoutSeconds) * time.Second,
Timeout: configuration.GetAppsecTimeout(config),
},
cacheClient: &cache.Client{},
captchaClient: &captcha.Client{},
+48
View File
@@ -1350,3 +1350,51 @@ func TestHandleNextServeHTTPBodyReadErrorIsNotABan(t *testing.T) {
})
}
}
func TestAppsecTimeoutMillisecondsSkipsSlowAppsec(t *testing.T) {
release := make(chan struct{})
appsecServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
select {
case <-release:
case <-time.After(3 * time.Second):
}
rw.WriteHeader(http.StatusOK)
}))
defer appsecServer.Close()
defer close(release)
cfg := CreateConfig()
cfg.Enabled = true
cfg.CrowdsecMode = configuration.AppsecMode
cfg.CrowdsecLapiKey = "test"
cfg.CrowdsecAppsecEnabled = true
cfg.CrowdsecAppsecScheme = configuration.HTTP
cfg.CrowdsecAppsecHost = strings.TrimPrefix(appsecServer.URL, "http://")
cfg.CrowdsecAppsecUnreachableBlock = false
cfg.HTTPTimeoutSeconds = 10
cfg.CrowdsecAppsecTimeoutMilliseconds = 100
nextCalled := false
next := http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
nextCalled = true
rw.WriteHeader(http.StatusOK)
})
handler, err := New(context.Background(), next, cfg, "appsec-timeout")
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodGet, "http://example.com/", nil)
req.RemoteAddr = "192.0.2.10:1234"
recorder := httptest.NewRecorder()
start := time.Now()
handler.ServeHTTP(recorder, req)
elapsed := time.Since(start)
if elapsed > time.Second {
t.Errorf("expected the AppSec call to give up after ~100ms, request took %s", elapsed)
}
if !nextCalled || recorder.Code != http.StatusOK {
t.Errorf("expected the request to reach the backend (fail open), got status %d nextCalled=%v", recorder.Code, nextCalled)
}
}
+15 -2
View File
@@ -15,6 +15,7 @@ import (
"regexp"
"strings"
"text/template"
"time"
ip "github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/ip"
location "github.com/maxlerebourg/crowdsec-bouncer-traefik-plugin/pkg/location"
@@ -67,6 +68,7 @@ type Config struct {
CrowdsecAppsecUnreadableBodyBlock bool `json:"crowdsecAppsecUnreadableBodyBlock,omitempty"`
CrowdsecAppsecExcludedLocations []string `json:"crowdsecAppsecExcludedLocations,omitempty"`
CrowdsecAppsecBodyLimit int64 `json:"crowdsecAppsecBodyLimit,omitempty"`
CrowdsecAppsecTimeoutMilliseconds int64 `json:"crowdsecAppsecTimeoutMilliseconds,omitempty"`
CrowdsecLapiScheme string `json:"crowdsecLapiScheme,omitempty"`
CrowdsecLapiHost string `json:"crowdsecLapiHost,omitempty"`
CrowdsecLapiPath string `json:"crowdsecLapiPath,omitempty"`
@@ -128,6 +130,15 @@ func contains(source []string, target string) bool {
return false
}
// GetAppsecTimeout returns the timeout of the requests sent to the Appsec server:
// CrowdsecAppsecTimeoutMilliseconds when set, HTTPTimeoutSeconds otherwise.
func GetAppsecTimeout(config *Config) time.Duration {
if config.CrowdsecAppsecTimeoutMilliseconds > 0 {
return time.Duration(config.CrowdsecAppsecTimeoutMilliseconds) * time.Millisecond
}
return time.Duration(config.HTTPTimeoutSeconds) * time.Second
}
// New creates the default plugin configuration.
func New() *Config {
return &Config{
@@ -142,6 +153,7 @@ func New() *Config {
CrowdsecAppsecUnreadableBodyBlock: true,
CrowdsecAppsecExcludedLocations: []string{},
CrowdsecAppsecBodyLimit: 10485760,
CrowdsecAppsecTimeoutMilliseconds: 0,
CrowdsecAppsecScheme: "",
CrowdsecAppsecHost: "crowdsec:7422",
CrowdsecAppsecPath: "/",
@@ -458,8 +470,9 @@ func validateParamsRequired(config *Config) error {
}
}
requiredInt0 := map[string]int64{
"CrowdsecAppsecBodyLimit": config.CrowdsecAppsecBodyLimit,
"MetricsUpdateIntervalSeconds": config.MetricsUpdateIntervalSeconds,
"CrowdsecAppsecBodyLimit": config.CrowdsecAppsecBodyLimit,
"CrowdsecAppsecTimeoutMilliseconds": config.CrowdsecAppsecTimeoutMilliseconds,
"MetricsUpdateIntervalSeconds": config.MetricsUpdateIntervalSeconds,
}
for key, val := range requiredInt0 {
if val < 0 {
+35
View File
@@ -326,3 +326,38 @@ func Test_getContentTypeFromPath(t *testing.T) {
})
}
}
func Test_GetAppsecTimeout(t *testing.T) {
tests := []struct {
name string
httpSeconds int64
appsecMillis int64
wantTimeoutMs int64
}{
{name: "falls back to HTTPTimeoutSeconds when unset", httpSeconds: 10, appsecMillis: 0, wantTimeoutMs: 10000},
{name: "uses CrowdsecAppsecTimeoutMilliseconds when set", httpSeconds: 10, appsecMillis: 300, wantTimeoutMs: 300},
{name: "may be longer than HTTPTimeoutSeconds", httpSeconds: 1, appsecMillis: 2500, wantTimeoutMs: 2500},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := getMinimalConfig()
cfg.HTTPTimeoutSeconds = tt.httpSeconds
cfg.CrowdsecAppsecTimeoutMilliseconds = tt.appsecMillis
if got := GetAppsecTimeout(cfg).Milliseconds(); got != tt.wantTimeoutMs {
t.Errorf("GetAppsecTimeout() = %dms, want %dms", got, tt.wantTimeoutMs)
}
})
}
}
func Test_validateParamsRequiredAppsecTimeout(t *testing.T) {
cfg := getMinimalConfig()
cfg.CrowdsecAppsecTimeoutMilliseconds = -1
if err := validateParamsRequired(cfg); err == nil {
t.Error("validateParamsRequired() accepted a negative CrowdsecAppsecTimeoutMilliseconds")
}
cfg.CrowdsecAppsecTimeoutMilliseconds = 0
if err := validateParamsRequired(cfg); err != nil {
t.Errorf("validateParamsRequired() rejected CrowdsecAppsecTimeoutMilliseconds=0: %v", err)
}
}