repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/accesslog/field_middleware.go
pkg/middlewares/accesslog/field_middleware.go
package accesslog import ( "net/http" "strings" "time" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/middlewares/capture" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/vulcand/oxy/v2/utils" ) // FieldApply function hook to add data in accesslog. type FieldApply func(rw http.ResponseWriter, r *http.Request, next http.Handler, data *LogData) // FieldHandler sends a new field to the logger. type FieldHandler struct { next http.Handler name string value string applyFn FieldApply } // NewFieldHandler creates a Field handler. func NewFieldHandler(next http.Handler, name, value string, applyFn FieldApply) http.Handler { return &FieldHandler{next: next, name: name, value: value, applyFn: applyFn} } func (f *FieldHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { table := GetLogData(req) if table == nil { f.next.ServeHTTP(rw, req) return } table.Core[f.name] = f.value if f.applyFn != nil { f.applyFn(rw, req, f.next, table) } else { f.next.ServeHTTP(rw, req) } } // AddServiceFields add service fields. func AddServiceFields(rw http.ResponseWriter, req *http.Request, next http.Handler, data *LogData) { start := time.Now().UTC() next.ServeHTTP(rw, req) // use UTC to handle switchover of daylight saving correctly data.Core[OriginDuration] = time.Now().UTC().Sub(start) // make copy of headers, so we can ensure there is no subsequent mutation // during response processing data.OriginResponse = make(http.Header) utils.CopyHeaders(data.OriginResponse, rw.Header()) ctx := req.Context() capt, err := capture.FromContext(ctx) if err != nil { log.Ctx(ctx).Error().Err(err).Str(logs.MiddlewareType, "AccessLogs").Msg("Could not get Capture") return } data.Core[OriginStatus] = capt.StatusCode() data.Core[OriginContentSize] = capt.ResponseSize() } // InitServiceFields init service fields. func InitServiceFields(rw http.ResponseWriter, req *http.Request, next http.Handler, data *LogData) { // Because they are expected to be initialized when the logger is processing the data table, // the origin fields are initialized in case the response is returned by Traefik itself, and not a service. data.Core[OriginDuration] = time.Duration(0) data.Core[OriginStatus] = 0 data.Core[OriginContentSize] = int64(0) next.ServeHTTP(rw, req) } const separator = " -> " // ConcatFieldHandler concatenates field values instead of overriding them. type ConcatFieldHandler struct { next http.Handler name string value string } // NewConcatFieldHandler creates a ConcatField handler that concatenates values. func NewConcatFieldHandler(next http.Handler, name, value string) http.Handler { return &ConcatFieldHandler{next: next, name: name, value: value} } func (c *ConcatFieldHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { table := GetLogData(req) if table == nil { c.next.ServeHTTP(rw, req) return } // Check if field already exists and concatenate if so if existingValue, exists := table.Core[c.name]; exists && existingValue != nil { if existingStr, ok := existingValue.(string); ok && strings.TrimSpace(existingStr) != "" { table.Core[c.name] = existingStr + separator + c.value c.next.ServeHTTP(rw, req) return } } table.Core[c.name] = c.value c.next.ServeHTTP(rw, req) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/accesslog/logger_test.go
pkg/middlewares/accesslog/logger_test.go
package accesslog import ( "bytes" "compress/gzip" "context" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "strconv" "strings" "testing" "time" "github.com/containous/alice" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/middlewares/capture" "github.com/traefik/traefik/v3/pkg/middlewares/observability" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "go.opentelemetry.io/collector/pdata/plog/plogotlp" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace/embedded" ) const delta float64 = 1e-10 var ( logFileNameSuffix = "/traefik/logger/test.log" testContent = "Hello, World" testServiceName = "http://127.0.0.1/testService" testRouterName = "testRouter" testStatus = 123 testContentSize int64 = 12 testHostname = "TestHost" testUsername = "TestUser" testPath = "testpath" testPort = 8181 testProto = "HTTP/0.0" testScheme = "http" testMethod = http.MethodPost testReferer = "testReferer" testUserAgent = "testUserAgent" testRetryAttempts = 2 testStart = time.Now() ) func TestOTelAccessLogWithBody(t *testing.T) { testCases := []struct { desc string format string bodyCheckFn func(*testing.T, string) }{ { desc: "Common format with log body", format: CommonFormat, bodyCheckFn: func(t *testing.T, log string) { t.Helper() // For common format, verify the body contains the Traefik common log formatted string assert.Regexp(t, `"body":{"stringValue":".*- /health -.*200.*[0-9]+ms.*"}`, log) }, }, { desc: "Generic CLF format with log body", format: GenericCLFFormat, bodyCheckFn: func(t *testing.T, log string) { t.Helper() // For generic CLF format, verify the body contains the CLF formatted string assert.Regexp(t, `"body":{"stringValue":".*- /health -.*200.*"}`, log) }, }, { desc: "JSON format with log body", format: JSONFormat, bodyCheckFn: func(t *testing.T, log string) { t.Helper() // For JSON format, verify the body contains the JSON formatted string assert.Regexp(t, `"body":{"stringValue":".*DownstreamStatus.*:200.*"}`, log) }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() logCh := make(chan string) collector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gzr, err := gzip.NewReader(r.Body) require.NoError(t, err) body, err := io.ReadAll(gzr) require.NoError(t, err) req := plogotlp.NewExportRequest() err = req.UnmarshalProto(body) require.NoError(t, err) marshalledReq, err := json.Marshal(req) require.NoError(t, err) logCh <- string(marshalledReq) })) t.Cleanup(collector.Close) config := &otypes.AccessLog{ Format: test.format, OTLP: &otypes.OTelLog{ ServiceName: "test", ResourceAttributes: map[string]string{"resource": "attribute"}, HTTP: &otypes.OTelHTTP{ Endpoint: collector.URL, }, }, } logHandler, err := NewHandler(t.Context(), config) require.NoError(t, err) t.Cleanup(func() { err := logHandler.Close() require.NoError(t, err) }) req := &http.Request{ Header: map[string][]string{}, URL: &url.URL{ Path: "/health", }, } ctx := trace.ContextWithSpanContext(t.Context(), trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8}, SpanID: trace.SpanID{0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8}, })) req = req.WithContext(ctx) chain := alice.New() chain = chain.Append(capture.Wrap) // Injection of the observability variables in the request context. chain = chain.Append(func(next http.Handler) (http.Handler, error) { return observability.WithObservabilityHandler(next, observability.Observability{ AccessLogsEnabled: true, }), nil }) chain = chain.Append(logHandler.AliceConstructor()) handler, err := chain.Then(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) })) require.NoError(t, err) handler.ServeHTTP(httptest.NewRecorder(), req) select { case <-time.After(5 * time.Second): t.Error("AccessLog not exported") case log := <-logCh: // Verify basic OTLP structure assert.Regexp(t, `{"key":"resource","value":{"stringValue":"attribute"}}`, log) assert.Regexp(t, `{"key":"service.name","value":{"stringValue":"test"}}`, log) assert.Regexp(t, `{"key":"DownstreamStatus","value":{"intValue":"200"}}`, log) assert.Regexp(t, `"traceId":"01020304050607080000000000000000","spanId":"0102030405060708"`, log) // Most importantly, verify the log body is populated (not empty) assert.NotRegexp(t, `"body":{"stringValue":""}`, log, "Log body should not be empty when OTLP is configured") // Run format-specific body checks test.bodyCheckFn(t, log) } }) } } func TestLogRotation(t *testing.T) { fileName := filepath.Join(t.TempDir(), "traefik.log") rotatedFileName := fileName + ".rotated" config := &otypes.AccessLog{FilePath: fileName, Format: CommonFormat} logHandler, err := NewHandler(t.Context(), config) require.NoError(t, err) t.Cleanup(func() { err := logHandler.Close() require.NoError(t, err) }) chain := alice.New() chain = chain.Append(capture.Wrap) // Injection of the observability variables in the request context. chain = chain.Append(func(next http.Handler) (http.Handler, error) { return observability.WithObservabilityHandler(next, observability.Observability{ AccessLogsEnabled: true, }), nil }) chain = chain.Append(logHandler.AliceConstructor()) handler, err := chain.Then(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) })) require.NoError(t, err) recorder := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "http://localhost", nil) iterations := 20 halfDone := make(chan bool) writeDone := make(chan bool) go func() { for i := range iterations { handler.ServeHTTP(recorder, req) if i == iterations/2 { halfDone <- true } } writeDone <- true }() <-halfDone err = os.Rename(fileName, rotatedFileName) if err != nil { t.Fatalf("Error renaming file: %s", err) } err = logHandler.Rotate() if err != nil { t.Fatalf("Error rotating file: %s", err) } select { case <-writeDone: gotLineCount := lineCount(t, fileName) + lineCount(t, rotatedFileName) if iterations != gotLineCount { t.Errorf("Wanted %d written log lines, got %d", iterations, gotLineCount) } case <-time.After(500 * time.Millisecond): t.Fatalf("test timed out") } close(halfDone) close(writeDone) } func lineCount(t *testing.T, fileName string) int { t.Helper() fileContents, err := os.ReadFile(fileName) if err != nil { t.Fatalf("Error reading from file %s: %s", fileName, err) } count := 0 for _, line := range strings.Split(string(fileContents), "\n") { if strings.TrimSpace(line) == "" { continue } count++ } return count } func TestLoggerHeaderFields(t *testing.T) { expectedValues := []string{"AAA", "BBB"} testCases := []struct { desc string accessLogFields otypes.AccessLogFields header string expected string }{ { desc: "with default mode", header: "User-Agent", expected: otypes.AccessLogDrop, accessLogFields: otypes.AccessLogFields{ DefaultMode: otypes.AccessLogDrop, Headers: &otypes.FieldHeaders{ DefaultMode: otypes.AccessLogDrop, Names: map[string]string{}, }, }, }, { desc: "with exact header name", header: "User-Agent", expected: otypes.AccessLogKeep, accessLogFields: otypes.AccessLogFields{ DefaultMode: otypes.AccessLogDrop, Headers: &otypes.FieldHeaders{ DefaultMode: otypes.AccessLogDrop, Names: map[string]string{ "User-Agent": otypes.AccessLogKeep, }, }, }, }, { desc: "with case-insensitive match on header name", header: "User-Agent", expected: otypes.AccessLogKeep, accessLogFields: otypes.AccessLogFields{ DefaultMode: otypes.AccessLogDrop, Headers: &otypes.FieldHeaders{ DefaultMode: otypes.AccessLogDrop, Names: map[string]string{ "user-agent": otypes.AccessLogKeep, }, }, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { logFile, err := os.CreateTemp(t.TempDir(), "*.log") require.NoError(t, err) config := &otypes.AccessLog{ FilePath: logFile.Name(), Format: CommonFormat, Fields: &test.accessLogFields, } logger, err := NewHandler(t.Context(), config) require.NoError(t, err) t.Cleanup(func() { err := logger.Close() require.NoError(t, err) }) if config.FilePath != "" { _, err = os.Stat(config.FilePath) require.NoErrorf(t, err, "logger should create %s", config.FilePath) } req := &http.Request{ Header: map[string][]string{}, URL: &url.URL{ Path: testPath, }, } for _, s := range expectedValues { req.Header.Add(test.header, s) } chain := alice.New() chain = chain.Append(capture.Wrap) // Injection of the observability variables in the request context. chain = chain.Append(func(next http.Handler) (http.Handler, error) { return observability.WithObservabilityHandler(next, observability.Observability{ AccessLogsEnabled: true, }), nil }) chain = chain.Append(logger.AliceConstructor()) handler, err := chain.Then(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) })) require.NoError(t, err) handler.ServeHTTP(httptest.NewRecorder(), req) logData, err := os.ReadFile(logFile.Name()) require.NoError(t, err) if test.expected == otypes.AccessLogDrop { assert.NotContains(t, string(logData), strings.Join(expectedValues, ",")) } else { assert.Contains(t, string(logData), strings.Join(expectedValues, ",")) } }) } } func TestCommonLogger(t *testing.T) { logFilePath := filepath.Join(t.TempDir(), logFileNameSuffix) config := &otypes.AccessLog{FilePath: logFilePath, Format: CommonFormat} doLogging(t, config, false) logData, err := os.ReadFile(logFilePath) require.NoError(t, err) expectedLog := ` TestHost - TestUser [13/Apr/2016:07:14:19 -0700] "POST testpath HTTP/0.0" 123 12 "testReferer" "testUserAgent" 1 "testRouter" "http://127.0.0.1/testService" 1ms` assertValidCommonLogData(t, expectedLog, logData) } func TestCommonLoggerWithBufferingSize(t *testing.T) { logFilePath := filepath.Join(t.TempDir(), logFileNameSuffix) config := &otypes.AccessLog{FilePath: logFilePath, Format: CommonFormat, BufferingSize: 1024} doLogging(t, config, false) // wait a bit for the buffer to be written in the file. time.Sleep(50 * time.Millisecond) logData, err := os.ReadFile(logFilePath) require.NoError(t, err) expectedLog := ` TestHost - TestUser [13/Apr/2016:07:14:19 -0700] "POST testpath HTTP/0.0" 123 12 "testReferer" "testUserAgent" 1 "testRouter" "http://127.0.0.1/testService" 1ms` assertValidCommonLogData(t, expectedLog, logData) } func TestLoggerGenericCLF(t *testing.T) { logFilePath := filepath.Join(t.TempDir(), logFileNameSuffix) config := &otypes.AccessLog{FilePath: logFilePath, Format: GenericCLFFormat} doLogging(t, config, false) logData, err := os.ReadFile(logFilePath) require.NoError(t, err) expectedLog := ` TestHost - TestUser [13/Apr/2016:07:14:19 -0700] "POST testpath HTTP/0.0" 123 12 "testReferer" "testUserAgent"` assertValidGenericCLFLogData(t, expectedLog, logData) } func TestLoggerGenericCLFWithBufferingSize(t *testing.T) { logFilePath := filepath.Join(t.TempDir(), logFileNameSuffix) config := &otypes.AccessLog{FilePath: logFilePath, Format: GenericCLFFormat, BufferingSize: 1024} doLogging(t, config, false) // wait a bit for the buffer to be written in the file. time.Sleep(50 * time.Millisecond) logData, err := os.ReadFile(logFilePath) require.NoError(t, err) expectedLog := ` TestHost - TestUser [13/Apr/2016:07:14:19 -0700] "POST testpath HTTP/0.0" 123 12 "testReferer" "testUserAgent"` assertValidGenericCLFLogData(t, expectedLog, logData) } func assertString(exp string) func(t *testing.T, actual interface{}) { return func(t *testing.T, actual interface{}) { t.Helper() assert.Equal(t, exp, actual) } } func assertNotEmpty() func(t *testing.T, actual interface{}) { return func(t *testing.T, actual interface{}) { t.Helper() assert.NotEmpty(t, actual) } } func assertFloat64(exp float64) func(t *testing.T, actual interface{}) { return func(t *testing.T, actual interface{}) { t.Helper() assert.InDelta(t, exp, actual, delta) } } func assertFloat64NotZero() func(t *testing.T, actual interface{}) { return func(t *testing.T, actual interface{}) { t.Helper() assert.NotZero(t, actual) } } func TestLoggerJSON(t *testing.T) { testCases := []struct { desc string config *otypes.AccessLog tls bool tracing bool expected map[string]func(t *testing.T, value interface{}) }{ { desc: "default config without tracing", config: &otypes.AccessLog{ FilePath: "", Format: JSONFormat, }, expected: map[string]func(t *testing.T, value interface{}){ RequestContentSize: assertFloat64(0), RequestHost: assertString(testHostname), RequestAddr: assertString(testHostname), RequestMethod: assertString(testMethod), RequestPath: assertString(testPath), RequestProtocol: assertString(testProto), RequestScheme: assertString(testScheme), RequestPort: assertString("-"), DownstreamStatus: assertFloat64(float64(testStatus)), DownstreamContentSize: assertFloat64(float64(len(testContent))), OriginContentSize: assertFloat64(float64(len(testContent))), OriginStatus: assertFloat64(float64(testStatus)), RequestRefererHeader: assertString(testReferer), RequestUserAgentHeader: assertString(testUserAgent), RouterName: assertString(testRouterName), ServiceURL: assertString(testServiceName), ClientUsername: assertString(testUsername), ClientHost: assertString(testHostname), ClientPort: assertString(strconv.Itoa(testPort)), ClientAddr: assertString(fmt.Sprintf("%s:%d", testHostname, testPort)), "level": assertString("info"), "msg": assertString(""), "downstream_Content-Type": assertString("text/plain; charset=utf-8"), RequestCount: assertFloat64NotZero(), Duration: assertFloat64NotZero(), Overhead: assertFloat64NotZero(), RetryAttempts: assertFloat64(float64(testRetryAttempts)), "time": assertNotEmpty(), "StartLocal": assertNotEmpty(), "StartUTC": assertNotEmpty(), }, }, { desc: "default config with tracing", config: &otypes.AccessLog{ FilePath: "", Format: JSONFormat, }, tracing: true, expected: map[string]func(t *testing.T, value interface{}){ RequestContentSize: assertFloat64(0), RequestHost: assertString(testHostname), RequestAddr: assertString(testHostname), RequestMethod: assertString(testMethod), RequestPath: assertString(testPath), RequestProtocol: assertString(testProto), RequestScheme: assertString(testScheme), RequestPort: assertString("-"), DownstreamStatus: assertFloat64(float64(testStatus)), DownstreamContentSize: assertFloat64(float64(len(testContent))), OriginContentSize: assertFloat64(float64(len(testContent))), OriginStatus: assertFloat64(float64(testStatus)), RequestRefererHeader: assertString(testReferer), RequestUserAgentHeader: assertString(testUserAgent), RouterName: assertString(testRouterName), ServiceURL: assertString(testServiceName), ClientUsername: assertString(testUsername), ClientHost: assertString(testHostname), ClientPort: assertString(strconv.Itoa(testPort)), ClientAddr: assertString(fmt.Sprintf("%s:%d", testHostname, testPort)), "level": assertString("info"), "msg": assertString(""), "downstream_Content-Type": assertString("text/plain; charset=utf-8"), RequestCount: assertFloat64NotZero(), Duration: assertFloat64NotZero(), Overhead: assertFloat64NotZero(), RetryAttempts: assertFloat64(float64(testRetryAttempts)), "time": assertNotEmpty(), "StartLocal": assertNotEmpty(), "StartUTC": assertNotEmpty(), TraceID: assertString("01000000000000000000000000000000"), SpanID: assertString("0100000000000000"), }, }, { desc: "default config, with TLS request", config: &otypes.AccessLog{ FilePath: "", Format: JSONFormat, }, tls: true, expected: map[string]func(t *testing.T, value interface{}){ RequestContentSize: assertFloat64(0), RequestHost: assertString(testHostname), RequestAddr: assertString(testHostname), RequestMethod: assertString(testMethod), RequestPath: assertString(testPath), RequestProtocol: assertString(testProto), RequestScheme: assertString("https"), RequestPort: assertString("-"), DownstreamStatus: assertFloat64(float64(testStatus)), DownstreamContentSize: assertFloat64(float64(len(testContent))), OriginContentSize: assertFloat64(float64(len(testContent))), OriginStatus: assertFloat64(float64(testStatus)), RequestRefererHeader: assertString(testReferer), RequestUserAgentHeader: assertString(testUserAgent), RouterName: assertString(testRouterName), ServiceURL: assertString(testServiceName), ClientUsername: assertString(testUsername), ClientHost: assertString(testHostname), ClientPort: assertString(strconv.Itoa(testPort)), ClientAddr: assertString(fmt.Sprintf("%s:%d", testHostname, testPort)), "level": assertString("info"), "msg": assertString(""), "downstream_Content-Type": assertString("text/plain; charset=utf-8"), RequestCount: assertFloat64NotZero(), Duration: assertFloat64NotZero(), Overhead: assertFloat64NotZero(), RetryAttempts: assertFloat64(float64(testRetryAttempts)), TLSClientSubject: assertString("CN=foobar"), TLSVersion: assertString("1.3"), TLSCipher: assertString("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"), "time": assertNotEmpty(), StartLocal: assertNotEmpty(), StartUTC: assertNotEmpty(), }, }, { desc: "default config drop all fields", config: &otypes.AccessLog{ FilePath: "", Format: JSONFormat, Fields: &otypes.AccessLogFields{ DefaultMode: "drop", }, }, expected: map[string]func(t *testing.T, value interface{}){ "level": assertString("info"), "msg": assertString(""), "time": assertNotEmpty(), "downstream_Content-Type": assertString("text/plain; charset=utf-8"), RequestRefererHeader: assertString(testReferer), RequestUserAgentHeader: assertString(testUserAgent), }, }, { desc: "default config drop all fields and headers", config: &otypes.AccessLog{ FilePath: "", Format: JSONFormat, Fields: &otypes.AccessLogFields{ DefaultMode: "drop", Headers: &otypes.FieldHeaders{ DefaultMode: "drop", }, }, }, expected: map[string]func(t *testing.T, value interface{}){ "level": assertString("info"), "msg": assertString(""), "time": assertNotEmpty(), }, }, { desc: "default config drop all fields and redact headers", config: &otypes.AccessLog{ FilePath: "", Format: JSONFormat, Fields: &otypes.AccessLogFields{ DefaultMode: "drop", Headers: &otypes.FieldHeaders{ DefaultMode: "redact", }, }, }, expected: map[string]func(t *testing.T, value interface{}){ "level": assertString("info"), "msg": assertString(""), "time": assertNotEmpty(), "downstream_Content-Type": assertString("REDACTED"), RequestRefererHeader: assertString("REDACTED"), RequestUserAgentHeader: assertString("REDACTED"), }, }, { desc: "default config drop all fields and headers but kept someone", config: &otypes.AccessLog{ FilePath: "", Format: JSONFormat, Fields: &otypes.AccessLogFields{ DefaultMode: "drop", Names: map[string]string{ RequestHost: "keep", }, Headers: &otypes.FieldHeaders{ DefaultMode: "drop", Names: map[string]string{ "Referer": "keep", }, }, }, }, expected: map[string]func(t *testing.T, value interface{}){ RequestHost: assertString(testHostname), "level": assertString("info"), "msg": assertString(""), "time": assertNotEmpty(), RequestRefererHeader: assertString(testReferer), }, }, { desc: "fields and headers with unconventional letter case", config: &otypes.AccessLog{ FilePath: "", Format: JSONFormat, Fields: &otypes.AccessLogFields{ DefaultMode: "drop", Names: map[string]string{ "rEqUeStHoSt": "keep", }, Headers: &otypes.FieldHeaders{ DefaultMode: "drop", Names: map[string]string{ "ReFeReR": "keep", }, }, }, }, expected: map[string]func(t *testing.T, value interface{}){ RequestHost: assertString(testHostname), "level": assertString("info"), "msg": assertString(""), "time": assertNotEmpty(), RequestRefererHeader: assertString(testReferer), }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() logFilePath := filepath.Join(t.TempDir(), logFileNameSuffix) test.config.FilePath = logFilePath if test.tls { doLoggingTLS(t, test.config, test.tracing) } else { doLogging(t, test.config, test.tracing) } logData, err := os.ReadFile(logFilePath) require.NoError(t, err) jsonData := make(map[string]interface{}) err = json.Unmarshal(logData, &jsonData) require.NoError(t, err) assert.Len(t, jsonData, len(test.expected)) for field, assertion := range test.expected { assertion(t, jsonData[field]) } }) } } func TestLogger_AbortedRequest(t *testing.T) { expected := map[string]func(t *testing.T, value interface{}){ RequestContentSize: assertFloat64(0), RequestHost: assertString(testHostname), RequestAddr: assertString(testHostname), RequestMethod: assertString(testMethod), RequestPath: assertString(""), RequestProtocol: assertString(testProto), RequestScheme: assertString(testScheme), RequestPort: assertString("-"), DownstreamStatus: assertFloat64(float64(200)), DownstreamContentSize: assertFloat64(float64(40)), RequestRefererHeader: assertString(testReferer), RequestUserAgentHeader: assertString(testUserAgent), ServiceURL: assertString("http://stream"), ServiceAddr: assertString("127.0.0.1"), ServiceName: assertString("stream"), ClientUsername: assertString(testUsername), ClientHost: assertString(testHostname), ClientPort: assertString(strconv.Itoa(testPort)), ClientAddr: assertString(fmt.Sprintf("%s:%d", testHostname, testPort)), "level": assertString("info"), "msg": assertString(""), RequestCount: assertFloat64NotZero(), Duration: assertFloat64NotZero(), Overhead: assertFloat64NotZero(), RetryAttempts: assertFloat64(float64(0)), "time": assertNotEmpty(), StartLocal: assertNotEmpty(), StartUTC: assertNotEmpty(), "downstream_Content-Type": assertString("text/plain"), "downstream_Transfer-Encoding": assertString("chunked"), "downstream_Cache-Control": assertString("no-cache"), } config := &otypes.AccessLog{ FilePath: filepath.Join(t.TempDir(), logFileNameSuffix), Format: JSONFormat, } doLoggingWithAbortedStream(t, config) logData, err := os.ReadFile(config.FilePath) require.NoError(t, err) jsonData := make(map[string]interface{}) err = json.Unmarshal(logData, &jsonData) require.NoError(t, err) assert.Len(t, jsonData, len(expected)) for field, assertion := range expected { assertion(t, jsonData[field]) if t.Failed() { return } } } func TestNewLogHandlerOutputStdout(t *testing.T) { testCases := []struct { desc string config *otypes.AccessLog expectedLog string }{ { desc: "default config", config: &otypes.AccessLog{ FilePath: "", Format: CommonFormat, }, expectedLog: `TestHost - TestUser [13/Apr/2016:07:14:19 -0700] "POST testpath HTTP/0.0" 123 12 "testReferer" "testUserAgent" 23 "testRouter" "http://127.0.0.1/testService" 1ms`, }, { desc: "default config with empty filters", config: &otypes.AccessLog{ FilePath: "", Format: CommonFormat, Filters: &otypes.AccessLogFilters{}, }, expectedLog: `TestHost - TestUser [13/Apr/2016:07:14:19 -0700] "POST testpath HTTP/0.0" 123 12 "testReferer" "testUserAgent" 23 "testRouter" "http://127.0.0.1/testService" 1ms`, }, { desc: "Status code filter not matching", config: &otypes.AccessLog{ FilePath: "", Format: CommonFormat, Filters: &otypes.AccessLogFilters{ StatusCodes: []string{"200"}, }, }, expectedLog: ``, }, { desc: "Status code filter matching", config: &otypes.AccessLog{ FilePath: "", Format: CommonFormat, Filters: &otypes.AccessLogFilters{ StatusCodes: []string{"123"}, }, }, expectedLog: `TestHost - TestUser [13/Apr/2016:07:14:19 -0700] "POST testpath HTTP/0.0" 123 12 "testReferer" "testUserAgent" 23 "testRouter" "http://127.0.0.1/testService" 1ms`, }, { desc: "Duration filter not matching", config: &otypes.AccessLog{ FilePath: "", Format: CommonFormat, Filters: &otypes.AccessLogFilters{ MinDuration: ptypes.Duration(1 * time.Hour), }, }, expectedLog: ``, }, { desc: "Duration filter matching", config: &otypes.AccessLog{ FilePath: "", Format: CommonFormat, Filters: &otypes.AccessLogFilters{ MinDuration: ptypes.Duration(1 * time.Millisecond), }, }, expectedLog: `TestHost - TestUser [13/Apr/2016:07:14:19 -0700] "POST testpath HTTP/0.0" 123 12 "testReferer" "testUserAgent" 23 "testRouter" "http://127.0.0.1/testService" 1ms`, }, { desc: "Retry attempts filter matching", config: &otypes.AccessLog{ FilePath: "", Format: CommonFormat, Filters: &otypes.AccessLogFilters{ RetryAttempts: true, }, }, expectedLog: `TestHost - TestUser [13/Apr/2016:07:14:19 -0700] "POST testpath HTTP/0.0" 123 12 "testReferer" "testUserAgent" 23 "testRouter" "http://127.0.0.1/testService" 1ms`, }, { desc: "Default mode keep", config: &otypes.AccessLog{ FilePath: "", Format: CommonFormat, Fields: &otypes.AccessLogFields{ DefaultMode: "keep", }, }, expectedLog: `TestHost - TestUser [13/Apr/2016:07:14:19 -0700] "POST testpath HTTP/0.0" 123 12 "testReferer" "testUserAgent" 23 "testRouter" "http://127.0.0.1/testService" 1ms`, }, { desc: "Default mode keep with override", config: &otypes.AccessLog{ FilePath: "", Format: CommonFormat, Fields: &otypes.AccessLogFields{ DefaultMode: "keep", Names: map[string]string{ ClientHost: "drop", }, }, }, expectedLog: `- - TestUser [13/Apr/2016:07:14:19 -0700] "POST testpath HTTP/0.0" 123 12 "testReferer" "testUserAgent" 23 "testRouter" "http://127.0.0.1/testService" 1ms`, }, { desc: "Default mode drop", config: &otypes.AccessLog{ FilePath: "", Format: CommonFormat, Fields: &otypes.AccessLogFields{ DefaultMode: "drop", }, }, expectedLog: `- - - [-] "- - -" - - "testReferer" "testUserAgent" - "-" "-" 0ms`, }, { desc: "Default mode drop with override", config: &otypes.AccessLog{ FilePath: "", Format: CommonFormat, Fields: &otypes.AccessLogFields{ DefaultMode: "drop", Names: map[string]string{ ClientHost: "drop", ClientUsername: "keep", }, }, }, expectedLog: `- - TestUser [-] "- - -" - - "testReferer" "testUserAgent" - "-" "-" 0ms`, }, { desc: "Default mode drop with header dropped", config: &otypes.AccessLog{ FilePath: "", Format: CommonFormat, Fields: &otypes.AccessLogFields{ DefaultMode: "drop", Names: map[string]string{ ClientHost: "drop", ClientUsername: "keep", }, Headers: &otypes.FieldHeaders{ DefaultMode: "drop", }, }, }, expectedLog: `- - TestUser [-] "- - -" - - "-" "-" - "-" "-" 0ms`, }, { desc: "Default mode drop with header redacted", config: &otypes.AccessLog{ FilePath: "", Format: CommonFormat, Fields: &otypes.AccessLogFields{ DefaultMode: "drop", Names: map[string]string{ ClientHost: "drop", ClientUsername: "keep", }, Headers: &otypes.FieldHeaders{ DefaultMode: "redact", }, }, }, expectedLog: `- - TestUser [-] "- - -" - - "REDACTED" "REDACTED" - "-" "-" 0ms`, }, { desc: "Default mode drop with header redacted", config: &otypes.AccessLog{ FilePath: "", Format: CommonFormat, Fields: &otypes.AccessLogFields{ DefaultMode: "drop", Names: map[string]string{ ClientHost: "drop", ClientUsername: "keep", }, Headers: &otypes.FieldHeaders{ DefaultMode: "keep", Names: map[string]string{ "Referer": "redact", }, }, }, }, expectedLog: `- - TestUser [-] "- - -" - - "REDACTED" "testUserAgent" - "-" "-" 0ms`, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { // NOTE: It is not possible to run these cases in parallel because we capture Stdout file, restoreStdout := captureStdout(t) defer restoreStdout() doLogging(t, test.config, false) written, err := os.ReadFile(file.Name()) require.NoError(t, err, "unable to read captured stdout from file") assertValidCommonLogData(t, test.expectedLog, written) }) } } func assertValidCommonLogData(t *testing.T, expected string, logData []byte) { t.Helper() if len(expected) == 0 { assert.Empty(t, logData) t.Log(string(logData)) return } result, err := ParseAccessLog(string(logData)) require.NoError(t, err) resultExpected, err := ParseAccessLog(expected) require.NoError(t, err) formatErrMessage := fmt.Sprintf("Expected:\t%q\nActual:\t%q", expected, string(logData)) require.Len(t, result, len(resultExpected), formatErrMessage)
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/accesslog/logger.go
pkg/middlewares/accesslog/logger.go
package accesslog import ( "context" "fmt" "io" "net" "net/http" "net/textproto" "net/url" "os" "path/filepath" "strings" "sync" "sync/atomic" "time" "github.com/containous/alice" "github.com/rs/zerolog/log" "github.com/sirupsen/logrus" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/middlewares/capture" "github.com/traefik/traefik/v3/pkg/middlewares/observability" "github.com/traefik/traefik/v3/pkg/observability/logs" otypes "github.com/traefik/traefik/v3/pkg/observability/types" traefiktls "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" "go.opentelemetry.io/contrib/bridges/otellogrus" "go.opentelemetry.io/otel/trace" ) type key string const ( // DataTableKey is the key within the request context used to store the Log Data Table. DataTableKey key = "LogDataTable" // CommonFormat is the common logging format (CLF). CommonFormat string = "common" // GenericCLFFormat is the generic CLF format. GenericCLFFormat string = "genericCLF" // JSONFormat is the JSON logging format. JSONFormat string = "json" ) type noopCloser struct { *os.File } func (n noopCloser) Write(p []byte) (int, error) { return n.File.Write(p) } func (n noopCloser) Close() error { // noop return nil } type handlerParams struct { ctx context.Context logDataTable *LogData } // Handler will write each request and its response to the access log. type Handler struct { config *otypes.AccessLog logger *logrus.Logger file io.WriteCloser mu sync.Mutex httpCodeRanges types.HTTPCodeRanges logHandlerChan chan handlerParams wg sync.WaitGroup } // AliceConstructor returns an alice.Constructor that wraps the Handler (conditionally) in a middleware chain. func (h *Handler) AliceConstructor() alice.Constructor { return func(next http.Handler) (http.Handler, error) { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { if h == nil { next.ServeHTTP(rw, req) return } h.ServeHTTP(rw, req, next) }), nil } } // NewHandler creates a new Handler. func NewHandler(ctx context.Context, config *otypes.AccessLog) (*Handler, error) { var file io.WriteCloser = noopCloser{os.Stdout} if len(config.FilePath) > 0 { f, err := openAccessLogFile(config.FilePath) if err != nil { return nil, fmt.Errorf("error opening access log file: %w", err) } file = f } logHandlerChan := make(chan handlerParams, config.BufferingSize) var formatter logrus.Formatter switch config.Format { case CommonFormat: formatter = new(CommonLogFormatter) case GenericCLFFormat: formatter = new(GenericCLFLogFormatter) case JSONFormat: formatter = new(logrus.JSONFormatter) default: log.Error().Msgf("Unsupported access log format: %q, defaulting to common format instead.", config.Format) formatter = new(CommonLogFormatter) } logger := &logrus.Logger{ Out: file, Formatter: formatter, Hooks: make(logrus.LevelHooks), Level: logrus.InfoLevel, } if config.OTLP != nil { otelLoggerProvider, err := config.OTLP.NewLoggerProvider(ctx) if err != nil { return nil, fmt.Errorf("setting up OpenTelemetry logger provider: %w", err) } logger.Hooks.Add(otellogrus.NewHook("traefik", otellogrus.WithLoggerProvider(otelLoggerProvider))) logger.Out = io.Discard } // Transform header names to a canonical form, to be used as is without further transformations, // and transform field names to lower case, to enable case-insensitive lookup. if config.Fields != nil { if len(config.Fields.Names) > 0 { fields := map[string]string{} for h, v := range config.Fields.Names { fields[strings.ToLower(h)] = v } config.Fields.Names = fields } if config.Fields.Headers != nil && len(config.Fields.Headers.Names) > 0 { fields := map[string]string{} for h, v := range config.Fields.Headers.Names { fields[textproto.CanonicalMIMEHeaderKey(h)] = v } config.Fields.Headers.Names = fields } } logHandler := &Handler{ config: config, logger: logger, file: file, logHandlerChan: logHandlerChan, } if config.Filters != nil { if httpCodeRanges, err := types.NewHTTPCodeRanges(config.Filters.StatusCodes); err != nil { log.Error().Err(err).Msg("Failed to create new HTTP code ranges") } else { logHandler.httpCodeRanges = httpCodeRanges } } if config.BufferingSize > 0 { logHandler.wg.Add(1) go func() { defer logHandler.wg.Done() for handlerParams := range logHandler.logHandlerChan { logHandler.logTheRoundTrip(handlerParams.ctx, handlerParams.logDataTable) } }() } return logHandler, nil } func openAccessLogFile(filePath string) (*os.File, error) { dir := filepath.Dir(filePath) if err := os.MkdirAll(dir, 0o755); err != nil { return nil, fmt.Errorf("failed to create log path %s: %w", dir, err) } file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o664) if err != nil { return nil, fmt.Errorf("error opening file %s: %w", filePath, err) } return file, nil } // GetLogData gets the request context object that contains logging data. // This creates data as the request passes through the middleware chain. func GetLogData(req *http.Request) *LogData { if ld, ok := req.Context().Value(DataTableKey).(*LogData); ok { return ld } return nil } func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request, next http.Handler) { if !observability.AccessLogsEnabled(req.Context()) { next.ServeHTTP(rw, req) return } now := time.Now().UTC() core := CoreLogData{ StartUTC: now, StartLocal: now.Local(), } logDataTable := &LogData{ Core: core, Request: request{ headers: req.Header, }, } if span := trace.SpanFromContext(req.Context()); span != nil { spanContext := span.SpanContext() if spanContext.HasTraceID() && spanContext.HasSpanID() { logDataTable.Core[TraceID] = spanContext.TraceID().String() logDataTable.Core[SpanID] = spanContext.SpanID().String() } } reqWithDataTable := req.WithContext(context.WithValue(req.Context(), DataTableKey, logDataTable)) core[RequestCount] = nextRequestCount() if req.Host != "" { core[RequestAddr] = req.Host core[RequestHost], core[RequestPort] = silentSplitHostPort(req.Host) } // copy the URL without the scheme, hostname etc urlCopy := &url.URL{ Path: req.URL.Path, RawPath: req.URL.RawPath, RawQuery: req.URL.RawQuery, ForceQuery: req.URL.ForceQuery, Fragment: req.URL.Fragment, } urlCopyString := urlCopy.String() core[RequestMethod] = req.Method core[RequestPath] = urlCopyString core[RequestProtocol] = req.Proto core[RequestScheme] = "http" if req.TLS != nil { core[RequestScheme] = "https" core[TLSVersion] = traefiktls.GetVersion(req.TLS) core[TLSCipher] = traefiktls.GetCipherName(req.TLS) if len(req.TLS.PeerCertificates) > 0 && req.TLS.PeerCertificates[0] != nil { core[TLSClientSubject] = req.TLS.PeerCertificates[0].Subject.String() } } core[ClientAddr] = req.RemoteAddr core[ClientHost], core[ClientPort] = silentSplitHostPort(req.RemoteAddr) if forwardedFor := req.Header.Get("X-Forwarded-For"); forwardedFor != "" { core[ClientHost] = forwardedFor } ctx := req.Context() capt, err := capture.FromContext(ctx) if err != nil { log.Ctx(ctx).Error().Err(err).Str(logs.MiddlewareType, "AccessLogs").Msg("Could not get Capture") return } defer func() { logDataTable.DownstreamResponse = downstreamResponse{ headers: rw.Header().Clone(), } logDataTable.DownstreamResponse.status = capt.StatusCode() logDataTable.DownstreamResponse.size = capt.ResponseSize() logDataTable.Request.size = capt.RequestSize() if _, ok := core[ClientUsername]; !ok { core[ClientUsername] = usernameIfPresent(reqWithDataTable.URL) } if h.config.BufferingSize > 0 { h.logHandlerChan <- handlerParams{ ctx: req.Context(), logDataTable: logDataTable, } return } h.logTheRoundTrip(req.Context(), logDataTable) }() next.ServeHTTP(rw, reqWithDataTable) } // Close closes the Logger (i.e. the file, drain logHandlerChan, etc). func (h *Handler) Close() error { close(h.logHandlerChan) h.wg.Wait() return h.file.Close() } // Rotate closes and reopens the log file to allow for rotation by an external source. func (h *Handler) Rotate() error { if h.config.FilePath == "" { return nil } if h.file != nil { defer func(f io.Closer) { _ = f.Close() }(h.file) } var err error h.file, err = os.OpenFile(h.config.FilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o664) if err != nil { return err } h.mu.Lock() defer h.mu.Unlock() h.logger.Out = h.file return nil } func silentSplitHostPort(value string) (host, port string) { host, port, err := net.SplitHostPort(value) if err != nil { return value, "-" } return host, port } func usernameIfPresent(theURL *url.URL) string { if theURL.User != nil { if name := theURL.User.Username(); name != "" { return name } } return "-" } // Logging handler to log frontend name, backend name, and elapsed time. func (h *Handler) logTheRoundTrip(ctx context.Context, logDataTable *LogData) { core := logDataTable.Core retryAttempts, ok := core[RetryAttempts].(int) if !ok { retryAttempts = 0 } core[RetryAttempts] = retryAttempts core[RequestContentSize] = logDataTable.Request.size status := logDataTable.DownstreamResponse.status core[DownstreamStatus] = status // n.b. take care to perform time arithmetic using UTC to avoid errors at DST boundaries. totalDuration := time.Now().UTC().Sub(core[StartUTC].(time.Time)) core[Duration] = totalDuration if !h.keepAccessLog(status, retryAttempts, totalDuration) { return } size := logDataTable.DownstreamResponse.size core[DownstreamContentSize] = size if original, ok := core[OriginContentSize]; ok { o64 := original.(int64) if size != o64 && size != 0 { core[GzipRatio] = float64(o64) / float64(size) } } core[Overhead] = totalDuration if origin, ok := core[OriginDuration]; ok { core[Overhead] = totalDuration - origin.(time.Duration) } fields := logrus.Fields{} for k, v := range logDataTable.Core { if h.config.Fields.Keep(strings.ToLower(k)) { fields[k] = v } } h.redactHeaders(logDataTable.Request.headers, fields, "request_") h.redactHeaders(logDataTable.OriginResponse, fields, "origin_") h.redactHeaders(logDataTable.DownstreamResponse.headers, fields, "downstream_") h.mu.Lock() defer h.mu.Unlock() entry := h.logger.WithContext(ctx).WithFields(fields) var message string if h.config.OTLP != nil { // If the logger is configured to use OpenTelemetry, // we compute the log body with the formatter. mBytes, err := h.logger.Formatter.Format(entry) if err != nil { message = fmt.Sprintf("Failed to format access log entry: %v", err) } else { message = string(mBytes) } } entry.Println(message) } func (h *Handler) redactHeaders(headers http.Header, fields logrus.Fields, prefix string) { for k := range headers { v := h.config.Fields.KeepHeader(k) switch v { case otypes.AccessLogKeep: fields[prefix+k] = strings.Join(headers.Values(k), ",") case otypes.AccessLogRedact: fields[prefix+k] = "REDACTED" } } } func (h *Handler) keepAccessLog(statusCode, retryAttempts int, duration time.Duration) bool { if h.config.Filters == nil { // no filters were specified return true } if len(h.httpCodeRanges) == 0 && !h.config.Filters.RetryAttempts && h.config.Filters.MinDuration == 0 { // empty filters were specified, e.g. by passing --accessLog.filters only (without other filter options) return true } if h.httpCodeRanges.Contains(statusCode) { return true } if h.config.Filters.RetryAttempts && retryAttempts > 0 { return true } if h.config.Filters.MinDuration > 0 && (ptypes.Duration(duration) > h.config.Filters.MinDuration) { return true } return false } var requestCounter uint64 // Request ID func nextRequestCount() uint64 { return atomic.AddUint64(&requestCounter, 1) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/accesslog/logdata.go
pkg/middlewares/accesslog/logdata.go
package accesslog import ( "net/http" ) const ( // StartUTC is the map key used for the time at which request processing started. StartUTC = "StartUTC" // StartLocal is the map key used for the local time at which request processing started. StartLocal = "StartLocal" // Duration is the map key used for the total time taken by processing the response, including the origin server's time but // not the log writing time. Duration = "Duration" // RouterName is the map key used for the name of the Traefik router. RouterName = "RouterName" // ServiceName is the map key used for the name of the Traefik backend. ServiceName = "ServiceName" // ServiceURL is the map key used for the URL of the Traefik backend. ServiceURL = "ServiceURL" // ServiceAddr is the map key used for the IP:port of the Traefik backend (extracted from BackendURL). ServiceAddr = "ServiceAddr" // ClientAddr is the map key used for the remote address in its original form (usually IP:port). ClientAddr = "ClientAddr" // ClientHost is the map key used for the remote IP address from which the client request was received. ClientHost = "ClientHost" // ClientPort is the map key used for the remote TCP port from which the client request was received. ClientPort = "ClientPort" // ClientUsername is the map key used for the username provided in the URL, if present. ClientUsername = "ClientUsername" // RequestAddr is the map key used for the HTTP Host header (usually IP:port). This is treated as not a header by the Go API. RequestAddr = "RequestAddr" // RequestHost is the map key used for the HTTP Host server name (not including port). RequestHost = "RequestHost" // RequestPort is the map key used for the TCP port from the HTTP Host. RequestPort = "RequestPort" // RequestMethod is the map key used for the HTTP method. RequestMethod = "RequestMethod" // RequestPath is the map key used for the HTTP request URI, not including the scheme, host or port. RequestPath = "RequestPath" // RequestProtocol is the map key used for the version of HTTP requested. RequestProtocol = "RequestProtocol" // RequestScheme is the map key used for the HTTP request scheme. RequestScheme = "RequestScheme" // RequestContentSize is the map key used for the number of bytes in the request entity (a.k.a. body) sent by the client. RequestContentSize = "RequestContentSize" // RequestRefererHeader is the Referer header in the request. RequestRefererHeader = "request_Referer" // RequestUserAgentHeader is the User-Agent header in the request. RequestUserAgentHeader = "request_User-Agent" // OriginDuration is the map key used for the time taken by the origin server ('upstream') to return its response. OriginDuration = "OriginDuration" // OriginContentSize is the map key used for the content length specified by the origin server, or 0 if unspecified. OriginContentSize = "OriginContentSize" // OriginStatus is the map key used for the HTTP status code returned by the origin server. // If the request was handled by this Traefik instance (e.g. with a redirect), then this value will be absent. OriginStatus = "OriginStatus" // DownstreamStatus is the map key used for the HTTP status code returned to the client. DownstreamStatus = "DownstreamStatus" // DownstreamContentSize is the map key used for the number of bytes in the response entity returned to the client. // This is in addition to the "Content-Length" header, which may be present in the origin response. DownstreamContentSize = "DownstreamContentSize" // RequestCount is the map key used for the number of requests received since the Traefik instance started. RequestCount = "RequestCount" // GzipRatio is the map key used for the response body compression ratio achieved. GzipRatio = "GzipRatio" // Overhead is the map key used for the processing time overhead caused by Traefik. Overhead = "Overhead" // RetryAttempts is the map key used for the amount of attempts the request was retried. RetryAttempts = "RetryAttempts" // TLSVersion is the version of TLS used in the request. TLSVersion = "TLSVersion" // TLSCipher is the cipher used in the request. TLSCipher = "TLSCipher" // TLSClientSubject is the string representation of the TLS client certificate's Subject. TLSClientSubject = "TLSClientSubject" // TraceID is the consistent identifier for tracking requests across services, including upstream ones managed by Traefik, shown as a 32-hex digit string. TraceID = "TraceId" // SpanID is the unique identifier for Traefik’s root span (EntryPoint) within a request trace, formatted as a 16-hex digit string. SpanID = "SpanId" ) // These are written out in the default case when no config is provided to specify keys of interest. var defaultCoreKeys = [...]string{ StartUTC, Duration, RouterName, ServiceName, ServiceURL, ClientHost, ClientPort, ClientUsername, RequestHost, RequestPort, RequestMethod, RequestPath, RequestProtocol, RequestScheme, RequestContentSize, OriginDuration, OriginContentSize, OriginStatus, DownstreamStatus, DownstreamContentSize, RequestCount, } // This contains the set of all keys, i.e. all the default keys plus all non-default keys. var allCoreKeys = make(map[string]struct{}) func init() { for _, k := range defaultCoreKeys { allCoreKeys[k] = struct{}{} } allCoreKeys[ServiceAddr] = struct{}{} allCoreKeys[ClientAddr] = struct{}{} allCoreKeys[RequestAddr] = struct{}{} allCoreKeys[GzipRatio] = struct{}{} allCoreKeys[StartLocal] = struct{}{} allCoreKeys[Overhead] = struct{}{} allCoreKeys[RetryAttempts] = struct{}{} allCoreKeys[TLSVersion] = struct{}{} allCoreKeys[TLSCipher] = struct{}{} allCoreKeys[TLSClientSubject] = struct{}{} } // CoreLogData holds the fields computed from the request/response. type CoreLogData map[string]interface{} // LogData is the data captured by the middleware so that it can be logged. type LogData struct { Core CoreLogData Request request OriginResponse http.Header DownstreamResponse downstreamResponse } type downstreamResponse struct { headers http.Header status int size int64 } type request struct { headers http.Header // Request body size size int64 }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/accesslog/save_retries.go
pkg/middlewares/accesslog/save_retries.go
package accesslog import ( "net/http" ) // SaveRetries is an implementation of RetryListener that stores RetryAttempts in the LogDataTable. type SaveRetries struct{} // Retried implements the RetryListener interface and will be called for each retry that happens. func (s *SaveRetries) Retried(req *http.Request, attempt int) { // it is the request attempt x, but the retry attempt is x-1 if attempt > 0 { attempt-- } table := GetLogData(req) if table != nil { table.Core[RetryAttempts] = attempt } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/accesslog/field_middleware_test.go
pkg/middlewares/accesslog/field_middleware_test.go
package accesslog import ( "context" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestConcatFieldHandler_ServeHTTP(t *testing.T) { testCases := []struct { desc string existingValue interface{} newValue string expectedResult string }{ { desc: "first router - no existing value", existingValue: nil, newValue: "router1", expectedResult: "router1", }, { desc: "second router - concatenate with existing string", existingValue: "router1", newValue: "router2", expectedResult: "router1 -> router2", }, { desc: "third router - concatenate with existing chain", existingValue: "router1 -> router2", newValue: "router3", expectedResult: "router1 -> router2 -> router3", }, { desc: "empty existing value - treat as first", existingValue: " ", newValue: "router1", expectedResult: "router1", }, { desc: "non-string existing value - replace with new value", existingValue: 123, newValue: "router1", expectedResult: "router1", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) logData := &LogData{ Core: CoreLogData{}, } if test.existingValue != nil { logData.Core[RouterName] = test.existingValue } req := httptest.NewRequest(http.MethodGet, "/test", nil) req = req.WithContext(context.WithValue(req.Context(), DataTableKey, logData)) handler := NewConcatFieldHandler(nextHandler, RouterName, test.newValue) rec := httptest.NewRecorder() handler.ServeHTTP(rec, req) assert.Equal(t, test.expectedResult, logData.Core[RouterName]) assert.Equal(t, http.StatusOK, rec.Code) }) } } func TestConcatFieldHandler_ServeHTTP_NoLogData(t *testing.T) { nextHandlerCalled := false nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { nextHandlerCalled = true w.WriteHeader(http.StatusOK) }) handler := NewConcatFieldHandler(nextHandler, RouterName, "router1") // Create request without LogData in context. req := httptest.NewRequest(http.MethodGet, "/test", nil) rec := httptest.NewRecorder() handler.ServeHTTP(rec, req) // Verify next handler was called and no panic occurred. assert.True(t, nextHandlerCalled) assert.Equal(t, http.StatusOK, rec.Code) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/ipwhitelist/ip_whitelist_test.go
pkg/middlewares/ipwhitelist/ip_whitelist_test.go
package ipwhitelist import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) func TestNewIPWhiteLister(t *testing.T) { testCases := []struct { desc string whiteList dynamic.IPWhiteList expectedError bool }{ { desc: "invalid IP", whiteList: dynamic.IPWhiteList{ SourceRange: []string{"foo"}, }, expectedError: true, }, { desc: "valid IP", whiteList: dynamic.IPWhiteList{ SourceRange: []string{"10.10.10.10"}, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) whiteLister, err := New(t.Context(), next, test.whiteList, "traefikTest") if test.expectedError { assert.Error(t, err) } else { require.NoError(t, err) assert.NotNil(t, whiteLister) } }) } } func TestIPWhiteLister_ServeHTTP(t *testing.T) { testCases := []struct { desc string whiteList dynamic.IPWhiteList remoteAddr string expected int }{ { desc: "authorized with remote address", whiteList: dynamic.IPWhiteList{ SourceRange: []string{"20.20.20.20"}, }, remoteAddr: "20.20.20.20:1234", expected: 200, }, { desc: "non authorized with remote address", whiteList: dynamic.IPWhiteList{ SourceRange: []string{"20.20.20.20"}, }, remoteAddr: "20.20.20.21:1234", expected: 403, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) whiteLister, err := New(t.Context(), next, test.whiteList, "traefikTest") require.NoError(t, err) recorder := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "http://10.10.10.10", nil) if len(test.remoteAddr) > 0 { req.RemoteAddr = test.remoteAddr } whiteLister.ServeHTTP(recorder, req) assert.Equal(t, test.expected, recorder.Code) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/ipwhitelist/ip_whitelist.go
pkg/middlewares/ipwhitelist/ip_whitelist.go
package ipwhitelist import ( "context" "errors" "fmt" "net/http" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/ip" "github.com/traefik/traefik/v3/pkg/middlewares" "github.com/traefik/traefik/v3/pkg/middlewares/observability" ) const ( typeName = "IPWhiteLister" ) // ipWhiteLister is a middleware that provides Checks of the Requesting IP against a set of Whitelists. type ipWhiteLister struct { next http.Handler whiteLister *ip.Checker strategy ip.Strategy name string } // New builds a new IPWhiteLister given a list of CIDR-Strings to whitelist. func New(ctx context.Context, next http.Handler, config dynamic.IPWhiteList, name string) (http.Handler, error) { logger := middlewares.GetLogger(ctx, name, typeName) logger.Debug().Msg("Creating middleware") if len(config.SourceRange) == 0 { return nil, errors.New("sourceRange is empty, IPWhiteLister not created") } checker, err := ip.NewChecker(config.SourceRange) if err != nil { return nil, fmt.Errorf("cannot parse CIDR whitelist %s: %w", config.SourceRange, err) } strategy, err := config.IPStrategy.Get() if err != nil { return nil, err } logger.Debug().Msgf("Setting up IPWhiteLister with sourceRange: %s", config.SourceRange) return &ipWhiteLister{ strategy: strategy, whiteLister: checker, next: next, name: name, }, nil } func (wl *ipWhiteLister) GetTracingInformation() (string, string) { return wl.name, typeName } func (wl *ipWhiteLister) ServeHTTP(rw http.ResponseWriter, req *http.Request) { logger := middlewares.GetLogger(req.Context(), wl.name, typeName) ctx := logger.WithContext(req.Context()) clientIP := wl.strategy.GetIP(req) err := wl.whiteLister.IsAuthorized(clientIP) if err != nil { logger.Debug().Msgf("Rejecting IP %s: %v", clientIP, err) observability.SetStatusErrorf(req.Context(), "Rejecting IP %s: %v", clientIP, err) reject(ctx, rw) return } logger.Debug().Msgf("Accepting IP %s", clientIP) wl.next.ServeHTTP(rw, req) } func reject(ctx context.Context, rw http.ResponseWriter) { statusCode := http.StatusForbidden rw.WriteHeader(statusCode) _, err := rw.Write([]byte(http.StatusText(statusCode))) if err != nil { log.Ctx(ctx).Error().Err(err).Send() } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/redirect/redirect_regex_test.go
pkg/middlewares/redirect/redirect_regex_test.go
package redirect import ( "crypto/tls" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) func TestRedirectRegexHandler(t *testing.T) { testCases := []struct { desc string config dynamic.RedirectRegex method string url string headers map[string]string secured bool expectedURL string expectedStatus int errorExpected bool }{ { desc: "simple redirection", config: dynamic.RedirectRegex{ Regex: `^(?:http?:\/\/)(foo)(\.com)(:\d+)(.*)$`, Replacement: "https://${1}bar$2:443$4", }, url: "http://foo.com:80", expectedURL: "https://foobar.com:443", expectedStatus: http.StatusFound, }, { desc: "URL doesn't match regex", config: dynamic.RedirectRegex{ Regex: `^(?:http?:\/\/)(foo)(\.com)(:\d+)(.*)$`, Replacement: "https://${1}bar$2:443$4", }, url: "http://bar.com:80", expectedStatus: http.StatusOK, }, { desc: "invalid rewritten URL", config: dynamic.RedirectRegex{ Regex: `^(.*)$`, Replacement: "http://192.168.0.%31/", }, url: "http://foo.com:80", expectedStatus: http.StatusBadGateway, }, { desc: "invalid regex", config: dynamic.RedirectRegex{ Regex: `^(.*`, Replacement: "$1", }, url: "http://foo.com:80", errorExpected: true, }, { desc: "HTTP to HTTPS permanent", config: dynamic.RedirectRegex{ Regex: `^http://`, Replacement: "https://$1", Permanent: true, }, url: "http://foo", expectedURL: "https://foo", expectedStatus: http.StatusMovedPermanently, }, { desc: "HTTPS to HTTP permanent", config: dynamic.RedirectRegex{ Regex: `https://foo`, Replacement: "http://foo", Permanent: true, }, secured: true, url: "https://foo", expectedURL: "http://foo", expectedStatus: http.StatusMovedPermanently, }, { desc: "HTTP to HTTPS", config: dynamic.RedirectRegex{ Regex: `http://foo:80`, Replacement: "https://foo:443", }, url: "http://foo:80", expectedURL: "https://foo:443", expectedStatus: http.StatusFound, }, { desc: "HTTP to HTTPS, with X-Forwarded-Proto", config: dynamic.RedirectRegex{ Regex: `http://foo:80`, Replacement: "https://foo:443", }, url: "http://foo:80", headers: map[string]string{ "X-Forwarded-Proto": "https", }, expectedURL: "https://foo:443", expectedStatus: http.StatusFound, }, { desc: "HTTPS to HTTP", config: dynamic.RedirectRegex{ Regex: `https://foo:443`, Replacement: "http://foo:80", }, secured: true, url: "https://foo:443", expectedURL: "http://foo:80", expectedStatus: http.StatusFound, }, { desc: "HTTP to HTTP", config: dynamic.RedirectRegex{ Regex: `http://foo:80`, Replacement: "http://foo:88", }, url: "http://foo:80", expectedURL: "http://foo:88", expectedStatus: http.StatusFound, }, { desc: "HTTP to HTTP POST", config: dynamic.RedirectRegex{ Regex: `^http://`, Replacement: "https://$1", }, url: "http://foo", method: http.MethodPost, expectedURL: "https://foo", expectedStatus: http.StatusTemporaryRedirect, }, { desc: "HTTP to HTTP POST permanent", config: dynamic.RedirectRegex{ Regex: `^http://`, Replacement: "https://$1", Permanent: true, }, url: "http://foo", method: http.MethodPost, expectedURL: "https://foo", expectedStatus: http.StatusPermanentRedirect, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) handler, err := NewRedirectRegex(t.Context(), next, test.config, "traefikTest") if test.errorExpected { require.Error(t, err) require.Nil(t, handler) } else { require.NoError(t, err) require.NotNil(t, handler) recorder := httptest.NewRecorder() method := http.MethodGet if test.method != "" { method = test.method } req := httptest.NewRequest(method, test.url, nil) if test.secured { req.TLS = &tls.ConnectionState{} } for k, v := range test.headers { req.Header.Set(k, v) } req.Header.Set("X-Foo", "bar") handler.ServeHTTP(recorder, req) assert.Equal(t, test.expectedStatus, recorder.Code) switch test.expectedStatus { case http.StatusMovedPermanently, http.StatusFound, http.StatusTemporaryRedirect, http.StatusPermanentRedirect: location, err := recorder.Result().Location() require.NoError(t, err) assert.Equal(t, test.expectedURL, location.String()) default: location, err := recorder.Result().Location() require.Errorf(t, err, "Location %v", location) } } }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/redirect/redirect_scheme.go
pkg/middlewares/redirect/redirect_scheme.go
package redirect import ( "context" "errors" "net" "net/http" "strings" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/middlewares" ) const ( typeSchemeName = "RedirectScheme" uriPattern = `^(https?:\/\/)?(\[[\w:.]+\]|[\w\._-]+)?(:\d+)?(.*)$` xForwardedProto = "X-Forwarded-Proto" ) type redirectScheme struct { http.Handler name string } // NewRedirectScheme creates a new RedirectScheme middleware. func NewRedirectScheme(ctx context.Context, next http.Handler, conf dynamic.RedirectScheme, name string) (http.Handler, error) { logger := middlewares.GetLogger(ctx, name, typeSchemeName) logger.Debug().Msg("Creating middleware") logger.Debug().Msgf("Setting up redirection to %s %s", conf.Scheme, conf.Port) if len(conf.Scheme) == 0 { return nil, errors.New("you must provide a target scheme") } port := "" if len(conf.Port) > 0 && !(conf.Scheme == schemeHTTP && conf.Port == "80" || conf.Scheme == schemeHTTPS && conf.Port == "443") { port = ":" + conf.Port } rs := &redirectScheme{name: name} handler, err := newRedirect(next, uriPattern, conf.Scheme+"://${2}"+port+"${4}", conf.Permanent, conf.ForcePermanentRedirect, rs.clientRequestURL, name) if err != nil { return nil, err } rs.Handler = handler return rs, nil } func (r *redirectScheme) clientRequestURL(req *http.Request) string { scheme := schemeHTTP host, port, err := net.SplitHostPort(req.Host) if err != nil { host = req.Host } else { port = ":" + port } uri := req.RequestURI if match := uriRegexp.FindStringSubmatch(req.RequestURI); len(match) > 0 { scheme = match[1] if len(match[2]) > 0 { host = match[2] } if len(match[3]) > 0 { port = match[3] } uri = match[4] } if req.TLS != nil { scheme = schemeHTTPS } if xProto := req.Header.Get(xForwardedProto); xProto != "" { // When the initial request is a connection upgrade request, // X-Forwarded-Proto header might have been set by a previous hop to ws(s), // even though the actual protocol used so far is HTTP(s). // Given that we're in a middleware that is only used in the context of HTTP(s) requests, // the only possible valid schemes are one of "http" or "https", so we convert back to them. switch { case strings.EqualFold(xProto, schemeHTTP), strings.EqualFold(xProto, "ws"): scheme = schemeHTTP case strings.EqualFold(xProto, schemeHTTPS), strings.EqualFold(xProto, "wss"): scheme = schemeHTTPS default: middlewares.GetLogger(req.Context(), r.name, typeSchemeName).Debug().Msgf("Invalid X-Forwarded-Proto: %s", xProto) } } if scheme == schemeHTTP && port == ":80" || scheme == schemeHTTPS && port == ":443" { port = "" } return strings.Join([]string{scheme, "://", host, port, uri}, "") }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/redirect/redirect_scheme_test.go
pkg/middlewares/redirect/redirect_scheme_test.go
package redirect import ( "crypto/tls" "net/http" "net/http/httptest" "regexp" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) func TestRedirectSchemeHandler(t *testing.T) { testCases := []struct { desc string config dynamic.RedirectScheme method string url string headers map[string]string secured bool expectedURL string expectedStatus int errorExpected bool }{ { desc: "Without scheme", config: dynamic.RedirectScheme{}, url: "http://foo", errorExpected: true, }, { desc: "HTTP to HTTPS", config: dynamic.RedirectScheme{ Scheme: "https", }, url: "http://foo", expectedURL: "https://foo", expectedStatus: http.StatusFound, }, { desc: "HTTP to HTTPS, with X-Forwarded-Proto", config: dynamic.RedirectScheme{ Scheme: "https", }, url: "http://foo", headers: map[string]string{ "X-Forwarded-Proto": "http", }, expectedURL: "https://foo", expectedStatus: http.StatusFound, }, { desc: "HTTP to HTTPS, with X-Forwarded-Proto to HTTPS", config: dynamic.RedirectScheme{ Scheme: "https", }, url: "http://foo", headers: map[string]string{ "X-Forwarded-Proto": "https", }, expectedStatus: http.StatusOK, }, { desc: "HTTP to HTTPS, with X-Forwarded-Proto to unknown value", config: dynamic.RedirectScheme{ Scheme: "https", }, url: "http://foo", headers: map[string]string{ "X-Forwarded-Proto": "bar", }, expectedURL: "https://foo", expectedStatus: http.StatusFound, }, { desc: "HTTP to HTTPS, with X-Forwarded-Proto to ws", config: dynamic.RedirectScheme{ Scheme: "https", }, url: "http://foo", headers: map[string]string{ "X-Forwarded-Proto": "ws", }, expectedURL: "https://foo", expectedStatus: http.StatusFound, }, { desc: "HTTP to HTTPS, with X-Forwarded-Proto to wss", config: dynamic.RedirectScheme{ Scheme: "https", }, url: "http://foo", headers: map[string]string{ "X-Forwarded-Proto": "wss", }, expectedStatus: http.StatusOK, }, { desc: "HTTP with port to HTTPS without port", config: dynamic.RedirectScheme{ Scheme: "https", }, url: "http://foo:8080", expectedURL: "https://foo", expectedStatus: http.StatusFound, }, { desc: "HTTP without port to HTTPS with port", config: dynamic.RedirectScheme{ Scheme: "https", Port: "8443", }, url: "http://foo", expectedURL: "https://foo:8443", expectedStatus: http.StatusFound, }, { desc: "HTTP with port to HTTPS with port", config: dynamic.RedirectScheme{ Scheme: "https", Port: "8443", }, url: "http://foo:8000", expectedURL: "https://foo:8443", expectedStatus: http.StatusFound, }, { desc: "HTTPS with port to HTTPS with port", config: dynamic.RedirectScheme{ Scheme: "https", Port: "8443", }, url: "https://foo:8000", expectedURL: "https://foo:8443", expectedStatus: http.StatusFound, }, { desc: "HTTPS with port to HTTPS without port", config: dynamic.RedirectScheme{ Scheme: "https", }, url: "https://foo:8000", expectedURL: "https://foo", expectedStatus: http.StatusFound, }, { desc: "redirection to HTTPS without port from an URL already in https", config: dynamic.RedirectScheme{ Scheme: "https", }, url: "https://foo:8000/theother", expectedURL: "https://foo/theother", expectedStatus: http.StatusFound, }, { desc: "HTTP to HTTPS permanent", config: dynamic.RedirectScheme{ Scheme: "https", Port: "8443", Permanent: true, }, url: "http://foo", expectedURL: "https://foo:8443", expectedStatus: http.StatusMovedPermanently, }, { desc: "HTTP to HTTPS with explicit 308 status code", config: dynamic.RedirectScheme{ Scheme: "https", ForcePermanentRedirect: true, }, url: "http://foo", expectedURL: "https://foo", expectedStatus: http.StatusPermanentRedirect, }, { desc: "HTTP to HTTPS with explicit 308 status code for GET request", method: http.MethodGet, config: dynamic.RedirectScheme{ Scheme: "https", ForcePermanentRedirect: true, }, url: "http://foo", expectedURL: "https://foo", expectedStatus: http.StatusPermanentRedirect, }, { desc: "to HTTP 80", config: dynamic.RedirectScheme{ Scheme: "http", Port: "80", }, url: "http://foo:80", expectedURL: "http://foo:80", expectedStatus: http.StatusOK, }, { desc: "to HTTPS 443", config: dynamic.RedirectScheme{ Scheme: "https", Port: "443", }, url: "https://foo:443", expectedURL: "https://foo:443", expectedStatus: http.StatusOK, }, { desc: "HTTP to wss", config: dynamic.RedirectScheme{ Scheme: "wss", Port: "9443", }, url: "http://foo", expectedURL: "wss://foo:9443", expectedStatus: http.StatusFound, }, { desc: "HTTP to wss without port", config: dynamic.RedirectScheme{ Scheme: "wss", }, url: "http://foo", expectedURL: "wss://foo", expectedStatus: http.StatusFound, }, { desc: "HTTP with port to wss without port", config: dynamic.RedirectScheme{ Scheme: "wss", }, url: "http://foo:5678", expectedURL: "wss://foo", expectedStatus: http.StatusFound, }, { desc: "HTTP to HTTPS without port", config: dynamic.RedirectScheme{ Scheme: "https", }, url: "http://foo:443", expectedURL: "https://foo", expectedStatus: http.StatusFound, }, { desc: "HTTP port redirection", config: dynamic.RedirectScheme{ Scheme: "http", Port: "8181", }, url: "http://foo:8080", expectedURL: "http://foo:8181", expectedStatus: http.StatusFound, }, { desc: "HTTPS with port 80 to HTTPS without port", config: dynamic.RedirectScheme{ Scheme: "https", }, url: "https://foo:80", expectedURL: "https://foo", expectedStatus: http.StatusFound, }, { desc: "IPV6 HTTP to HTTPS redirection without port", config: dynamic.RedirectScheme{ Scheme: "https", }, url: "http://[::1]", expectedURL: "https://[::1]", expectedStatus: http.StatusFound, }, { desc: "IPV6 HTTP to HTTPS redirection with port", config: dynamic.RedirectScheme{ Scheme: "https", Port: "8443", }, url: "http://[::1]", expectedURL: "https://[::1]:8443", expectedStatus: http.StatusFound, }, { desc: "IPV6 HTTP with port 80 to HTTPS redirection without port", config: dynamic.RedirectScheme{ Scheme: "https", }, url: "http://[::1]:80", expectedURL: "https://[::1]", expectedStatus: http.StatusFound, }, { desc: "IPV6 HTTP with port 80 to HTTPS redirection with port", config: dynamic.RedirectScheme{ Scheme: "https", Port: "8443", }, url: "http://[::1]:80", expectedURL: "https://[::1]:8443", expectedStatus: http.StatusFound, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) handler, err := NewRedirectScheme(t.Context(), next, test.config, "traefikTest") if test.errorExpected { require.Error(t, err) require.Nil(t, handler) } else { require.NoError(t, err) require.NotNil(t, handler) recorder := httptest.NewRecorder() method := http.MethodGet if test.method != "" { method = test.method } req := httptest.NewRequest(method, test.url, nil) for k, v := range test.headers { req.Header.Set(k, v) } if test.secured { req.TLS = &tls.ConnectionState{} } req.Header.Set("X-Foo", "bar") handler.ServeHTTP(recorder, req) assert.Equal(t, test.expectedStatus, recorder.Code) switch test.expectedStatus { case http.StatusMovedPermanently, http.StatusFound, http.StatusTemporaryRedirect, http.StatusPermanentRedirect: location, err := recorder.Result().Location() require.NoError(t, err) assert.Equal(t, test.expectedURL, location.String()) default: location, err := recorder.Result().Location() require.Errorf(t, err, "Location %v", location) } schemeRegex := `^(https?):\/\/(\[[\w:.]+\]|[\w\._-]+)?(:\d+)?(.*)$` re, _ := regexp.Compile(schemeRegex) if re.MatchString(test.url) { match := re.FindStringSubmatch(test.url) req.RequestURI = match[4] handler.ServeHTTP(recorder, req) assert.Equal(t, test.expectedStatus, recorder.Code) if test.expectedStatus == http.StatusMovedPermanently || test.expectedStatus == http.StatusFound || test.expectedStatus == http.StatusTemporaryRedirect || test.expectedStatus == http.StatusPermanentRedirect { location, err := recorder.Result().Location() require.NoError(t, err) assert.Equal(t, test.expectedURL, location.String()) } else { location, err := recorder.Result().Location() require.Errorf(t, err, "Location %v", location) } } } }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/redirect/redirect_regex.go
pkg/middlewares/redirect/redirect_regex.go
package redirect import ( "context" "net/http" "strings" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/middlewares" ) const typeRegexName = "RedirectRegex" // NewRedirectRegex creates a redirect middleware. func NewRedirectRegex(ctx context.Context, next http.Handler, conf dynamic.RedirectRegex, name string) (http.Handler, error) { logger := middlewares.GetLogger(ctx, name, typeRegexName) logger.Debug().Msg("Creating middleware") logger.Debug().Msgf("Setting up redirection from %s to %s", conf.Regex, conf.Replacement) return newRedirect(next, conf.Regex, conf.Replacement, conf.Permanent, false, rawURL, name) } func rawURL(req *http.Request) string { scheme := schemeHTTP host := req.Host port := "" uri := req.RequestURI if match := uriRegexp.FindStringSubmatch(req.RequestURI); len(match) > 0 { scheme = match[1] if len(match[2]) > 0 { host = match[2] } if len(match[3]) > 0 { port = match[3] } uri = match[4] } if req.TLS != nil { scheme = schemeHTTPS } return strings.Join([]string{scheme, "://", host, port, uri}, "") }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/redirect/redirect.go
pkg/middlewares/redirect/redirect.go
package redirect import ( "net/http" "net/url" "regexp" "github.com/vulcand/oxy/v2/utils" ) const ( schemeHTTP = "http" schemeHTTPS = "https" ) const typeName = "Redirect" var uriRegexp = regexp.MustCompile(`^(https?):\/\/(\[[\w:.]+\]|[\w\._-]+)?(:\d+)?(.*)$`) type redirect struct { next http.Handler regex *regexp.Regexp replacement string permanent bool forcePermanentRedirect bool errHandler utils.ErrorHandler name string rawURL func(*http.Request) string } // New creates a Redirect middleware. func newRedirect(next http.Handler, regex, replacement string, permanent bool, forcePermanentRedirect bool, rawURL func(*http.Request) string, name string) (http.Handler, error) { re, err := regexp.Compile(regex) if err != nil { return nil, err } return &redirect{ regex: re, replacement: replacement, permanent: permanent, forcePermanentRedirect: forcePermanentRedirect, errHandler: utils.DefaultHandler, next: next, name: name, rawURL: rawURL, }, nil } func (r *redirect) GetTracingInformation() (string, string) { return r.name, typeName } func (r *redirect) ServeHTTP(rw http.ResponseWriter, req *http.Request) { oldURL := r.rawURL(req) // If the Regexp doesn't match, skip to the next handler. if !r.regex.MatchString(oldURL) { r.next.ServeHTTP(rw, req) return } // Apply a rewrite regexp to the URL. newURL := r.regex.ReplaceAllString(oldURL, r.replacement) // Parse the rewritten URL and replace request URL with it. parsedURL, err := url.Parse(newURL) if err != nil { r.errHandler.ServeHTTP(rw, req, err) return } if newURL != oldURL { handler := &moveHandler{location: parsedURL, permanent: r.permanent, forcePermanentRedirect: r.forcePermanentRedirect} handler.ServeHTTP(rw, req) return } req.URL = parsedURL // Make sure the request URI corresponds the rewritten URL. req.RequestURI = req.URL.RequestURI() r.next.ServeHTTP(rw, req) } type moveHandler struct { location *url.URL permanent bool forcePermanentRedirect bool } func (m *moveHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("Location", m.location.String()) status := http.StatusFound if req.Method != http.MethodGet { status = http.StatusTemporaryRedirect } if m.permanent { status = http.StatusMovedPermanently if req.Method != http.MethodGet { status = http.StatusPermanentRedirect } } if m.forcePermanentRedirect { status = http.StatusPermanentRedirect } rw.WriteHeader(status) _, err := rw.Write([]byte(http.StatusText(status))) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/healthcheck/healthcheck.go
pkg/healthcheck/healthcheck.go
package healthcheck import ( "bufio" "context" "errors" "fmt" "net" "net/http" "net/http/httptrace" "net/url" "strconv" "sync" "time" gokitmetrics "github.com/go-kit/kit/metrics" "github.com/rs/zerolog/log" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "golang.org/x/sync/singleflight" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/insecure" healthpb "google.golang.org/grpc/health/grpc_health_v1" "google.golang.org/grpc/status" ) const modeGRPC = "grpc" // StatusSetter should be implemented by a service that, when the status of a // registered target change, needs to be notified of that change. type StatusSetter interface { SetStatus(ctx context.Context, childName string, up bool) } // StatusUpdater should be implemented by a service that, when its status // changes (e.g. all if its children are down), needs to propagate upwards (to // their parent(s)) that change. type StatusUpdater interface { RegisterStatusUpdater(fn func(up bool)) error } type metricsHealthCheck interface { ServiceServerUpGauge() gokitmetrics.Gauge } type target struct { targetURL *url.URL name string } type ServiceHealthChecker struct { balancer StatusSetter info *runtime.ServiceInfo config *dynamic.ServerHealthCheck interval time.Duration unhealthyInterval time.Duration timeout time.Duration metrics metricsHealthCheck client *http.Client healthyTargets chan target unhealthyTargets chan target serviceName string } func NewServiceHealthChecker(ctx context.Context, metrics metricsHealthCheck, config *dynamic.ServerHealthCheck, service StatusSetter, info *runtime.ServiceInfo, transport http.RoundTripper, targets map[string]*url.URL, serviceName string) *ServiceHealthChecker { logger := log.Ctx(ctx) interval := time.Duration(config.Interval) if interval <= 0 { logger.Error().Msg("Health check interval smaller than zero, default value will be used instead.") interval = time.Duration(dynamic.DefaultHealthCheckInterval) } // If the unhealthyInterval option is not set, we use the interval option value, // to check the unhealthy targets as often as the healthy ones. var unhealthyInterval time.Duration if config.UnhealthyInterval == nil { unhealthyInterval = interval } else { unhealthyInterval = time.Duration(*config.UnhealthyInterval) if unhealthyInterval <= 0 { logger.Error().Msg("Health check unhealthy interval smaller than zero, default value will be used instead.") unhealthyInterval = time.Duration(dynamic.DefaultHealthCheckInterval) } } timeout := time.Duration(config.Timeout) if timeout <= 0 { logger.Error().Msg("Health check timeout smaller than zero, default value will be used instead.") timeout = time.Duration(dynamic.DefaultHealthCheckTimeout) } client := &http.Client{ Transport: transport, } if config.FollowRedirects != nil && !*config.FollowRedirects { client.CheckRedirect = func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse } } healthyTargets := make(chan target, len(targets)) for name, targetURL := range targets { healthyTargets <- target{ targetURL: targetURL, name: name, } } unhealthyTargets := make(chan target, len(targets)) return &ServiceHealthChecker{ balancer: service, info: info, config: config, interval: interval, unhealthyInterval: unhealthyInterval, timeout: timeout, healthyTargets: healthyTargets, unhealthyTargets: unhealthyTargets, serviceName: serviceName, client: client, metrics: metrics, } } func (shc *ServiceHealthChecker) Launch(ctx context.Context) { go shc.healthcheck(ctx, shc.unhealthyTargets, shc.unhealthyInterval) shc.healthcheck(ctx, shc.healthyTargets, shc.interval) } func (shc *ServiceHealthChecker) healthcheck(ctx context.Context, targets chan target, interval time.Duration) { ticker := time.NewTicker(interval) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ticker.C: // We collect the targets to check once for all, // to avoid rechecking a target that has been moved during the health check. var targetsToCheck []target hasMoreTargets := true for hasMoreTargets { select { case <-ctx.Done(): return case target := <-targets: targetsToCheck = append(targetsToCheck, target) default: hasMoreTargets = false } } // Now we can check the targets. for _, target := range targetsToCheck { select { case <-ctx.Done(): return default: } up := true serverUpMetricValue := float64(1) if err := shc.executeHealthCheck(ctx, shc.config, target.targetURL); err != nil { // The context is canceled when the dynamic configuration is refreshed. if errors.Is(err, context.Canceled) { return } log.Ctx(ctx).Warn(). Str("targetURL", target.targetURL.String()). Err(err). Msg("Health check failed.") up = false serverUpMetricValue = float64(0) } shc.balancer.SetStatus(ctx, target.name, up) var statusStr string if up { statusStr = runtime.StatusUp shc.healthyTargets <- target } else { statusStr = runtime.StatusDown shc.unhealthyTargets <- target } shc.info.UpdateServerStatus(target.targetURL.String(), statusStr) shc.metrics.ServiceServerUpGauge(). With("service", shc.serviceName, "url", target.targetURL.String()). Set(serverUpMetricValue) } } } } func (shc *ServiceHealthChecker) executeHealthCheck(ctx context.Context, config *dynamic.ServerHealthCheck, target *url.URL) error { ctx, cancel := context.WithDeadline(ctx, time.Now().Add(shc.timeout)) defer cancel() if config.Mode == modeGRPC { return shc.checkHealthGRPC(ctx, target) } return shc.checkHealthHTTP(ctx, target) } // checkHealthHTTP returns an error with a meaningful description if the health check failed. // Dedicated to HTTP servers. func (shc *ServiceHealthChecker) checkHealthHTTP(ctx context.Context, target *url.URL) error { req, err := shc.newRequest(ctx, target) if err != nil { return fmt.Errorf("create HTTP request: %w", err) } resp, err := shc.client.Do(req) if err != nil { return fmt.Errorf("HTTP request failed: %w", err) } defer resp.Body.Close() if shc.config.Status == 0 && (resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest) { return fmt.Errorf("received error status code: %v", resp.StatusCode) } if shc.config.Status != 0 && shc.config.Status != resp.StatusCode { return fmt.Errorf("received error status code: %v expected status code: %v", resp.StatusCode, shc.config.Status) } return nil } func (shc *ServiceHealthChecker) newRequest(ctx context.Context, target *url.URL) (*http.Request, error) { u, err := target.Parse(shc.config.Path) if err != nil { return nil, err } if len(shc.config.Scheme) > 0 { u.Scheme = shc.config.Scheme } if shc.config.Port != 0 { u.Host = net.JoinHostPort(u.Hostname(), strconv.Itoa(shc.config.Port)) } req, err := http.NewRequestWithContext(ctx, shc.config.Method, u.String(), http.NoBody) if err != nil { return nil, fmt.Errorf("failed to create HTTP request: %w", err) } if shc.config.Hostname != "" { req.Host = shc.config.Hostname } for k, v := range shc.config.Headers { req.Header.Set(k, v) } return req, nil } // checkHealthGRPC returns an error with a meaningful description if the health check failed. // Dedicated to gRPC servers implementing gRPC Health Checking Protocol v1. func (shc *ServiceHealthChecker) checkHealthGRPC(ctx context.Context, serverURL *url.URL) error { u, err := serverURL.Parse(shc.config.Path) if err != nil { return fmt.Errorf("failed to parse server URL: %w", err) } port := u.Port() if shc.config.Port != 0 { port = strconv.Itoa(shc.config.Port) } serverAddr := net.JoinHostPort(u.Hostname(), port) var opts []grpc.DialOption switch shc.config.Scheme { case "http", "h2c", "": opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials())) } conn, err := grpc.DialContext(ctx, serverAddr, opts...) if err != nil { if errors.Is(err, context.DeadlineExceeded) { return fmt.Errorf("fail to connect to %s within %s: %w", serverAddr, shc.config.Timeout, err) } return fmt.Errorf("fail to connect to %s: %w", serverAddr, err) } defer func() { _ = conn.Close() }() resp, err := healthpb.NewHealthClient(conn).Check(ctx, &healthpb.HealthCheckRequest{}) if err != nil { if stat, ok := status.FromError(err); ok { switch stat.Code() { case codes.Unimplemented: return fmt.Errorf("gRPC server does not implement the health protocol: %w", err) case codes.DeadlineExceeded: return fmt.Errorf("gRPC health check timeout: %w", err) case codes.Canceled: return context.Canceled } } return fmt.Errorf("gRPC health check failed: %w", err) } if resp.GetStatus() != healthpb.HealthCheckResponse_SERVING { return fmt.Errorf("received gRPC status code: %v", resp.GetStatus()) } return nil } type PassiveServiceHealthChecker struct { serviceName string balancer StatusSetter metrics metricsHealthCheck maxFailedAttempts int failureWindow ptypes.Duration hasActiveHealthCheck bool failuresMu sync.RWMutex failures map[string][]time.Time timersGroup singleflight.Group timers sync.Map } func NewPassiveHealthChecker(serviceName string, balancer StatusSetter, maxFailedAttempts int, failureWindow ptypes.Duration, hasActiveHealthCheck bool, metrics metricsHealthCheck) *PassiveServiceHealthChecker { return &PassiveServiceHealthChecker{ serviceName: serviceName, balancer: balancer, failures: make(map[string][]time.Time), maxFailedAttempts: maxFailedAttempts, failureWindow: failureWindow, hasActiveHealthCheck: hasActiveHealthCheck, metrics: metrics, } } func (p *PassiveServiceHealthChecker) WrapHandler(ctx context.Context, next http.Handler, targetURL string) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { var backendCalled bool trace := &httptrace.ClientTrace{ WroteHeaders: func() { backendCalled = true }, WroteRequest: func(httptrace.WroteRequestInfo) { backendCalled = true }, } clientTraceCtx := httptrace.WithClientTrace(req.Context(), trace) codeCatcher := &codeCatcher{ ResponseWriter: rw, } next.ServeHTTP(codeCatcher, req.WithContext(clientTraceCtx)) if backendCalled && codeCatcher.statusCode < http.StatusInternalServerError { p.failuresMu.Lock() p.failures[targetURL] = nil p.failuresMu.Unlock() return } p.failuresMu.Lock() p.failures[targetURL] = append(p.failures[targetURL], time.Now()) p.failuresMu.Unlock() if p.healthy(targetURL) { return } // We need to guarantee that only one goroutine (request) will update the status and create a timer for the target. _, _, _ = p.timersGroup.Do(targetURL, func() (interface{}, error) { // A timer is already running for this target; // it means that the target is already considered unhealthy. if _, ok := p.timers.Load(targetURL); ok { return nil, nil } p.balancer.SetStatus(ctx, targetURL, false) p.metrics.ServiceServerUpGauge().With("service", p.serviceName, "url", targetURL).Set(0) // If the service has an active health check, the passive health checker should not reset the status. // The active health check will handle the status updates. if p.hasActiveHealthCheck { return nil, nil } go func() { timer := time.NewTimer(time.Duration(p.failureWindow)) defer timer.Stop() p.timers.Store(targetURL, timer) select { case <-ctx.Done(): case <-timer.C: p.timers.Delete(targetURL) p.balancer.SetStatus(ctx, targetURL, true) p.metrics.ServiceServerUpGauge().With("service", p.serviceName, "url", targetURL).Set(1) } }() return nil, nil }) }) } func (p *PassiveServiceHealthChecker) healthy(targetURL string) bool { windowStart := time.Now().Add(-time.Duration(p.failureWindow)) p.failuresMu.Lock() defer p.failuresMu.Unlock() // Filter failures within the sliding window. failures := p.failures[targetURL] for i, t := range failures { if t.After(windowStart) { p.failures[targetURL] = failures[i:] break } } // Check if failures exceed maxFailedAttempts. return len(p.failures[targetURL]) < p.maxFailedAttempts } type codeCatcher struct { http.ResponseWriter statusCode int } func (c *codeCatcher) WriteHeader(statusCode int) { // Here we allow the overriding of the status code, // for the health check we care about the last status code written. c.statusCode = statusCode c.ResponseWriter.WriteHeader(statusCode) } func (c *codeCatcher) Write(bytes []byte) (int, error) { // At the time of writing, if the status code is not set, // or set to an informational status code (1xx), // we set it to http.StatusOK (200). if c.statusCode < http.StatusOK { c.statusCode = http.StatusOK } return c.ResponseWriter.Write(bytes) } func (c *codeCatcher) Flush() { if flusher, ok := c.ResponseWriter.(http.Flusher); ok { flusher.Flush() } } func (c *codeCatcher) Hijack() (net.Conn, *bufio.ReadWriter, error) { if h, ok := c.ResponseWriter.(http.Hijacker); ok { return h.Hijack() } return nil, nil, fmt.Errorf("not a hijacker: %T", c.ResponseWriter) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/healthcheck/healthcheck_test.go
pkg/healthcheck/healthcheck_test.go
package healthcheck import ( "context" "net/http" "net/http/httptest" "net/url" "sync" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/testhelpers" healthpb "google.golang.org/grpc/health/grpc_health_v1" ) const delta float64 = 1e-10 func pointer[T any](v T) *T { return &v } func TestNewServiceHealthChecker_durations(t *testing.T) { testCases := []struct { desc string config *dynamic.ServerHealthCheck expInterval time.Duration expTimeout time.Duration }{ { desc: "default values", config: &dynamic.ServerHealthCheck{}, expInterval: time.Duration(dynamic.DefaultHealthCheckInterval), expTimeout: time.Duration(dynamic.DefaultHealthCheckTimeout), }, { desc: "out of range values", config: &dynamic.ServerHealthCheck{ Interval: ptypes.Duration(-time.Second), Timeout: ptypes.Duration(-time.Second), }, expInterval: time.Duration(dynamic.DefaultHealthCheckInterval), expTimeout: time.Duration(dynamic.DefaultHealthCheckTimeout), }, { desc: "custom durations", config: &dynamic.ServerHealthCheck{ Interval: ptypes.Duration(time.Second * 10), Timeout: ptypes.Duration(time.Second * 5), }, expInterval: time.Second * 10, expTimeout: time.Second * 5, }, { desc: "interval shorter than timeout", config: &dynamic.ServerHealthCheck{ Interval: ptypes.Duration(time.Second), Timeout: ptypes.Duration(time.Second * 5), }, expInterval: time.Second, expTimeout: time.Second * 5, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() healthChecker := NewServiceHealthChecker(t.Context(), nil, test.config, nil, nil, http.DefaultTransport, nil, "") assert.Equal(t, test.expInterval, healthChecker.interval) assert.Equal(t, test.expTimeout, healthChecker.timeout) }) } } func TestServiceHealthChecker_newRequest(t *testing.T) { testCases := []struct { desc string targetURL string config dynamic.ServerHealthCheck expTarget string expError bool expHostname string expHeader string expMethod string }{ { desc: "no port override", targetURL: "http://backend1:80", config: dynamic.ServerHealthCheck{ Path: "/test", Port: 0, }, expError: false, expTarget: "http://backend1:80/test", expHostname: "backend1:80", expMethod: http.MethodGet, }, { desc: "port override", targetURL: "http://backend2:80", config: dynamic.ServerHealthCheck{ Path: "/test", Port: 8080, }, expError: false, expTarget: "http://backend2:8080/test", expHostname: "backend2:8080", expMethod: http.MethodGet, }, { desc: "no port override with no port in server URL", targetURL: "http://backend1", config: dynamic.ServerHealthCheck{ Path: "/health", Port: 0, }, expError: false, expTarget: "http://backend1/health", expHostname: "backend1", expMethod: http.MethodGet, }, { desc: "port override with no port in server URL", targetURL: "http://backend2", config: dynamic.ServerHealthCheck{ Path: "/health", Port: 8080, }, expError: false, expTarget: "http://backend2:8080/health", expHostname: "backend2:8080", expMethod: http.MethodGet, }, { desc: "scheme override", targetURL: "https://backend1:80", config: dynamic.ServerHealthCheck{ Scheme: "http", Path: "/test", Port: 0, }, expError: false, expTarget: "http://backend1:80/test", expHostname: "backend1:80", expMethod: http.MethodGet, }, { desc: "path with param", targetURL: "http://backend1:80", config: dynamic.ServerHealthCheck{ Path: "/health?powpow=do", Port: 0, }, expError: false, expTarget: "http://backend1:80/health?powpow=do", expHostname: "backend1:80", expMethod: http.MethodGet, }, { desc: "path with params", targetURL: "http://backend1:80", config: dynamic.ServerHealthCheck{ Path: "/health?powpow=do&do=powpow", Port: 0, }, expError: false, expTarget: "http://backend1:80/health?powpow=do&do=powpow", expHostname: "backend1:80", expMethod: http.MethodGet, }, { desc: "path with invalid path", targetURL: "http://backend1:80", config: dynamic.ServerHealthCheck{ Path: ":", Port: 0, }, expError: true, expTarget: "", expHostname: "backend1:80", expMethod: http.MethodGet, }, { desc: "override hostname", targetURL: "http://backend1:80", config: dynamic.ServerHealthCheck{ Hostname: "myhost", Path: "/", }, expTarget: "http://backend1:80/", expHostname: "myhost", expHeader: "", expMethod: http.MethodGet, }, { desc: "not override hostname", targetURL: "http://backend1:80", config: dynamic.ServerHealthCheck{ Hostname: "", Path: "/", }, expTarget: "http://backend1:80/", expHostname: "backend1:80", expHeader: "", expMethod: http.MethodGet, }, { desc: "custom header", targetURL: "http://backend1:80", config: dynamic.ServerHealthCheck{ Headers: map[string]string{"Custom-Header": "foo"}, Hostname: "", Path: "/", }, expTarget: "http://backend1:80/", expHostname: "backend1:80", expHeader: "foo", expMethod: http.MethodGet, }, { desc: "custom header with hostname override", targetURL: "http://backend1:80", config: dynamic.ServerHealthCheck{ Headers: map[string]string{"Custom-Header": "foo"}, Hostname: "myhost", Path: "/", }, expTarget: "http://backend1:80/", expHostname: "myhost", expHeader: "foo", expMethod: http.MethodGet, }, { desc: "custom method", targetURL: "http://backend1:80", config: dynamic.ServerHealthCheck{ Path: "/", Method: http.MethodHead, }, expTarget: "http://backend1:80/", expHostname: "backend1:80", expMethod: http.MethodHead, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() shc := ServiceHealthChecker{config: &test.config} u := testhelpers.MustParseURL(test.targetURL) req, err := shc.newRequest(t.Context(), u) if test.expError { require.Error(t, err) assert.Nil(t, req) } else { require.NoError(t, err, "failed to create new request") require.NotNil(t, req) assert.Equal(t, test.expTarget, req.URL.String()) assert.Equal(t, test.expHeader, req.Header.Get("Custom-Header")) assert.Equal(t, test.expHostname, req.Host) assert.Equal(t, test.expMethod, req.Method) } }) } } func TestServiceHealthChecker_checkHealthHTTP_NotFollowingRedirects(t *testing.T) { redirectServerCalled := false redirectTestServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { redirectServerCalled = true })) defer redirectTestServer.Close() ctx, cancel := context.WithTimeout(t.Context(), time.Duration(dynamic.DefaultHealthCheckTimeout)) defer cancel() server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Add("location", redirectTestServer.URL) rw.WriteHeader(http.StatusSeeOther) })) defer server.Close() config := &dynamic.ServerHealthCheck{ Path: "/path", FollowRedirects: pointer(false), Interval: dynamic.DefaultHealthCheckInterval, Timeout: dynamic.DefaultHealthCheckTimeout, } healthChecker := NewServiceHealthChecker(ctx, nil, config, nil, nil, http.DefaultTransport, nil, "") err := healthChecker.checkHealthHTTP(ctx, testhelpers.MustParseURL(server.URL)) require.NoError(t, err) assert.False(t, redirectServerCalled, "HTTP redirect must not be followed") } func TestServiceHealthChecker_Launch(t *testing.T) { testCases := []struct { desc string mode string status int server StartTestServer expNumRemovedServers int expNumUpsertedServers int expGaugeValue float64 targetStatus string }{ { desc: "healthy server staying healthy", server: newHTTPServer(http.StatusOK), expNumRemovedServers: 0, expNumUpsertedServers: 1, expGaugeValue: 1, targetStatus: runtime.StatusUp, }, { desc: "healthy server staying healthy, with custom code status check", server: newHTTPServer(http.StatusNotFound), status: http.StatusNotFound, expNumRemovedServers: 0, expNumUpsertedServers: 1, expGaugeValue: 1, targetStatus: runtime.StatusUp, }, { desc: "healthy server staying healthy (StatusNoContent)", server: newHTTPServer(http.StatusNoContent), expNumRemovedServers: 0, expNumUpsertedServers: 1, expGaugeValue: 1, targetStatus: runtime.StatusUp, }, { desc: "healthy server staying healthy (StatusPermanentRedirect)", server: newHTTPServer(http.StatusPermanentRedirect), expNumRemovedServers: 0, expNumUpsertedServers: 1, expGaugeValue: 1, targetStatus: runtime.StatusUp, }, { desc: "healthy server becoming sick", server: newHTTPServer(http.StatusServiceUnavailable), expNumRemovedServers: 1, expNumUpsertedServers: 0, expGaugeValue: 0, targetStatus: runtime.StatusDown, }, { desc: "healthy server becoming sick, with custom code status check", server: newHTTPServer(http.StatusOK), status: http.StatusServiceUnavailable, expNumRemovedServers: 1, expNumUpsertedServers: 0, expGaugeValue: 0, targetStatus: runtime.StatusDown, }, { desc: "healthy server toggling to sick and back to healthy", server: newHTTPServer(http.StatusServiceUnavailable, http.StatusOK), expNumRemovedServers: 1, expNumUpsertedServers: 1, expGaugeValue: 1, targetStatus: runtime.StatusUp, }, { desc: "healthy server toggling to healthy and go to sick", server: newHTTPServer(http.StatusOK, http.StatusServiceUnavailable), expNumRemovedServers: 1, expNumUpsertedServers: 1, expGaugeValue: 0, targetStatus: runtime.StatusDown, }, { desc: "healthy grpc server staying healthy", mode: "grpc", server: newGRPCServer(healthpb.HealthCheckResponse_SERVING), expNumRemovedServers: 0, expNumUpsertedServers: 1, expGaugeValue: 1, targetStatus: runtime.StatusUp, }, { desc: "healthy grpc server becoming sick", mode: "grpc", server: newGRPCServer(healthpb.HealthCheckResponse_NOT_SERVING), expNumRemovedServers: 1, expNumUpsertedServers: 0, expGaugeValue: 0, targetStatus: runtime.StatusDown, }, { desc: "healthy grpc server toggling to sick and back to healthy", mode: "grpc", server: newGRPCServer(healthpb.HealthCheckResponse_NOT_SERVING, healthpb.HealthCheckResponse_SERVING), expNumRemovedServers: 1, expNumUpsertedServers: 1, expGaugeValue: 1, targetStatus: runtime.StatusUp, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() // The context is passed to the health check and // canonically canceled by the test server once all expected requests have been received. ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) targetURL, timeout := test.server.Start(t, cancel) lb := &testLoadBalancer{RWMutex: &sync.RWMutex{}} config := &dynamic.ServerHealthCheck{ Mode: test.mode, Status: test.status, Path: "/path", Interval: ptypes.Duration(500 * time.Millisecond), UnhealthyInterval: pointer(ptypes.Duration(500 * time.Millisecond)), Timeout: ptypes.Duration(499 * time.Millisecond), } gauge := &testhelpers.CollectingGauge{} serviceInfo := &runtime.ServiceInfo{} hc := NewServiceHealthChecker(ctx, &MetricsMock{gauge}, config, lb, serviceInfo, http.DefaultTransport, map[string]*url.URL{"test": targetURL}, "foobar") wg := sync.WaitGroup{} wg.Add(1) go func() { hc.Launch(ctx) wg.Done() }() select { case <-time.After(timeout): t.Fatal("test did not complete in time") case <-ctx.Done(): wg.Wait() } lb.Lock() defer lb.Unlock() assert.Equal(t, test.expNumRemovedServers, lb.numRemovedServers, "removed servers") assert.Equal(t, test.expNumUpsertedServers, lb.numUpsertedServers, "upserted servers") assert.InDelta(t, test.expGaugeValue, gauge.GaugeValue, delta, "ServerUp Gauge") assert.Equal(t, []string{"service", "foobar", "url", targetURL.String()}, gauge.LastLabelValues) assert.Equal(t, map[string]string{targetURL.String(): test.targetStatus}, serviceInfo.GetAllStatus()) }) } } func TestDifferentIntervals(t *testing.T) { // The context is passed to the health check and // canonically canceled by the test server once all expected requests have been received. ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) healthyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.WriteHeader(http.StatusOK) })) healthyURL := testhelpers.MustParseURL(healthyServer.URL) unhealthyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.WriteHeader(http.StatusServiceUnavailable) })) unhealthyURL := testhelpers.MustParseURL(unhealthyServer.URL) lb := &testLoadBalancer{RWMutex: &sync.RWMutex{}} config := &dynamic.ServerHealthCheck{ Mode: "http", Path: "/path", Interval: ptypes.Duration(500 * time.Millisecond), UnhealthyInterval: pointer(ptypes.Duration(50 * time.Millisecond)), Timeout: ptypes.Duration(499 * time.Millisecond), } gauge := &testhelpers.CollectingGauge{} serviceInfo := &runtime.ServiceInfo{} hc := NewServiceHealthChecker(ctx, &MetricsMock{gauge}, config, lb, serviceInfo, http.DefaultTransport, map[string]*url.URL{"healthy": healthyURL, "unhealthy": unhealthyURL}, "foobar") wg := sync.WaitGroup{} wg.Add(1) go func() { hc.Launch(ctx) wg.Done() }() select { case <-time.After(2 * time.Second): break case <-ctx.Done(): wg.Wait() } lb.Lock() defer lb.Unlock() assert.Greater(t, lb.numRemovedServers, lb.numUpsertedServers, "removed servers greater than upserted servers") }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/healthcheck/healthcheck_tcp.go
pkg/healthcheck/healthcheck_tcp.go
package healthcheck import ( "context" "errors" "fmt" "net" "strconv" "time" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/tcp" ) // maxPayloadSize is the maximum payload size that can be sent during health checks. const maxPayloadSize = 65535 type TCPHealthCheckTarget struct { Address string TLS bool Dialer tcp.Dialer } type ServiceTCPHealthChecker struct { balancer StatusSetter info *runtime.TCPServiceInfo config *dynamic.TCPServerHealthCheck interval time.Duration unhealthyInterval time.Duration timeout time.Duration healthyTargets chan *TCPHealthCheckTarget unhealthyTargets chan *TCPHealthCheckTarget serviceName string } func NewServiceTCPHealthChecker(ctx context.Context, config *dynamic.TCPServerHealthCheck, service StatusSetter, info *runtime.TCPServiceInfo, targets []TCPHealthCheckTarget, serviceName string) *ServiceTCPHealthChecker { logger := log.Ctx(ctx) interval := time.Duration(config.Interval) if interval <= 0 { logger.Error().Msg("Health check interval smaller than zero, default value will be used instead.") interval = time.Duration(dynamic.DefaultHealthCheckInterval) } // If the unhealthyInterval option is not set, we use the interval option value, // to check the unhealthy targets as often as the healthy ones. var unhealthyInterval time.Duration if config.UnhealthyInterval == nil { unhealthyInterval = interval } else { unhealthyInterval = time.Duration(*config.UnhealthyInterval) if unhealthyInterval <= 0 { logger.Error().Msg("Health check unhealthy interval smaller than zero, default value will be used instead.") unhealthyInterval = time.Duration(dynamic.DefaultHealthCheckInterval) } } timeout := time.Duration(config.Timeout) if timeout <= 0 { logger.Error().Msg("Health check timeout smaller than zero, default value will be used instead.") timeout = time.Duration(dynamic.DefaultHealthCheckTimeout) } if config.Send != "" && len(config.Send) > maxPayloadSize { logger.Error().Msgf("Health check payload size exceeds maximum allowed size of %d bytes, falling back to connect only check.", maxPayloadSize) config.Send = "" } if config.Expect != "" && len(config.Expect) > maxPayloadSize { logger.Error().Msgf("Health check expected response size exceeds maximum allowed size of %d bytes, falling back to close without response.", maxPayloadSize) config.Expect = "" } healthyTargets := make(chan *TCPHealthCheckTarget, len(targets)) for _, target := range targets { healthyTargets <- &target } unhealthyTargets := make(chan *TCPHealthCheckTarget, len(targets)) return &ServiceTCPHealthChecker{ balancer: service, info: info, config: config, interval: interval, unhealthyInterval: unhealthyInterval, timeout: timeout, healthyTargets: healthyTargets, unhealthyTargets: unhealthyTargets, serviceName: serviceName, } } func (thc *ServiceTCPHealthChecker) Launch(ctx context.Context) { go thc.healthcheck(ctx, thc.unhealthyTargets, thc.unhealthyInterval) thc.healthcheck(ctx, thc.healthyTargets, thc.interval) } func (thc *ServiceTCPHealthChecker) healthcheck(ctx context.Context, targets chan *TCPHealthCheckTarget, interval time.Duration) { ticker := time.NewTicker(interval) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ticker.C: // We collect the targets to check once for all, // to avoid rechecking a target that has been moved during the health check. var targetsToCheck []*TCPHealthCheckTarget hasMoreTargets := true for hasMoreTargets { select { case <-ctx.Done(): return case target := <-targets: targetsToCheck = append(targetsToCheck, target) default: hasMoreTargets = false } } // Now we can check the targets. for _, target := range targetsToCheck { select { case <-ctx.Done(): return default: } up := true if err := thc.executeHealthCheck(ctx, thc.config, target); err != nil { // The context is canceled when the dynamic configuration is refreshed. if errors.Is(err, context.Canceled) { return } log.Ctx(ctx).Warn(). Str("targetAddress", target.Address). Err(err). Msg("Health check failed.") up = false } thc.balancer.SetStatus(ctx, target.Address, up) var statusStr string if up { statusStr = runtime.StatusUp thc.healthyTargets <- target } else { statusStr = runtime.StatusDown thc.unhealthyTargets <- target } thc.info.UpdateServerStatus(target.Address, statusStr) // TODO: add a TCP server up metric (like for HTTP). } } } } func (thc *ServiceTCPHealthChecker) executeHealthCheck(ctx context.Context, config *dynamic.TCPServerHealthCheck, target *TCPHealthCheckTarget) error { addr := target.Address if config.Port != 0 { host, _, err := net.SplitHostPort(target.Address) if err != nil { return fmt.Errorf("parsing address %q: %w", target.Address, err) } addr = net.JoinHostPort(host, strconv.Itoa(config.Port)) } ctx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Duration(config.Timeout))) defer cancel() conn, err := target.Dialer.DialContext(ctx, "tcp", addr, nil) if err != nil { return fmt.Errorf("connecting to %s: %w", addr, err) } defer conn.Close() if err := conn.SetDeadline(time.Now().Add(thc.timeout)); err != nil { return fmt.Errorf("setting timeout to %s: %w", thc.timeout, err) } if config.Send != "" { if _, err = conn.Write([]byte(config.Send)); err != nil { return fmt.Errorf("sending to %s: %w", addr, err) } } if config.Expect != "" { buf := make([]byte, len(config.Expect)) if _, err = conn.Read(buf); err != nil { return fmt.Errorf("reading from %s: %w", addr, err) } if string(buf) != config.Expect { return errors.New("unexpected heath check response") } } return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/healthcheck/healthcheck_tcp_test.go
pkg/healthcheck/healthcheck_tcp_test.go
package healthcheck import ( "context" "crypto/tls" "crypto/x509" "net" "strings" "sync" "testing" "time" "github.com/rs/zerolog/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" truntime "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/tcp" ) var localhostCert = []byte(`-----BEGIN CERTIFICATE----- MIIDJzCCAg+gAwIBAgIUe3vnWg3cTbflL6kz2TyPUxmV8Y4wDQYJKoZIhvcNAQEL BQAwFjEUMBIGA1UEAwwLZXhhbXBsZS5jb20wIBcNMjUwMzA1MjAwOTM4WhgPMjA1 NTAyMjYyMDA5MzhaMBYxFDASBgNVBAMMC2V4YW1wbGUuY29tMIIBIjANBgkqhkiG 9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4Mm4Sp6xzJvFZJWAv/KVmI1krywiuef8Fhlf JR2M0caKixjBcNt4U8KwrzIrqL+8nilbps1QuwpQ09+6ztlbUXUL6DqR8ZC+4oCp gOZ3yyVX2vhMigkATbQyJrX/WVjWSHD5rIUBP2BrsaYLt1qETnFP9wwQ3YEi7V4l c4+jDrZOtJvrv+tRClt9gQJVgkr7Y30X+dx+rsh+ROaA2+/VTDX0qtoqd/4fjhcJ OY9VLm0eU66VUMyOTNeUm6ZAXRBp/EonIM1FXOlj82S0pZQbPrvyWWqWoAjtPvLU qRzqp/BQJqx3EHz1dP6s+xUjP999B+7jhiHoFhZ/bfVVlx8XkwIDAQABo2swaTAd BgNVHQ4EFgQUhJiJ37LW6RODCpBPAApG1zQxFtAwHwYDVR0jBBgwFoAUhJiJ37LW 6RODCpBPAApG1zQxFtAwDwYDVR0TAQH/BAUwAwEB/zAWBgNVHREEDzANggtleGFt cGxlLmNvbTANBgkqhkiG9w0BAQsFAAOCAQEAfnDPHllA1TFlQ6zY46tqM20d68bR kXeGMKLoaATFPbDea5H8/GM5CU6CPD7RUuEB9CvxvaM0aOInxkgstozG7BOr8hcs WS9fMgM0oO5yGiSOv+Qa0Rc0BFb6A1fUJRta5MI5DTdTJLoyoRX/5aocSI34T67x ULbkJvVXw6hnx/KZ65apNobfmVQSy7DR8Fo82eB4hSoaLpXyUUTLmctGgrRCoKof GVUJfKsDJ4Ts8WIR1np74flSoxksWSHEOYk79AZOPANYgJwPMMiiZKsKm17GBoGu DxI0om4eX8GaSSZAtG6TOt3O3v1oCjKNsAC+u585HN0x0MFA33TUzC15NA== -----END CERTIFICATE-----`) var localhostKey = []byte(`-----BEGIN PRIVATE KEY----- MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDgybhKnrHMm8Vk lYC/8pWYjWSvLCK55/wWGV8lHYzRxoqLGMFw23hTwrCvMiuov7yeKVumzVC7ClDT 37rO2VtRdQvoOpHxkL7igKmA5nfLJVfa+EyKCQBNtDImtf9ZWNZIcPmshQE/YGux pgu3WoROcU/3DBDdgSLtXiVzj6MOtk60m+u/61EKW32BAlWCSvtjfRf53H6uyH5E 5oDb79VMNfSq2ip3/h+OFwk5j1UubR5TrpVQzI5M15SbpkBdEGn8SicgzUVc6WPz ZLSllBs+u/JZapagCO0+8tSpHOqn8FAmrHcQfPV0/qz7FSM/330H7uOGIegWFn9t 9VWXHxeTAgMBAAECggEALinfGhv7Iaz/3cdCOKlGBZ1MBxmGTC2TPKqbOpEWAWLH wwcjetznmjQKewBPrQkrYEPYGapioPbeYJS61Y4XzeO+vUOCA10ZhoSrytgJ1ANo RoTlmxd8I3kVL5QCy8ONxjTFYaOy/OP9We9iypXhRAbLSE4HDKZfmOXTxSbDctql Kq7uV3LX1KCfr9C6M8d79a0Rdr4p8IXp8MOg3tXq6n75vZbepRFyAujhg7o/kkTp lgv87h89lrK97K+AjqtvCIT3X3VXfA+LYp3AoQFdOluKgyJT221MyHkTeI/7gggt Z57lVGD71UJH/LGUJWrraJqXd9uDxZWprD/s66BIAQKBgQD8CtHUJ/VuS7gP0ebN 688zrmRtENj6Gqi+URm/Pwgr9b7wKKlf9jjhg5F/ue+BgB7/nK6N7yJ4Xx3JJ5ox LqsRGLFa4fDBxogF/FN27obD8naOxe2wS1uTjM6LSrvdJ+HjeNEwHYhjuDjTAHj5 VVEMagZWgkE4jBiFUYefiYLsAQKBgQDkUVdW8cXaYri5xxDW86JNUzI1tUPyd6I+ AkOHV/V0y2zpwTHVLcETRpdVGpc5TH3J5vWf+5OvSz6RDTGjv7blDb8vB/kVkFmn uXTi0dB9P+SYTsm+X3V7hOAFsyVYZ1D9IFsKUyMgxMdF+qgERjdPKx5IdLV/Jf3q P9pQ922TkwKBgCKllhyU9Z8Y14+NKi4qeUxAb9uyUjFnUsT+vwxULNpmKL44yLfB UCZoAKtPMwZZR2mZ70Dhm5pycNTDFeYm5Ssvesnkf0UT9oTkH9EcjvgGr5eGy9rN MSSCWa46MsL/BYVQiWkU1jfnDiCrUvXrbX3IYWCo/TA5yfEhuQQMUiwBAoGADyzo 5TqEsBNHu/FjSSZAb2tMNw2pSoBxJDX6TxClm/G5d4AD0+uKncFfZaSy0HgpFDZp tQx/sHML4ZBC8GNZwLe9MV8SS0Cg9Oj6v+i6Ntj8VLNH7YNix6b5TOevX8TeOTTh WDpWZ2Ms65XRfRc9reFrzd0UAzN/QQaleCQ6AEkCgYBe4Ucows7JGbv7fNkz3nb1 kyH+hk9ecnq/evDKX7UUxKO1wwTi74IYKgcRB2uPLpHKL35gPz+LAfCphCW5rwpR lvDhS+Pi/1KCBJxLHMv+V/WrckDRgHFnAhDaBZ+2vI/s09rKDnpjcTzV7x22kL0b XIJCEEE8JZ4AXIZ+IcB6LA== -----END PRIVATE KEY-----`) func TestNewServiceTCPHealthChecker(t *testing.T) { testCases := []struct { desc string config *dynamic.TCPServerHealthCheck expectedInterval time.Duration expectedTimeout time.Duration }{ { desc: "default values", config: &dynamic.TCPServerHealthCheck{}, expectedInterval: time.Duration(dynamic.DefaultHealthCheckInterval), expectedTimeout: time.Duration(dynamic.DefaultHealthCheckTimeout), }, { desc: "out of range values", config: &dynamic.TCPServerHealthCheck{ Interval: ptypes.Duration(-time.Second), Timeout: ptypes.Duration(-time.Second), }, expectedInterval: time.Duration(dynamic.DefaultHealthCheckInterval), expectedTimeout: time.Duration(dynamic.DefaultHealthCheckTimeout), }, { desc: "custom durations", config: &dynamic.TCPServerHealthCheck{ Interval: ptypes.Duration(time.Second * 10), Timeout: ptypes.Duration(time.Second * 5), }, expectedInterval: time.Second * 10, expectedTimeout: time.Second * 5, }, { desc: "interval shorter than timeout", config: &dynamic.TCPServerHealthCheck{ Interval: ptypes.Duration(time.Second), Timeout: ptypes.Duration(time.Second * 5), }, expectedInterval: time.Second, expectedTimeout: time.Second * 5, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() healthChecker := NewServiceTCPHealthChecker(t.Context(), test.config, nil, nil, nil, "") assert.Equal(t, test.expectedInterval, healthChecker.interval) assert.Equal(t, test.expectedTimeout, healthChecker.timeout) }) } } func TestServiceTCPHealthChecker_executeHealthCheck_connection(t *testing.T) { testCases := []struct { desc string address string config *dynamic.TCPServerHealthCheck expectedAddress string }{ { desc: "no port override - uses original address", address: "127.0.0.1:8080", config: &dynamic.TCPServerHealthCheck{Port: 0}, expectedAddress: "127.0.0.1:8080", }, { desc: "port override - uses overridden port", address: "127.0.0.1:8080", config: &dynamic.TCPServerHealthCheck{Port: 9090}, expectedAddress: "127.0.0.1:9090", }, { desc: "IPv6 address with port override", address: "[::1]:8080", config: &dynamic.TCPServerHealthCheck{Port: 9090}, expectedAddress: "[::1]:9090", }, { desc: "successful connection without port override", address: "localhost:3306", config: &dynamic.TCPServerHealthCheck{Port: 0}, expectedAddress: "localhost:3306", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() // Create a mock dialer that records the address it was asked to dial. var gotAddress string mockDialer := &dialerMock{ onDial: func(network, addr string) (net.Conn, error) { gotAddress = addr return &connMock{}, nil }, } targets := []TCPHealthCheckTarget{{ Address: test.address, Dialer: mockDialer, }} healthChecker := NewServiceTCPHealthChecker(t.Context(), test.config, nil, nil, targets, "test") // Execute a health check to see what address it tries to connect to. err := healthChecker.executeHealthCheck(t.Context(), test.config, &targets[0]) require.NoError(t, err) // Verify that the health check attempted to connect to the expected address. assert.Equal(t, test.expectedAddress, gotAddress) }) } } func TestServiceTCPHealthChecker_executeHealthCheck_payloadHandling(t *testing.T) { testCases := []struct { desc string config *dynamic.TCPServerHealthCheck mockResponse string expectedSentData string expectedSuccess bool }{ { desc: "successful send and expect", config: &dynamic.TCPServerHealthCheck{ Send: "PING", Expect: "PONG", }, mockResponse: "PONG", expectedSentData: "PING", expectedSuccess: true, }, { desc: "send without expect", config: &dynamic.TCPServerHealthCheck{ Send: "STATUS", Expect: "", }, expectedSentData: "STATUS", expectedSuccess: true, }, { desc: "send without expect, ignores response", config: &dynamic.TCPServerHealthCheck{ Send: "STATUS", }, mockResponse: strings.Repeat("A", maxPayloadSize+1), expectedSentData: "STATUS", expectedSuccess: true, }, { desc: "expect without send", config: &dynamic.TCPServerHealthCheck{ Expect: "READY", }, mockResponse: "READY", expectedSuccess: true, }, { desc: "wrong response received", config: &dynamic.TCPServerHealthCheck{ Send: "PING", Expect: "PONG", }, mockResponse: "WRONG", expectedSentData: "PING", expectedSuccess: false, }, { desc: "send payload too large - gets truncated", config: &dynamic.TCPServerHealthCheck{ Send: strings.Repeat("A", maxPayloadSize+1), // Will be truncated to empty Expect: "OK", }, mockResponse: "OK", expectedSuccess: true, }, { desc: "expect payload too large - gets truncated", config: &dynamic.TCPServerHealthCheck{ Send: "PING", Expect: strings.Repeat("B", maxPayloadSize+1), // Will be truncated to empty }, expectedSentData: "PING", expectedSuccess: true, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() var sentData []byte mockConn := &connMock{ writeFunc: func(data []byte) (int, error) { sentData = append([]byte{}, data...) return len(data), nil }, readFunc: func(buf []byte) (int, error) { return copy(buf, test.mockResponse), nil }, } mockDialer := &dialerMock{ onDial: func(network, addr string) (net.Conn, error) { return mockConn, nil }, } targets := []TCPHealthCheckTarget{{ Address: "127.0.0.1:8080", TLS: false, Dialer: mockDialer, }} healthChecker := NewServiceTCPHealthChecker(t.Context(), test.config, nil, nil, targets, "test") err := healthChecker.executeHealthCheck(t.Context(), test.config, &targets[0]) if test.expectedSuccess { assert.NoError(t, err, "Health check should succeed") } else { assert.Error(t, err, "Health check should fail") } assert.Equal(t, test.expectedSentData, string(sentData), "Should send the expected data") }) } } func TestServiceTCPHealthChecker_Launch(t *testing.T) { testCases := []struct { desc string server *sequencedTCPServer config *dynamic.TCPServerHealthCheck expNumRemovedServers int expNumUpsertedServers int targetStatus string }{ { desc: "connection-only healthy server staying healthy", server: newTCPServer(t, false, tcpMockSequence{accept: true}, tcpMockSequence{accept: true}, tcpMockSequence{accept: true}, ), config: &dynamic.TCPServerHealthCheck{ Interval: ptypes.Duration(time.Millisecond * 50), Timeout: ptypes.Duration(time.Millisecond * 40), }, expNumRemovedServers: 0, expNumUpsertedServers: 3, // 3 health check sequences targetStatus: truntime.StatusUp, }, { desc: "connection-only healthy server becoming unhealthy", server: newTCPServer(t, false, tcpMockSequence{accept: true}, tcpMockSequence{accept: false}, ), config: &dynamic.TCPServerHealthCheck{ Interval: ptypes.Duration(time.Millisecond * 50), Timeout: ptypes.Duration(time.Millisecond * 40), }, expNumRemovedServers: 1, expNumUpsertedServers: 1, targetStatus: truntime.StatusDown, }, { desc: "connection-only server toggling unhealthy to healthy", server: newTCPServer(t, false, tcpMockSequence{accept: false}, tcpMockSequence{accept: true}, ), config: &dynamic.TCPServerHealthCheck{ Interval: ptypes.Duration(time.Millisecond * 50), Timeout: ptypes.Duration(time.Millisecond * 40), }, expNumRemovedServers: 1, // 1 failure call expNumUpsertedServers: 1, // 1 success call targetStatus: truntime.StatusUp, }, { desc: "connection-only server toggling healthy to unhealthy to healthy", server: newTCPServer(t, false, tcpMockSequence{accept: true}, tcpMockSequence{accept: false}, tcpMockSequence{accept: true}, ), config: &dynamic.TCPServerHealthCheck{ Interval: ptypes.Duration(time.Millisecond * 50), Timeout: ptypes.Duration(time.Millisecond * 40), }, expNumRemovedServers: 1, expNumUpsertedServers: 2, targetStatus: truntime.StatusUp, }, { desc: "send/expect healthy server staying healthy", server: newTCPServer(t, false, tcpMockSequence{accept: true, payloadIn: "PING", payloadOut: "PONG"}, tcpMockSequence{accept: true, payloadIn: "PING", payloadOut: "PONG"}, ), config: &dynamic.TCPServerHealthCheck{ Send: "PING", Expect: "PONG", Interval: ptypes.Duration(time.Millisecond * 50), Timeout: ptypes.Duration(time.Millisecond * 40), }, expNumRemovedServers: 0, expNumUpsertedServers: 2, // 2 successful health checks targetStatus: truntime.StatusUp, }, { desc: "send/expect server with wrong response", server: newTCPServer(t, false, tcpMockSequence{accept: true, payloadIn: "PING", payloadOut: "PONG"}, tcpMockSequence{accept: true, payloadIn: "PING", payloadOut: "WRONG"}, ), config: &dynamic.TCPServerHealthCheck{ Send: "PING", Expect: "PONG", Interval: ptypes.Duration(time.Millisecond * 50), Timeout: ptypes.Duration(time.Millisecond * 40), }, expNumRemovedServers: 1, expNumUpsertedServers: 1, targetStatus: truntime.StatusDown, }, { desc: "TLS healthy server staying healthy", server: newTCPServer(t, true, tcpMockSequence{accept: true, payloadIn: "HELLO", payloadOut: "WORLD"}, ), config: &dynamic.TCPServerHealthCheck{ Send: "HELLO", Expect: "WORLD", Interval: ptypes.Duration(time.Millisecond * 500), Timeout: ptypes.Duration(time.Millisecond * 2000), // Even longer timeout for TLS handshake }, expNumRemovedServers: 0, expNumUpsertedServers: 1, // 1 TLS health check sequence targetStatus: truntime.StatusUp, }, { desc: "send-only healthcheck (no expect)", server: newTCPServer(t, false, tcpMockSequence{accept: true, payloadIn: "STATUS"}, tcpMockSequence{accept: true, payloadIn: "STATUS"}, ), config: &dynamic.TCPServerHealthCheck{ Send: "STATUS", Interval: ptypes.Duration(time.Millisecond * 50), Timeout: ptypes.Duration(time.Millisecond * 40), }, expNumRemovedServers: 0, expNumUpsertedServers: 2, targetStatus: truntime.StatusUp, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() ctx, cancel := context.WithCancel(log.Logger.WithContext(t.Context())) defer cancel() test.server.Start(t) dialerManager := tcp.NewDialerManager(nil) dialerManager.Update(map[string]*dynamic.TCPServersTransport{"default@internal": { TLS: &dynamic.TLSClientConfig{ InsecureSkipVerify: true, ServerName: "example.com", }, }}) dialer, err := dialerManager.Build(&dynamic.TCPServersLoadBalancer{}, test.server.TLS) require.NoError(t, err) targets := []TCPHealthCheckTarget{ { Address: test.server.Addr.String(), TLS: test.server.TLS, Dialer: dialer, }, } lb := &testLoadBalancer{} serviceInfo := &truntime.TCPServiceInfo{} service := NewServiceTCPHealthChecker(ctx, test.config, lb, serviceInfo, targets, "serviceName") go service.Launch(ctx) // How much time to wait for the health check to actually complete. deadline := time.Now().Add(200 * time.Millisecond) // TLS handshake can take much longer. if test.server.TLS { deadline = time.Now().Add(1000 * time.Millisecond) } // Wait for all health checks to complete deterministically for i := range test.server.StatusSequence { test.server.Next() initialUpserted := lb.numUpsertedServers initialRemoved := lb.numRemovedServers for time.Now().Before(deadline) { time.Sleep(5 * time.Millisecond) if lb.numUpsertedServers > initialUpserted || lb.numRemovedServers > initialRemoved { // Stop the health checker immediately after the last expected sequence completes // to prevent extra health checks from firing and modifying the counters. if i == len(test.server.StatusSequence)-1 { cancel() } break } } } assert.Equal(t, test.expNumRemovedServers, lb.numRemovedServers, "removed servers") assert.Equal(t, test.expNumUpsertedServers, lb.numUpsertedServers, "upserted servers") assert.Equal(t, map[string]string{test.server.Addr.String(): test.targetStatus}, serviceInfo.GetAllStatus()) }) } } func TestServiceTCPHealthChecker_differentIntervals(t *testing.T) { // Test that unhealthy servers are checked more frequently than healthy servers // when UnhealthyInterval is set to a lower value than Interval ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) // Create a healthy TCP server that always accepts connections healthyServer := newTCPServer(t, false, tcpMockSequence{accept: true}, tcpMockSequence{accept: true}, tcpMockSequence{accept: true}, tcpMockSequence{accept: true}, tcpMockSequence{accept: true}, ) healthyServer.Start(t) // Create an unhealthy TCP server that always rejects connections unhealthyServer := newTCPServer(t, false, tcpMockSequence{accept: false}, tcpMockSequence{accept: false}, tcpMockSequence{accept: false}, tcpMockSequence{accept: false}, tcpMockSequence{accept: false}, tcpMockSequence{accept: false}, tcpMockSequence{accept: false}, tcpMockSequence{accept: false}, tcpMockSequence{accept: false}, tcpMockSequence{accept: false}, ) unhealthyServer.Start(t) lb := &testLoadBalancer{RWMutex: &sync.RWMutex{}} // Set normal interval to 500ms but unhealthy interval to 50ms // This means unhealthy servers should be checked 10x more frequently config := &dynamic.TCPServerHealthCheck{ Interval: ptypes.Duration(500 * time.Millisecond), UnhealthyInterval: pointer(ptypes.Duration(50 * time.Millisecond)), Timeout: ptypes.Duration(100 * time.Millisecond), } // Set up dialer manager dialerManager := tcp.NewDialerManager(nil) dialerManager.Update(map[string]*dynamic.TCPServersTransport{ "default@internal": { DialTimeout: ptypes.Duration(100 * time.Millisecond), DialKeepAlive: ptypes.Duration(100 * time.Millisecond), }, }) // Get dialer for targets dialer, err := dialerManager.Build(&dynamic.TCPServersLoadBalancer{}, false) require.NoError(t, err) targets := []TCPHealthCheckTarget{ {Address: healthyServer.Addr.String(), TLS: false, Dialer: dialer}, {Address: unhealthyServer.Addr.String(), TLS: false, Dialer: dialer}, } serviceInfo := &truntime.TCPServiceInfo{} hc := NewServiceTCPHealthChecker(ctx, config, lb, serviceInfo, targets, "test-service") wg := sync.WaitGroup{} wg.Add(1) go func() { hc.Launch(ctx) wg.Done() }() // Let it run for 2 seconds to see the different check frequencies select { case <-time.After(2 * time.Second): cancel() case <-ctx.Done(): } wg.Wait() lb.Lock() defer lb.Unlock() // The unhealthy server should be checked more frequently (50ms interval) // compared to the healthy server (500ms interval), so we should see // significantly more "removed" events than "upserted" events assert.Greater(t, lb.numRemovedServers, lb.numUpsertedServers, "unhealthy servers checked more frequently") } type tcpMockSequence struct { accept bool payloadIn string payloadOut string } type sequencedTCPServer struct { Addr *net.TCPAddr StatusSequence []tcpMockSequence TLS bool release chan struct{} } func newTCPServer(t *testing.T, tlsEnabled bool, statusSequence ...tcpMockSequence) *sequencedTCPServer { t.Helper() addr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:0") require.NoError(t, err) listener, err := net.ListenTCP("tcp", addr) require.NoError(t, err) tcpAddr, ok := listener.Addr().(*net.TCPAddr) require.True(t, ok) listener.Close() return &sequencedTCPServer{ Addr: tcpAddr, TLS: tlsEnabled, StatusSequence: statusSequence, release: make(chan struct{}), } } func (s *sequencedTCPServer) Next() { s.release <- struct{}{} } func (s *sequencedTCPServer) Start(t *testing.T) { t.Helper() go func() { var listener net.Listener for _, seq := range s.StatusSequence { <-s.release if listener != nil { listener.Close() } if !seq.accept { continue } lis, err := net.ListenTCP("tcp", s.Addr) require.NoError(t, err) listener = lis if s.TLS { cert, err := tls.X509KeyPair(localhostCert, localhostKey) require.NoError(t, err) x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) require.NoError(t, err) certpool := x509.NewCertPool() certpool.AddCert(x509Cert) listener = tls.NewListener( listener, &tls.Config{ RootCAs: certpool, Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true, ServerName: "example.com", MinVersion: tls.VersionTLS12, MaxVersion: tls.VersionTLS12, ClientAuth: tls.VerifyClientCertIfGiven, ClientCAs: certpool, }, ) } conn, err := listener.Accept() require.NoError(t, err) t.Cleanup(func() { _ = conn.Close() }) // For TLS connections, perform handshake first if s.TLS { if tlsConn, ok := conn.(*tls.Conn); ok { if err := tlsConn.Handshake(); err != nil { continue // Skip this sequence on handshake failure } } } if seq.payloadIn == "" { continue } buf := make([]byte, len(seq.payloadIn)) n, err := conn.Read(buf) require.NoError(t, err) recv := strings.TrimSpace(string(buf[:n])) switch recv { case seq.payloadIn: if _, err := conn.Write([]byte(seq.payloadOut)); err != nil { t.Errorf("failed to write payload: %v", err) } default: if _, err := conn.Write([]byte("FAULT\n")); err != nil { t.Errorf("failed to write payload: %v", err) } } } defer close(s.release) }() } type dialerMock struct { onDial func(network, addr string) (net.Conn, error) } func (dm *dialerMock) Dial(network, addr string, _ tcp.ClientConn) (net.Conn, error) { return dm.onDial(network, addr) } func (dm *dialerMock) DialContext(_ context.Context, network, addr string, _ tcp.ClientConn) (net.Conn, error) { return dm.onDial(network, addr) } func (dm *dialerMock) TerminationDelay() time.Duration { return 0 } type connMock struct { writeFunc func([]byte) (int, error) readFunc func([]byte) (int, error) } func (cm *connMock) Read(b []byte) (n int, err error) { if cm.readFunc != nil { return cm.readFunc(b) } return 0, nil } func (cm *connMock) Write(b []byte) (n int, err error) { if cm.writeFunc != nil { return cm.writeFunc(b) } return len(b), nil } func (cm *connMock) Close() error { return nil } func (cm *connMock) LocalAddr() net.Addr { return &net.TCPAddr{} } func (cm *connMock) RemoteAddr() net.Addr { return &net.TCPAddr{} } func (cm *connMock) SetDeadline(_ time.Time) error { return nil } func (cm *connMock) SetReadDeadline(_ time.Time) error { return nil } func (cm *connMock) SetWriteDeadline(_ time.Time) error { return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/healthcheck/mock_test.go
pkg/healthcheck/mock_test.go
package healthcheck import ( "context" "net" "net/http" "net/http/httptest" "net/url" "sync" "testing" "time" gokitmetrics "github.com/go-kit/kit/metrics" "github.com/stretchr/testify/assert" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/testhelpers" "google.golang.org/grpc" healthpb "google.golang.org/grpc/health/grpc_health_v1" ) type StartTestServer interface { Start(t *testing.T, done func()) (*url.URL, time.Duration) } type Status interface { ~int | ~int32 } type HealthSequence[T Status] struct { sequenceMu sync.Mutex sequence []T } func (s *HealthSequence[T]) Pop() T { s.sequenceMu.Lock() defer s.sequenceMu.Unlock() stat := s.sequence[0] s.sequence = s.sequence[1:] return stat } func (s *HealthSequence[T]) IsEmpty() bool { s.sequenceMu.Lock() defer s.sequenceMu.Unlock() return len(s.sequence) == 0 } type GRPCServer struct { status HealthSequence[healthpb.HealthCheckResponse_ServingStatus] done func() } func newGRPCServer(healthSequence ...healthpb.HealthCheckResponse_ServingStatus) *GRPCServer { gRPCService := &GRPCServer{ status: HealthSequence[healthpb.HealthCheckResponse_ServingStatus]{ sequence: healthSequence, }, } return gRPCService } func (s *GRPCServer) List(_ context.Context, _ *healthpb.HealthListRequest) (*healthpb.HealthListResponse, error) { return nil, nil } func (s *GRPCServer) Check(_ context.Context, _ *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) { if s.status.IsEmpty() { s.done() return &healthpb.HealthCheckResponse{ Status: healthpb.HealthCheckResponse_SERVICE_UNKNOWN, }, nil } stat := s.status.Pop() return &healthpb.HealthCheckResponse{ Status: stat, }, nil } func (s *GRPCServer) Watch(_ *healthpb.HealthCheckRequest, server healthpb.Health_WatchServer) error { if s.status.IsEmpty() { s.done() return server.Send(&healthpb.HealthCheckResponse{ Status: healthpb.HealthCheckResponse_SERVICE_UNKNOWN, }) } stat := s.status.Pop() return server.Send(&healthpb.HealthCheckResponse{ Status: stat, }) } func (s *GRPCServer) Start(t *testing.T, done func()) (*url.URL, time.Duration) { t.Helper() listener, err := net.Listen("tcp4", "127.0.0.1:0") assert.NoError(t, err) t.Cleanup(func() { _ = listener.Close() }) server := grpc.NewServer() t.Cleanup(server.Stop) s.done = done healthpb.RegisterHealthServer(server, s) go func() { err := server.Serve(listener) assert.NoError(t, err) }() // Make test timeout dependent on number of expected requests, health check interval, and a safety margin. return testhelpers.MustParseURL("http://" + listener.Addr().String()), time.Duration(len(s.status.sequence)*int(dynamic.DefaultHealthCheckInterval) + 500) } type HTTPServer struct { status HealthSequence[int] done func() } func newHTTPServer(healthSequence ...int) *HTTPServer { handler := &HTTPServer{ status: HealthSequence[int]{ sequence: healthSequence, }, } return handler } // ServeHTTP returns HTTP response codes following a status sequences. // It calls the given 'done' function once all request health indicators have been depleted. func (s *HTTPServer) ServeHTTP(w http.ResponseWriter, _ *http.Request) { if s.status.IsEmpty() { s.done() // This ensures that the health-checker will handle the context cancellation error before receiving the HTTP response. time.Sleep(500 * time.Millisecond) return } stat := s.status.Pop() w.WriteHeader(stat) } func (s *HTTPServer) Start(t *testing.T, done func()) (*url.URL, time.Duration) { t.Helper() s.done = done ts := httptest.NewServer(s) t.Cleanup(ts.Close) // Make test timeout dependent on number of expected requests, health check interval, and a safety margin. return testhelpers.MustParseURL(ts.URL), time.Duration(len(s.status.sequence)*int(dynamic.DefaultHealthCheckInterval) + 500) } type testLoadBalancer struct { // RWMutex needed due to parallel test execution: Both the system-under-test // and the test assertions reference the counters. *sync.RWMutex numRemovedServers int numUpsertedServers int } func (lb *testLoadBalancer) SetStatus(ctx context.Context, childName string, up bool) { if up { lb.numUpsertedServers++ } else { lb.numRemovedServers++ } } type MetricsMock struct { Gauge gokitmetrics.Gauge } func (m *MetricsMock) ServiceServerUpGauge() gokitmetrics.Gauge { return m.Gauge }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/safe/safe_test.go
pkg/safe/safe_test.go
package safe import "testing" func TestSafe(t *testing.T) { const ts1 = "test1" const ts2 = "test2" s := New(ts1) result, ok := s.Get().(string) if !ok { t.Fatalf("Safe.Get() failed, got type '%T', expected string", s.Get()) } if result != ts1 { t.Errorf("Safe.Get() failed, got '%s', expected '%s'", result, ts1) } s.Set(ts2) result, ok = s.Get().(string) if !ok { t.Fatalf("Safe.Get() after Safe.Set() failed, got type '%T', expected string", s.Get()) } if result != ts2 { t.Errorf("Safe.Get() after Safe.Set() failed, got '%s', expected '%s'", result, ts2) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/safe/routine_test.go
pkg/safe/routine_test.go
package safe import ( "context" "errors" "sync" "testing" "time" "github.com/cenkalti/backoff/v4" ) func TestNewPoolContext(t *testing.T) { type testKeyType string testKey := testKeyType("test") ctx := context.WithValue(t.Context(), testKey, "test") p := NewPool(ctx) p.GoCtx(func(ctx context.Context) { retCtxVal, ok := ctx.Value(testKey).(string) if !ok || retCtxVal != "test" { t.Errorf("Pool.Ctx() did not return a derived context, got %#v, expected context with test value", ctx) } }) p.Stop() } type fakeRoutine struct { sync.Mutex started bool startSig chan bool } func newFakeRoutine() *fakeRoutine { return &fakeRoutine{ startSig: make(chan bool), } } func (tr *fakeRoutine) routineCtx(ctx context.Context) { tr.Lock() tr.started = true tr.Unlock() tr.startSig <- true <-ctx.Done() } func TestPoolWithCtx(t *testing.T) { testRoutine := newFakeRoutine() testCases := []struct { desc string fn func(*Pool) }{ { desc: "GoCtx()", fn: func(p *Pool) { p.GoCtx(testRoutine.routineCtx) }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { // These subtests cannot be run in parallel, since the testRoutine // is shared across the subtests. p := NewPool(t.Context()) timer := time.NewTimer(500 * time.Millisecond) defer timer.Stop() test.fn(p) defer p.Stop() testDone := make(chan bool, 1) go func() { <-testRoutine.startSig p.Stop() testDone <- true }() select { case <-timer.C: testRoutine.Lock() defer testRoutine.Unlock() t.Fatalf("Pool test did not complete in time, goroutine started equals '%t'", testRoutine.started) case <-testDone: return } }) } } func TestPoolCleanupWithGoPanicking(t *testing.T) { p := NewPool(t.Context()) timer := time.NewTimer(500 * time.Millisecond) defer timer.Stop() p.GoCtx(func(ctx context.Context) { panic("BOOM") }) testDone := make(chan bool, 1) go func() { p.Stop() testDone <- true }() select { case <-timer.C: t.Fatalf("Pool.Cleanup() did not complete in time with a panicking goroutine") case <-testDone: return } } func TestGoroutineRecover(t *testing.T) { // if recover fails the test will panic Go(func() { panic("BOOM") }) } func TestOperationWithRecover(t *testing.T) { operation := func() error { return nil } err := backoff.Retry(OperationWithRecover(operation), &backoff.StopBackOff{}) if err != nil { t.Fatalf("Error in OperationWithRecover: %s", err) } } func TestOperationWithRecoverPanic(t *testing.T) { operation := func() error { panic("BOOM") } err := backoff.Retry(OperationWithRecover(operation), &backoff.StopBackOff{}) if err == nil { t.Fatalf("Error in OperationWithRecover: %s", err) } } func TestOperationWithRecoverError(t *testing.T) { operation := func() error { return errors.New("ERROR") } err := backoff.Retry(OperationWithRecover(operation), &backoff.StopBackOff{}) if err == nil { t.Fatalf("Error in OperationWithRecover: %s", err) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/safe/safe.go
pkg/safe/safe.go
package safe import ( "sync" ) // Safe contains a thread-safe value. type Safe struct { value interface{} lock sync.RWMutex } // New create a new Safe instance given a value. func New(value interface{}) *Safe { return &Safe{value: value, lock: sync.RWMutex{}} } // Get returns the value. func (s *Safe) Get() interface{} { s.lock.RLock() defer s.lock.RUnlock() return s.value } // Set sets a new value. func (s *Safe) Set(value interface{}) { s.lock.Lock() defer s.lock.Unlock() s.value = value }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/safe/routine.go
pkg/safe/routine.go
package safe import ( "context" "fmt" "runtime/debug" "sync" "github.com/cenkalti/backoff/v4" "github.com/rs/zerolog/log" ) type routineCtx func(ctx context.Context) // Pool is a pool of go routines. type Pool struct { waitGroup sync.WaitGroup ctx context.Context cancel context.CancelFunc } // NewPool creates a Pool. func NewPool(parentCtx context.Context) *Pool { ctx, cancel := context.WithCancel(parentCtx) return &Pool{ ctx: ctx, cancel: cancel, } } // GoCtx starts a recoverable goroutine with a context. func (p *Pool) GoCtx(goroutine routineCtx) { p.waitGroup.Add(1) Go(func() { defer p.waitGroup.Done() goroutine(p.ctx) }) } // Stop stops all started routines, waiting for their termination. func (p *Pool) Stop() { p.cancel() p.waitGroup.Wait() } // Go starts a recoverable goroutine. func Go(goroutine func()) { GoWithRecover(goroutine, defaultRecoverGoroutine) } // GoWithRecover starts a recoverable goroutine using given customRecover() function. func GoWithRecover(goroutine func(), customRecover func(err interface{})) { go func() { defer func() { if err := recover(); err != nil { customRecover(err) } }() goroutine() }() } func defaultRecoverGoroutine(err interface{}) { log.Error().Interface("error", err).Msg("Error in Go routine") log.Error().Msgf("Stack: %s", debug.Stack()) } // OperationWithRecover wrap a backoff operation in a Recover. func OperationWithRecover(operation backoff.Operation) backoff.Operation { return func() (err error) { defer func() { if res := recover(); res != nil { defaultRecoverGoroutine(res) err = fmt.Errorf("panic in operation: %w", err) } }() return operation() } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/server_entrypoint_tcp.go
pkg/server/server_entrypoint_tcp.go
package server import ( "context" "errors" "expvar" "fmt" stdlog "log" "net" "net/http" "net/url" "os" "strings" "sync" "sync/atomic" "syscall" "time" "github.com/containous/alice" gokitmetrics "github.com/go-kit/kit/metrics" "github.com/pires/go-proxyproto" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/ip" "github.com/traefik/traefik/v3/pkg/middlewares" "github.com/traefik/traefik/v3/pkg/middlewares/contenttype" "github.com/traefik/traefik/v3/pkg/middlewares/forwardedheaders" "github.com/traefik/traefik/v3/pkg/middlewares/requestdecorator" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/observability/metrics" "github.com/traefik/traefik/v3/pkg/safe" tcprouter "github.com/traefik/traefik/v3/pkg/server/router/tcp" "github.com/traefik/traefik/v3/pkg/server/service" "github.com/traefik/traefik/v3/pkg/tcp" "github.com/traefik/traefik/v3/pkg/types" ) type key string const ( connStateKey key = "connState" debugConnectionEnv string = "DEBUG_CONNECTION" ) var ( clientConnectionStates = map[string]*connState{} clientConnectionStatesMu = sync.RWMutex{} ) type connState struct { State string KeepAliveState string Start time.Time HTTPRequestCount int } type httpForwarder struct { net.Listener connChan chan net.Conn errChan chan error closeChan chan struct{} closeOnce sync.Once } func newHTTPForwarder(ln net.Listener) *httpForwarder { return &httpForwarder{ Listener: ln, connChan: make(chan net.Conn), errChan: make(chan error), closeChan: make(chan struct{}), } } // ServeTCP uses the connection to serve it later in "Accept". func (h *httpForwarder) ServeTCP(conn tcp.WriteCloser) { h.connChan <- conn } // Accept retrieves a served connection in ServeTCP. func (h *httpForwarder) Accept() (net.Conn, error) { select { case <-h.closeChan: return nil, errors.New("listener closed") case conn := <-h.connChan: return conn, nil case err := <-h.errChan: return nil, err } } // Close closes the wrapped listener and unblocks Accept. func (h *httpForwarder) Close() error { h.closeOnce.Do(func() { close(h.closeChan) }) return h.Listener.Close() } // TCPEntryPoints holds a map of TCPEntryPoint (the entrypoint names being the keys). type TCPEntryPoints map[string]*TCPEntryPoint // NewTCPEntryPoints creates a new TCPEntryPoints. func NewTCPEntryPoints(entryPointsConfig static.EntryPoints, hostResolverConfig *types.HostResolverConfig, metricsRegistry metrics.Registry) (TCPEntryPoints, error) { if os.Getenv(debugConnectionEnv) != "" { expvar.Publish("clientConnectionStates", expvar.Func(func() any { return clientConnectionStates })) } serverEntryPointsTCP := make(TCPEntryPoints) for entryPointName, config := range entryPointsConfig { protocol, err := config.GetProtocol() if err != nil { return nil, fmt.Errorf("error while building entryPoint %s: %w", entryPointName, err) } if protocol != "tcp" { continue } ctx := log.With().Str(logs.EntryPointName, entryPointName).Logger().WithContext(context.Background()) openConnectionsGauge := metricsRegistry. OpenConnectionsGauge(). With("entrypoint", entryPointName, "protocol", "TCP") serverEntryPointsTCP[entryPointName], err = NewTCPEntryPoint(ctx, entryPointName, config, hostResolverConfig, openConnectionsGauge) if err != nil { return nil, fmt.Errorf("error while building entryPoint %s: %w", entryPointName, err) } } return serverEntryPointsTCP, nil } // Start the server entry points. func (eps TCPEntryPoints) Start() { for entryPointName, serverEntryPoint := range eps { ctx := log.With().Str(logs.EntryPointName, entryPointName).Logger().WithContext(context.Background()) go serverEntryPoint.Start(ctx) } } // Stop the server entry points. func (eps TCPEntryPoints) Stop() { var wg sync.WaitGroup for epn, ep := range eps { wg.Add(1) go func(entryPointName string, entryPoint *TCPEntryPoint) { defer wg.Done() logger := log.With().Str(logs.EntryPointName, entryPointName).Logger() entryPoint.Shutdown(logger.WithContext(context.Background())) logger.Debug().Msg("Entrypoint closed") }(epn, ep) } wg.Wait() } // Switch the TCP routers. func (eps TCPEntryPoints) Switch(routersTCP map[string]*tcprouter.Router) { for entryPointName, rt := range routersTCP { eps[entryPointName].SwitchRouter(rt) } } // TCPEntryPoint is the TCP server. type TCPEntryPoint struct { listener net.Listener switcher *tcp.HandlerSwitcher transportConfiguration *static.EntryPointsTransport tracker *connectionTracker httpServer *httpServer httpsServer *httpServer http3Server *http3server // inShutdown reports whether the Shutdown method has been called. inShutdown atomic.Bool } // NewTCPEntryPoint creates a new TCPEntryPoint. func NewTCPEntryPoint(ctx context.Context, name string, config *static.EntryPoint, hostResolverConfig *types.HostResolverConfig, openConnectionsGauge gokitmetrics.Gauge) (*TCPEntryPoint, error) { tracker := newConnectionTracker(openConnectionsGauge) listener, err := buildListener(ctx, name, config) if err != nil { return nil, fmt.Errorf("building listener: %w", err) } rt, err := tcprouter.NewRouter() if err != nil { return nil, fmt.Errorf("creating TCP router: %w", err) } reqDecorator := requestdecorator.New(hostResolverConfig) httpServer, err := newHTTPServer(ctx, listener, config, true, reqDecorator) if err != nil { return nil, fmt.Errorf("creating HTTP server: %w", err) } rt.SetHTTPForwarder(httpServer.Forwarder) httpsServer, err := newHTTPServer(ctx, listener, config, false, reqDecorator) if err != nil { return nil, fmt.Errorf("creating HTTPS server: %w", err) } h3Server, err := newHTTP3Server(ctx, name, config, httpsServer) if err != nil { return nil, fmt.Errorf("creating HTTP3 server: %w", err) } rt.SetHTTPSForwarder(httpsServer.Forwarder) tcpSwitcher := &tcp.HandlerSwitcher{} tcpSwitcher.Switch(rt) return &TCPEntryPoint{ listener: listener, switcher: tcpSwitcher, transportConfiguration: config.Transport, tracker: tracker, httpServer: httpServer, httpsServer: httpsServer, http3Server: h3Server, }, nil } // Start starts the TCP server. func (e *TCPEntryPoint) Start(ctx context.Context) { logger := log.Ctx(ctx) logger.Debug().Msg("Starting TCP Server") if e.http3Server != nil { go func() { _ = e.http3Server.Start() }() } for { conn, err := e.listener.Accept() // As the Shutdown method has been called, an error is expected. // Thus, it is not necessary to log it. if err != nil && e.inShutdown.Load() { return } if err != nil { logger.Error().Err(err).Send() var opErr *net.OpError if errors.As(err, &opErr) && opErr.Temporary() { continue } var urlErr *url.Error if errors.As(err, &urlErr) && urlErr.Temporary() { continue } e.httpServer.Forwarder.errChan <- err e.httpsServer.Forwarder.errChan <- err return } writeCloser, err := writeCloser(conn) if err != nil { panic(err) } safe.Go(func() { // Enforce read/write deadlines at the connection level, // because when we're peeking the first byte to determine whether we are doing TLS, // the deadlines at the server level are not taken into account. if e.transportConfiguration.RespondingTimeouts.ReadTimeout > 0 { err := writeCloser.SetReadDeadline(time.Now().Add(time.Duration(e.transportConfiguration.RespondingTimeouts.ReadTimeout))) if err != nil { logger.Error().Err(err).Msg("Error while setting read deadline") } } if e.transportConfiguration.RespondingTimeouts.WriteTimeout > 0 { err = writeCloser.SetWriteDeadline(time.Now().Add(time.Duration(e.transportConfiguration.RespondingTimeouts.WriteTimeout))) if err != nil { logger.Error().Err(err).Msg("Error while setting write deadline") } } e.switcher.ServeTCP(newTrackedConnection(writeCloser, e.tracker)) }) } } // Shutdown stops the TCP connections. func (e *TCPEntryPoint) Shutdown(ctx context.Context) { logger := log.Ctx(ctx) e.inShutdown.Store(true) reqAcceptGraceTimeOut := time.Duration(e.transportConfiguration.LifeCycle.RequestAcceptGraceTimeout) if reqAcceptGraceTimeOut > 0 { logger.Info().Msgf("Waiting %s for incoming requests to cease", reqAcceptGraceTimeOut) time.Sleep(reqAcceptGraceTimeOut) } graceTimeOut := time.Duration(e.transportConfiguration.LifeCycle.GraceTimeOut) ctx, cancel := context.WithTimeout(ctx, graceTimeOut) logger.Debug().Msgf("Waiting %s seconds before killing connections", graceTimeOut) var wg sync.WaitGroup shutdownServer := func(server stoppable) { defer wg.Done() err := server.Shutdown(ctx) if err == nil { return } if errors.Is(ctx.Err(), context.DeadlineExceeded) { logger.Debug().Err(err).Msg("Server failed to shutdown within deadline") if err = server.Close(); err != nil { logger.Error().Err(err).Send() } return } logger.Error().Err(err).Send() // We expect Close to fail again because Shutdown most likely failed when trying to close a listener. // We still call it however, to make sure that all connections get closed as well. server.Close() } if e.httpServer.Server != nil { wg.Add(1) go shutdownServer(e.httpServer.Server) } if e.httpsServer.Server != nil { wg.Add(1) go shutdownServer(e.httpsServer.Server) if e.http3Server != nil { wg.Add(1) go shutdownServer(e.http3Server) } } if e.tracker != nil { wg.Add(1) go func() { defer wg.Done() err := e.tracker.Shutdown(ctx) if err == nil { return } if errors.Is(ctx.Err(), context.DeadlineExceeded) { logger.Debug().Err(err).Msg("Server failed to shutdown before deadline") } e.tracker.Close() }() } wg.Wait() cancel() } // SwitchRouter switches the TCP router handler. func (e *TCPEntryPoint) SwitchRouter(rt *tcprouter.Router) { rt.SetHTTPForwarder(e.httpServer.Forwarder) httpHandler := rt.GetHTTPHandler() if httpHandler == nil { httpHandler = http.NotFoundHandler() } e.httpServer.Switcher.UpdateHandler(httpHandler) rt.SetHTTPSForwarder(e.httpsServer.Forwarder) httpsHandler := rt.GetHTTPSHandler() if httpsHandler == nil { httpsHandler = http.NotFoundHandler() } e.httpsServer.Switcher.UpdateHandler(httpsHandler) e.switcher.Switch(rt) if e.http3Server != nil { e.http3Server.Switch(rt) } } // writeCloserWrapper wraps together a connection, and the concrete underlying // connection type that was found to satisfy WriteCloser. type writeCloserWrapper struct { net.Conn writeCloser tcp.WriteCloser } func (c *writeCloserWrapper) CloseWrite() error { return c.writeCloser.CloseWrite() } // writeCloser returns the given connection, augmented with the WriteCloser // implementation, if any was found within the underlying conn. func writeCloser(conn net.Conn) (tcp.WriteCloser, error) { switch typedConn := conn.(type) { case *proxyproto.Conn: underlying, ok := typedConn.TCPConn() if !ok { return nil, errors.New("underlying connection is not a tcp connection") } return &writeCloserWrapper{writeCloser: underlying, Conn: typedConn}, nil case *net.TCPConn: return typedConn, nil default: return nil, fmt.Errorf("unknown connection type %T", typedConn) } } // tcpKeepAliveListener sets TCP keep-alive timeouts on accepted // connections. type tcpKeepAliveListener struct { *net.TCPListener } func (ln tcpKeepAliveListener) Accept() (net.Conn, error) { tc, err := ln.AcceptTCP() if err != nil { return nil, err } if err := tc.SetKeepAlive(true); err != nil { return nil, err } if err := tc.SetKeepAlivePeriod(3 * time.Minute); err != nil { // Some systems, such as OpenBSD, have no user-settable per-socket TCP keepalive options. if !errors.Is(err, syscall.ENOPROTOOPT) { return nil, err } } return tc, nil } func buildProxyProtocolListener(ctx context.Context, entryPoint *static.EntryPoint, listener net.Listener) (net.Listener, error) { timeout := entryPoint.Transport.RespondingTimeouts.ReadTimeout // proxyproto use 200ms if ReadHeaderTimeout is set to 0 and not no timeout if timeout == 0 { timeout = -1 } proxyListener := &proxyproto.Listener{Listener: listener, ReadHeaderTimeout: time.Duration(timeout)} if entryPoint.ProxyProtocol.Insecure { log.Ctx(ctx).Info().Msg("Enabling ProxyProtocol without trusted IPs: Insecure") return proxyListener, nil } checker, err := ip.NewChecker(entryPoint.ProxyProtocol.TrustedIPs) if err != nil { return nil, err } proxyListener.Policy = func(upstream net.Addr) (proxyproto.Policy, error) { ipAddr, ok := upstream.(*net.TCPAddr) if !ok { return proxyproto.REJECT, fmt.Errorf("type error %v", upstream) } if !checker.ContainsIP(ipAddr.IP) { log.Ctx(ctx).Debug().Msgf("IP %s is not in trusted IPs list, ignoring ProxyProtocol Headers and bypass connection", ipAddr.IP) return proxyproto.IGNORE, nil } return proxyproto.USE, nil } log.Ctx(ctx).Info().Msgf("Enabling ProxyProtocol for trusted IPs %v", entryPoint.ProxyProtocol.TrustedIPs) return proxyListener, nil } type onceCloseListener struct { net.Listener once sync.Once closeErr error } func (oc *onceCloseListener) Close() error { oc.once.Do(func() { oc.closeErr = oc.Listener.Close() }) return oc.closeErr } func buildListener(ctx context.Context, name string, config *static.EntryPoint) (net.Listener, error) { var listener net.Listener var err error // if we have predefined listener from socket activation if socketActivation.isEnabled() { listener, err = socketActivation.getListener(name) if err != nil { log.Ctx(ctx).Warn().Err(err).Str("name", name).Msg("Unable to use socket activation for entrypoint") } } if listener == nil { listenConfig := newListenConfig(config) // TODO: Look into configuring keepAlive period through listenConfig instead of our custom tcpKeepAliveListener, to reactivate MultipathTCP? // MultipathTCP is not supported on all platforms, and is notably unsupported in combination with TCP keep-alive. if !strings.Contains(os.Getenv("GODEBUG"), "multipathtcp") { listenConfig.SetMultipathTCP(false) } listener, err = listenConfig.Listen(ctx, "tcp", config.GetAddress()) if err != nil { return nil, fmt.Errorf("error opening listener: %w", err) } } listener = tcpKeepAliveListener{listener.(*net.TCPListener)} if config.ProxyProtocol != nil { listener, err = buildProxyProtocolListener(ctx, config, listener) if err != nil { return nil, fmt.Errorf("error creating proxy protocol listener: %w", err) } } return &onceCloseListener{Listener: listener}, nil } func newConnectionTracker(openConnectionsGauge gokitmetrics.Gauge) *connectionTracker { return &connectionTracker{ conns: make(map[net.Conn]struct{}), openConnectionsGauge: openConnectionsGauge, } } type connectionTracker struct { connsMu sync.RWMutex conns map[net.Conn]struct{} openConnectionsGauge gokitmetrics.Gauge } // AddConnection add a connection in the tracked connections list. func (c *connectionTracker) AddConnection(conn net.Conn) { defer c.syncOpenConnectionGauge() c.connsMu.Lock() c.conns[conn] = struct{}{} c.connsMu.Unlock() } // RemoveConnection remove a connection from the tracked connections list. func (c *connectionTracker) RemoveConnection(conn net.Conn) { defer c.syncOpenConnectionGauge() c.connsMu.Lock() delete(c.conns, conn) c.connsMu.Unlock() } // syncOpenConnectionGauge updates openConnectionsGauge value with the conns map length. func (c *connectionTracker) syncOpenConnectionGauge() { if c.openConnectionsGauge == nil { return } c.connsMu.RLock() c.openConnectionsGauge.Set(float64(len(c.conns))) c.connsMu.RUnlock() } func (c *connectionTracker) isEmpty() bool { c.connsMu.RLock() defer c.connsMu.RUnlock() return len(c.conns) == 0 } // Shutdown wait for the connection closing. func (c *connectionTracker) Shutdown(ctx context.Context) error { ticker := time.NewTicker(500 * time.Millisecond) defer ticker.Stop() for { if c.isEmpty() { return nil } select { case <-ctx.Done(): return ctx.Err() case <-ticker.C: } } } // Close close all the connections in the tracked connections list. func (c *connectionTracker) Close() { c.connsMu.Lock() defer c.connsMu.Unlock() for conn := range c.conns { if err := conn.Close(); err != nil { log.Error().Err(err).Msg("Error while closing connection") } delete(c.conns, conn) } } type stoppable interface { Shutdown(ctx context.Context) error Close() error } type stoppableServer interface { stoppable Serve(listener net.Listener) error } type httpServer struct { Server stoppableServer Forwarder *httpForwarder Switcher *middlewares.HTTPHandlerSwitcher } func newHTTPServer(ctx context.Context, ln net.Listener, configuration *static.EntryPoint, withH2c bool, reqDecorator *requestdecorator.RequestDecorator) (*httpServer, error) { if configuration.HTTP2.MaxConcurrentStreams < 0 { return nil, errors.New("max concurrent streams value must be greater than or equal to zero") } if configuration.HTTP2.MaxDecoderHeaderTableSize < 0 { return nil, errors.New("max decoder header table size value must be greater than or equal to zero") } if configuration.HTTP2.MaxEncoderHeaderTableSize < 0 { return nil, errors.New("max encoder header table size value must be greater than or equal to zero") } httpSwitcher := middlewares.NewHandlerSwitcher(http.NotFoundHandler()) next, err := alice.New(requestdecorator.WrapHandler(reqDecorator)).Then(httpSwitcher) if err != nil { return nil, err } var handler http.Handler handler, err = forwardedheaders.NewXForwarded( configuration.ForwardedHeaders.Insecure, configuration.ForwardedHeaders.TrustedIPs, configuration.ForwardedHeaders.Connection, configuration.ForwardedHeaders.NotAppendXForwardedFor, next) if err != nil { return nil, err } debugConnection := os.Getenv(debugConnectionEnv) != "" if debugConnection || (configuration.Transport != nil && (configuration.Transport.KeepAliveMaxTime > 0 || configuration.Transport.KeepAliveMaxRequests > 0)) { handler = newKeepAliveMiddleware(handler, configuration.Transport.KeepAliveMaxRequests, configuration.Transport.KeepAliveMaxTime) } var protocols http.Protocols protocols.SetHTTP1(true) protocols.SetHTTP2(true) // With the addition of UnencryptedHTTP2 in http.Server#Protocols in go1.24 setting the h2c handler is not necessary anymore. protocols.SetUnencryptedHTTP2(withH2c) handler = contenttype.DisableAutoDetection(handler) if configuration.HTTP.EncodeQuerySemicolons { handler = encodeQuerySemicolons(handler) } else { handler = http.AllowQuerySemicolons(handler) } // Note that the Path sanitization has to be done after the path normalization, // hence the wrapping has to be done before the normalize path wrapping. if configuration.HTTP.SanitizePath != nil && *configuration.HTTP.SanitizePath { handler = sanitizePath(handler) } handler = normalizePath(handler) serverHTTP := &http.Server{ Protocols: &protocols, Handler: handler, ErrorLog: stdlog.New(logs.NoLevel(log.Logger, zerolog.DebugLevel), "", 0), ReadTimeout: time.Duration(configuration.Transport.RespondingTimeouts.ReadTimeout), WriteTimeout: time.Duration(configuration.Transport.RespondingTimeouts.WriteTimeout), IdleTimeout: time.Duration(configuration.Transport.RespondingTimeouts.IdleTimeout), MaxHeaderBytes: configuration.HTTP.MaxHeaderBytes, HTTP2: &http.HTTP2Config{ MaxConcurrentStreams: int(configuration.HTTP2.MaxConcurrentStreams), MaxDecoderHeaderTableSize: int(configuration.HTTP2.MaxDecoderHeaderTableSize), MaxEncoderHeaderTableSize: int(configuration.HTTP2.MaxEncoderHeaderTableSize), }, } if debugConnection || (configuration.Transport != nil && (configuration.Transport.KeepAliveMaxTime > 0 || configuration.Transport.KeepAliveMaxRequests > 0)) { serverHTTP.ConnContext = func(ctx context.Context, c net.Conn) context.Context { cState := &connState{Start: time.Now()} if debugConnection { clientConnectionStatesMu.Lock() clientConnectionStates[getConnKey(c)] = cState clientConnectionStatesMu.Unlock() } return context.WithValue(ctx, connStateKey, cState) } if debugConnection { serverHTTP.ConnState = func(c net.Conn, state http.ConnState) { clientConnectionStatesMu.Lock() if clientConnectionStates[getConnKey(c)] != nil { clientConnectionStates[getConnKey(c)].State = state.String() } clientConnectionStatesMu.Unlock() } } } prevConnContext := serverHTTP.ConnContext serverHTTP.ConnContext = func(ctx context.Context, c net.Conn) context.Context { // This adds an empty struct in order to store a RoundTripper in the ConnContext in case of Kerberos or NTLM. ctx = service.AddTransportOnContext(ctx) if prevConnContext != nil { return prevConnContext(ctx, c) } return ctx } listener := newHTTPForwarder(ln) go func() { err := serverHTTP.Serve(listener) if err != nil && !errors.Is(err, http.ErrServerClosed) { log.Ctx(ctx).Error().Err(err).Msg("Error while running HTTP server") } }() return &httpServer{ Server: serverHTTP, Forwarder: listener, Switcher: httpSwitcher, }, nil } func getConnKey(conn net.Conn) string { return fmt.Sprintf("%s => %s", conn.RemoteAddr(), conn.LocalAddr()) } func newTrackedConnection(conn tcp.WriteCloser, tracker *connectionTracker) *trackedConnection { tracker.AddConnection(conn) return &trackedConnection{ WriteCloser: conn, tracker: tracker, } } type trackedConnection struct { tracker *connectionTracker tcp.WriteCloser } func (t *trackedConnection) Close() error { t.tracker.RemoveConnection(t.WriteCloser) return t.WriteCloser.Close() } // This function is inspired by http.AllowQuerySemicolons. func encodeQuerySemicolons(h http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { if strings.Contains(req.URL.RawQuery, ";") { r2 := new(http.Request) *r2 = *req r2.URL = new(url.URL) *r2.URL = *req.URL r2.URL.RawQuery = strings.ReplaceAll(req.URL.RawQuery, ";", "%3B") // Because the reverse proxy director is building query params from requestURI it needs to be updated as well. r2.RequestURI = r2.URL.RequestURI() h.ServeHTTP(rw, r2) } else { h.ServeHTTP(rw, req) } }) } // sanitizePath removes the "..", "." and duplicate slash segments from the URL according to https://datatracker.ietf.org/doc/html/rfc3986#section-6.2.2.3. // It cleans the request URL Path and RawPath, and updates the request URI. func sanitizePath(h http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { r2 := new(http.Request) *r2 = *req // Cleans the URL raw path and path. r2.URL = r2.URL.JoinPath() // Because the reverse proxy director is building query params from requestURI it needs to be updated as well. r2.RequestURI = r2.URL.RequestURI() h.ServeHTTP(rw, r2) }) } // unreservedCharacters contains the mapping of the percent-encoded form to the ASCII form // of the unreserved characters according to https://datatracker.ietf.org/doc/html/rfc3986#section-2.3. var unreservedCharacters = map[string]rune{ "%41": 'A', "%42": 'B', "%43": 'C', "%44": 'D', "%45": 'E', "%46": 'F', "%47": 'G', "%48": 'H', "%49": 'I', "%4A": 'J', "%4B": 'K', "%4C": 'L', "%4D": 'M', "%4E": 'N', "%4F": 'O', "%50": 'P', "%51": 'Q', "%52": 'R', "%53": 'S', "%54": 'T', "%55": 'U', "%56": 'V', "%57": 'W', "%58": 'X', "%59": 'Y', "%5A": 'Z', "%61": 'a', "%62": 'b', "%63": 'c', "%64": 'd', "%65": 'e', "%66": 'f', "%67": 'g', "%68": 'h', "%69": 'i', "%6A": 'j', "%6B": 'k', "%6C": 'l', "%6D": 'm', "%6E": 'n', "%6F": 'o', "%70": 'p', "%71": 'q', "%72": 'r', "%73": 's', "%74": 't', "%75": 'u', "%76": 'v', "%77": 'w', "%78": 'x', "%79": 'y', "%7A": 'z', "%30": '0', "%31": '1', "%32": '2', "%33": '3', "%34": '4', "%35": '5', "%36": '6', "%37": '7', "%38": '8', "%39": '9', "%2D": '-', "%2E": '.', "%5F": '_', "%7E": '~', } // normalizePath removes from the RawPath unreserved percent-encoded characters as they are equivalent to their non-encoded // form according to https://datatracker.ietf.org/doc/html/rfc3986#section-2.3 and capitalizes percent-encoded characters // according to https://datatracker.ietf.org/doc/html/rfc3986#section-6.2.2.1. func normalizePath(h http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rawPath := req.URL.RawPath // When the RawPath is empty the encoded form of the Path is equivalent to the original request Path. // Thus, the normalization is not needed as no unreserved characters were encoded and the encoded version // of Path obtained with URL.EscapedPath contains only percent-encoded characters in upper case. if rawPath == "" { h.ServeHTTP(rw, req) return } var normalizedRawPathBuilder strings.Builder for i := 0; i < len(rawPath); i++ { if rawPath[i] != '%' { normalizedRawPathBuilder.WriteString(string(rawPath[i])) continue } // This should never happen as the standard library will reject requests containing invalid percent-encodings. // This discards URLs with a percent character at the end. if i+2 >= len(rawPath) { rw.WriteHeader(http.StatusBadRequest) return } encodedCharacter := strings.ToUpper(rawPath[i : i+3]) if r, unreserved := unreservedCharacters[encodedCharacter]; unreserved { normalizedRawPathBuilder.WriteRune(r) } else { normalizedRawPathBuilder.WriteString(encodedCharacter) } i += 2 } normalizedRawPath := normalizedRawPathBuilder.String() // We do not have to alter the request URL as the original RawPath is already normalized. if normalizedRawPath == rawPath { h.ServeHTTP(rw, req) return } r2 := new(http.Request) *r2 = *req // Decoding unreserved characters only alter the RAW version of the URL, // as unreserved percent-encoded characters are equivalent to their non encoded form. r2.URL.RawPath = normalizedRawPath // Because the reverse proxy director is building query params from RequestURI it needs to be updated as well. r2.RequestURI = r2.URL.RequestURI() h.ServeHTTP(rw, r2) }) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/aggregator_test.go
pkg/server/aggregator_test.go
package server import ( "testing" "github.com/go-acme/lego/v4/challenge/tlsalpn01" "github.com/stretchr/testify/assert" "github.com/traefik/traefik/v3/pkg/config/dynamic" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "github.com/traefik/traefik/v3/pkg/tls" ) func Test_mergeConfiguration(t *testing.T) { testCases := []struct { desc string given dynamic.Configurations expected *dynamic.HTTPConfiguration }{ { desc: "Nil returns an empty configuration", given: nil, expected: &dynamic.HTTPConfiguration{ Routers: make(map[string]*dynamic.Router), Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: make(map[string]*dynamic.Model), ServersTransports: make(map[string]*dynamic.ServersTransport), }, }, { desc: "Returns fully qualified elements from a mono-provider configuration map", given: dynamic.Configurations{ "provider-1": &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "router-1": {}, }, Middlewares: map[string]*dynamic.Middleware{ "middleware-1": {}, }, Services: map[string]*dynamic.Service{ "service-1": {}, }, }, }, }, expected: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "router-1@provider-1": { EntryPoints: []string{"defaultEP"}, }, }, Middlewares: map[string]*dynamic.Middleware{ "middleware-1@provider-1": {}, }, Services: map[string]*dynamic.Service{ "service-1@provider-1": {}, }, Models: make(map[string]*dynamic.Model), ServersTransports: make(map[string]*dynamic.ServersTransport), }, }, { desc: "Returns fully qualified elements from a multi-provider configuration map", given: dynamic.Configurations{ "provider-1": &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "router-1": {}, }, Middlewares: map[string]*dynamic.Middleware{ "middleware-1": {}, }, Services: map[string]*dynamic.Service{ "service-1": {}, }, }, }, "provider-2": &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "router-1": {}, }, Middlewares: map[string]*dynamic.Middleware{ "middleware-1": {}, }, Services: map[string]*dynamic.Service{ "service-1": {}, }, }, }, }, expected: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "router-1@provider-1": { EntryPoints: []string{"defaultEP"}, }, "router-1@provider-2": { EntryPoints: []string{"defaultEP"}, }, }, Middlewares: map[string]*dynamic.Middleware{ "middleware-1@provider-1": {}, "middleware-1@provider-2": {}, }, Services: map[string]*dynamic.Service{ "service-1@provider-1": {}, "service-1@provider-2": {}, }, Models: make(map[string]*dynamic.Model), ServersTransports: make(map[string]*dynamic.ServersTransport), }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() actual := mergeConfiguration(test.given, []string{"defaultEP"}) assert.Equal(t, test.expected, actual.HTTP) }) } } func Test_mergeConfiguration_tlsCertificates(t *testing.T) { testCases := []struct { desc string given dynamic.Configurations expected []*tls.CertAndStores }{ { desc: "Skip temp certificates from another provider than tlsalpn", given: dynamic.Configurations{ "provider-1": &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{ Certificates: []*tls.CertAndStores{ {Certificate: tls.Certificate{}, Stores: []string{tlsalpn01.ACMETLS1Protocol}}, }, }, }, }, expected: nil, }, { desc: "Allows tlsalpn provider to give certificates", given: dynamic.Configurations{ "tlsalpn.acme": &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{ Certificates: []*tls.CertAndStores{{ Certificate: tls.Certificate{CertFile: "foo", KeyFile: "bar"}, Stores: []string{tlsalpn01.ACMETLS1Protocol}, }}, }, }, }, expected: []*tls.CertAndStores{{ Certificate: tls.Certificate{CertFile: "foo", KeyFile: "bar"}, Stores: []string{tlsalpn01.ACMETLS1Protocol}, }}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() actual := mergeConfiguration(test.given, []string{"defaultEP"}) assert.Equal(t, test.expected, actual.TLS.Certificates) }) } } func Test_mergeConfiguration_tlsOptions(t *testing.T) { testCases := []struct { desc string given dynamic.Configurations expected map[string]tls.Options }{ { desc: "Nil returns an empty configuration", given: nil, expected: map[string]tls.Options{ "default": tls.DefaultTLSOptions, }, }, { desc: "Returns fully qualified elements from a mono-provider configuration map", given: dynamic.Configurations{ "provider-1": &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "foo": { MinVersion: "VersionTLS12", }, }, }, }, }, expected: map[string]tls.Options{ "default": tls.DefaultTLSOptions, "foo@provider-1": { MinVersion: "VersionTLS12", }, }, }, { desc: "Returns fully qualified elements from a multi-provider configuration map", given: dynamic.Configurations{ "provider-1": &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "foo": { MinVersion: "VersionTLS13", }, }, }, }, "provider-2": &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "foo": { MinVersion: "VersionTLS12", }, }, }, }, }, expected: map[string]tls.Options{ "default": tls.DefaultTLSOptions, "foo@provider-1": { MinVersion: "VersionTLS13", }, "foo@provider-2": { MinVersion: "VersionTLS12", }, }, }, { desc: "Create a valid default tls option when appears only in one provider", given: dynamic.Configurations{ "provider-1": &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "foo": { MinVersion: "VersionTLS13", }, "default": { MinVersion: "VersionTLS11", }, }, }, }, "provider-2": &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "foo": { MinVersion: "VersionTLS12", }, }, }, }, }, expected: map[string]tls.Options{ "default": { MinVersion: "VersionTLS11", }, "foo@provider-1": { MinVersion: "VersionTLS13", }, "foo@provider-2": { MinVersion: "VersionTLS12", }, }, }, { desc: "No default tls option if it is defined in multiple providers", given: dynamic.Configurations{ "provider-1": &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "foo": { MinVersion: "VersionTLS12", }, "default": { MinVersion: "VersionTLS11", }, }, }, }, "provider-2": &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "foo": { MinVersion: "VersionTLS13", }, "default": { MinVersion: "VersionTLS12", }, }, }, }, }, expected: map[string]tls.Options{ "foo@provider-1": { MinVersion: "VersionTLS12", }, "foo@provider-2": { MinVersion: "VersionTLS13", }, }, }, { desc: "Create a default TLS Options configuration if none was provided", given: dynamic.Configurations{ "provider-1": &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "foo": { MinVersion: "VersionTLS12", }, }, }, }, "provider-2": &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "foo": { MinVersion: "VersionTLS13", }, }, }, }, }, expected: map[string]tls.Options{ "default": tls.DefaultTLSOptions, "foo@provider-1": { MinVersion: "VersionTLS12", }, "foo@provider-2": { MinVersion: "VersionTLS13", }, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() actual := mergeConfiguration(test.given, []string{"defaultEP"}) assert.Equal(t, test.expected, actual.TLS.Options) }) } } func Test_mergeConfiguration_tlsStore(t *testing.T) { testCases := []struct { desc string given dynamic.Configurations expected map[string]tls.Store }{ { desc: "Create a valid default tls store when appears only in one provider", given: dynamic.Configurations{ "provider-1": &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{ "default": { DefaultCertificate: &tls.Certificate{ CertFile: "foo", KeyFile: "bar", }, }, }, }, }, "provider-2": &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{ "foo": { DefaultCertificate: &tls.Certificate{ CertFile: "foo", KeyFile: "bar", }, }, }, }, }, }, expected: map[string]tls.Store{ "default": { DefaultCertificate: &tls.Certificate{ CertFile: "foo", KeyFile: "bar", }, }, "foo@provider-2": { DefaultCertificate: &tls.Certificate{ CertFile: "foo", KeyFile: "bar", }, }, }, }, { desc: "Don't default tls store when appears two times", given: dynamic.Configurations{ "provider-1": &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{ "default": { DefaultCertificate: &tls.Certificate{ CertFile: "foo", KeyFile: "bar", }, }, }, }, }, "provider-2": &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{ "default": { DefaultCertificate: &tls.Certificate{ CertFile: "foo", KeyFile: "bar", }, }, }, }, }, }, expected: map[string]tls.Store{}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() actual := mergeConfiguration(test.given, []string{"defaultEP"}) assert.Equal(t, test.expected, actual.TLS.Stores) }) } } func Test_mergeConfiguration_defaultTCPEntryPoint(t *testing.T) { given := dynamic.Configurations{ "provider-1": &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "router-1": {}, }, Services: map[string]*dynamic.TCPService{ "service-1": {}, }, }, }, } expected := &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "router-1@provider-1": { EntryPoints: []string{"defaultEP"}, }, }, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{ "service-1@provider-1": {}, }, Models: map[string]*dynamic.TCPModel{}, ServersTransports: make(map[string]*dynamic.TCPServersTransport), } actual := mergeConfiguration(given, []string{"defaultEP"}) assert.Equal(t, expected, actual.TCP) } func Test_applyModel(t *testing.T) { testCases := []struct { desc string input dynamic.Configuration expected dynamic.Configuration }{ { desc: "empty configuration", input: dynamic.Configuration{}, expected: dynamic.Configuration{}, }, { desc: "without model", input: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: make(map[string]*dynamic.Router), Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: make(map[string]*dynamic.Model), }, }, expected: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: make(map[string]*dynamic.Router), Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: make(map[string]*dynamic.Model), }, }, }, { desc: "without model, one router", input: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{"test": {}}, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: make(map[string]*dynamic.Model), }, }, expected: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "test": { Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: make(map[string]*dynamic.Model), }, }, }, { desc: "with model, not used", input: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: make(map[string]*dynamic.Router), Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "ep@internal": { Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{}, }, }, }, }, expected: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: make(map[string]*dynamic.Router), Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "ep@internal": { Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{}, }, }, }, }, }, { desc: "with model, one entry point", input: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "test": { EntryPoints: []string{"websecure"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "websecure@internal": { Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{}, }, }, }, }, expected: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "test": { EntryPoints: []string{"websecure"}, Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{}, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "websecure@internal": { Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{}, }, }, }, }, }, { desc: "with model, one entry point with observability", input: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "test": { EntryPoints: []string{"websecure"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "websecure@internal": { Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{}, Observability: dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Tracing: pointer(true), Metrics: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, }, }, }, expected: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "test": { EntryPoints: []string{"websecure"}, Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{}, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Tracing: pointer(true), Metrics: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "websecure@internal": { Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{}, Observability: dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Tracing: pointer(true), Metrics: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, }, }, }, }, { desc: "with model, one entry point, and router with tls", input: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "test": { EntryPoints: []string{"websecure"}, TLS: &dynamic.RouterTLSConfig{CertResolver: "router"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "websecure@internal": { Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{CertResolver: "ep"}, }, }, }, }, expected: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "test": { EntryPoints: []string{"websecure"}, Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{CertResolver: "router"}, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "websecure@internal": { Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{CertResolver: "ep"}, }, }, }, }, }, { desc: "with model, two entry points", input: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "test": { EntryPoints: []string{"websecure", "web"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "websecure@internal": { Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{}, }, }, }, }, expected: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "test": { EntryPoints: []string{"web"}, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, "websecure-test": { EntryPoints: []string{"websecure"}, Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{}, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "websecure@internal": { Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{}, }, }, }, }, }, { desc: "with TCP model, two entry points", input: dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "test": { EntryPoints: []string{"websecure", "web"}, }, "test2": { EntryPoints: []string{"web"}, RuleSyntax: "barfoo", }, }, Middlewares: make(map[string]*dynamic.TCPMiddleware), Services: make(map[string]*dynamic.TCPService), Models: map[string]*dynamic.TCPModel{ "websecure@internal": { DefaultRuleSyntax: "foobar", }, }, }, }, expected: dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "test": { EntryPoints: []string{"websecure", "web"}, RuleSyntax: "foobar", }, "test2": { EntryPoints: []string{"web"}, RuleSyntax: "barfoo", }, }, Middlewares: make(map[string]*dynamic.TCPMiddleware), Services: make(map[string]*dynamic.TCPService), Models: map[string]*dynamic.TCPModel{ "websecure@internal": { DefaultRuleSyntax: "foobar", }, }, }, }, }, { desc: "child router with parentRefs, parent not split", input: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "parent": { EntryPoints: []string{"web"}, }, "child": { ParentRefs: []string{"parent"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: make(map[string]*dynamic.Model), }, }, expected: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "parent": { EntryPoints: []string{"web"}, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, "child": { ParentRefs: []string{"parent"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: make(map[string]*dynamic.Model), }, }, }, { desc: "child router with parentRefs, parent split by model", input: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "parent": { EntryPoints: []string{"websecure", "web"}, }, "child": { ParentRefs: []string{"parent"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "websecure@internal": { Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{}, }, }, }, }, expected: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "parent": { EntryPoints: []string{"web"}, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, "websecure-parent": { EntryPoints: []string{"websecure"}, Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{}, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, "child": { ParentRefs: []string{"parent", "websecure-parent"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "websecure@internal": { Middlewares: []string{"test"}, TLS: &dynamic.RouterTLSConfig{}, }, }, }, }, }, { desc: "multiple child routers with parentRefs, parent split by model", input: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "parent": { EntryPoints: []string{"websecure", "web"}, }, "child1": { ParentRefs: []string{"parent"}, }, "child2": { ParentRefs: []string{"parent"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "websecure@internal": { Middlewares: []string{"auth"}, }, }, }, }, expected: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "parent": { EntryPoints: []string{"web"}, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, "websecure-parent": { EntryPoints: []string{"websecure"}, Middlewares: []string{"auth"}, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, "child1": { ParentRefs: []string{"parent", "websecure-parent"}, }, "child2": { ParentRefs: []string{"parent", "websecure-parent"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "websecure@internal": { Middlewares: []string{"auth"}, }, }, }, }, }, { desc: "child router with parentRefs to non-existing parent", input: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "child": { ParentRefs: []string{"nonexistent"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: make(map[string]*dynamic.Model), }, }, expected: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "child": { ParentRefs: []string{"nonexistent"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: make(map[string]*dynamic.Model), }, }, }, { desc: "child router with multiple parentRefs, some split", input: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "parent1": { EntryPoints: []string{"websecure", "web"}, }, "parent2": { EntryPoints: []string{"web"}, }, "child": { ParentRefs: []string{"parent1", "parent2"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "websecure@internal": { TLS: &dynamic.RouterTLSConfig{}, }, }, }, }, expected: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "parent1": { EntryPoints: []string{"web"}, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, "websecure-parent1": { EntryPoints: []string{"websecure"}, TLS: &dynamic.RouterTLSConfig{}, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, "parent2": { EntryPoints: []string{"web"}, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, "child": { ParentRefs: []string{"parent1", "websecure-parent1", "parent2"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "websecure@internal": { TLS: &dynamic.RouterTLSConfig{}, }, }, }, }, }, { desc: "child router with multiple parentRefs, all split", input: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "parent1": { EntryPoints: []string{"websecure", "web"}, }, "parent2": { EntryPoints: []string{"web"}, }, "child": { ParentRefs: []string{"parent1", "parent2"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "web@internal": { TLS: &dynamic.RouterTLSConfig{}, }, "websecure@internal": { TLS: &dynamic.RouterTLSConfig{}, }, }, }, }, expected: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "web-parent1": { EntryPoints: []string{"web"}, TLS: &dynamic.RouterTLSConfig{}, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, "websecure-parent1": { EntryPoints: []string{"websecure"}, TLS: &dynamic.RouterTLSConfig{}, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, "parent2": { EntryPoints: []string{"web"}, TLS: &dynamic.RouterTLSConfig{}, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, "child": { ParentRefs: []string{"websecure-parent1", "web-parent1", "parent2"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "web@internal": { TLS: &dynamic.RouterTLSConfig{}, }, "websecure@internal": { TLS: &dynamic.RouterTLSConfig{}, }, }, }, }, }, { desc: "child router with parentRefs, parent split into three routers", input: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "parent": { EntryPoints: []string{"websecure", "web", "admin"}, }, "child": { ParentRefs: []string{"parent"}, }, }, Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: map[string]*dynamic.Model{ "websecure@internal": { TLS: &dynamic.RouterTLSConfig{}, }, "admin@internal": {
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/server_entrypoint_listenconfig_unix.go
pkg/server/server_entrypoint_listenconfig_unix.go
//go:build linux || freebsd || openbsd || darwin package server import ( "fmt" "net" "syscall" "github.com/traefik/traefik/v3/pkg/config/static" "golang.org/x/sys/unix" ) // newListenConfig creates a new net.ListenConfig for the given configuration of // the entry point. func newListenConfig(configuration *static.EntryPoint) (lc net.ListenConfig) { if configuration != nil && configuration.ReusePort { lc.Control = controlReusePort } return } // controlReusePort is a net.ListenConfig.Control function that enables SO_REUSEPORT // on the socket. func controlReusePort(network, address string, c syscall.RawConn) error { var setSockOptErr error err := c.Control(func(fd uintptr) { // Note that net.ListenConfig enables unix.SO_REUSEADDR by default, // as seen in https://go.dev/src/net/sockopt_linux.go. Therefore, no // additional action is required to enable it here. setSockOptErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unixSOREUSEPORT, 1) if setSockOptErr != nil { return } }) if err != nil { return fmt.Errorf("control: %w", err) } if setSockOptErr != nil { return fmt.Errorf("setsockopt: %w", setSockOptErr) } return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/server_entrypoint_listenconfig_other.go
pkg/server/server_entrypoint_listenconfig_other.go
//go:build !(linux || freebsd || openbsd || darwin) package server import ( "net" "github.com/traefik/traefik/v3/pkg/config/static" ) // newListenConfig creates a new net.ListenConfig for the given configuration of // the entry point. func newListenConfig(configuration *static.EntryPoint) (lc net.ListenConfig) { return }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/configurationwatcher_test.go
pkg/server/configurationwatcher_test.go
package server import ( "context" "errors" "strconv" "sync" "testing" "time" "github.com/stretchr/testify/assert" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/provider/aggregator" "github.com/traefik/traefik/v3/pkg/safe" th "github.com/traefik/traefik/v3/pkg/testhelpers" "github.com/traefik/traefik/v3/pkg/tls" ) type mockProvider struct { messages []dynamic.Message wait time.Duration first chan struct{} throttleDuration time.Duration } func (p *mockProvider) Provide(configurationChan chan<- dynamic.Message, _ *safe.Pool) error { wait := p.wait if wait == 0 { wait = 20 * time.Millisecond } if len(p.messages) == 0 { return errors.New("no messages available") } configurationChan <- p.messages[0] if p.first != nil { <-p.first } for _, message := range p.messages[1:] { time.Sleep(wait) configurationChan <- message } return nil } // ThrottleDuration returns the throttle duration. func (p *mockProvider) ThrottleDuration() time.Duration { return p.throttleDuration } func (p *mockProvider) Init() error { return nil } func TestNewConfigurationWatcher(t *testing.T) { routinesPool := safe.NewPool(t.Context()) t.Cleanup(routinesPool.Stop) pvd := &mockProvider{ messages: []dynamic.Message{{ ProviderName: "mock", Configuration: &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters( th.WithRouter("test", th.WithEntryPoints("e"), th.WithServiceName("scv"))), ), }, }}, } watcher := NewConfigurationWatcher(routinesPool, pvd, []string{}, "") run := make(chan struct{}) watcher.AddListener(func(conf dynamic.Configuration) { expected := dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters( th.WithRouter("test@mock", th.WithEntryPoints("e"), th.WithServiceName("scv"), th.WithObservability())), th.WithMiddlewares(), th.WithLoadBalancerServices(), ), TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, Models: map[string]*dynamic.TCPModel{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "default": tls.DefaultTLSOptions, }, Stores: map[string]tls.Store{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, } assert.Equal(t, expected, conf) close(run) }) watcher.Start() <-run } func TestWaitForRequiredProvider(t *testing.T) { routinesPool := safe.NewPool(t.Context()) pvdAggregator := &mockProvider{ wait: 5 * time.Millisecond, } config := &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("foo", th.WithEntryPoints("ep"))), th.WithLoadBalancerServices(th.WithService("bar")), ), } pvdAggregator.messages = append(pvdAggregator.messages, dynamic.Message{ ProviderName: "mock", Configuration: config, }) pvdAggregator.messages = append(pvdAggregator.messages, dynamic.Message{ ProviderName: "required", Configuration: config, }) pvdAggregator.messages = append(pvdAggregator.messages, dynamic.Message{ ProviderName: "mock2", Configuration: config, }) watcher := NewConfigurationWatcher(routinesPool, pvdAggregator, []string{}, "required") publishedConfigCount := 0 watcher.AddListener(func(_ dynamic.Configuration) { publishedConfigCount++ }) watcher.Start() t.Cleanup(watcher.Stop) t.Cleanup(routinesPool.Stop) // give some time so that the configuration can be processed time.Sleep(20 * time.Millisecond) // after 20 milliseconds we should have 2 configs published assert.Equal(t, 2, publishedConfigCount, "times configs were published") } func TestIgnoreTransientConfiguration(t *testing.T) { routinesPool := safe.NewPool(t.Context()) config := &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("foo", th.WithEntryPoints("ep"))), th.WithLoadBalancerServices(th.WithService("bar")), ), } expectedConfig := dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("foo@mock", th.WithEntryPoints("ep"), th.WithObservability())), th.WithLoadBalancerServices(th.WithService("bar@mock")), th.WithMiddlewares(), ), TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, Models: map[string]*dynamic.TCPModel{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "default": tls.DefaultTLSOptions, }, Stores: map[string]tls.Store{}, }, } expectedConfig3 := dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("foo@mock", th.WithEntryPoints("ep"), th.WithObservability())), th.WithLoadBalancerServices(th.WithService("bar-config3@mock")), th.WithMiddlewares(), ), TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, Models: map[string]*dynamic.TCPModel{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "default": tls.DefaultTLSOptions, }, Stores: map[string]tls.Store{}, }, } config2 := &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("baz", th.WithEntryPoints("ep"))), th.WithLoadBalancerServices(th.WithService("toto")), ), } config3 := &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("foo", th.WithEntryPoints("ep"))), th.WithLoadBalancerServices(th.WithService("bar-config3")), ), } watcher := NewConfigurationWatcher(routinesPool, &mockProvider{}, []string{}, "") // To be able to "block" the writes, we change the chan to remove buffering. watcher.allProvidersConfigs = make(chan dynamic.Message) publishedConfigCount := 0 firstConfigHandled := make(chan struct{}) blockConfConsumer := make(chan struct{}) blockConfConsumerAssert := make(chan struct{}) watcher.AddListener(func(config dynamic.Configuration) { publishedConfigCount++ if publishedConfigCount > 2 { t.Fatal("More than 2 published configuration") } if publishedConfigCount == 1 { assert.Equal(t, expectedConfig, config) close(firstConfigHandled) <-blockConfConsumer time.Sleep(500 * time.Millisecond) } if publishedConfigCount == 2 { assert.Equal(t, expectedConfig3, config) close(blockConfConsumerAssert) } }) watcher.Start() t.Cleanup(watcher.Stop) t.Cleanup(routinesPool.Stop) watcher.allProvidersConfigs <- dynamic.Message{ ProviderName: "mock", Configuration: config, } <-firstConfigHandled watcher.allProvidersConfigs <- dynamic.Message{ ProviderName: "mock", Configuration: config2, } watcher.allProvidersConfigs <- dynamic.Message{ ProviderName: "mock", Configuration: config, } close(blockConfConsumer) watcher.allProvidersConfigs <- dynamic.Message{ ProviderName: "mock", Configuration: config3, } select { case <-blockConfConsumerAssert: case <-time.After(10 * time.Second): t.Fatal("Timeout") } } func TestListenProvidersThrottleProviderConfigReload(t *testing.T) { routinesPool := safe.NewPool(t.Context()) pvd := &mockProvider{ wait: 10 * time.Millisecond, throttleDuration: 30 * time.Millisecond, } for i := range 5 { pvd.messages = append(pvd.messages, dynamic.Message{ ProviderName: "mock", Configuration: &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("foo"+strconv.Itoa(i), th.WithEntryPoints("ep"))), th.WithLoadBalancerServices(th.WithService("bar")), ), }, }) } providerAggregator := &aggregator.ProviderAggregator{} err := providerAggregator.AddProvider(pvd) assert.NoError(t, err) watcher := NewConfigurationWatcher(routinesPool, providerAggregator, []string{}, "") publishedConfigCount := 0 watcher.AddListener(func(_ dynamic.Configuration) { publishedConfigCount++ }) watcher.Start() t.Cleanup(watcher.Stop) t.Cleanup(routinesPool.Stop) // Give some time so that the configuration can be processed. time.Sleep(100 * time.Millisecond) // To load 5 new configs it would require 150ms (5 configs * 30ms). // In 100ms, we should only have time to load 3 configs. assert.LessOrEqual(t, publishedConfigCount, 3, "config was applied too many times") assert.Positive(t, publishedConfigCount, "config was not applied at least once") } func TestListenProvidersSkipsEmptyConfigs(t *testing.T) { routinesPool := safe.NewPool(t.Context()) pvd := &mockProvider{ messages: []dynamic.Message{{ProviderName: "mock"}}, } watcher := NewConfigurationWatcher(routinesPool, pvd, []string{}, "") watcher.AddListener(func(_ dynamic.Configuration) { t.Error("An empty configuration was published but it should not") }) watcher.Start() t.Cleanup(watcher.Stop) t.Cleanup(routinesPool.Stop) // give some time so that the configuration can be processed time.Sleep(100 * time.Millisecond) } func TestListenProvidersSkipsSameConfigurationForProvider(t *testing.T) { routinesPool := safe.NewPool(t.Context()) message := dynamic.Message{ ProviderName: "mock", Configuration: &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("foo", th.WithEntryPoints("ep"))), th.WithLoadBalancerServices(th.WithService("bar")), ), }, } pvd := &mockProvider{ messages: []dynamic.Message{message, message}, } watcher := NewConfigurationWatcher(routinesPool, pvd, []string{}, "") var configurationReloads int watcher.AddListener(func(_ dynamic.Configuration) { configurationReloads++ }) watcher.Start() t.Cleanup(watcher.Stop) t.Cleanup(routinesPool.Stop) // give some time so that the configuration can be processed time.Sleep(100 * time.Millisecond) assert.Equal(t, 1, configurationReloads, "Same configuration should not be published multiple times") } func TestListenProvidersDoesNotSkipFlappingConfiguration(t *testing.T) { routinesPool := safe.NewPool(t.Context()) configuration := &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("foo", th.WithEntryPoints("ep"))), th.WithLoadBalancerServices(th.WithService("bar")), ), } transientConfiguration := &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("bad", th.WithEntryPoints("ep"))), th.WithLoadBalancerServices(th.WithService("bad")), ), } pvd := &mockProvider{ wait: 5 * time.Millisecond, // The last message needs to be received before the second has been fully processed throttleDuration: 15 * time.Millisecond, messages: []dynamic.Message{ {ProviderName: "mock", Configuration: configuration}, {ProviderName: "mock", Configuration: transientConfiguration}, {ProviderName: "mock", Configuration: configuration}, }, } watcher := NewConfigurationWatcher(routinesPool, pvd, []string{}, "") var lastConfig dynamic.Configuration watcher.AddListener(func(conf dynamic.Configuration) { lastConfig = conf }) watcher.Start() t.Cleanup(watcher.Stop) t.Cleanup(routinesPool.Stop) // give some time so that the configuration can be processed time.Sleep(100 * time.Millisecond) expected := dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("foo@mock", th.WithEntryPoints("ep"), th.WithObservability())), th.WithLoadBalancerServices(th.WithService("bar@mock")), th.WithMiddlewares(), ), TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, Models: map[string]*dynamic.TCPModel{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "default": tls.DefaultTLSOptions, }, Stores: map[string]tls.Store{}, }, } assert.Equal(t, expected, lastConfig) } func TestListenProvidersIgnoreSameConfig(t *testing.T) { routinesPool := safe.NewPool(t.Context()) configuration := &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("foo", th.WithEntryPoints("ep"))), th.WithLoadBalancerServices(th.WithService("bar")), ), } transientConfiguration := &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("bad", th.WithEntryPoints("ep"))), th.WithLoadBalancerServices(th.WithService("bad")), ), } // The transient configuration is sent alternatively with the configuration we want to be applied. // It is intended to show that even if the configurations are different, // those transient configurations will be ignored if they are sent in a time frame // lower than the provider throttle duration. pvd := &mockProvider{ wait: 1 * time.Microsecond, // Enqueue them fast throttleDuration: time.Millisecond, first: make(chan struct{}), messages: []dynamic.Message{ {ProviderName: "mock", Configuration: configuration}, {ProviderName: "mock", Configuration: transientConfiguration}, {ProviderName: "mock", Configuration: configuration}, {ProviderName: "mock", Configuration: transientConfiguration}, {ProviderName: "mock", Configuration: configuration}, }, } providerAggregator := &aggregator.ProviderAggregator{} err := providerAggregator.AddProvider(pvd) assert.NoError(t, err) watcher := NewConfigurationWatcher(routinesPool, providerAggregator, []string{}, "") var configurationReloads int var lastConfig dynamic.Configuration var once sync.Once watcher.AddListener(func(conf dynamic.Configuration) { configurationReloads++ lastConfig = conf // Allows next configurations to be sent by the mock provider as soon as the first configuration message is applied. once.Do(func() { pvd.first <- struct{}{} // Wait for all configuration messages to pile in time.Sleep(5 * time.Millisecond) }) }) watcher.Start() t.Cleanup(watcher.Stop) t.Cleanup(routinesPool.Stop) // Wait long enough time.Sleep(50 * time.Millisecond) expected := dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("foo@mock", th.WithEntryPoints("ep"), th.WithObservability())), th.WithLoadBalancerServices(th.WithService("bar@mock")), th.WithMiddlewares(), ), TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, Models: map[string]*dynamic.TCPModel{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "default": tls.DefaultTLSOptions, }, Stores: map[string]tls.Store{}, }, } assert.Equal(t, expected, lastConfig) assert.Equal(t, 1, configurationReloads) } func TestApplyConfigUnderStress(t *testing.T) { routinesPool := safe.NewPool(t.Context()) watcher := NewConfigurationWatcher(routinesPool, &mockProvider{}, []string{}, "") routinesPool.GoCtx(func(ctx context.Context) { i := 0 for { select { case <-ctx.Done(): return case watcher.allProvidersConfigs <- dynamic.Message{ProviderName: "mock", Configuration: &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("foo"+strconv.Itoa(i), th.WithEntryPoints("ep"))), th.WithLoadBalancerServices(th.WithService("bar")), ), }}: } i++ } }) var configurationReloads int watcher.AddListener(func(conf dynamic.Configuration) { configurationReloads++ }) watcher.Start() t.Cleanup(watcher.Stop) t.Cleanup(routinesPool.Stop) time.Sleep(100 * time.Millisecond) // Ensure that at least two configurations have been applied // if we simulate being spammed configuration changes by the provider(s). // In theory, checking at least one would be sufficient, // but checking for two also ensures that we're looping properly, // and that the whole algo holds, etc. t.Log(configurationReloads) assert.GreaterOrEqual(t, configurationReloads, 2) } func TestListenProvidersIgnoreIntermediateConfigs(t *testing.T) { routinesPool := safe.NewPool(t.Context()) configuration := &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("foo", th.WithEntryPoints("ep"))), th.WithLoadBalancerServices(th.WithService("bar")), ), } transientConfiguration := &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("bad", th.WithEntryPoints("ep"))), th.WithLoadBalancerServices(th.WithService("bad")), ), } transientConfiguration2 := &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("bad2", th.WithEntryPoints("ep"))), th.WithLoadBalancerServices(th.WithService("bad2")), ), } finalConfiguration := &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("final", th.WithEntryPoints("ep"))), th.WithLoadBalancerServices(th.WithService("final")), ), } pvd := &mockProvider{ wait: 10 * time.Microsecond, // Enqueue them fast throttleDuration: 10 * time.Millisecond, messages: []dynamic.Message{ {ProviderName: "mock", Configuration: configuration}, {ProviderName: "mock", Configuration: transientConfiguration}, {ProviderName: "mock", Configuration: transientConfiguration2}, {ProviderName: "mock", Configuration: finalConfiguration}, }, } providerAggregator := &aggregator.ProviderAggregator{} err := providerAggregator.AddProvider(pvd) assert.NoError(t, err) watcher := NewConfigurationWatcher(routinesPool, providerAggregator, []string{}, "") var configurationReloads int var lastConfig dynamic.Configuration watcher.AddListener(func(conf dynamic.Configuration) { configurationReloads++ lastConfig = conf }) watcher.Start() t.Cleanup(watcher.Stop) t.Cleanup(routinesPool.Stop) // Wait long enough time.Sleep(500 * time.Millisecond) expected := dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("final@mock", th.WithEntryPoints("ep"), th.WithObservability())), th.WithLoadBalancerServices(th.WithService("final@mock")), th.WithMiddlewares(), ), TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, Models: map[string]*dynamic.TCPModel{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "default": tls.DefaultTLSOptions, }, Stores: map[string]tls.Store{}, }, } assert.Equal(t, expected, lastConfig) assert.Equal(t, 2, configurationReloads) } func TestListenProvidersPublishesConfigForEachProvider(t *testing.T) { routinesPool := safe.NewPool(t.Context()) configuration := &dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters(th.WithRouter("foo", th.WithEntryPoints("ep"))), th.WithLoadBalancerServices(th.WithService("bar")), ), } pvd := &mockProvider{ messages: []dynamic.Message{ {ProviderName: "mock", Configuration: configuration}, {ProviderName: "mock2", Configuration: configuration}, }, } watcher := NewConfigurationWatcher(routinesPool, pvd, []string{}, "") var publishedProviderConfig dynamic.Configuration watcher.AddListener(func(conf dynamic.Configuration) { publishedProviderConfig = conf }) watcher.Start() t.Cleanup(watcher.Stop) t.Cleanup(routinesPool.Stop) // give some time so that the configuration can be processed time.Sleep(100 * time.Millisecond) expected := dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters( th.WithRouter("foo@mock", th.WithEntryPoints("ep"), th.WithObservability()), th.WithRouter("foo@mock2", th.WithEntryPoints("ep"), th.WithObservability()), ), th.WithLoadBalancerServices( th.WithService("bar@mock"), th.WithService("bar@mock2"), ), th.WithMiddlewares(), ), TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, Models: map[string]*dynamic.TCPModel{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "default": tls.DefaultTLSOptions, }, Stores: map[string]tls.Store{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, } assert.Equal(t, expected, publishedProviderConfig) } func TestPublishConfigUpdatedByProvider(t *testing.T) { routinesPool := safe.NewPool(t.Context()) pvdConfiguration := dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "foo": {}, }, }, } pvd := &mockProvider{ wait: 10 * time.Millisecond, messages: []dynamic.Message{ { ProviderName: "mock", Configuration: &pvdConfiguration, }, { ProviderName: "mock", Configuration: &pvdConfiguration, }, }, } watcher := NewConfigurationWatcher(routinesPool, pvd, []string{}, "") publishedConfigCount := 0 watcher.AddListener(func(configuration dynamic.Configuration) { publishedConfigCount++ // Update the provider configuration published in next dynamic Message which should trigger a new publishing. pvdConfiguration.TCP.Routers["bar"] = &dynamic.TCPRouter{} }) watcher.Start() t.Cleanup(watcher.Stop) t.Cleanup(routinesPool.Stop) // give some time so that the configuration can be processed. time.Sleep(100 * time.Millisecond) assert.Equal(t, 2, publishedConfigCount) } func TestPublishConfigUpdatedByConfigWatcherListener(t *testing.T) { routinesPool := safe.NewPool(t.Context()) pvd := &mockProvider{ wait: 10 * time.Millisecond, messages: []dynamic.Message{ { ProviderName: "mock", Configuration: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "foo": {}, }, }, }, }, { ProviderName: "mock", Configuration: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "foo": {}, }, }, }, }, }, } watcher := NewConfigurationWatcher(routinesPool, pvd, []string{}, "") publishedConfigCount := 0 watcher.AddListener(func(configuration dynamic.Configuration) { publishedConfigCount++ // Modify the provided configuration. // This should not modify the configuration stored in the configuration watcher and therefore there will be no new publishing. configuration.TCP.Routers["foo@mock"].Rule = "bar" }) watcher.Start() t.Cleanup(watcher.Stop) t.Cleanup(routinesPool.Stop) // give some time so that the configuration can be processed. time.Sleep(100 * time.Millisecond) assert.Equal(t, 1, publishedConfigCount) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/server_entrypoint_tcp_http3_test.go
pkg/server/server_entrypoint_tcp_http3_test.go
package server import ( "bufio" "crypto/tls" "crypto/x509" "net/http" "testing" "time" "github.com/quic-go/quic-go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/static" tcprouter "github.com/traefik/traefik/v3/pkg/server/router/tcp" "github.com/traefik/traefik/v3/pkg/types" ) // LocalhostCert is a PEM-encoded TLS cert with SAN IPs // "127.0.0.1" and "[::1]", expiring at Jan 29 16:00:00 2084 GMT. // generated from src/crypto/tls: // go run generate_cert.go --rsa-bits 2048 --host 127.0.0.1,::1,example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h var ( localhostCert = types.FileOrContent(`-----BEGIN CERTIFICATE----- MIIDOTCCAiGgAwIBAgIQSRJrEpBGFc7tNb1fb5pKFzANBgkqhkiG9w0BAQsFADAS MRAwDgYDVQQKEwdBY21lIENvMCAXDTcwMDEwMTAwMDAwMFoYDzIwODQwMTI5MTYw MDAwWjASMRAwDgYDVQQKEwdBY21lIENvMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A MIIBCgKCAQEA6Gba5tHV1dAKouAaXO3/ebDUU4rvwCUg/CNaJ2PT5xLD4N1Vcb8r bFSW2HXKq+MPfVdwIKR/1DczEoAGf/JWQTW7EgzlXrCd3rlajEX2D73faWJekD0U aUgz5vtrTXZ90BQL7WvRICd7FlEZ6FPOcPlumiyNmzUqtwGhO+9ad1W5BqJaRI6P YfouNkwR6Na4TzSj5BrqUfP0FwDizKSJ0XXmh8g8G9mtwxOSN3Ru1QFc61Xyeluk POGKBV/q6RBNklTNe0gI8usUMlYyoC7ytppNMW7X2vodAelSu25jgx2anj9fDVZu h7AXF5+4nJS4AAt0n1lNY7nGSsdZas8PbQIDAQABo4GIMIGFMA4GA1UdDwEB/wQE AwICpDATBgNVHSUEDDAKBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud DgQWBBStsdjh3/JCXXYlQryOrL4Sh7BW5TAuBgNVHREEJzAlggtleGFtcGxlLmNv bYcEfwAAAYcQAAAAAAAAAAAAAAAAAAAAATANBgkqhkiG9w0BAQsFAAOCAQEAxWGI 5NhpF3nwwy/4yB4i/CwwSpLrWUa70NyhvprUBC50PxiXav1TeDzwzLx/o5HyNwsv cxv3HdkLW59i/0SlJSrNnWdfZ19oTcS+6PtLoVyISgtyN6DpkKpdG1cOkW3Cy2P2 +tK/tKHRP1Y/Ra0RiDpOAmqn0gCOFGz8+lqDIor/T7MTpibL3IxqWfPrvfVRHL3B grw/ZQTTIVjjh4JBSW3WyWgNo/ikC1lrVxzl4iPUGptxT36Cr7Zk2Bsg0XqwbOvK 5d+NTDREkSnUbie4GeutujmX3Dsx88UiV6UY/4lHJa6I5leHUNOHahRbpbWeOfs/ WkBKOclmOV2xlTVuPw== -----END CERTIFICATE-----`) // LocalhostKey is the private key for localhostCert. localhostKey = types.FileOrContent(`-----BEGIN RSA PRIVATE KEY----- MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDoZtrm0dXV0Aqi 4Bpc7f95sNRTiu/AJSD8I1onY9PnEsPg3VVxvytsVJbYdcqr4w99V3AgpH/UNzMS gAZ/8lZBNbsSDOVesJ3euVqMRfYPvd9pYl6QPRRpSDPm+2tNdn3QFAvta9EgJ3sW URnoU85w+W6aLI2bNSq3AaE771p3VbkGolpEjo9h+i42TBHo1rhPNKPkGupR8/QX AOLMpInRdeaHyDwb2a3DE5I3dG7VAVzrVfJ6W6Q84YoFX+rpEE2SVM17SAjy6xQy VjKgLvK2mk0xbtfa+h0B6VK7bmODHZqeP18NVm6HsBcXn7iclLgAC3SfWU1jucZK x1lqzw9tAgMBAAECggEABWzxS1Y2wckblnXY57Z+sl6YdmLV+gxj2r8Qib7g4ZIk lIlWR1OJNfw7kU4eryib4fc6nOh6O4AWZyYqAK6tqNQSS/eVG0LQTLTTEldHyVJL dvBe+MsUQOj4nTndZW+QvFzbcm2D8lY5n2nBSxU5ypVoKZ1EqQzytFcLZpTN7d89 EPj0qDyrV4NZlWAwL1AygCwnlwhMQjXEalVF1ylXwU3QzyZ/6MgvF6d3SSUlh+sq XefuyigXw484cQQgbzopv6niMOmGP3of+yV4JQqUSb3IDmmT68XjGd2Dkxl4iPki 6ZwXf3CCi+c+i/zVEcufgZ3SLf8D99kUGE7v7fZ6AQKBgQD1ZX3RAla9hIhxCf+O 3D+I1j2LMrdjAh0ZKKqwMR4JnHX3mjQI6LwqIctPWTU8wYFECSh9klEclSdCa64s uI/GNpcqPXejd0cAAdqHEEeG5sHMDt0oFSurL4lyud0GtZvwlzLuwEweuDtvT9cJ Wfvl86uyO36IW8JdvUprYDctrQKBgQDycZ697qutBieZlGkHpnYWUAeImVA878sJ w44NuXHvMxBPz+lbJGAg8Cn8fcxNAPqHIraK+kx3po8cZGQywKHUWsxi23ozHoxo +bGqeQb9U661TnfdDspIXia+xilZt3mm5BPzOUuRqlh4Y9SOBpSWRmEhyw76w4ZP OPxjWYAgwQKBgA/FehSYxeJgRjSdo+MWnK66tjHgDJE8bYpUZsP0JC4R9DL5oiaA brd2fI6Y+SbyeNBallObt8LSgzdtnEAbjIH8uDJqyOmknNePRvAvR6mP4xyuR+Bv m+Lgp0DMWTw5J9CKpydZDItc49T/mJ5tPhdFVd+am0NAQnmr1MCZ6nHxAoGABS3Y LkaC9FdFUUqSU8+Chkd/YbOkuyiENdkvl6t2e52jo5DVc1T7mLiIrRQi4SI8N9bN /3oJWCT+uaSLX2ouCtNFunblzWHBrhxnZzTeqVq4SLc8aESAnbslKL4i8/+vYZlN s8xtiNcSvL+lMsOBORSXzpj/4Ot8WwTkn1qyGgECgYBKNTypzAHeLE6yVadFp3nQ Ckq9yzvP/ib05rvgbvrne00YeOxqJ9gtTrzgh7koqJyX1L4NwdkEza4ilDWpucn0 xiUZS4SoaJq6ZvcBYS62Yr1t8n09iG47YL8ibgtmH3L+svaotvpVxVK+d7BLevA/ ZboOWVe3icTy64BT3OQhmg== -----END RSA PRIVATE KEY-----`) ) func TestHTTP3AdvertisedPort(t *testing.T) { certContent, err := localhostCert.Read() require.NoError(t, err) keyContent, err := localhostKey.Read() require.NoError(t, err) tlsCert, err := tls.X509KeyPair(certContent, keyContent) require.NoError(t, err) epConfig := &static.EntryPointsTransport{} epConfig.SetDefaults() entryPoint, err := NewTCPEntryPoint(t.Context(), "foo", &static.EntryPoint{ Address: "127.0.0.1:0", Transport: epConfig, ForwardedHeaders: &static.ForwardedHeaders{}, HTTP2: &static.HTTP2Config{}, HTTP3: &static.HTTP3Config{ AdvertisedPort: 8080, }, }, nil, nil) require.NoError(t, err) router, err := tcprouter.NewRouter() require.NoError(t, err) router.AddHTTPTLSConfig("*", &tls.Config{ Certificates: []tls.Certificate{tlsCert}, }) router.SetHTTPSHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) }), nil) ctx := t.Context() go entryPoint.Start(ctx) entryPoint.SwitchRouter(router) conn, err := tls.Dial("tcp", entryPoint.listener.Addr().String(), &tls.Config{ InsecureSkipVerify: true, }) require.NoError(t, err) t.Cleanup(func() { _ = conn.Close() entryPoint.Shutdown(ctx) }) // We are racing with the http3Server readiness happening in the goroutine starting the entrypoint time.Sleep(time.Second) request, err := http.NewRequest(http.MethodGet, "https://127.0.0.1:8090", nil) require.NoError(t, err) err = request.Write(conn) require.NoError(t, err) r, err := http.ReadResponse(bufio.NewReader(conn), nil) require.NoError(t, err) assert.NotContains(t, r.Header.Get("Alt-Svc"), ":8090") assert.Contains(t, r.Header.Get("Alt-Svc"), ":8080") } func TestHTTP30RTT(t *testing.T) { certContent, err := localhostCert.Read() require.NoError(t, err) keyContent, err := localhostKey.Read() require.NoError(t, err) tlsCert, err := tls.X509KeyPair(certContent, keyContent) require.NoError(t, err) epConfig := &static.EntryPointsTransport{} epConfig.SetDefaults() entryPoint, err := NewTCPEntryPoint(t.Context(), "foo", &static.EntryPoint{ Address: "127.0.0.1:8090", Transport: epConfig, ForwardedHeaders: &static.ForwardedHeaders{}, HTTP2: &static.HTTP2Config{}, HTTP3: &static.HTTP3Config{}, }, nil, nil) require.NoError(t, err) router, err := tcprouter.NewRouter() require.NoError(t, err) router.AddHTTPTLSConfig("example.com", &tls.Config{ Certificates: []tls.Certificate{tlsCert}, }) router.SetHTTPSHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) }), nil) ctx := t.Context() go entryPoint.Start(ctx) entryPoint.SwitchRouter(router) // We are racing with the http3Server readiness happening in the goroutine starting the entrypoint. time.Sleep(time.Second) certPool := x509.NewCertPool() certPool.AppendCertsFromPEM(certContent) tlsConf := &tls.Config{ RootCAs: certPool, ServerName: "example.com", NextProtos: []string{"h3"}, } // Define custom cache. gets := make(chan string, 100) puts := make(chan string, 100) cache := newClientSessionCache(tls.NewLRUClientSessionCache(10), gets, puts) tlsConf.ClientSessionCache = cache // This first DialAddrEarly connection is here to populate the cache. earlyConnection, err := quic.DialAddrEarly(t.Context(), "127.0.0.1:8090", tlsConf, &quic.Config{}) require.NoError(t, err) t.Cleanup(func() { _ = earlyConnection.CloseWithError(0, "") entryPoint.Shutdown(ctx) }) // wait for the handshake complete. <-earlyConnection.HandshakeComplete() // 0RTT is always false on the first connection. require.False(t, earlyConnection.ConnectionState().Used0RTT) earlyConnection, err = quic.DialAddrEarly(t.Context(), "127.0.0.1:8090", tlsConf, &quic.Config{}) require.NoError(t, err) <-earlyConnection.HandshakeComplete() // 0RTT need to be false. assert.False(t, earlyConnection.ConnectionState().Used0RTT) } type clientSessionCache struct { cache tls.ClientSessionCache gets chan<- string puts chan<- string } func newClientSessionCache(cache tls.ClientSessionCache, gets, puts chan<- string) *clientSessionCache { return &clientSessionCache{ cache: cache, gets: gets, puts: puts, } } var _ tls.ClientSessionCache = &clientSessionCache{} func (c *clientSessionCache) Get(sessionKey string) (*tls.ClientSessionState, bool) { session, ok := c.cache.Get(sessionKey) c.gets <- sessionKey return session, ok } func (c *clientSessionCache) Put(sessionKey string, cs *tls.ClientSessionState) { c.cache.Put(sessionKey, cs) c.puts <- sessionKey }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/keep_alive_middleware.go
pkg/server/keep_alive_middleware.go
package server import ( "net/http" "time" "github.com/rs/zerolog/log" ptypes "github.com/traefik/paerser/types" ) func newKeepAliveMiddleware(next http.Handler, maxRequests int, maxTime ptypes.Duration) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { state, ok := req.Context().Value(connStateKey).(*connState) if ok { state.HTTPRequestCount++ if maxRequests > 0 && state.HTTPRequestCount >= maxRequests { log.Debug().Msg("Close because of too many requests") state.KeepAliveState = "Close because of too many requests" rw.Header().Set("Connection", "close") } if maxTime > 0 && time.Now().After(state.Start.Add(time.Duration(maxTime))) { log.Debug().Msg("Close because of too long connection") state.KeepAliveState = "Close because of too long connection" rw.Header().Set("Connection", "close") } } next.ServeHTTP(rw, req) }) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/routerfactory_test.go
pkg/server/routerfactory_test.go
package server import ( "net/http" "net/http/httptest" "net/url" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/server/middleware" "github.com/traefik/traefik/v3/pkg/server/service" "github.com/traefik/traefik/v3/pkg/tcp" th "github.com/traefik/traefik/v3/pkg/testhelpers" "github.com/traefik/traefik/v3/pkg/tls" ) func TestReuseService(t *testing.T) { testServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) })) defer testServer.Close() staticConfig := static.Configuration{ EntryPoints: map[string]*static.EntryPoint{ "web": {}, }, } dynamicConfigs := th.BuildConfiguration( th.WithRouters( th.WithRouter("foo", th.WithEntryPoints("web"), th.WithServiceName("bar"), th.WithRule("Path(`/ok`)")), th.WithRouter("foo2", th.WithEntryPoints("web"), th.WithRule("Path(`/unauthorized`)"), th.WithServiceName("bar"), th.WithRouterMiddlewares("basicauth")), ), th.WithMiddlewares(th.WithMiddleware("basicauth", th.WithBasicAuth(&dynamic.BasicAuth{Users: []string{"foo:bar"}}), )), th.WithLoadBalancerServices(th.WithService("bar", th.WithServers(th.WithServer(testServer.URL))), ), ) transportManager := service.NewTransportManager(nil) transportManager.Update(map[string]*dynamic.ServersTransport{"default@internal": {}}) managerFactory := service.NewManagerFactory(staticConfig, nil, nil, transportManager, proxyBuilderMock{}, nil) tlsManager := tls.NewManager(nil) dialerManager := tcp.NewDialerManager(nil) dialerManager.Update(map[string]*dynamic.TCPServersTransport{"default@internal": {}}) factory, err := NewRouterFactory(staticConfig, managerFactory, tlsManager, nil, nil, dialerManager) require.NoError(t, err) entryPointsHandlers, _ := factory.CreateRouters(runtime.NewConfig(dynamic.Configuration{HTTP: dynamicConfigs})) // Test that the /ok path returns a status 200. responseRecorderOk := &httptest.ResponseRecorder{} requestOk := httptest.NewRequest(http.MethodGet, testServer.URL+"/ok", nil) entryPointsHandlers["web"].GetHTTPHandler().ServeHTTP(responseRecorderOk, requestOk) assert.Equal(t, http.StatusOK, responseRecorderOk.Result().StatusCode, "status code") // Test that the /unauthorized path returns a 401 because of // the basic authentication defined on the frontend. responseRecorderUnauthorized := &httptest.ResponseRecorder{} requestUnauthorized := httptest.NewRequest(http.MethodGet, testServer.URL+"/unauthorized", nil) entryPointsHandlers["web"].GetHTTPHandler().ServeHTTP(responseRecorderUnauthorized, requestUnauthorized) assert.Equal(t, http.StatusUnauthorized, responseRecorderUnauthorized.Result().StatusCode, "status code") } func TestServerResponseEmptyBackend(t *testing.T) { const requestPath = "/path" const routeRule = "Path(`" + requestPath + "`)" testCases := []struct { desc string config func(testServerURL string) *dynamic.HTTPConfiguration expectedStatusCode int }{ { desc: "Ok", config: func(testServerURL string) *dynamic.HTTPConfiguration { return th.BuildConfiguration( th.WithRouters(th.WithRouter("foo", th.WithEntryPoints("web"), th.WithServiceName("bar"), th.WithRule(routeRule)), ), th.WithLoadBalancerServices(th.WithService("bar", th.WithServers(th.WithServer(testServerURL))), ), ) }, expectedStatusCode: http.StatusOK, }, { desc: "No Frontend", config: func(testServerURL string) *dynamic.HTTPConfiguration { return th.BuildConfiguration() }, expectedStatusCode: http.StatusNotFound, }, { desc: "Empty Backend LB", config: func(testServerURL string) *dynamic.HTTPConfiguration { return th.BuildConfiguration( th.WithRouters(th.WithRouter("foo", th.WithEntryPoints("web"), th.WithServiceName("bar"), th.WithRule(routeRule)), ), th.WithLoadBalancerServices(th.WithService("bar")), ) }, expectedStatusCode: http.StatusServiceUnavailable, }, { desc: "Empty Backend LB Sticky", config: func(testServerURL string) *dynamic.HTTPConfiguration { return th.BuildConfiguration( th.WithRouters(th.WithRouter("foo", th.WithEntryPoints("web"), th.WithServiceName("bar"), th.WithRule(routeRule)), ), th.WithLoadBalancerServices(th.WithService("bar", th.WithSticky("test")), ), ) }, expectedStatusCode: http.StatusServiceUnavailable, }, { desc: "Empty Backend LB", config: func(testServerURL string) *dynamic.HTTPConfiguration { return th.BuildConfiguration( th.WithRouters(th.WithRouter("foo", th.WithEntryPoints("web"), th.WithServiceName("bar"), th.WithRule(routeRule)), ), th.WithLoadBalancerServices(th.WithService("bar")), ) }, expectedStatusCode: http.StatusServiceUnavailable, }, { desc: "Empty Backend LB Sticky", config: func(testServerURL string) *dynamic.HTTPConfiguration { return th.BuildConfiguration( th.WithRouters(th.WithRouter("foo", th.WithEntryPoints("web"), th.WithServiceName("bar"), th.WithRule(routeRule)), ), th.WithLoadBalancerServices(th.WithService("bar", th.WithSticky("test")), ), ) }, expectedStatusCode: http.StatusServiceUnavailable, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() testServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) })) defer testServer.Close() staticConfig := static.Configuration{ EntryPoints: map[string]*static.EntryPoint{ "web": {}, }, } transportManager := service.NewTransportManager(nil) transportManager.Update(map[string]*dynamic.ServersTransport{"default@internal": {}}) managerFactory := service.NewManagerFactory(staticConfig, nil, nil, transportManager, proxyBuilderMock{}, nil) tlsManager := tls.NewManager(nil) dialerManager := tcp.NewDialerManager(nil) dialerManager.Update(map[string]*dynamic.TCPServersTransport{"default@internal": {}}) observabiltyMgr := middleware.NewObservabilityMgr(staticConfig, nil, nil, nil, nil, nil) factory, err := NewRouterFactory(staticConfig, managerFactory, tlsManager, observabiltyMgr, nil, dialerManager) require.NoError(t, err) entryPointsHandlers, _ := factory.CreateRouters(runtime.NewConfig(dynamic.Configuration{HTTP: test.config(testServer.URL)})) responseRecorder := &httptest.ResponseRecorder{} request := httptest.NewRequest(http.MethodGet, testServer.URL+requestPath, nil) entryPointsHandlers["web"].GetHTTPHandler().ServeHTTP(responseRecorder, request) assert.Equal(t, test.expectedStatusCode, responseRecorder.Result().StatusCode, "status code") }) } } func TestInternalServices(t *testing.T) { testServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) })) defer testServer.Close() staticConfig := static.Configuration{ API: &static.API{}, EntryPoints: map[string]*static.EntryPoint{ "web": {}, }, } dynamicConfigs := th.BuildConfiguration( th.WithRouters( th.WithRouter("foo", th.WithEntryPoints("web"), th.WithServiceName("api@internal"), th.WithRule("PathPrefix(`/api`)")), ), ) transportManager := service.NewTransportManager(nil) transportManager.Update(map[string]*dynamic.ServersTransport{"default@internal": {}}) managerFactory := service.NewManagerFactory(staticConfig, nil, nil, transportManager, nil, nil) tlsManager := tls.NewManager(nil) dialerManager := tcp.NewDialerManager(nil) dialerManager.Update(map[string]*dynamic.TCPServersTransport{"default@internal": {}}) factory, err := NewRouterFactory(staticConfig, managerFactory, tlsManager, nil, nil, dialerManager) require.NoError(t, err) entryPointsHandlers, _ := factory.CreateRouters(runtime.NewConfig(dynamic.Configuration{HTTP: dynamicConfigs})) // Test that the /ok path returns a status 200. responseRecorderOk := &httptest.ResponseRecorder{} requestOk := httptest.NewRequest(http.MethodGet, testServer.URL+"/api/rawdata", nil) entryPointsHandlers["web"].GetHTTPHandler().ServeHTTP(responseRecorderOk, requestOk) assert.Equal(t, http.StatusOK, responseRecorderOk.Result().StatusCode, "status code") } type proxyBuilderMock struct{} func (p proxyBuilderMock) Build(_ string, _ *url.URL, _, _ bool, _ time.Duration) (http.Handler, error) { return http.HandlerFunc(func(responseWriter http.ResponseWriter, req *http.Request) {}), nil } func (p proxyBuilderMock) Update(_ map[string]*dynamic.ServersTransport) { panic("implement me") }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/aggregator.go
pkg/server/aggregator.go
package server import ( "slices" "strings" "github.com/go-acme/lego/v4/challenge/tlsalpn01" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/observability/logs" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "github.com/traefik/traefik/v3/pkg/server/provider" "github.com/traefik/traefik/v3/pkg/tls" ) func mergeConfiguration(configurations dynamic.Configurations, defaultEntryPoints []string) dynamic.Configuration { // TODO: see if we can use DeepCopies inside, so that the given argument is left // untouched, and the modified copy is returned. conf := dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: make(map[string]*dynamic.Router), Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: make(map[string]*dynamic.Model), ServersTransports: make(map[string]*dynamic.ServersTransport), }, TCP: &dynamic.TCPConfiguration{ Routers: make(map[string]*dynamic.TCPRouter), Services: make(map[string]*dynamic.TCPService), Middlewares: make(map[string]*dynamic.TCPMiddleware), Models: make(map[string]*dynamic.TCPModel), ServersTransports: make(map[string]*dynamic.TCPServersTransport), }, UDP: &dynamic.UDPConfiguration{ Routers: make(map[string]*dynamic.UDPRouter), Services: make(map[string]*dynamic.UDPService), }, TLS: &dynamic.TLSConfiguration{ Stores: make(map[string]tls.Store), Options: make(map[string]tls.Options), }, } var defaultTLSOptionProviders []string var defaultTLSStoreProviders []string for pvd, configuration := range configurations { if configuration.HTTP != nil { for routerName, router := range configuration.HTTP.Routers { // If no entrypoint is defined, and the router has no parentRefs (i.e. is not a child router), // we set the default entrypoints. if len(router.EntryPoints) == 0 && router.ParentRefs == nil { log.Debug(). Str(logs.RouterName, routerName). Strs(logs.EntryPointName, defaultEntryPoints). Msg("No entryPoint defined for this router, using the default one(s) instead") router.EntryPoints = defaultEntryPoints } // The `ruleSyntax` option is deprecated. // We exclude the "default" value to avoid logging it, // as it is the value used for internal models and computed rules. if router.RuleSyntax != "" && router.RuleSyntax != "default" { log.Warn(). Str(logs.RouterName, routerName). Msg("Router's `ruleSyntax` option is deprecated, please remove any usage of this option.") } var qualifiedParentRefs []string for _, parentRef := range router.ParentRefs { if parts := strings.Split(parentRef, "@"); len(parts) == 1 { parentRef = provider.MakeQualifiedName(pvd, parentRef) } qualifiedParentRefs = append(qualifiedParentRefs, parentRef) } router.ParentRefs = qualifiedParentRefs conf.HTTP.Routers[provider.MakeQualifiedName(pvd, routerName)] = router } for middlewareName, middleware := range configuration.HTTP.Middlewares { conf.HTTP.Middlewares[provider.MakeQualifiedName(pvd, middlewareName)] = middleware } for serviceName, service := range configuration.HTTP.Services { conf.HTTP.Services[provider.MakeQualifiedName(pvd, serviceName)] = service } for modelName, model := range configuration.HTTP.Models { conf.HTTP.Models[provider.MakeQualifiedName(pvd, modelName)] = model } for serversTransportName, serversTransport := range configuration.HTTP.ServersTransports { conf.HTTP.ServersTransports[provider.MakeQualifiedName(pvd, serversTransportName)] = serversTransport } } if configuration.TCP != nil { for routerName, router := range configuration.TCP.Routers { if len(router.EntryPoints) == 0 { log.Debug(). Str(logs.RouterName, routerName). Msgf("No entryPoint defined for this TCP router, using the default one(s) instead: %+v", defaultEntryPoints) router.EntryPoints = defaultEntryPoints } conf.TCP.Routers[provider.MakeQualifiedName(pvd, routerName)] = router } for middlewareName, middleware := range configuration.TCP.Middlewares { conf.TCP.Middlewares[provider.MakeQualifiedName(pvd, middlewareName)] = middleware } for serviceName, service := range configuration.TCP.Services { conf.TCP.Services[provider.MakeQualifiedName(pvd, serviceName)] = service } for modelName, model := range configuration.TCP.Models { conf.TCP.Models[provider.MakeQualifiedName(pvd, modelName)] = model } for serversTransportName, serversTransport := range configuration.TCP.ServersTransports { conf.TCP.ServersTransports[provider.MakeQualifiedName(pvd, serversTransportName)] = serversTransport } } if configuration.UDP != nil { for routerName, router := range configuration.UDP.Routers { conf.UDP.Routers[provider.MakeQualifiedName(pvd, routerName)] = router } for serviceName, service := range configuration.UDP.Services { conf.UDP.Services[provider.MakeQualifiedName(pvd, serviceName)] = service } } if configuration.TLS != nil { for _, cert := range configuration.TLS.Certificates { if slices.Contains(cert.Stores, tlsalpn01.ACMETLS1Protocol) && pvd != "tlsalpn.acme" { continue } conf.TLS.Certificates = append(conf.TLS.Certificates, cert) } for key, store := range configuration.TLS.Stores { if key != tls.DefaultTLSStoreName { key = provider.MakeQualifiedName(pvd, key) } else { defaultTLSStoreProviders = append(defaultTLSStoreProviders, pvd) } conf.TLS.Stores[key] = store } for tlsOptionsName, options := range configuration.TLS.Options { if tlsOptionsName != "default" { tlsOptionsName = provider.MakeQualifiedName(pvd, tlsOptionsName) } else { defaultTLSOptionProviders = append(defaultTLSOptionProviders, pvd) } conf.TLS.Options[tlsOptionsName] = options } } } if len(defaultTLSStoreProviders) > 1 { log.Error().Msgf("Default TLS Store defined in multiple providers: %v", defaultTLSStoreProviders) delete(conf.TLS.Stores, tls.DefaultTLSStoreName) } if len(defaultTLSOptionProviders) == 0 { conf.TLS.Options[tls.DefaultTLSConfigName] = tls.DefaultTLSOptions } else if len(defaultTLSOptionProviders) > 1 { log.Error().Msgf("Default TLS Options defined in multiple providers %v", defaultTLSOptionProviders) // We do not set an empty tls.TLS{} as above so that we actually get a "cascading failure" later on, // i.e. routers depending on this missing TLS option will fail to initialize as well. delete(conf.TLS.Options, tls.DefaultTLSConfigName) } return conf } func applyModel(cfg dynamic.Configuration) dynamic.Configuration { if cfg.HTTP != nil && len(cfg.HTTP.Models) > 0 { rts := make(map[string]*dynamic.Router) modelRouterNames := make(map[string][]string) for name, rt := range cfg.HTTP.Routers { // Only root routers can have models applied. if rt.ParentRefs != nil { rts[name] = rt continue } router := rt.DeepCopy() if !router.DefaultRule && router.RuleSyntax == "" { for modelName, model := range cfg.HTTP.Models { // models cannot be provided by another provider than the internal one. if !strings.HasSuffix(modelName, "@internal") { continue } router.RuleSyntax = model.DefaultRuleSyntax break } } eps := router.EntryPoints router.EntryPoints = nil for _, epName := range eps { m, ok := cfg.HTTP.Models[epName+"@internal"] if ok { cp := router.DeepCopy() cp.EntryPoints = []string{epName} if cp.TLS == nil { cp.TLS = m.TLS } cp.Middlewares = append(m.Middlewares, cp.Middlewares...) if m.DeniedEncodedPathCharacters != nil { // As the denied encoded path characters option is not configurable at the router level, // we can simply copy the whole structure to override the router's default config. cp.DeniedEncodedPathCharacters = *m.DeniedEncodedPathCharacters } if cp.Observability == nil { cp.Observability = &dynamic.RouterObservabilityConfig{} } if cp.Observability.AccessLogs == nil { cp.Observability.AccessLogs = m.Observability.AccessLogs } if cp.Observability.Metrics == nil { cp.Observability.Metrics = m.Observability.Metrics } if cp.Observability.Tracing == nil { cp.Observability.Tracing = m.Observability.Tracing } if cp.Observability.TraceVerbosity == "" { cp.Observability.TraceVerbosity = m.Observability.TraceVerbosity } rtName := name if len(eps) > 1 { rtName = epName + "-" + name modelRouterNames[name] = append(modelRouterNames[name], rtName) } rts[rtName] = cp } else { router.EntryPoints = append(router.EntryPoints, epName) rts[name] = router } } } for _, rt := range rts { if rt.ParentRefs == nil { continue } var parentRefs []string for _, ref := range rt.ParentRefs { // Only add the initial parent ref if it still exists. if _, ok := rts[ref]; ok { parentRefs = append(parentRefs, ref) } if names, ok := modelRouterNames[ref]; ok { parentRefs = append(parentRefs, names...) } } rt.ParentRefs = parentRefs } cfg.HTTP.Routers = rts } // Apply the default observability model to HTTP routers. applyDefaultObservabilityModel(cfg) if cfg.TCP == nil || len(cfg.TCP.Models) == 0 { return cfg } tcpRouters := make(map[string]*dynamic.TCPRouter) for name, rt := range cfg.TCP.Routers { router := rt.DeepCopy() if router.RuleSyntax == "" { for _, model := range cfg.TCP.Models { router.RuleSyntax = model.DefaultRuleSyntax break } } tcpRouters[name] = router } cfg.TCP.Routers = tcpRouters return cfg } // applyDefaultObservabilityModel applies the default observability model to the configuration. // This function is used to ensure that the observability configuration is set for all routers, // and make sure it is serialized and available in the API. // We could have introduced a "default" model, but it would have been more complex to manage for now. // This could be generalized in the future. // TODO: check if we can remove this and rely on the SetDefaults instead. func applyDefaultObservabilityModel(cfg dynamic.Configuration) { if cfg.HTTP != nil { for _, router := range cfg.HTTP.Routers { // Only root routers can have models applied. if router.ParentRefs != nil { continue } if router.Observability == nil { router.Observability = &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, } continue } if router.Observability.AccessLogs == nil { router.Observability.AccessLogs = pointer(true) } if router.Observability.Metrics == nil { router.Observability.Metrics = pointer(true) } if router.Observability.Tracing == nil { router.Observability.Tracing = pointer(true) } if router.Observability.TraceVerbosity == "" { router.Observability.TraceVerbosity = otypes.MinimalVerbosity } } } } func pointer[T any](v T) *T { return &v }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/socket_activation_windows.go
pkg/server/socket_activation_windows.go
//go:build windows package server func populateSocketActivationListeners() *SocketActivation { return &SocketActivation{enabled: false} }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/server_entrypoint_listenconfig_unix_sockopt_other.go
pkg/server/server_entrypoint_listenconfig_unix_sockopt_other.go
//go:build linux || openbsd || darwin package server import "golang.org/x/sys/unix" const unixSOREUSEPORT = unix.SO_REUSEPORT
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/configurationwatcher.go
pkg/server/configurationwatcher.go
package server import ( "context" "encoding/json" "reflect" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/safe" "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" ) // ConfigurationWatcher watches configuration changes. type ConfigurationWatcher struct { providerAggregator provider.Provider defaultEntryPoints []string allProvidersConfigs chan dynamic.Message newConfigs chan dynamic.Configurations requiredProvider string configurationListeners []func(dynamic.Configuration) routinesPool *safe.Pool } // NewConfigurationWatcher creates a new ConfigurationWatcher. func NewConfigurationWatcher( routinesPool *safe.Pool, pvd provider.Provider, defaultEntryPoints []string, requiredProvider string, ) *ConfigurationWatcher { return &ConfigurationWatcher{ providerAggregator: pvd, allProvidersConfigs: make(chan dynamic.Message, 100), newConfigs: make(chan dynamic.Configurations), routinesPool: routinesPool, defaultEntryPoints: defaultEntryPoints, requiredProvider: requiredProvider, } } // Start the configuration watcher. func (c *ConfigurationWatcher) Start() { c.routinesPool.GoCtx(c.receiveConfigurations) c.routinesPool.GoCtx(c.applyConfigurations) c.startProviderAggregator() } // Stop the configuration watcher. func (c *ConfigurationWatcher) Stop() { close(c.allProvidersConfigs) close(c.newConfigs) } // AddListener adds a new listener function used when new configuration is provided. func (c *ConfigurationWatcher) AddListener(listener func(dynamic.Configuration)) { if c.configurationListeners == nil { c.configurationListeners = make([]func(dynamic.Configuration), 0) } c.configurationListeners = append(c.configurationListeners, listener) } func (c *ConfigurationWatcher) startProviderAggregator() { log.Info().Msgf("Starting provider aggregator %T", c.providerAggregator) safe.Go(func() { err := c.providerAggregator.Provide(c.allProvidersConfigs, c.routinesPool) if err != nil { log.Error().Err(err).Msgf("Error starting provider aggregator %T", c.providerAggregator) } }) } // receiveConfigurations receives configuration changes from the providers. // The configuration message then gets passed along a series of check, notably // to verify that, for a given provider, the configuration that was just received // is at least different from the previously received one. // The full set of configurations is then sent to the throttling goroutine, // (throttleAndApplyConfigurations) via a RingChannel, which ensures that we can // constantly send in a non-blocking way to the throttling goroutine the last // global state we are aware of. func (c *ConfigurationWatcher) receiveConfigurations(ctx context.Context) { newConfigurations := make(dynamic.Configurations) var output chan dynamic.Configurations for { select { case <-ctx.Done(): return // DeepCopy is necessary because newConfigurations gets modified later by the consumer of c.newConfigs case output <- newConfigurations.DeepCopy(): output = nil default: select { case <-ctx.Done(): return case configMsg, ok := <-c.allProvidersConfigs: if !ok { return } logger := log.Ctx(ctx).With().Str(logs.ProviderName, configMsg.ProviderName).Logger() if configMsg.Configuration == nil { logger.Debug().Msg("Skipping nil configuration") continue } if isEmptyConfiguration(configMsg.Configuration) { logger.Debug().Msg("Skipping empty configuration") continue } logConfiguration(logger, configMsg) if reflect.DeepEqual(newConfigurations[configMsg.ProviderName], configMsg.Configuration) { // no change, do nothing logger.Debug().Msg("Skipping unchanged configuration") continue } newConfigurations[configMsg.ProviderName] = configMsg.Configuration.DeepCopy() output = c.newConfigs // DeepCopy is necessary because newConfigurations gets modified later by the consumer of c.newConfigs case output <- newConfigurations.DeepCopy(): output = nil } } } } // applyConfigurations blocks on a RingChannel that receives the new // set of configurations that is compiled and sent by receiveConfigurations as soon // as a provider change occurs. If the new set is different from the previous set // that had been applied, the new set is applied, and we sleep for a while before // listening on the channel again. func (c *ConfigurationWatcher) applyConfigurations(ctx context.Context) { var lastConfigurations dynamic.Configurations for { select { case <-ctx.Done(): return case newConfigs, ok := <-c.newConfigs: if !ok { return } // We wait for first configuration of the required provider before applying configurations. if _, ok := newConfigs[c.requiredProvider]; c.requiredProvider != "" && !ok { continue } if reflect.DeepEqual(newConfigs, lastConfigurations) { continue } conf := mergeConfiguration(newConfigs.DeepCopy(), c.defaultEntryPoints) conf = applyModel(conf) for _, listener := range c.configurationListeners { listener(conf) } lastConfigurations = newConfigs } } } func logConfiguration(logger zerolog.Logger, configMsg dynamic.Message) { if logger.GetLevel() > zerolog.DebugLevel { return } copyConf := configMsg.Configuration.DeepCopy() if copyConf.TLS != nil { copyConf.TLS.Certificates = nil if copyConf.TLS.Options != nil { cleanedOptions := make(map[string]tls.Options, len(copyConf.TLS.Options)) for name, option := range copyConf.TLS.Options { option.ClientAuth.CAFiles = []types.FileOrContent{} cleanedOptions[name] = option } copyConf.TLS.Options = cleanedOptions } for k := range copyConf.TLS.Stores { st := copyConf.TLS.Stores[k] st.DefaultCertificate = nil copyConf.TLS.Stores[k] = st } } if copyConf.HTTP != nil { for _, transport := range copyConf.HTTP.ServersTransports { transport.Certificates = tls.Certificates{} transport.RootCAs = []types.FileOrContent{} } } if copyConf.TCP != nil { for _, transport := range copyConf.TCP.ServersTransports { if transport.TLS != nil { transport.TLS.Certificates = tls.Certificates{} transport.TLS.RootCAs = []types.FileOrContent{} } } } jsonConf, err := json.Marshal(copyConf) if err != nil { logger.Error().Err(err).Msg("Could not marshal dynamic configuration") logger.Debug().Msgf("Configuration received: [struct] %#v", copyConf) } else { logger.Debug().RawJSON("config", jsonConf).Msg("Configuration received") } } func isEmptyConfiguration(conf *dynamic.Configuration) bool { if conf.TCP == nil { conf.TCP = &dynamic.TCPConfiguration{} } if conf.HTTP == nil { conf.HTTP = &dynamic.HTTPConfiguration{} } if conf.UDP == nil { conf.UDP = &dynamic.UDPConfiguration{} } httpEmpty := conf.HTTP.Routers == nil && conf.HTTP.Services == nil && conf.HTTP.Middlewares == nil tlsEmpty := conf.TLS == nil || conf.TLS.Certificates == nil && conf.TLS.Stores == nil && conf.TLS.Options == nil tcpEmpty := conf.TCP.Routers == nil && conf.TCP.Services == nil && conf.TCP.Middlewares == nil udpEmpty := conf.UDP.Routers == nil && conf.UDP.Services == nil return httpEmpty && tlsEmpty && tcpEmpty && udpEmpty }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/server_signals_windows.go
pkg/server/server_signals_windows.go
//go:build windows // +build windows package server import "context" func (s *Server) configureSignals() {} func (s *Server) listenSignals(ctx context.Context) {}
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/socket_activation_unix.go
pkg/server/socket_activation_unix.go
//go:build !windows package server import ( "net" "github.com/coreos/go-systemd/v22/activation" "github.com/rs/zerolog/log" ) func populateSocketActivationListeners() *SocketActivation { // We use Files api due to activation not providing method for get PacketConn with names files := activation.Files(true) sa := &SocketActivation{enabled: false} sa.listeners = make(map[string]net.Listener) sa.conns = make(map[string]net.PacketConn) if len(files) > 0 { sa.enabled = true for _, f := range files { if lc, err := net.FileListener(f); err == nil { _, ok := sa.listeners[f.Name()] if ok { log.Error().Str("listenersName", f.Name()).Msg("Socket activation TCP listeners must have one and only one listener per name") } else { sa.listeners[f.Name()] = lc } f.Close() } else if pc, err := net.FilePacketConn(f); err == nil { _, ok := sa.conns[f.Name()] if ok { log.Error().Str("listenersName", f.Name()).Msg("Socket activation UDP listeners must have one and only one listener per name") } else { sa.conns[f.Name()] = pc } f.Close() } } } return sa }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/server_entrypoint_tcp_test.go
pkg/server/server_entrypoint_tcp_test.go
package server import ( "bufio" "context" "crypto/tls" "errors" "io" "net" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/middlewares/requestdecorator" tcprouter "github.com/traefik/traefik/v3/pkg/server/router/tcp" "github.com/traefik/traefik/v3/pkg/tcp" "golang.org/x/net/http2" ) func TestShutdownHijacked(t *testing.T) { router, err := tcprouter.NewRouter() require.NoError(t, err) router.SetHTTPHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { conn, _, err := rw.(http.Hijacker).Hijack() require.NoError(t, err) resp := http.Response{StatusCode: http.StatusOK} err = resp.Write(conn) require.NoError(t, err) })) testShutdown(t, router) } func TestShutdownHTTP(t *testing.T) { router, err := tcprouter.NewRouter() require.NoError(t, err) router.SetHTTPHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) time.Sleep(time.Second) })) testShutdown(t, router) } func TestShutdownTCP(t *testing.T) { router, err := tcprouter.NewRouter() require.NoError(t, err) err = router.AddTCPRoute("HostSNI(`*`)", 0, tcp.HandlerFunc(func(conn tcp.WriteCloser) { _, err := http.ReadRequest(bufio.NewReader(conn)) if err != nil { return } resp := http.Response{StatusCode: http.StatusOK} _ = resp.Write(conn) })) require.NoError(t, err) testShutdown(t, router) } func testShutdown(t *testing.T, router *tcprouter.Router) { t.Helper() epConfig := &static.EntryPointsTransport{} epConfig.SetDefaults() epConfig.LifeCycle.RequestAcceptGraceTimeout = 0 epConfig.LifeCycle.GraceTimeOut = ptypes.Duration(5 * time.Second) epConfig.RespondingTimeouts.ReadTimeout = ptypes.Duration(5 * time.Second) epConfig.RespondingTimeouts.WriteTimeout = ptypes.Duration(5 * time.Second) entryPoint, err := NewTCPEntryPoint(t.Context(), "", &static.EntryPoint{ // We explicitly use an IPV4 address because on Alpine, with an IPV6 address // there seems to be shenanigans related to properly cleaning up file descriptors Address: "127.0.0.1:0", Transport: epConfig, ForwardedHeaders: &static.ForwardedHeaders{}, HTTP2: &static.HTTP2Config{}, }, nil, nil) require.NoError(t, err) conn, err := startEntrypoint(t, entryPoint, router) require.NoError(t, err) t.Cleanup(func() { _ = conn.Close() }) epAddr := entryPoint.listener.Addr().String() request, err := http.NewRequest(http.MethodHead, "http://127.0.0.1:8082", nil) require.NoError(t, err) time.Sleep(100 * time.Millisecond) // We need to do a write on conn before the shutdown to make it "exist". // Because the connection indeed exists as far as TCP is concerned, // but since we only pass it along to the HTTP server after at least one byte is peeked, // the HTTP server (and hence its shutdown) does not know about the connection until that first byte peeked. err = request.Write(conn) require.NoError(t, err) reader := bufio.NewReaderSize(conn, 1) // Wait for first byte in response. _, err = reader.Peek(1) require.NoError(t, err) go entryPoint.Shutdown(t.Context()) // Make sure that new connections are not permitted anymore. // Note that this should be true not only after Shutdown has returned, // but technically also as early as the Shutdown has closed the listener, // i.e. during the shutdown and before the gracetime is over. var testOk bool for range 10 { loopConn, err := net.Dial("tcp", epAddr) if err == nil { loopConn.Close() time.Sleep(100 * time.Millisecond) continue } if !strings.HasSuffix(err.Error(), "connection refused") && !strings.HasSuffix(err.Error(), "reset by peer") { t.Fatalf(`unexpected error: got %v, wanted "connection refused" or "reset by peer"`, err) } testOk = true break } if !testOk { t.Fatal("entry point never closed") } // And make sure that the connection we had opened before shutting things down is still operational resp, err := http.ReadResponse(reader, request) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) } func startEntrypoint(t *testing.T, entryPoint *TCPEntryPoint, router *tcprouter.Router) (net.Conn, error) { t.Helper() go entryPoint.Start(t.Context()) entryPoint.SwitchRouter(router) for range 10 { conn, err := net.Dial("tcp", entryPoint.listener.Addr().String()) if err != nil { time.Sleep(100 * time.Millisecond) continue } return conn, err } return nil, errors.New("entry point never started") } func TestReadTimeoutWithoutFirstByte(t *testing.T) { epConfig := &static.EntryPointsTransport{} epConfig.SetDefaults() epConfig.RespondingTimeouts.ReadTimeout = ptypes.Duration(2 * time.Second) entryPoint, err := NewTCPEntryPoint(t.Context(), "", &static.EntryPoint{ Address: ":0", Transport: epConfig, ForwardedHeaders: &static.ForwardedHeaders{}, HTTP2: &static.HTTP2Config{}, }, nil, nil) require.NoError(t, err) router, err := tcprouter.NewRouter() require.NoError(t, err) router.SetHTTPHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) })) conn, err := startEntrypoint(t, entryPoint, router) require.NoError(t, err) errChan := make(chan error) go func() { b := make([]byte, 2048) _, err := conn.Read(b) errChan <- err }() select { case err := <-errChan: require.Equal(t, io.EOF, err) case <-time.Tick(5 * time.Second): t.Error("Timeout while read") } } func TestReadTimeoutWithFirstByte(t *testing.T) { epConfig := &static.EntryPointsTransport{} epConfig.SetDefaults() epConfig.RespondingTimeouts.ReadTimeout = ptypes.Duration(2 * time.Second) entryPoint, err := NewTCPEntryPoint(t.Context(), "", &static.EntryPoint{ Address: ":0", Transport: epConfig, ForwardedHeaders: &static.ForwardedHeaders{}, HTTP2: &static.HTTP2Config{}, }, nil, nil) require.NoError(t, err) router, err := tcprouter.NewRouter() require.NoError(t, err) router.SetHTTPHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) })) conn, err := startEntrypoint(t, entryPoint, router) require.NoError(t, err) _, err = conn.Write([]byte("GET /some HTTP/1.1\r\n")) require.NoError(t, err) errChan := make(chan error) go func() { b := make([]byte, 2048) _, err := conn.Read(b) errChan <- err }() select { case err := <-errChan: require.Equal(t, io.EOF, err) case <-time.Tick(5 * time.Second): t.Error("Timeout while read") } } func TestKeepAliveMaxRequests(t *testing.T) { epConfig := &static.EntryPointsTransport{} epConfig.SetDefaults() epConfig.KeepAliveMaxRequests = 3 entryPoint, err := NewTCPEntryPoint(t.Context(), "", &static.EntryPoint{ Address: ":0", Transport: epConfig, ForwardedHeaders: &static.ForwardedHeaders{}, HTTP2: &static.HTTP2Config{}, }, nil, nil) require.NoError(t, err) router, err := tcprouter.NewRouter() require.NoError(t, err) router.SetHTTPHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) })) conn, err := startEntrypoint(t, entryPoint, router) require.NoError(t, err) http.DefaultClient.Transport = &http.Transport{ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { return conn, nil }, } resp, err := http.Get("http://" + entryPoint.listener.Addr().String()) require.NoError(t, err) require.False(t, resp.Close) err = resp.Body.Close() require.NoError(t, err) resp, err = http.Get("http://" + entryPoint.listener.Addr().String()) require.NoError(t, err) require.False(t, resp.Close) err = resp.Body.Close() require.NoError(t, err) resp, err = http.Get("http://" + entryPoint.listener.Addr().String()) require.NoError(t, err) require.True(t, resp.Close) err = resp.Body.Close() require.NoError(t, err) } func TestKeepAliveMaxTime(t *testing.T) { epConfig := &static.EntryPointsTransport{} epConfig.SetDefaults() epConfig.KeepAliveMaxTime = ptypes.Duration(time.Millisecond) entryPoint, err := NewTCPEntryPoint(t.Context(), "", &static.EntryPoint{ Address: ":0", Transport: epConfig, ForwardedHeaders: &static.ForwardedHeaders{}, HTTP2: &static.HTTP2Config{}, }, nil, nil) require.NoError(t, err) router, err := tcprouter.NewRouter() require.NoError(t, err) router.SetHTTPHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) })) conn, err := startEntrypoint(t, entryPoint, router) require.NoError(t, err) http.DefaultClient.Transport = &http.Transport{ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { return conn, nil }, } resp, err := http.Get("http://" + entryPoint.listener.Addr().String()) require.NoError(t, err) require.False(t, resp.Close) err = resp.Body.Close() require.NoError(t, err) time.Sleep(time.Millisecond) resp, err = http.Get("http://" + entryPoint.listener.Addr().String()) require.NoError(t, err) require.True(t, resp.Close) err = resp.Body.Close() require.NoError(t, err) } func TestKeepAliveH2c(t *testing.T) { epConfig := &static.EntryPointsTransport{} epConfig.SetDefaults() epConfig.KeepAliveMaxRequests = 1 entryPoint, err := NewTCPEntryPoint(t.Context(), "", &static.EntryPoint{ Address: ":0", Transport: epConfig, ForwardedHeaders: &static.ForwardedHeaders{}, HTTP2: &static.HTTP2Config{}, }, nil, nil) require.NoError(t, err) router, err := tcprouter.NewRouter() require.NoError(t, err) router.SetHTTPHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) })) conn, err := startEntrypoint(t, entryPoint, router) require.NoError(t, err) http2Transport := &http2.Transport{ AllowHTTP: true, DialTLSContext: func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error) { return conn, nil }, } client := &http.Client{Transport: http2Transport} resp, err := client.Get("http://" + entryPoint.listener.Addr().String()) require.NoError(t, err) require.False(t, resp.Close) err = resp.Body.Close() require.NoError(t, err) _, err = client.Get("http://" + entryPoint.listener.Addr().String()) require.Error(t, err) // Unlike HTTP/1, where we can directly check `resp.Close`, HTTP/2 uses a different // mechanism: it sends a GOAWAY frame when the connection is closing. // We can only check the error type. The error received should be poll.ErrClosed from // the `internal/poll` package, but we cannot directly reference the error type due to // package restrictions. Since this error message ("use of closed network connection") // is distinct and specific, we rely on its consistency, assuming it is stable and unlikely // to change. require.Contains(t, err.Error(), "use of closed network connection") } func TestSanitizePath(t *testing.T) { tests := []struct { path string expected string }{ {path: "/b", expected: "/b"}, {path: "/b/", expected: "/b/"}, {path: "/../../b/", expected: "/b/"}, {path: "/../../b", expected: "/b"}, {path: "/a/b/..", expected: "/a"}, {path: "/a/b/../", expected: "/a/"}, {path: "/a/../../b", expected: "/b"}, {path: "/..///b///", expected: "/b/"}, {path: "/a/../b", expected: "/b"}, {path: "/a/./b", expected: "/a/b"}, {path: "/a//b", expected: "/a/b"}, {path: "/a/../../b", expected: "/b"}, {path: "/a/../c/../b", expected: "/b"}, {path: "/a/../../../c/../b", expected: "/b"}, {path: "/a/../c/../../b", expected: "/b"}, {path: "/a/..//c/.././b", expected: "/b"}, } for _, test := range tests { t.Run("Testing case: "+test.path, func(t *testing.T) { t.Parallel() var callCount int clean := sanitizePath(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { callCount++ assert.Equal(t, test.expected, r.URL.Path) })) request := httptest.NewRequest(http.MethodGet, "http://foo"+test.path, http.NoBody) clean.ServeHTTP(httptest.NewRecorder(), request) assert.Equal(t, 1, callCount) }) } } func TestNormalizePath(t *testing.T) { unreservedDecoded := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" unreserved := []string{ "%41", "%42", "%43", "%44", "%45", "%46", "%47", "%48", "%49", "%4A", "%4B", "%4C", "%4D", "%4E", "%4F", "%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57", "%58", "%59", "%5A", "%61", "%62", "%63", "%64", "%65", "%66", "%67", "%68", "%69", "%6A", "%6B", "%6C", "%6D", "%6E", "%6F", "%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77", "%78", "%79", "%7A", "%30", "%31", "%32", "%33", "%34", "%35", "%36", "%37", "%38", "%39", "%2D", "%2E", "%5F", "%7E", } reserved := []string{ "%3A", "%2F", "%3F", "%23", "%5B", "%5D", "%40", "%21", "%24", "%26", "%27", "%28", "%29", "%2A", "%2B", "%2C", "%3B", "%3D", "%25", } reservedJoined := strings.Join(reserved, "") unallowedCharacter := "%0a" // line feed unallowedCharacterUpperCased := "%0A" // line feed upper case var callCount int handler := normalizePath(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { callCount++ wantRawPath := "/" + unreservedDecoded + reservedJoined + unallowedCharacterUpperCased assert.Equal(t, wantRawPath, r.URL.RawPath) })) req := httptest.NewRequest(http.MethodGet, "http://foo/"+strings.Join(unreserved, "")+reservedJoined+unallowedCharacter, http.NoBody) res := httptest.NewRecorder() handler.ServeHTTP(res, req) assert.Equal(t, http.StatusOK, res.Code) assert.Equal(t, 1, callCount) } func TestNormalizePath_malformedPercentEncoding(t *testing.T) { tests := []struct { desc string path string wantErr bool }{ { desc: "well formed path", path: "/%20", }, { desc: "percent sign at the end", path: "/%", wantErr: true, }, { desc: "incomplete percent encoding at the end", path: "/%f", wantErr: true, }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { t.Parallel() var callCount int handler := normalizePath(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { callCount++ })) req := httptest.NewRequest(http.MethodGet, "http://foo", http.NoBody) req.URL.RawPath = test.path res := httptest.NewRecorder() handler.ServeHTTP(res, req) if test.wantErr { assert.Equal(t, http.StatusBadRequest, res.Code) assert.Equal(t, 0, callCount) } else { assert.Equal(t, http.StatusOK, res.Code) assert.Equal(t, 1, callCount) } }) } } // TestPathOperations tests the whole behavior of normalizePath, and sanitizePath combined through the use of the newHTTPServer func. // It aims to guarantee the server entrypoint handler is secure regarding a large variety of cases that could lead to path traversal attacks. func TestPathOperations(t *testing.T) { // Create a listener for the server. ln, err := net.Listen("tcp", "127.0.0.1:0") require.NoError(t, err) t.Cleanup(func() { _ = ln.Close() }) // Define the server configuration. configuration := &static.EntryPoint{} configuration.SetDefaults() // We need to allow some of the suspicious encoded characters to test the path operations in case they are authorized. configuration.HTTP.EncodedCharacters = &static.EncodedCharacters{ AllowEncodedSlash: true, AllowEncodedPercent: true, } // Create the HTTP server using newHTTPServer. server, err := newHTTPServer(t.Context(), ln, configuration, false, requestdecorator.New(nil)) require.NoError(t, err) server.Switcher.UpdateHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Path", r.URL.Path) w.Header().Set("RawPath", r.URL.EscapedPath()) w.WriteHeader(http.StatusOK) })) go func() { // server is expected to return an error if the listener is closed. _ = server.Server.Serve(ln) }() client := http.Client{ Transport: &http.Transport{ ResponseHeaderTimeout: 1 * time.Second, }, } tests := []struct { desc string rawPath string expectedPath string expectedRaw string expectedStatus int }{ { desc: "normalize and sanitize path", rawPath: "/a/../b/%41%42%43//%2f/", expectedPath: "/b/ABC///", expectedRaw: "/b/ABC/%2F/", expectedStatus: http.StatusOK, }, { desc: "path with traversal attempt", rawPath: "/../../b/", expectedPath: "/b/", expectedRaw: "/b/", expectedStatus: http.StatusOK, }, { desc: "path with multiple traversal attempts", rawPath: "/a/../../b/../c/", expectedPath: "/c/", expectedRaw: "/c/", expectedStatus: http.StatusOK, }, { desc: "path with mixed traversal and valid segments", rawPath: "/a/../b/./c/../d/", expectedPath: "/b/d/", expectedRaw: "/b/d/", expectedStatus: http.StatusOK, }, { desc: "path with trailing slash and traversal", rawPath: "/a/b/../", expectedPath: "/a/", expectedRaw: "/a/", expectedStatus: http.StatusOK, }, { desc: "path with encoded traversal sequences", rawPath: "/a/%2E%2E/%2E%2E/b/", expectedPath: "/b/", expectedRaw: "/b/", expectedStatus: http.StatusOK, }, { desc: "path with over-encoded traversal sequences", rawPath: "/a/%252E%252E/%252E%252E/b/", expectedPath: "/a/%2E%2E/%2E%2E/b/", expectedRaw: "/a/%252E%252E/%252E%252E/b/", expectedStatus: http.StatusOK, }, { desc: "routing path with unallowed percent-encoded character", rawPath: "/foo%20bar", expectedPath: "/foo bar", expectedRaw: "/foo%20bar", expectedStatus: http.StatusOK, }, { desc: "routing path with reserved percent-encoded character", rawPath: "/foo%2Fbar", expectedPath: "/foo/bar", expectedRaw: "/foo%2Fbar", expectedStatus: http.StatusOK, }, { desc: "routing path with unallowed and reserved percent-encoded character", rawPath: "/foo%20%2Fbar", expectedPath: "/foo /bar", expectedRaw: "/foo%20%2Fbar", expectedStatus: http.StatusOK, }, { desc: "path with traversal and encoded slash", rawPath: "/a/..%2Fb/", expectedPath: "/a/../b/", expectedRaw: "/a/..%2Fb/", expectedStatus: http.StatusOK, }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { t.Parallel() req, err := http.NewRequest(http.MethodGet, "http://"+ln.Addr().String()+test.rawPath, http.NoBody) require.NoError(t, err) res, err := client.Do(req) require.NoError(t, err) assert.Equal(t, test.expectedStatus, res.StatusCode) assert.Equal(t, test.expectedPath, res.Header.Get("Path")) assert.Equal(t, test.expectedRaw, res.Header.Get("RawPath")) }) } } func TestHTTP2Config(t *testing.T) { expectedMaxConcurrentStreams := 42 expectedEncoderTableSize := 128 expectedDecoderTableSize := 256 // Create a listener for the server. ln, err := net.Listen("tcp", "127.0.0.1:0") require.NoError(t, err) t.Cleanup(func() { _ = ln.Close() }) // Define the server configuration. configuration := &static.EntryPoint{} configuration.SetDefaults() configuration.HTTP2.MaxConcurrentStreams = int32(expectedMaxConcurrentStreams) configuration.HTTP2.MaxEncoderHeaderTableSize = int32(expectedEncoderTableSize) configuration.HTTP2.MaxDecoderHeaderTableSize = int32(expectedDecoderTableSize) // Create the HTTP server using newHTTPServer. server, err := newHTTPServer(t.Context(), ln, configuration, false, requestdecorator.New(nil)) require.NoError(t, err) // Get the underlying HTTP Server. httpServer := server.Server.(*http.Server) assert.Equal(t, expectedMaxConcurrentStreams, httpServer.HTTP2.MaxConcurrentStreams) assert.Equal(t, expectedEncoderTableSize, httpServer.HTTP2.MaxEncoderHeaderTableSize) assert.Equal(t, expectedDecoderTableSize, httpServer.HTTP2.MaxDecoderHeaderTableSize) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/server.go
pkg/server/server.go
package server import ( "context" "errors" "os" "os/signal" "time" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/observability/metrics" "github.com/traefik/traefik/v3/pkg/safe" "github.com/traefik/traefik/v3/pkg/server/middleware" ) // Server is the reverse-proxy/load-balancer engine. type Server struct { watcher *ConfigurationWatcher tcpEntryPoints TCPEntryPoints udpEntryPoints UDPEntryPoints observabilityMgr *middleware.ObservabilityMgr signals chan os.Signal stopChan chan bool routinesPool *safe.Pool } // NewServer returns an initialized Server. func NewServer(routinesPool *safe.Pool, entryPoints TCPEntryPoints, entryPointsUDP UDPEntryPoints, watcher *ConfigurationWatcher, observabilityMgr *middleware.ObservabilityMgr) *Server { srv := &Server{ watcher: watcher, tcpEntryPoints: entryPoints, observabilityMgr: observabilityMgr, signals: make(chan os.Signal, 1), stopChan: make(chan bool, 1), routinesPool: routinesPool, udpEntryPoints: entryPointsUDP, } srv.configureSignals() return srv } // Start starts the server and Stop/Close it when context is Done. func (s *Server) Start(ctx context.Context) { go func() { <-ctx.Done() logger := log.Ctx(ctx) logger.Info().Msg("I have to go...") logger.Info().Msg("Stopping server gracefully") s.Stop() }() s.tcpEntryPoints.Start() s.udpEntryPoints.Start() s.watcher.Start() s.routinesPool.GoCtx(s.listenSignals) } // Wait blocks until the server shutdown. func (s *Server) Wait() { <-s.stopChan } // Stop stops the server. func (s *Server) Stop() { defer log.Info().Msg("Server stopped") s.tcpEntryPoints.Stop() s.udpEntryPoints.Stop() s.stopChan <- true } // Close destroys the server. func (s *Server) Close() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) go func(ctx context.Context) { <-ctx.Done() if errors.Is(ctx.Err(), context.Canceled) { return } else if errors.Is(ctx.Err(), context.DeadlineExceeded) { panic("Timeout while stopping traefik, killing instance ✝") } }(ctx) stopMetricsClients() s.routinesPool.Stop() signal.Stop(s.signals) close(s.signals) close(s.stopChan) s.observabilityMgr.Close() cancel() } func stopMetricsClients() { metrics.StopDatadog() metrics.StopStatsd() metrics.StopInfluxDB2() metrics.StopOpenTelemetry() }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/server_entrypoint_listenconfig_unix_test.go
pkg/server/server_entrypoint_listenconfig_unix_test.go
//go:build linux || freebsd || openbsd || darwin package server import ( "net" "testing" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/static" ) func TestNewListenConfig(t *testing.T) { ep := static.EntryPoint{Address: ":0"} listenConfig := newListenConfig(&ep) require.Nil(t, listenConfig.Control) require.Zero(t, listenConfig.KeepAlive) l1, err := listenConfig.Listen(t.Context(), "tcp", ep.Address) require.NoError(t, err) require.NotNil(t, l1) defer l1.Close() l2, err := listenConfig.Listen(t.Context(), "tcp", l1.Addr().String()) require.Error(t, err) require.ErrorContains(t, err, "address already in use") require.Nil(t, l2) ep = static.EntryPoint{Address: ":0", ReusePort: true} listenConfig = newListenConfig(&ep) require.NotNil(t, listenConfig.Control) require.Zero(t, listenConfig.KeepAlive) l3, err := listenConfig.Listen(t.Context(), "tcp", ep.Address) require.NoError(t, err) require.NotNil(t, l3) defer l3.Close() l4, err := listenConfig.Listen(t.Context(), "tcp", l3.Addr().String()) require.NoError(t, err) require.NotNil(t, l4) defer l4.Close() _, l3Port, err := net.SplitHostPort(l3.Addr().String()) require.NoError(t, err) l5, err := listenConfig.Listen(t.Context(), "tcp", "127.0.0.1:"+l3Port) require.NoError(t, err) require.NotNil(t, l5) defer l5.Close() l6, err := listenConfig.Listen(t.Context(), "tcp", l1.Addr().String()) require.Error(t, err) require.ErrorContains(t, err, "address already in use") require.Nil(t, l6) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/server_entrypoint_listenconfig_unix_sockopt_freebsd.go
pkg/server/server_entrypoint_listenconfig_unix_sockopt_freebsd.go
//go:build freebsd package server import "golang.org/x/sys/unix" const unixSOREUSEPORT = unix.SO_REUSEPORT_LB
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/server_signals.go
pkg/server/server_signals.go
//go:build !windows // +build !windows package server import ( "context" "os/signal" "syscall" "github.com/rs/zerolog/log" ) func (s *Server) configureSignals() { signal.Notify(s.signals, syscall.SIGUSR1) } func (s *Server) listenSignals(ctx context.Context) { for { select { case <-ctx.Done(): return case sig := <-s.signals: if sig == syscall.SIGUSR1 { log.Info().Msgf("Closing and re-opening log files for rotation: %+v", sig) if err := s.observabilityMgr.RotateAccessLogs(); err != nil { log.Error().Err(err).Msg("Error rotating access log") } } } } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/socket_activation.go
pkg/server/socket_activation.go
package server import ( "errors" "net" ) type SocketActivation struct { enabled bool listeners map[string]net.Listener conns map[string]net.PacketConn } func (s *SocketActivation) isEnabled() bool { return s.enabled } func (s *SocketActivation) getListener(name string) (net.Listener, error) { listener, ok := s.listeners[name] if !ok { return nil, errors.New("unable to find socket activation TCP listener for entryPoint") } return listener, nil } func (s *SocketActivation) getConn(name string) (net.PacketConn, error) { conn, ok := s.conns[name] if !ok { return nil, errors.New("unable to find socket activation UDP listener for entryPoint") } return conn, nil } var socketActivation *SocketActivation func init() { // Populates pre-defined TCP and UDP listeners provided by systemd socket activation. socketActivation = populateSocketActivationListeners() }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/server_entrypoint_listenconfig_other_test.go
pkg/server/server_entrypoint_listenconfig_other_test.go
//go:build !(linux || freebsd || openbsd || darwin) package server import ( "context" "testing" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/static" ) func TestNewListenConfig(t *testing.T) { ep := static.EntryPoint{Address: ":0"} listenConfig := newListenConfig(&ep) require.Nil(t, listenConfig.Control) require.Zero(t, listenConfig.KeepAlive) l1, err := listenConfig.Listen(t.Context(), "tcp", ep.Address) require.NoError(t, err) require.NotNil(t, l1) defer l1.Close() l2, err := listenConfig.Listen(t.Context(), "tcp", l1.Addr().String()) require.Error(t, err) require.ErrorContains(t, err, "address already in use") require.Nil(t, l2) ep = static.EntryPoint{Address: ":0", ReusePort: true} listenConfig = newListenConfig(&ep) require.Nil(t, listenConfig.Control) require.Zero(t, listenConfig.KeepAlive) l3, err := listenConfig.Listen(t.Context(), "tcp", ep.Address) require.NoError(t, err) require.NotNil(t, l3) defer l3.Close() l4, err := listenConfig.Listen(t.Context(), "tcp", l3.Addr().String()) require.Error(t, err) require.ErrorContains(t, err, "address already in use") require.Nil(t, l4) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/server_entrypoint_udp_test.go
pkg/server/server_entrypoint_udp_test.go
package server import ( "io" "net" "testing" "time" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/udp" ) func TestShutdownUDPConn(t *testing.T) { ep := static.EntryPoint{ Address: ":0", Transport: &static.EntryPointsTransport{ LifeCycle: &static.LifeCycle{ GraceTimeOut: ptypes.Duration(5 * time.Second), }, }, } ep.SetDefaults() entryPoint, err := NewUDPEntryPoint(&ep, "") require.NoError(t, err) go entryPoint.Start(t.Context()) entryPoint.Switch(udp.HandlerFunc(func(conn *udp.Conn) { for { b := make([]byte, 1024*1024) n, err := conn.Read(b) if err != nil { return } // We control the termination, otherwise we would block on the Read above, // until conn is closed by a timeout. // Which means we would get an error, // and even though we are in a goroutine and the current test might be over, // go test would still yell at us if this happens while other tests are still running. if string(b[:n]) == "CLOSE" { return } _, _ = conn.Write(b[:n]) } })) conn, err := net.Dial("udp", entryPoint.listener.Addr().String()) require.NoError(t, err) // Start sending packets, to create a "session" with the server. requireEcho(t, "TEST", conn, time.Second) shutdownStartedChan := make(chan struct{}) doneChan := make(chan struct{}) go func() { close(shutdownStartedChan) entryPoint.Shutdown(t.Context()) close(doneChan) }() // Wait until shutdown has started, and hopefully after 100 ms the listener has stopped accepting new sessions. <-shutdownStartedChan time.Sleep(100 * time.Millisecond) // Make sure that our session is still live even after the shutdown. requireEcho(t, "TEST2", conn, time.Second) // And make sure that on the other hand, opening new sessions is not possible anymore. conn2, err := net.Dial("udp", entryPoint.listener.Addr().String()) require.NoError(t, err) _, err = conn2.Write([]byte("TEST")) // Packet is accepted, but dropped require.NoError(t, err) // Make sure that our session is yet again still live. // This is specifically to make sure we don't create a regression in listener's readLoop, // i.e. that we only terminate the listener's readLoop goroutine by closing its pConn. requireEcho(t, "TEST3", conn, time.Second) done := make(chan bool) go func() { defer close(done) b := make([]byte, 1024*1024) n, err := conn2.Read(b) require.Error(t, err) require.Equal(t, 0, n) }() conn2.Close() select { case <-done: case <-time.Tick(time.Second): t.Fatal("Timeout") } _, err = conn.Write([]byte("CLOSE")) require.NoError(t, err) select { case <-doneChan: case <-time.Tick(10 * time.Second): // In case we introduce a regression that would make the test wait forever. t.Fatal("Timeout during shutdown") } } // requireEcho tests that conn session is live and functional, // by writing data through it, // and expecting the same data as a response when reading on it. // It fatals if the read blocks longer than timeout, // which is useful to detect regressions that would make a test wait forever. func requireEcho(t *testing.T, data string, conn io.ReadWriter, timeout time.Duration) { t.Helper() _, err := conn.Write([]byte(data)) require.NoError(t, err) doneChan := make(chan struct{}) go func() { b := make([]byte, 1024*1024) n, err := conn.Read(b) require.NoError(t, err) require.Equal(t, data, string(b[:n])) close(doneChan) }() select { case <-doneChan: case <-time.Tick(timeout): t.Fatalf("Timeout during echo for: %s", data) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/routerfactory.go
pkg/server/routerfactory.go
package server import ( "context" "fmt" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/config/static" httpmuxer "github.com/traefik/traefik/v3/pkg/muxer/http" "github.com/traefik/traefik/v3/pkg/server/middleware" tcpmiddleware "github.com/traefik/traefik/v3/pkg/server/middleware/tcp" "github.com/traefik/traefik/v3/pkg/server/router" tcprouter "github.com/traefik/traefik/v3/pkg/server/router/tcp" udprouter "github.com/traefik/traefik/v3/pkg/server/router/udp" "github.com/traefik/traefik/v3/pkg/server/service" tcpsvc "github.com/traefik/traefik/v3/pkg/server/service/tcp" udpsvc "github.com/traefik/traefik/v3/pkg/server/service/udp" "github.com/traefik/traefik/v3/pkg/tcp" "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/udp" ) // RouterFactory the factory of TCP/UDP routers. type RouterFactory struct { entryPointsTCP []string entryPointsUDP []string allowACMEByPass map[string]bool managerFactory *service.ManagerFactory pluginBuilder middleware.PluginsBuilder observabilityMgr *middleware.ObservabilityMgr tlsManager *tls.Manager dialerManager *tcp.DialerManager cancelPrevState func() parser httpmuxer.SyntaxParser } // NewRouterFactory creates a new RouterFactory. func NewRouterFactory(staticConfiguration static.Configuration, managerFactory *service.ManagerFactory, tlsManager *tls.Manager, observabilityMgr *middleware.ObservabilityMgr, pluginBuilder middleware.PluginsBuilder, dialerManager *tcp.DialerManager, ) (*RouterFactory, error) { handlesTLSChallenge := false for _, resolver := range staticConfiguration.CertificatesResolvers { if resolver.ACME != nil && resolver.ACME.TLSChallenge != nil { handlesTLSChallenge = true break } } allowACMEByPass := map[string]bool{} var entryPointsTCP, entryPointsUDP []string for name, ep := range staticConfiguration.EntryPoints { allowACMEByPass[name] = ep.AllowACMEByPass || !handlesTLSChallenge protocol, err := ep.GetProtocol() if err != nil { // Should never happen because Traefik should not start if protocol is invalid. log.Error().Err(err).Msg("Invalid protocol") } if protocol == "udp" { entryPointsUDP = append(entryPointsUDP, name) } else { entryPointsTCP = append(entryPointsTCP, name) } } parser, err := httpmuxer.NewSyntaxParser() if err != nil { return nil, fmt.Errorf("creating parser: %w", err) } return &RouterFactory{ entryPointsTCP: entryPointsTCP, entryPointsUDP: entryPointsUDP, managerFactory: managerFactory, observabilityMgr: observabilityMgr, tlsManager: tlsManager, pluginBuilder: pluginBuilder, dialerManager: dialerManager, allowACMEByPass: allowACMEByPass, parser: parser, }, nil } // CreateRouters creates new TCPRouters and UDPRouters. func (f *RouterFactory) CreateRouters(rtConf *runtime.Configuration) (map[string]*tcprouter.Router, map[string]udp.Handler) { if f.cancelPrevState != nil { f.cancelPrevState() } var ctx context.Context ctx, f.cancelPrevState = context.WithCancel(context.Background()) // HTTP serviceManager := f.managerFactory.Build(rtConf) middlewaresBuilder := middleware.NewBuilder(rtConf.Middlewares, serviceManager, f.pluginBuilder) routerManager := router.NewManager(rtConf, serviceManager, middlewaresBuilder, f.observabilityMgr, f.tlsManager, f.parser) routerManager.ParseRouterTree() handlersNonTLS := routerManager.BuildHandlers(ctx, f.entryPointsTCP, false) handlersTLS := routerManager.BuildHandlers(ctx, f.entryPointsTCP, true) serviceManager.LaunchHealthCheck(ctx) // TCP svcTCPManager := tcpsvc.NewManager(rtConf, f.dialerManager) middlewaresTCPBuilder := tcpmiddleware.NewBuilder(rtConf.TCPMiddlewares) rtTCPManager := tcprouter.NewManager(rtConf, svcTCPManager, middlewaresTCPBuilder, handlersNonTLS, handlersTLS, f.tlsManager) routersTCP := rtTCPManager.BuildHandlers(ctx, f.entryPointsTCP) for ep, r := range routersTCP { if allowACMEByPass, ok := f.allowACMEByPass[ep]; ok && allowACMEByPass { r.EnableACMETLSPassthrough() } } svcTCPManager.LaunchHealthCheck(ctx) // UDP svcUDPManager := udpsvc.NewManager(rtConf) rtUDPManager := udprouter.NewManager(rtConf, svcUDPManager) routersUDP := rtUDPManager.BuildHandlers(ctx, f.entryPointsUDP) rtConf.PopulateUsedBy() return routersTCP, routersUDP }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/server_entrypoint_udp.go
pkg/server/server_entrypoint_udp.go
package server import ( "context" "fmt" "sync" "time" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/udp" ) // UDPEntryPoints maps UDP entry points by their names. type UDPEntryPoints map[string]*UDPEntryPoint // NewUDPEntryPoints returns all the UDP entry points, keyed by name. func NewUDPEntryPoints(config static.EntryPoints) (UDPEntryPoints, error) { entryPoints := make(UDPEntryPoints) for entryPointName, entryPoint := range config { protocol, err := entryPoint.GetProtocol() if err != nil { return nil, fmt.Errorf("error while building entryPoint %s: %w", entryPointName, err) } if protocol != "udp" { continue } ep, err := NewUDPEntryPoint(entryPoint, entryPointName) if err != nil { return nil, fmt.Errorf("error while building entryPoint %s: %w", entryPointName, err) } entryPoints[entryPointName] = ep } return entryPoints, nil } // Start commences the listening for all the entry points. func (eps UDPEntryPoints) Start() { for entryPointName, ep := range eps { ctx := log.With().Str(logs.EntryPointName, entryPointName).Logger().WithContext(context.Background()) go ep.Start(ctx) } } // Stop makes all the entry points stop listening, and release associated resources. func (eps UDPEntryPoints) Stop() { var wg sync.WaitGroup for epn, ep := range eps { wg.Add(1) go func(entryPointName string, entryPoint *UDPEntryPoint) { defer wg.Done() logger := log.With().Str(logs.EntryPointName, entryPointName).Logger() entryPoint.Shutdown(logger.WithContext(context.Background())) logger.Debug().Msg("Entry point closed") }(epn, ep) } wg.Wait() } // Switch swaps out all the given handlers in their associated entrypoints. func (eps UDPEntryPoints) Switch(handlers map[string]udp.Handler) { for epName, handler := range handlers { if ep, ok := eps[epName]; ok { ep.Switch(handler) continue } log.Error().Str(logs.EntryPointName, epName).Msg("EntryPoint does not exist") } } // UDPEntryPoint is an entry point where we listen for UDP packets. type UDPEntryPoint struct { listener *udp.Listener switcher *udp.HandlerSwitcher transportConfiguration *static.EntryPointsTransport } // NewUDPEntryPoint returns a UDP entry point. func NewUDPEntryPoint(config *static.EntryPoint, name string) (*UDPEntryPoint, error) { var listener *udp.Listener var err error timeout := time.Duration(config.UDP.Timeout) // if we have predefined connections from socket activation if socketActivation.isEnabled() { if conn, err := socketActivation.getConn(name); err == nil { listener, err = udp.ListenPacketConn(conn, timeout) if err != nil { log.Warn().Err(err).Str("name", name).Msg("Unable to create socket activation listener") } } else { log.Warn().Err(err).Str("name", name).Msg("Unable to use socket activation for entrypoint") } } if listener == nil { listenConfig := newListenConfig(config) listener, err = udp.Listen(listenConfig, "udp", config.GetAddress(), timeout) if err != nil { return nil, fmt.Errorf("error creating listener: %w", err) } } return &UDPEntryPoint{listener: listener, switcher: &udp.HandlerSwitcher{}, transportConfiguration: config.Transport}, nil } // Start commences the listening for ep. func (ep *UDPEntryPoint) Start(ctx context.Context) { log.Ctx(ctx).Debug().Msg("Start UDP Server") for { conn, err := ep.listener.Accept() if err != nil { // Only errClosedListener can happen that's why we return return } go ep.switcher.ServeUDP(conn) } } // Shutdown closes ep's listener. It eventually closes all "sessions" and // releases associated resources, but only after it has waited for a graceTimeout, // if any was configured. func (ep *UDPEntryPoint) Shutdown(ctx context.Context) { logger := log.Ctx(ctx) reqAcceptGraceTimeOut := time.Duration(ep.transportConfiguration.LifeCycle.RequestAcceptGraceTimeout) if reqAcceptGraceTimeOut > 0 { logger.Info().Msgf("Waiting %s for incoming requests to cease", reqAcceptGraceTimeOut) time.Sleep(reqAcceptGraceTimeOut) } graceTimeOut := time.Duration(ep.transportConfiguration.LifeCycle.GraceTimeOut) if err := ep.listener.Shutdown(graceTimeOut); err != nil { logger.Error().Err(err).Send() } } // Switch replaces ep's handler with the one given as argument. func (ep *UDPEntryPoint) Switch(handler udp.Handler) { ep.switcher.Switch(handler) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/server_entrypoint_tcp_http3.go
pkg/server/server_entrypoint_tcp_http3.go
package server import ( "context" "crypto/tls" "errors" "fmt" "net" "net/http" "sync" "github.com/quic-go/quic-go" "github.com/quic-go/quic-go/http3" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/static" tcprouter "github.com/traefik/traefik/v3/pkg/server/router/tcp" ) type http3server struct { *http3.Server http3conn net.PacketConn lock sync.RWMutex getter func(info *tls.ClientHelloInfo) (*tls.Config, error) } func newHTTP3Server(ctx context.Context, name string, config *static.EntryPoint, httpsServer *httpServer) (*http3server, error) { var conn net.PacketConn var err error if config.HTTP3 == nil { return nil, nil } if config.HTTP3.AdvertisedPort < 0 { return nil, errors.New("advertised port must be greater than or equal to zero") } // if we have predefined connections from socket activation if socketActivation.isEnabled() { conn, err = socketActivation.getConn(name) if err != nil { log.Ctx(ctx).Warn().Err(err).Str("name", name).Msg("Unable to use socket activation for entrypoint") } } if conn == nil { listenConfig := newListenConfig(config) conn, err = listenConfig.ListenPacket(ctx, "udp", config.GetAddress()) if err != nil { return nil, fmt.Errorf("starting listener: %w", err) } } h3 := &http3server{ http3conn: conn, getter: func(info *tls.ClientHelloInfo) (*tls.Config, error) { return nil, errors.New("no tls config") }, } h3.Server = &http3.Server{ Addr: config.GetAddress(), Port: config.HTTP3.AdvertisedPort, Handler: httpsServer.Server.(*http.Server).Handler, TLSConfig: &tls.Config{GetConfigForClient: h3.getGetConfigForClient}, QUICConfig: &quic.Config{ Allow0RTT: false, }, } previousHandler := httpsServer.Server.(*http.Server).Handler httpsServer.Server.(*http.Server).Handler = http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { if err := h3.Server.SetQUICHeaders(rw.Header()); err != nil { log.Ctx(ctx).Error().Err(err).Msg("Failed to set HTTP3 headers") } previousHandler.ServeHTTP(rw, req) }) return h3, nil } func (e *http3server) Start() error { return e.Serve(e.http3conn) } func (e *http3server) Switch(rt *tcprouter.Router) { e.lock.Lock() defer e.lock.Unlock() e.getter = rt.GetTLSGetClientInfo() } func (e *http3server) getGetConfigForClient(info *tls.ClientHelloInfo) (*tls.Config, error) { e.lock.RLock() defer e.lock.RUnlock() return e.getter(info) } func (e *http3server) Shutdown(_ context.Context) error { // TODO: use e.Server.CloseGracefully() when available. return e.Server.Close() }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/managerfactory.go
pkg/server/service/managerfactory.go
package service import ( "net/http" "github.com/gorilla/mux" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/api" "github.com/traefik/traefik/v3/pkg/api/dashboard" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/observability/metrics" "github.com/traefik/traefik/v3/pkg/safe" "github.com/traefik/traefik/v3/pkg/server/middleware" ) // ManagerFactory a factory of service manager. type ManagerFactory struct { observabilityMgr *middleware.ObservabilityMgr transportManager *TransportManager proxyBuilder ProxyBuilder api func(configuration *runtime.Configuration) http.Handler restHandler http.Handler dashboardHandler http.Handler metricsHandler http.Handler pingHandler http.Handler acmeHTTPHandler http.Handler routinesPool *safe.Pool } // NewManagerFactory creates a new ManagerFactory. func NewManagerFactory(staticConfiguration static.Configuration, routinesPool *safe.Pool, observabilityMgr *middleware.ObservabilityMgr, transportManager *TransportManager, proxyBuilder ProxyBuilder, acmeHTTPHandler http.Handler) *ManagerFactory { factory := &ManagerFactory{ observabilityMgr: observabilityMgr, routinesPool: routinesPool, transportManager: transportManager, proxyBuilder: proxyBuilder, acmeHTTPHandler: acmeHTTPHandler, } if staticConfiguration.API != nil { apiRouterBuilder := api.NewBuilder(staticConfiguration) if staticConfiguration.API.Dashboard { factory.dashboardHandler = dashboard.Handler{BasePath: staticConfiguration.API.BasePath} factory.api = func(configuration *runtime.Configuration) http.Handler { router := apiRouterBuilder(configuration).(*mux.Router) if err := dashboard.Append(router, staticConfiguration.API.BasePath, nil); err != nil { log.Error().Err(err).Msg("Error appending dashboard to API router") } return router } } else { factory.api = apiRouterBuilder } } if staticConfiguration.Providers != nil && staticConfiguration.Providers.Rest != nil { factory.restHandler = staticConfiguration.Providers.Rest.CreateRouter() } if staticConfiguration.Metrics != nil && staticConfiguration.Metrics.Prometheus != nil { factory.metricsHandler = metrics.PrometheusHandler() } // This check is necessary because even when staticConfiguration.Ping == nil , // the affectation would make factory.pingHandle become a typed nil, which does not pass the nil test, // and would break things elsewhere. if staticConfiguration.Ping != nil { factory.pingHandler = staticConfiguration.Ping } return factory } // Build creates a service manager. func (f *ManagerFactory) Build(configuration *runtime.Configuration) *Manager { var apiHandler http.Handler if f.api != nil { apiHandler = f.api(configuration) } internalHandlers := NewInternalHandlers(apiHandler, f.restHandler, f.metricsHandler, f.pingHandler, f.dashboardHandler, f.acmeHTTPHandler) return NewManager(configuration.Services, f.observabilityMgr, f.routinesPool, f.transportManager, f.proxyBuilder, internalHandlers) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/transport_test.go
pkg/server/service/transport_test.go
package service import ( "crypto/rand" "crypto/rsa" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "math/big" "net" "net/http" "net/http/httptest" "net/url" "sync/atomic" "testing" "time" "github.com/spiffe/go-spiffe/v2/bundle/x509bundle" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/spiffe/go-spiffe/v2/spiffetls/tlsconfig" "github.com/spiffe/go-spiffe/v2/svid/x509svid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" traefiktls "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" ) // LocalhostCert is a PEM-encoded TLS cert // for host example.com, www.example.com // expiring at Jan 29 16:00:00 2084 GMT. // go run $GOROOT/src/crypto/tls/generate_cert.go --rsa-bits 1024 --host example.com,www.example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h var LocalhostCert = []byte(`-----BEGIN CERTIFICATE----- MIICDDCCAXWgAwIBAgIQH20JmcOlcRWHNuf62SYwszANBgkqhkiG9w0BAQsFADAS MRAwDgYDVQQKEwdBY21lIENvMCAXDTcwMDEwMTAwMDAwMFoYDzIwODQwMTI5MTYw MDAwWjASMRAwDgYDVQQKEwdBY21lIENvMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB iQKBgQC0qINy3F4oq6viDnlpDDE5J08iSRGggg6EylJKBKZfphEG2ufgK78Dufl3 +7b0LlEY2AeZHwviHODqC9a6ihj1ZYQk0/djAh+OeOhFEWu+9T/VP8gVFarFqT8D Opy+hrG7YJivUIzwb4fmJQRI7FajzsnGyM6LiXLU+0qzb7ZO/QIDAQABo2EwXzAO BgNVHQ8BAf8EBAMCAqQwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDwYDVR0TAQH/BAUw AwEB/zAnBgNVHREEIDAeggtleGFtcGxlLmNvbYIPd3d3LmV4YW1wbGUuY29tMA0G CSqGSIb3DQEBCwUAA4GBAB+eluoQYzyyMfeEEAOtlldevx5MtDENT05NB0WI+91R we7mX8lv763u0XuCWPxbHszhclI6FFjoQef0Z1NYLRm8ZRq58QqWDFZ3E6wdDK+B +OWvkW+hRavo6R9LzIZPfbv8yBo4M9PK/DXw8hLqH7VkkI+Gh793iH7Ugd4A7wvT -----END CERTIFICATE-----`) // LocalhostKey is the private key for localhostCert. var LocalhostKey = []byte(`-----BEGIN PRIVATE KEY----- MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALSog3LcXiirq+IO eWkMMTknTyJJEaCCDoTKUkoEpl+mEQba5+ArvwO5+Xf7tvQuURjYB5kfC+Ic4OoL 1rqKGPVlhCTT92MCH4546EURa771P9U/yBUVqsWpPwM6nL6GsbtgmK9QjPBvh+Yl BEjsVqPOycbIzouJctT7SrNvtk79AgMBAAECgYB1wMT1MBgbkFIXpXGTfAP1id61 rUTVBxCpkypx3ngHLjo46qRq5Hi72BN4FlTY8fugIudI8giP2FztkMvkiLDc4m0p Gn+QMJzjlBjjTuNLvLy4aSmNRLIC3mtbx9PdU71DQswEpJHFj/vmsxbuSrG1I1YE r1reuSo2ow6fOAjXLQJBANpz+RkOiPSPuvl+gi1sp2pLuynUJVDVqWZi386YRpfg DiKCLpqwqYDkOozm/fwFALvwXKGmsyyL43HO8eI+2NsCQQDTtY32V+02GPecdsyq msK06EPVTSaYwj9Mm+q709KsmYFHLXDqXjcKV4UgKYKRPz7my1fXodMmGmfuh1a3 /HMHAkEAmOQKN0tA90mRJwUvvvMIyRBv0fq0kzq28P3KfiF9ZtZdjjFmxMVYHOmf QPZ6VGR7+w1jB5BQXqEZcpHQIPSzeQJBAIy9tZJ/AYNlNbcegxEnsSjy/6VdlLsY 51vWi0Yym2uC4R6gZuBnoc+OP0ISVmqY0Qg9RjhjrCs4gr9f2ZaWjSECQCxqZMq1 3viJ8BGCC0m/5jv1EHur3YgwphYCkf4Li6DKwIdMLk1WXkTcPIY3V2Jqj8rPEB5V rqPRSAtd/h6oZbs= -----END PRIVATE KEY-----`) // openssl req -newkey rsa:2048 \ // -new -nodes -x509 \ // -days 3650 \ // -out cert.pem \ // -keyout key.pem \ // -subj "/CN=example.com" // -addext "subjectAltName = DNS:example.com" var mTLSCert = []byte(`-----BEGIN CERTIFICATE----- MIIDJTCCAg2gAwIBAgIUYKnGcLnmMosOSKqTn4ydAMURE4gwDQYJKoZIhvcNAQEL BQAwFjEUMBIGA1UEAwwLZXhhbXBsZS5jb20wHhcNMjAwODEzMDkyNzIwWhcNMzAw ODExMDkyNzIwWjAWMRQwEgYDVQQDDAtleGFtcGxlLmNvbTCCASIwDQYJKoZIhvcN AQEBBQADggEPADCCAQoCggEBAOAe+QM1c9lZ2TPRgoiuPAq2A3Pfu+i82lmqrTJ0 PR2Cx1fPbccCUTFJPlxSDiaMrwtvqw1yP9L2Pu/vJK5BY4YDVDtFGKjpRBau1otJ iY50O5qMo3sfLqR4/1VsQGlLVZYLD3dyc4ZTmOp8+7tJ2SyGorojbIKfimZT7XD7 dzrVr4h4Gn+SzzOnoKyx29uaNRP+XuMYHmHyQcJE03pUGhkTOvMwBlF96QdQ9WG0 D+1CxRciEsZXE+imKBHoaTgrTkpnFHzsrIEw+OHQYf30zuT/k/lkgv1vqEwINHjz W2VeTur5eqVvA7zZdoEXMRy7BUvh/nZk5AXkXAmZLn0eUg8CAwEAAaNrMGkwHQYD VR0OBBYEFEDrbhPDt+hi3ZOzk6S/CFAVHwk0MB8GA1UdIwQYMBaAFEDrbhPDt+hi 3ZOzk6S/CFAVHwk0MA8GA1UdEwEB/wQFMAMBAf8wFgYDVR0RBA8wDYILZXhhbXBs ZS5jb20wDQYJKoZIhvcNAQELBQADggEBAG/JRJWeUNx2mDJAk8W7Syq3gmQB7s9f +yY/XVRJZGahOPilABqFpC6GVn2HWuvuOqy8/RGk9ja5abKVXqE6YKrljqo3XfzB KQcOz4SFirpkHvNCiEcK3kggN3wJWqL2QyXAxWldBBBCO9yx7a3cux31C//sTUOG xq4JZDg171U1UOpfN1t0BFMdt05XZFEM247N7Dcf7HoXwAa7eyLKgtKWqPDqGrFa fvGDDKK9X/KVsU2x9V3pG+LsJg7ogUnSyD2r5G1F3Y8OVs2T/783PaN0M35fDL38 09VbsxA2GasOHZrghUzT4UvZWWZbWEmG975hFYvdj6DlK9K0s5TdKIs= -----END CERTIFICATE-----`) var mTLSKey = []byte(`-----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDgHvkDNXPZWdkz 0YKIrjwKtgNz37vovNpZqq0ydD0dgsdXz23HAlExST5cUg4mjK8Lb6sNcj/S9j7v 7ySuQWOGA1Q7RRio6UQWrtaLSYmOdDuajKN7Hy6keP9VbEBpS1WWCw93cnOGU5jq fPu7SdkshqK6I2yCn4pmU+1w+3c61a+IeBp/ks8zp6CssdvbmjUT/l7jGB5h8kHC RNN6VBoZEzrzMAZRfekHUPVhtA/tQsUXIhLGVxPopigR6Gk4K05KZxR87KyBMPjh 0GH99M7k/5P5ZIL9b6hMCDR481tlXk7q+XqlbwO82XaBFzEcuwVL4f52ZOQF5FwJ mS59HlIPAgMBAAECggEAAKLV3hZ2v7UrkqQTlMO50+X0WI3YAK8Yh4yedTgzPDQ0 0KD8FMaC6HrmvGhXNfDMRmIIwD8Ew1qDjzbEieIRoD2+LXTivwf6c34HidmplEfs K2IezKin/zuArgNio2ndUlGxt4sRnN373x5/sGZjQWcYayLSmgRN5kByuhFco0Qa oSrXcXNUlb+KgRQXPDU4+M35tPHvLdyg+tko/m/5uK9dc9MNvGZHOMBKg0VNURJb V1l3dR+evwvpqHzBvWiqN/YOiUUvIxlFKA35hJkfCl7ivFs4CLqqFNCKDao95fWe s0UR9iMakT48jXV76IfwZnyX10OhIWzKls5trjDL8QKBgQD3thQJ8e0FL9y1W+Ph mCdEaoffSPkgSn64wIsQ9bMmv4y+KYBK5AhqaHgYm4LgW4x1+CURNFu+YFEyaNNA kNCXFyRX3Em3vxcShP5jIqg+f07mtXPKntWP/zBeKQWgdHX371oFTfaAlNuKX/7S n0jBYjr4Iof1bnquMQvUoHCYWwKBgQDnntFU9/AQGaQIvhfeU1XKFkQ/BfhIsd27 RlmiCi0ee9Ce74cMAhWr/9yg0XUxzrh+Ui1xnkMVTZ5P8tWIxROokznLUTGJA5rs zB+ovCPFZcquTwNzn7SBnpHTR0OqJd8sd89P5ST2SqufeSF/gGi5sTs4EocOLCpZ EPVIfm47XQKBgB4d5RHQeCDJUOw739jtxthqm1pqZN+oLwAHaOEG/mEXqOT15sM0 NlG5oeBcB+1/M/Sj1t3gn8blrvmSBR00fifgiGqmPdA5S3TU9pjW/d2bXNxv80QP S6fWPusz0ZtQjYc3cppygCXh808/nJu/AfmBF+pTSHRumjvTery/RPFBAoGBAMi/ zCta4cTylEvHhqR5kiefePMu120aTFYeuV1KeKStJ7o5XNE5lVMIZk80e+D5jMpf q2eIhhgWuBoPHKh4N3uqbzMbYlWgvEx09xOmTVKv0SWW8iTqzOZza2y1nZ4BSRcf mJ1ku86EFZAYysHZp+saA3usA0ZzXRjpK87zVdM5AoGBAOSqI+t48PnPtaUDFdpd taNNVDbcecJatm3w8VDWnarahfWe66FIqc9wUkqekqAgwZLa0AGdUalvXfGrHfNs PtvuNc5EImfSkuPBYLBslNxtjbBvAYgacEdY+gRhn2TeIUApnND58lCWsKbNHLFZ ajIPbTY+Fe9OTOFTN48ujXNn -----END PRIVATE KEY-----`) func TestKeepConnectionWhenSameConfiguration(t *testing.T) { srv := httptest.NewUnstartedServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) })) connCount := pointer[int32](0) srv.Config.ConnState = func(conn net.Conn, state http.ConnState) { if state == http.StateNew { atomic.AddInt32(connCount, 1) } } cert, err := tls.X509KeyPair(LocalhostCert, LocalhostKey) require.NoError(t, err) srv.TLS = &tls.Config{Certificates: []tls.Certificate{cert}} srv.StartTLS() transportManager := NewTransportManager(nil) dynamicConf := map[string]*dynamic.ServersTransport{ "test": { ServerName: "example.com", RootCAs: []types.FileOrContent{types.FileOrContent(LocalhostCert)}, }, } for range 10 { transportManager.Update(dynamicConf) tr, err := transportManager.GetRoundTripper("test") require.NoError(t, err) client := http.Client{Transport: tr} resp, err := client.Get(srv.URL) require.NoError(t, err) require.Equal(t, http.StatusOK, resp.StatusCode) } count := atomic.LoadInt32(connCount) require.EqualValues(t, 1, count) dynamicConf = map[string]*dynamic.ServersTransport{ "test": { ServerName: "www.example.com", RootCAs: []types.FileOrContent{types.FileOrContent(LocalhostCert)}, }, } transportManager.Update(dynamicConf) tr, err := transportManager.GetRoundTripper("test") require.NoError(t, err) client := http.Client{Transport: tr} resp, err := client.Get(srv.URL) require.NoError(t, err) require.Equal(t, http.StatusOK, resp.StatusCode) count = atomic.LoadInt32(connCount) assert.EqualValues(t, 2, count) } func TestMTLS(t *testing.T) { srv := httptest.NewUnstartedServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) })) cert, err := tls.X509KeyPair(LocalhostCert, LocalhostKey) require.NoError(t, err) clientPool := x509.NewCertPool() clientPool.AppendCertsFromPEM(mTLSCert) srv.TLS = &tls.Config{ // For TLS Certificates: []tls.Certificate{cert}, // For mTLS ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: clientPool, } srv.StartTLS() transportManager := NewTransportManager(nil) dynamicConf := map[string]*dynamic.ServersTransport{ "test": { ServerName: "example.com", // For TLS RootCAs: []types.FileOrContent{types.FileOrContent(LocalhostCert)}, // For mTLS Certificates: traefiktls.Certificates{ traefiktls.Certificate{ CertFile: types.FileOrContent(mTLSCert), KeyFile: types.FileOrContent(mTLSKey), }, }, }, } transportManager.Update(dynamicConf) tr, err := transportManager.GetRoundTripper("test") require.NoError(t, err) client := http.Client{Transport: tr} resp, err := client.Get(srv.URL) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) } func TestSpiffeMTLS(t *testing.T) { srv := httptest.NewUnstartedServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) })) trustDomain := spiffeid.RequireTrustDomainFromString("spiffe://traefik.test") pki, err := newFakeSpiffePKI(trustDomain) require.NoError(t, err) clientSVID, err := pki.genSVID(spiffeid.RequireFromPath(trustDomain, "/client")) require.NoError(t, err) serverSVID, err := pki.genSVID(spiffeid.RequireFromPath(trustDomain, "/server")) require.NoError(t, err) serverSource := fakeSpiffeSource{ svid: serverSVID, bundle: pki.bundle, } // go-spiffe's `tlsconfig.MTLSServerConfig` (that should be used here) does not set a certificate on // the returned `tls.Config` and relies instead on `GetCertificate` being always called. // But it turns out that `StartTLS` from `httptest.Server`, enforces a default certificate // if no certificate is previously set on the configured TLS config. // It makes the test server always serve the httptest default certificate, and not the SPIFFE certificate, // as GetCertificate is in that case never called (there's a default cert, and SNI is not used). // To bypass this issue, we're manually extracting the server ceritificate from the server SVID // and use another initialization method that forces serving the server SPIFFE certificate. serverCert, err := tlsconfig.GetCertificate(&serverSource)(nil) require.NoError(t, err) srv.TLS = tlsconfig.MTLSWebServerConfig( serverCert, &serverSource, tlsconfig.AuthorizeAny(), ) srv.StartTLS() defer srv.Close() clientSource := fakeSpiffeSource{ svid: clientSVID, bundle: pki.bundle, } testCases := []struct { desc string config dynamic.Spiffe clientSource SpiffeX509Source wantStatusCode int wantError bool }{ { desc: "supports SPIFFE mTLS", config: dynamic.Spiffe{}, clientSource: &clientSource, wantStatusCode: http.StatusOK, }, { desc: "allows expected server SPIFFE ID", config: dynamic.Spiffe{ IDs: []string{"spiffe://traefik.test/server"}, }, clientSource: &clientSource, wantStatusCode: http.StatusOK, }, { desc: "blocks unexpected server SPIFFE ID", config: dynamic.Spiffe{ IDs: []string{"spiffe://traefik.test/not-server"}, }, clientSource: &clientSource, wantError: true, }, { desc: "allows expected server trust domain", config: dynamic.Spiffe{ TrustDomain: "spiffe://traefik.test", }, clientSource: &clientSource, wantStatusCode: http.StatusOK, }, { desc: "denies unexpected server trust domain", config: dynamic.Spiffe{ TrustDomain: "spiffe://not-traefik.test", }, clientSource: &clientSource, wantError: true, }, { desc: "spiffe IDs allowlist takes precedence", config: dynamic.Spiffe{ IDs: []string{"spiffe://traefik.test/not-server"}, TrustDomain: "spiffe://not-traefik.test", }, clientSource: &clientSource, wantError: true, }, { desc: "raises an error when spiffe is enabled on the transport but no workloadapi address is given", config: dynamic.Spiffe{}, clientSource: nil, wantError: true, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { transportManager := NewTransportManager(test.clientSource) dynamicConf := map[string]*dynamic.ServersTransport{ "test": { Spiffe: &test.config, }, } transportManager.Update(dynamicConf) tr, err := transportManager.GetRoundTripper("test") require.NoError(t, err) client := http.Client{Transport: tr} resp, err := client.Get(srv.URL) if test.wantError { require.Error(t, err) return } require.NoError(t, err) assert.Equal(t, test.wantStatusCode, resp.StatusCode) }) } } func TestDisableHTTP2(t *testing.T) { testCases := []struct { desc string disableHTTP2 bool serverHTTP2 bool expectedProto string }{ { desc: "HTTP1 capable client with HTTP1 server", disableHTTP2: true, expectedProto: "HTTP/1.1", }, { desc: "HTTP1 capable client with HTTP2 server", disableHTTP2: true, serverHTTP2: true, expectedProto: "HTTP/1.1", }, { desc: "HTTP2 capable client with HTTP1 server", expectedProto: "HTTP/1.1", }, { desc: "HTTP2 capable client with HTTP2 server", serverHTTP2: true, expectedProto: "HTTP/2.0", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() srv := httptest.NewUnstartedServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) })) srv.EnableHTTP2 = test.serverHTTP2 srv.StartTLS() transportManager := NewTransportManager(nil) dynamicConf := map[string]*dynamic.ServersTransport{ "test": { DisableHTTP2: test.disableHTTP2, InsecureSkipVerify: true, }, } transportManager.Update(dynamicConf) tr, err := transportManager.GetRoundTripper("test") require.NoError(t, err) client := http.Client{Transport: tr} resp, err := client.Get(srv.URL) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, test.expectedProto, resp.Proto) }) } } // fakeSpiffePKI simulates a SPIFFE aware PKI and allows generating multiple valid SVIDs. type fakeSpiffePKI struct { caPrivateKey *rsa.PrivateKey bundle *x509bundle.Bundle } func newFakeSpiffePKI(trustDomain spiffeid.TrustDomain) (fakeSpiffePKI, error) { caPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return fakeSpiffePKI{}, err } caTemplate := x509.Certificate{ SerialNumber: big.NewInt(2000), Subject: pkix.Name{ Organization: []string{"spiffe"}, }, URIs: []*url.URL{spiffeid.RequireFromPath(trustDomain, "/ca").URL()}, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour), SubjectKeyId: []byte("ca"), KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, BasicConstraintsValid: true, IsCA: true, PublicKey: caPrivateKey.Public(), } caCertDER, err := x509.CreateCertificate( rand.Reader, &caTemplate, &caTemplate, caPrivateKey.Public(), caPrivateKey, ) if err != nil { return fakeSpiffePKI{}, err } bundle, err := x509bundle.ParseRaw( trustDomain, caCertDER, ) if err != nil { return fakeSpiffePKI{}, err } return fakeSpiffePKI{ bundle: bundle, caPrivateKey: caPrivateKey, }, nil } func (f *fakeSpiffePKI) genSVID(id spiffeid.ID) (*x509svid.SVID, error) { privateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return nil, err } template := x509.Certificate{ SerialNumber: big.NewInt(200001), URIs: []*url.URL{id.URL()}, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour), SubjectKeyId: []byte("svid"), KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{ x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth, }, BasicConstraintsValid: true, PublicKey: privateKey.PublicKey, } certDER, err := x509.CreateCertificate( rand.Reader, &template, f.bundle.X509Authorities()[0], privateKey.Public(), f.caPrivateKey, ) if err != nil { return nil, err } keyPKCS8, err := x509.MarshalPKCS8PrivateKey(privateKey) if err != nil { return nil, err } return x509svid.ParseRaw(certDER, keyPKCS8) } // fakeSpiffeSource allows retrieving statically an SVID and its associated bundle. type fakeSpiffeSource struct { bundle *x509bundle.Bundle svid *x509svid.SVID } func (s *fakeSpiffeSource) GetX509BundleForTrustDomain(trustDomain spiffeid.TrustDomain) (*x509bundle.Bundle, error) { return s.bundle, nil } func (s *fakeSpiffeSource) GetX509SVID() (*x509svid.SVID, error) { return s.svid, nil } type roundTripperFn func(req *http.Request) (*http.Response, error) func (r roundTripperFn) RoundTrip(request *http.Request) (*http.Response, error) { return r(request) } func TestKerberosRoundTripper(t *testing.T) { testCases := []struct { desc string originalRoundTripperHeaders map[string][]string expectedStatusCode []int expectedDedicatedCount int expectedOriginalCount int }{ { desc: "without special header", expectedStatusCode: []int{http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized}, expectedOriginalCount: 3, }, { desc: "with Negotiate (Kerberos)", originalRoundTripperHeaders: map[string][]string{"Www-Authenticate": {"Negotiate"}}, expectedStatusCode: []int{http.StatusUnauthorized, http.StatusOK, http.StatusOK}, expectedOriginalCount: 1, expectedDedicatedCount: 2, }, { desc: "with NTLM", originalRoundTripperHeaders: map[string][]string{"Www-Authenticate": {"NTLM"}}, expectedStatusCode: []int{http.StatusUnauthorized, http.StatusOK, http.StatusOK}, expectedOriginalCount: 1, expectedDedicatedCount: 2, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() origCount := 0 dedicatedCount := 0 rt := kerberosRoundTripper{ new: func() http.RoundTripper { return roundTripperFn(func(req *http.Request) (*http.Response, error) { dedicatedCount++ return &http.Response{ StatusCode: http.StatusOK, }, nil }) }, OriginalRoundTripper: roundTripperFn(func(req *http.Request) (*http.Response, error) { origCount++ return &http.Response{ StatusCode: http.StatusUnauthorized, Header: test.originalRoundTripperHeaders, }, nil }), } ctx := AddTransportOnContext(t.Context()) for _, expected := range test.expectedStatusCode { req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://127.0.0.1", http.NoBody) require.NoError(t, err) resp, err := rt.RoundTrip(req) require.NoError(t, err) require.Equal(t, expected, resp.StatusCode) } require.Equal(t, test.expectedOriginalCount, origCount) require.Equal(t, test.expectedDedicatedCount, dedicatedCount) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/service.go
pkg/server/service/service.go
package service import ( "context" "encoding/json" "errors" "fmt" "math/rand" "net/http" "net/url" "reflect" "strings" "time" "github.com/containous/alice" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/healthcheck" "github.com/traefik/traefik/v3/pkg/middlewares/accesslog" metricsMiddle "github.com/traefik/traefik/v3/pkg/middlewares/metrics" "github.com/traefik/traefik/v3/pkg/middlewares/observability" "github.com/traefik/traefik/v3/pkg/middlewares/retry" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/proxy/httputil" "github.com/traefik/traefik/v3/pkg/safe" "github.com/traefik/traefik/v3/pkg/server/cookie" "github.com/traefik/traefik/v3/pkg/server/middleware" "github.com/traefik/traefik/v3/pkg/server/provider" "github.com/traefik/traefik/v3/pkg/server/service/loadbalancer/failover" "github.com/traefik/traefik/v3/pkg/server/service/loadbalancer/hrw" "github.com/traefik/traefik/v3/pkg/server/service/loadbalancer/leasttime" "github.com/traefik/traefik/v3/pkg/server/service/loadbalancer/mirror" "github.com/traefik/traefik/v3/pkg/server/service/loadbalancer/p2c" "github.com/traefik/traefik/v3/pkg/server/service/loadbalancer/wrr" "google.golang.org/grpc/status" ) // ProxyBuilder builds reverse proxy handlers. type ProxyBuilder interface { Build(cfgName string, targetURL *url.URL, passHostHeader, preservePath bool, flushInterval time.Duration) (http.Handler, error) Update(configs map[string]*dynamic.ServersTransport) } // ServiceBuilder is a Service builder. type ServiceBuilder interface { BuildHTTP(rootCtx context.Context, serviceName string) (http.Handler, error) } // Manager The service manager. type Manager struct { routinePool *safe.Pool observabilityMgr *middleware.ObservabilityMgr transportManager httputil.TransportManager proxyBuilder ProxyBuilder serviceBuilders []ServiceBuilder services map[string]http.Handler configs map[string]*runtime.ServiceInfo healthCheckers map[string]*healthcheck.ServiceHealthChecker rand *rand.Rand // For the initial shuffling of load-balancers. } // NewManager creates a new Manager. func NewManager(configs map[string]*runtime.ServiceInfo, observabilityMgr *middleware.ObservabilityMgr, routinePool *safe.Pool, transportManager httputil.TransportManager, proxyBuilder ProxyBuilder, serviceBuilders ...ServiceBuilder) *Manager { return &Manager{ routinePool: routinePool, observabilityMgr: observabilityMgr, transportManager: transportManager, proxyBuilder: proxyBuilder, serviceBuilders: serviceBuilders, services: make(map[string]http.Handler), configs: configs, healthCheckers: make(map[string]*healthcheck.ServiceHealthChecker), rand: rand.New(rand.NewSource(time.Now().UnixNano())), } } // BuildHTTP Creates a http.Handler for a service configuration. func (m *Manager) BuildHTTP(rootCtx context.Context, serviceName string) (http.Handler, error) { serviceName = provider.GetQualifiedName(rootCtx, serviceName) ctx := log.Ctx(rootCtx).With().Str(logs.ServiceName, serviceName).Logger(). WithContext(provider.AddInContext(rootCtx, serviceName)) handler, ok := m.services[serviceName] if ok { return handler, nil } // Must be before we get configs to handle services without config. for _, builder := range m.serviceBuilders { handler, err := builder.BuildHTTP(rootCtx, serviceName) if err != nil { return nil, err } if handler != nil { m.services[serviceName] = handler return handler, nil } } conf, ok := m.configs[serviceName] if !ok { return nil, fmt.Errorf("the service %q does not exist", serviceName) } if conf.Status == runtime.StatusDisabled { return nil, errors.New(strings.Join(conf.Err, ", ")) } value := reflect.ValueOf(*conf.Service) var count int for i := range value.NumField() { if !value.Field(i).IsNil() { count++ } } if count > 1 { err := errors.New("cannot create service: multi-types service not supported, consider declaring two different pieces of service instead") conf.AddError(err, true) return nil, err } var lb http.Handler switch { case conf.LoadBalancer != nil: var err error lb, err = m.getLoadBalancerServiceHandler(ctx, serviceName, conf) if err != nil { conf.AddError(err, true) return nil, err } case conf.Weighted != nil: var err error lb, err = m.getWRRServiceHandler(ctx, serviceName, conf.Weighted) if err != nil { conf.AddError(err, true) return nil, err } case conf.HighestRandomWeight != nil: var err error lb, err = m.getHRWServiceHandler(ctx, serviceName, conf.HighestRandomWeight) if err != nil { conf.AddError(err, true) return nil, err } case conf.Mirroring != nil: var err error lb, err = m.getMirrorServiceHandler(ctx, conf.Mirroring) if err != nil { conf.AddError(err, true) return nil, err } case conf.Failover != nil: var err error lb, err = m.getFailoverServiceHandler(ctx, serviceName, conf.Failover) if err != nil { conf.AddError(err, true) return nil, err } default: sErr := fmt.Errorf("the service %q does not have any type defined", serviceName) conf.AddError(sErr, true) return nil, sErr } m.services[serviceName] = lb return lb, nil } func (m *Manager) getFailoverServiceHandler(ctx context.Context, serviceName string, config *dynamic.Failover) (http.Handler, error) { f := failover.New(config.HealthCheck) serviceHandler, err := m.BuildHTTP(ctx, config.Service) if err != nil { return nil, err } f.SetHandler(serviceHandler) updater, ok := serviceHandler.(healthcheck.StatusUpdater) if !ok { return nil, fmt.Errorf("child service %v of %v not a healthcheck.StatusUpdater (%T)", config.Service, serviceName, serviceHandler) } if err := updater.RegisterStatusUpdater(func(up bool) { f.SetHandlerStatus(ctx, up) }); err != nil { return nil, fmt.Errorf("cannot register %v as updater for %v: %w", config.Service, serviceName, err) } fallbackHandler, err := m.BuildHTTP(ctx, config.Fallback) if err != nil { return nil, err } f.SetFallbackHandler(fallbackHandler) // Do not report the health of the fallback handler. if config.HealthCheck == nil { return f, nil } fallbackUpdater, ok := fallbackHandler.(healthcheck.StatusUpdater) if !ok { return nil, fmt.Errorf("child service %v of %v not a healthcheck.StatusUpdater (%T)", config.Fallback, serviceName, fallbackHandler) } if err := fallbackUpdater.RegisterStatusUpdater(func(up bool) { f.SetFallbackHandlerStatus(ctx, up) }); err != nil { return nil, fmt.Errorf("cannot register %v as updater for %v: %w", config.Fallback, serviceName, err) } return f, nil } func (m *Manager) getMirrorServiceHandler(ctx context.Context, config *dynamic.Mirroring) (http.Handler, error) { serviceHandler, err := m.BuildHTTP(ctx, config.Service) if err != nil { return nil, err } mirrorBody := dynamic.MirroringDefaultMirrorBody if config.MirrorBody != nil { mirrorBody = *config.MirrorBody } maxBodySize := dynamic.MirroringDefaultMaxBodySize if config.MaxBodySize != nil { maxBodySize = *config.MaxBodySize } handler := mirror.New(serviceHandler, m.routinePool, mirrorBody, maxBodySize, config.HealthCheck) for _, mirrorConfig := range config.Mirrors { mirrorHandler, err := m.BuildHTTP(ctx, mirrorConfig.Name) if err != nil { return nil, err } err = handler.AddMirror(mirrorHandler, mirrorConfig.Percent) if err != nil { return nil, err } } return handler, nil } func (m *Manager) getWRRServiceHandler(ctx context.Context, serviceName string, config *dynamic.WeightedRoundRobin) (http.Handler, error) { // TODO Handle accesslog and metrics with multiple service name if config.Sticky != nil && config.Sticky.Cookie != nil { config.Sticky.Cookie.Name = cookie.GetName(config.Sticky.Cookie.Name, serviceName) } balancer := wrr.New(config.Sticky, config.HealthCheck != nil) for _, service := range shuffle(config.Services, m.rand) { serviceHandler, err := m.getServiceHandler(ctx, service) if err != nil { return nil, err } balancer.Add(service.Name, serviceHandler, service.Weight, false) if config.HealthCheck == nil { continue } updater, ok := serviceHandler.(healthcheck.StatusUpdater) if !ok { return nil, fmt.Errorf("child service %v of %v not a healthcheck.StatusUpdater (%T)", service.Name, serviceName, serviceHandler) } if err := updater.RegisterStatusUpdater(func(up bool) { balancer.SetStatus(ctx, service.Name, up) }); err != nil { return nil, fmt.Errorf("cannot register %v as updater for %v: %w", service.Name, serviceName, err) } log.Ctx(ctx).Debug().Str("parent", serviceName).Str("child", service.Name). Msg("Child service will update parent on status change") } return balancer, nil } func (m *Manager) getServiceHandler(ctx context.Context, service dynamic.WRRService) (http.Handler, error) { if service.Status != nil { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(*service.Status) }), nil } if service.GRPCStatus != nil { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { st := status.New(service.GRPCStatus.Code, service.GRPCStatus.Msg) body, err := json.Marshal(st.Proto()) if err != nil { http.Error(rw, "Failed to marshal status to JSON", http.StatusInternalServerError) return } rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(http.StatusOK) _, _ = rw.Write(body) }), nil } svcHandler, err := m.BuildHTTP(ctx, service.Name) if err != nil { return nil, fmt.Errorf("building HTTP service: %w", err) } if service.Headers != nil { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { for k, v := range service.Headers { req.Header.Set(k, v) } svcHandler.ServeHTTP(rw, req) }), nil } return svcHandler, nil } func (m *Manager) getHRWServiceHandler(ctx context.Context, serviceName string, config *dynamic.HighestRandomWeight) (http.Handler, error) { // TODO Handle accesslog and metrics with multiple service name balancer := hrw.New(config.HealthCheck != nil) for _, service := range shuffle(config.Services, m.rand) { serviceHandler, err := m.BuildHTTP(ctx, service.Name) if err != nil { return nil, err } balancer.Add(service.Name, serviceHandler, service.Weight, false) if config.HealthCheck == nil { continue } updater, ok := serviceHandler.(healthcheck.StatusUpdater) if !ok { return nil, fmt.Errorf("child service %v of %v not a healthcheck.StatusUpdater (%T)", service.Name, serviceName, serviceHandler) } if err := updater.RegisterStatusUpdater(func(up bool) { balancer.SetStatus(ctx, service.Name, up) }); err != nil { return nil, fmt.Errorf("cannot register %v as updater for %v: %w", service.Name, serviceName, err) } log.Ctx(ctx).Debug().Str("parent", serviceName).Str("child", service.Name). Msg("Child service will update parent on status change") } return balancer, nil } type serverBalancer interface { http.Handler healthcheck.StatusSetter AddServer(name string, handler http.Handler, server dynamic.Server) } func (m *Manager) getLoadBalancerServiceHandler(ctx context.Context, serviceName string, info *runtime.ServiceInfo) (http.Handler, error) { service := info.LoadBalancer logger := log.Ctx(ctx) logger.Debug().Msg("Creating load-balancer") // TODO: should we keep this config value as Go is now handling stream response correctly? flushInterval := time.Duration(dynamic.DefaultFlushInterval) if service.ResponseForwarding != nil { flushInterval = time.Duration(service.ResponseForwarding.FlushInterval) } if len(service.ServersTransport) > 0 { service.ServersTransport = provider.GetQualifiedName(ctx, service.ServersTransport) } if service.Sticky != nil && service.Sticky.Cookie != nil { service.Sticky.Cookie.Name = cookie.GetName(service.Sticky.Cookie.Name, serviceName) } // We make sure that the PassHostHeader value is defined to avoid panics. passHostHeader := dynamic.DefaultPassHostHeader if service.PassHostHeader != nil { passHostHeader = *service.PassHostHeader } var lb serverBalancer switch service.Strategy { // Here we are handling the empty value to comply with providers that are not applying defaults (e.g. REST provider) // TODO: remove this empty check when all providers apply default values. case dynamic.BalancerStrategyWRR, "": lb = wrr.New(service.Sticky, service.HealthCheck != nil) case dynamic.BalancerStrategyP2C: lb = p2c.New(service.Sticky, service.HealthCheck != nil) case dynamic.BalancerStrategyHRW: lb = hrw.New(service.HealthCheck != nil) case dynamic.BalancerStrategyLeastTime: lb = leasttime.New(service.Sticky, service.HealthCheck != nil) default: return nil, fmt.Errorf("unsupported load-balancer strategy %q", service.Strategy) } var passiveHealthChecker *healthcheck.PassiveServiceHealthChecker if service.PassiveHealthCheck != nil { passiveHealthChecker = healthcheck.NewPassiveHealthChecker( serviceName, lb, service.PassiveHealthCheck.MaxFailedAttempts, service.PassiveHealthCheck.FailureWindow, service.HealthCheck != nil, m.observabilityMgr.MetricsRegistry()) } healthCheckTargets := make(map[string]*url.URL) for i, server := range shuffle(service.Servers, m.rand) { target, err := url.Parse(server.URL) if err != nil { return nil, fmt.Errorf("error parsing server URL %s: %w", server.URL, err) } logger.Debug().Int(logs.ServerIndex, i).Str("URL", server.URL). Msg("Creating server") qualifiedSvcName := provider.GetQualifiedName(ctx, serviceName) proxy, err := m.proxyBuilder.Build(service.ServersTransport, target, passHostHeader, server.PreservePath, flushInterval) if err != nil { return nil, fmt.Errorf("error building proxy for server URL %s: %w", server.URL, err) } if passiveHealthChecker != nil { // If passive health check is enabled, we wrap the proxy with the passive health checker. proxy = passiveHealthChecker.WrapHandler(ctx, proxy, target.String()) } // The retry wrapping must be done just before the proxy handler, // to make sure that the retry will not be triggered/disabled by // middlewares in the chain. proxy = retry.WrapHandler(proxy) // Access logs, metrics, and tracing middlewares are idempotent if the associated signal is disabled. proxy = accesslog.NewFieldHandler(proxy, accesslog.ServiceURL, target.String(), nil) proxy = accesslog.NewFieldHandler(proxy, accesslog.ServiceAddr, target.Host, nil) proxy = accesslog.NewFieldHandler(proxy, accesslog.ServiceName, qualifiedSvcName, accesslog.AddServiceFields) metricsHandler := metricsMiddle.ServiceMetricsHandler(ctx, m.observabilityMgr.MetricsRegistry(), qualifiedSvcName) metricsHandler = observability.WrapMiddleware(ctx, metricsHandler) proxy, err = alice.New(). Append(metricsHandler). Then(proxy) if err != nil { return nil, fmt.Errorf("error wrapping metrics handler: %w", err) } proxy = observability.NewService(ctx, qualifiedSvcName, proxy) lb.AddServer(server.URL, proxy, server) // Servers are considered UP by default. info.UpdateServerStatus(target.String(), runtime.StatusUp) healthCheckTargets[server.URL] = target } if service.HealthCheck != nil { roundTripper, err := m.transportManager.GetRoundTripper(service.ServersTransport) if err != nil { return nil, fmt.Errorf("getting RoundTripper: %w", err) } m.healthCheckers[serviceName] = healthcheck.NewServiceHealthChecker( ctx, m.observabilityMgr.MetricsRegistry(), service.HealthCheck, lb, info, roundTripper, healthCheckTargets, serviceName, ) } return lb, nil } // LaunchHealthCheck launches the health checks. func (m *Manager) LaunchHealthCheck(ctx context.Context) { for serviceName, hc := range m.healthCheckers { logger := log.Ctx(ctx).With().Str(logs.ServiceName, serviceName).Logger() go hc.Launch(logger.WithContext(ctx)) } } func shuffle[T any](values []T, r *rand.Rand) []T { shuffled := make([]T, len(values)) copy(shuffled, values) r.Shuffle(len(shuffled), func(i, j int) { shuffled[i], shuffled[j] = shuffled[j], shuffled[i] }) return shuffled }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/service_test.go
pkg/server/service/service_test.go
package service import ( "context" "crypto/tls" "io" "net/http" "net/http/httptest" "net/http/httptrace" "net/textproto" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/proxy/httputil" "github.com/traefik/traefik/v3/pkg/server/provider" "github.com/traefik/traefik/v3/pkg/testhelpers" ) func pointer[T any](v T) *T { return &v } func TestGetLoadBalancer(t *testing.T) { sm := Manager{ transportManager: &transportManagerMock{}, } testCases := []struct { desc string serviceName string service *dynamic.ServersLoadBalancer fwd http.Handler expectError bool }{ { desc: "Fails when provided an invalid URL", serviceName: "test", service: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: ":", }, }, }, fwd: &forwarderMock{}, expectError: true, }, { desc: "Succeeds when there are no servers", serviceName: "test", service: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, }, fwd: &forwarderMock{}, expectError: false, }, { desc: "Succeeds when sticky.cookie is set", serviceName: "test", service: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Sticky: &dynamic.Sticky{Cookie: &dynamic.Cookie{}}, }, fwd: &forwarderMock{}, expectError: false, }, { desc: "Succeeds when passive health checker is set", serviceName: "test", service: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassiveHealthCheck: &dynamic.PassiveServerHealthCheck{ FailureWindow: ptypes.Duration(30 * time.Second), MaxFailedAttempts: 3, }, }, fwd: &forwarderMock{}, expectError: false, }, { desc: "Fails when unsupported strategy is set", serviceName: "test", service: &dynamic.ServersLoadBalancer{ Strategy: "invalid", Servers: []dynamic.Server{ { URL: "http://localhost:8080", }, }, }, fwd: &forwarderMock{}, expectError: true, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() serviceInfo := &runtime.ServiceInfo{Service: &dynamic.Service{LoadBalancer: test.service}} handler, err := sm.getLoadBalancerServiceHandler(t.Context(), test.serviceName, serviceInfo) if test.expectError { require.Error(t, err) assert.Nil(t, handler) } else { require.NoError(t, err) assert.NotNil(t, handler) } }) } } func TestGetLoadBalancerServiceHandler(t *testing.T) { pb := httputil.NewProxyBuilder(&transportManagerMock{}, nil) sm := NewManager(nil, nil, nil, transportManagerMock{}, pb) server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-From", "first") })) t.Cleanup(server1.Close) server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-From", "second") })) t.Cleanup(server2.Close) serverPassHost := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-From", "passhost") assert.Equal(t, "callme", r.Host) })) t.Cleanup(serverPassHost.Close) serverPassHostFalse := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-From", "passhostfalse") assert.NotEqual(t, "callme", r.Host) })) t.Cleanup(serverPassHostFalse.Close) hasNoUserAgent := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Empty(t, r.Header.Get("User-Agent")) })) t.Cleanup(hasNoUserAgent.Close) hasUserAgent := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, "foobar", r.Header.Get("User-Agent")) })) t.Cleanup(hasUserAgent.Close) type ExpectedResult struct { StatusCode int XFrom string LoadBalanced bool SecureCookie bool HTTPOnlyCookie bool } testCases := []struct { desc string serviceName string service *dynamic.ServersLoadBalancer responseModifier func(*http.Response) error cookieRawValue string userAgent string expected []ExpectedResult }{ { desc: "Load balances between the two servers", serviceName: "test", service: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), Servers: []dynamic.Server{ { URL: server1.URL, }, { URL: server2.URL, }, }, }, expected: []ExpectedResult{ { StatusCode: http.StatusOK, LoadBalanced: true, }, { StatusCode: http.StatusOK, LoadBalanced: true, }, }, }, { desc: "StatusBadGateway when the server is not reachable", serviceName: "test", service: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://foo", }, }, }, expected: []ExpectedResult{ { StatusCode: http.StatusBadGateway, }, }, }, { desc: "ServiceUnavailable when no servers are available", serviceName: "test", service: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{}, }, expected: []ExpectedResult{ { StatusCode: http.StatusServiceUnavailable, }, }, }, { desc: "Always call the same server when sticky.cookie is true", serviceName: "test", service: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Sticky: &dynamic.Sticky{Cookie: &dynamic.Cookie{}}, Servers: []dynamic.Server{ { URL: server1.URL, }, { URL: server2.URL, }, }, }, expected: []ExpectedResult{ { StatusCode: http.StatusOK, }, { StatusCode: http.StatusOK, }, }, }, { desc: "Sticky Cookie's options set correctly", serviceName: "test", service: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Sticky: &dynamic.Sticky{Cookie: &dynamic.Cookie{HTTPOnly: true, Secure: true}}, Servers: []dynamic.Server{ { URL: server1.URL, }, }, }, expected: []ExpectedResult{ { StatusCode: http.StatusOK, XFrom: "first", SecureCookie: true, HTTPOnlyCookie: true, }, }, }, { desc: "PassHost passes the host instead of the IP", serviceName: "test", service: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Sticky: &dynamic.Sticky{Cookie: &dynamic.Cookie{}}, PassHostHeader: pointer(true), Servers: []dynamic.Server{ { URL: serverPassHost.URL, }, }, }, expected: []ExpectedResult{ { StatusCode: http.StatusOK, XFrom: "passhost", }, }, }, { desc: "PassHost doesn't pass the host instead of the IP", serviceName: "test", service: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(false), Sticky: &dynamic.Sticky{Cookie: &dynamic.Cookie{}}, Servers: []dynamic.Server{ { URL: serverPassHostFalse.URL, }, }, }, expected: []ExpectedResult{ { StatusCode: http.StatusOK, XFrom: "passhostfalse", }, }, }, { desc: "No user-agent", serviceName: "test", service: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: hasNoUserAgent.URL, }, }, }, expected: []ExpectedResult{ { StatusCode: http.StatusOK, }, }, }, { desc: "Custom user-agent", serviceName: "test", userAgent: "foobar", service: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: hasUserAgent.URL, }, }, }, expected: []ExpectedResult{ { StatusCode: http.StatusOK, }, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { serviceInfo := &runtime.ServiceInfo{Service: &dynamic.Service{LoadBalancer: test.service}} handler, err := sm.getLoadBalancerServiceHandler(t.Context(), test.serviceName, serviceInfo) assert.NoError(t, err) assert.NotNil(t, handler) req := testhelpers.MustNewRequest(http.MethodGet, "http://callme", nil) assert.Empty(t, req.Header.Get("User-Agent")) if test.userAgent != "" { req.Header.Set("User-Agent", test.userAgent) } if test.cookieRawValue != "" { req.Header.Set("Cookie", test.cookieRawValue) } var prevXFrom string for _, expected := range test.expected { recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, req) assert.Equal(t, expected.StatusCode, recorder.Code) if expected.XFrom != "" { assert.Equal(t, expected.XFrom, recorder.Header().Get("X-From")) } xFrom := recorder.Header().Get("X-From") if prevXFrom != "" { if expected.LoadBalanced { assert.NotEqual(t, prevXFrom, xFrom) } else { assert.Equal(t, prevXFrom, xFrom) } } prevXFrom = xFrom cookieHeader := recorder.Header().Get("Set-Cookie") if len(cookieHeader) > 0 { req.Header.Set("Cookie", cookieHeader) assert.Equal(t, expected.SecureCookie, strings.Contains(cookieHeader, "Secure")) assert.Equal(t, expected.HTTPOnlyCookie, strings.Contains(cookieHeader, "HttpOnly")) assert.NotContains(t, cookieHeader, "://") } } }) } } // This test is an adapted version of net/http/httputil.Test1xxResponses test. func Test1xxResponses(t *testing.T) { pb := httputil.NewProxyBuilder(&transportManagerMock{}, nil) sm := NewManager(nil, nil, nil, &transportManagerMock{}, pb) backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h := w.Header() h.Add("Link", "</style.css>; rel=preload; as=style") h.Add("Link", "</script.js>; rel=preload; as=script") w.WriteHeader(http.StatusEarlyHints) h.Add("Link", "</foo.js>; rel=preload; as=script") w.WriteHeader(http.StatusProcessing) _, _ = w.Write([]byte("Hello")) })) t.Cleanup(backend.Close) info := &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: backend.URL, }, }, }, }, } handler, err := sm.getLoadBalancerServiceHandler(t.Context(), "foobar", info) assert.NoError(t, err) frontend := httptest.NewServer(handler) t.Cleanup(frontend.Close) frontendClient := frontend.Client() checkLinkHeaders := func(t *testing.T, expected, got []string) { t.Helper() if len(expected) != len(got) { t.Errorf("Expected %d link headers; got %d", len(expected), len(got)) } for i := range expected { if i >= len(got) { t.Errorf("Expected %q link header; got nothing", expected[i]) continue } if expected[i] != got[i] { t.Errorf("Expected %q link header; got %q", expected[i], got[i]) } } } var respCounter uint8 trace := &httptrace.ClientTrace{ Got1xxResponse: func(code int, header textproto.MIMEHeader) error { switch code { case http.StatusEarlyHints: checkLinkHeaders(t, []string{"</style.css>; rel=preload; as=style", "</script.js>; rel=preload; as=script"}, header["Link"]) case http.StatusProcessing: checkLinkHeaders(t, []string{"</style.css>; rel=preload; as=style", "</script.js>; rel=preload; as=script", "</foo.js>; rel=preload; as=script"}, header["Link"]) default: t.Error("Unexpected 1xx response") } respCounter++ return nil }, } req, _ := http.NewRequestWithContext(httptrace.WithClientTrace(t.Context(), trace), http.MethodGet, frontend.URL, nil) res, err := frontendClient.Do(req) assert.NoError(t, err) defer res.Body.Close() if respCounter != 2 { t.Errorf("Expected 2 1xx responses; got %d", respCounter) } checkLinkHeaders(t, []string{"</style.css>; rel=preload; as=style", "</script.js>; rel=preload; as=script", "</foo.js>; rel=preload; as=script"}, res.Header["Link"]) body, _ := io.ReadAll(res.Body) if string(body) != "Hello" { t.Errorf("Read body %q; want Hello", body) } } func TestManager_ServiceBuilders(t *testing.T) { var internalHandler internalHandler manager := NewManager(map[string]*runtime.ServiceInfo{ "test@test": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, }, }, }, }, nil, nil, &TransportManager{ roundTrippers: map[string]http.RoundTripper{ "default@internal": http.DefaultTransport, }, }, nil, serviceBuilderFunc(func(rootCtx context.Context, serviceName string) (http.Handler, error) { if strings.HasSuffix(serviceName, "@internal") { return internalHandler, nil } return nil, nil })) h, err := manager.BuildHTTP(t.Context(), "test@internal") require.NoError(t, err) assert.Equal(t, internalHandler, h) h, err = manager.BuildHTTP(t.Context(), "test@test") require.NoError(t, err) assert.NotNil(t, h) _, err = manager.BuildHTTP(t.Context(), "wrong@test") assert.Error(t, err) } func TestManager_Build(t *testing.T) { testCases := []struct { desc string serviceName string configs map[string]*runtime.ServiceInfo providerName string }{ { desc: "Simple service name", serviceName: "serviceName", configs: map[string]*runtime.ServiceInfo{ "serviceName": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, }, }, }, }, }, { desc: "Service name with provider", serviceName: "serviceName@provider-1", configs: map[string]*runtime.ServiceInfo{ "serviceName@provider-1": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, }, }, }, }, }, { desc: "Service name with provider in context", serviceName: "serviceName", configs: map[string]*runtime.ServiceInfo{ "serviceName@provider-1": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, }, }, }, }, providerName: "provider-1", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() manager := NewManager(test.configs, nil, nil, &transportManagerMock{}, nil) ctx := t.Context() if len(test.providerName) > 0 { ctx = provider.AddInContext(ctx, "foobar@"+test.providerName) } _, err := manager.BuildHTTP(ctx, test.serviceName) require.NoError(t, err) }) } } func TestMultipleTypeOnBuildHTTP(t *testing.T) { services := map[string]*runtime.ServiceInfo{ "test@file": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{}, Weighted: &dynamic.WeightedRoundRobin{}, }, }, } manager := NewManager(services, nil, nil, &transportManagerMock{}, nil) _, err := manager.BuildHTTP(t.Context(), "test@file") assert.Error(t, err, "cannot create service: multi-types service not supported, consider declaring two different pieces of service instead") } func TestGetServiceHandler_Headers(t *testing.T) { pb := httputil.NewProxyBuilder(&transportManagerMock{}, nil) testCases := []struct { desc string service dynamic.WRRService userAgent string expectedHeaders map[string]string }{ { desc: "Service with custom headers", service: dynamic.WRRService{ Name: "target-service", Headers: map[string]string{ "X-Custom-Header": "custom-value", "X-Service-Type": "knative-service", "Authorization": "bearer token123", }, }, userAgent: "test-agent", expectedHeaders: map[string]string{ "X-Custom-Header": "custom-value", "X-Service-Type": "knative-service", "Authorization": "bearer token123", }, }, { desc: "Service with empty headers map", service: dynamic.WRRService{ Name: "target-service", Headers: map[string]string{}, }, userAgent: "test-agent", expectedHeaders: map[string]string{}, }, { desc: "Service with nil headers", service: dynamic.WRRService{ Name: "target-service", Headers: nil, }, userAgent: "test-agent", expectedHeaders: map[string]string{}, }, { desc: "Service with headers that override existing request headers", service: dynamic.WRRService{ Name: "target-service", Headers: map[string]string{ "User-Agent": "overridden-agent", "Accept": "application/json", }, }, userAgent: "original-agent", expectedHeaders: map[string]string{ "User-Agent": "overridden-agent", "Accept": "application/json", }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { // Create a test server that will verify the headers are properly set for this specific test case testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Verify expected headers are present for key, expectedValue := range test.expectedHeaders { actualValue := r.Header.Get(key) assert.Equal(t, expectedValue, actualValue, "Header %s should be %s", key, expectedValue) } w.Header().Set("X-Response", "success") w.WriteHeader(http.StatusOK) })) t.Cleanup(testServer.Close) // Create the target service that the WRRService will point to targetServiceInfo := &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ {URL: testServer.URL}, }, }, }, } // Create a fresh manager for each test case sm := NewManager(map[string]*runtime.ServiceInfo{ "target-service": targetServiceInfo, }, nil, nil, &transportManagerMock{}, pb) // Get the service handler handler, err := sm.getServiceHandler(t.Context(), test.service) require.NoError(t, err) require.NotNil(t, handler) // Create a test request req := testhelpers.MustNewRequest(http.MethodGet, "http://test.example.com/path", nil) if test.userAgent != "" { req.Header.Set("User-Agent", test.userAgent) } // Execute the request recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, req) // Verify the response was successful assert.Equal(t, http.StatusOK, recorder.Code) }) } } type serviceBuilderFunc func(ctx context.Context, serviceName string) (http.Handler, error) func (s serviceBuilderFunc) BuildHTTP(ctx context.Context, serviceName string) (http.Handler, error) { return s(ctx, serviceName) } type internalHandler struct{} func (internalHandler) ServeHTTP(_ http.ResponseWriter, _ *http.Request) {} type forwarderMock struct{} func (forwarderMock) ServeHTTP(http.ResponseWriter, *http.Request) { panic("not available") } type transportManagerMock struct{} func (t transportManagerMock) GetRoundTripper(_ string) (http.RoundTripper, error) { return &http.Transport{}, nil } func (t transportManagerMock) GetTLSConfig(_ string) (*tls.Config, error) { return nil, nil } func (t transportManagerMock) Get(_ string) (*dynamic.ServersTransport, error) { return &dynamic.ServersTransport{}, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/internalhandler.go
pkg/server/service/internalhandler.go
package service import ( "context" "errors" "fmt" "net/http" "strings" ) // InternalHandlers is the internal HTTP handlers builder. type InternalHandlers struct { api http.Handler dashboard http.Handler rest http.Handler prometheus http.Handler ping http.Handler acmeHTTP http.Handler } // NewInternalHandlers creates a new InternalHandlers. func NewInternalHandlers(apiHandler, rest, metricsHandler, pingHandler, dashboard, acmeHTTP http.Handler) *InternalHandlers { return &InternalHandlers{ api: apiHandler, dashboard: dashboard, rest: rest, prometheus: metricsHandler, ping: pingHandler, acmeHTTP: acmeHTTP, } } // BuildHTTP builds an HTTP handler. func (m *InternalHandlers) BuildHTTP(rootCtx context.Context, serviceName string) (http.Handler, error) { if !strings.HasSuffix(serviceName, "@internal") { return nil, nil } internalHandler, err := m.get(serviceName) if err != nil { return nil, err } return internalHandler, nil } func (m *InternalHandlers) get(serviceName string) (http.Handler, error) { switch serviceName { case "noop@internal": return http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.WriteHeader(http.StatusTeapot) }), nil case "acme-http@internal": if m.acmeHTTP == nil { return nil, errors.New("HTTP challenge is not enabled") } return m.acmeHTTP, nil case "api@internal": if m.api == nil { return nil, errors.New("api is not enabled") } return m.api, nil case "dashboard@internal": if m.dashboard == nil { return nil, errors.New("dashboard is not enabled") } return m.dashboard, nil case "rest@internal": if m.rest == nil { return nil, errors.New("rest is not enabled") } return m.rest, nil case "ping@internal": if m.ping == nil { return nil, errors.New("ping is not enabled") } return m.ping, nil case "prometheus@internal": if m.prometheus == nil { return nil, errors.New("prometheus is not enabled") } return m.prometheus, nil default: return nil, fmt.Errorf("unknown internal service %s", serviceName) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/smart_roundtripper.go
pkg/server/service/smart_roundtripper.go
package service import ( "crypto/tls" "net" "net/http" "time" "github.com/traefik/traefik/v3/pkg/config/dynamic" "golang.org/x/net/http/httpguts" "golang.org/x/net/http2" ) type h2cTransportWrapper struct { *http2.Transport } func (t *h2cTransportWrapper) RoundTrip(req *http.Request) (*http.Response, error) { req.URL.Scheme = "http" return t.Transport.RoundTrip(req) } func newSmartRoundTripper(transport *http.Transport, forwardingTimeouts *dynamic.ForwardingTimeouts) (*smartRoundTripper, error) { transportHTTP1 := transport.Clone() transportHTTP2, err := http2.ConfigureTransports(transport) if err != nil { return nil, err } if forwardingTimeouts != nil { transportHTTP2.ReadIdleTimeout = time.Duration(forwardingTimeouts.ReadIdleTimeout) transportHTTP2.PingTimeout = time.Duration(forwardingTimeouts.PingTimeout) } transportH2C := &h2cTransportWrapper{ Transport: &http2.Transport{ DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { return net.Dial(network, addr) }, AllowHTTP: true, }, } if forwardingTimeouts != nil { transportH2C.ReadIdleTimeout = time.Duration(forwardingTimeouts.ReadIdleTimeout) transportH2C.PingTimeout = time.Duration(forwardingTimeouts.PingTimeout) } transport.RegisterProtocol("h2c", transportH2C) return &smartRoundTripper{ http2: transport, http: transportHTTP1, }, nil } // smartRoundTripper implements RoundTrip while making sure that HTTP/2 is not used // with protocols that start with a Connection Upgrade, such as SPDY or Websocket. type smartRoundTripper struct { http2 *http.Transport http *http.Transport } func (m *smartRoundTripper) Clone() http.RoundTripper { h := m.http.Clone() h2 := m.http2.Clone() return &smartRoundTripper{http: h, http2: h2} } func (m *smartRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { // If we have a connection upgrade, we don't use HTTP/2 if httpguts.HeaderValuesContainsToken(req.Header["Connection"], "Upgrade") { return m.http.RoundTrip(req) } return m.http2.RoundTrip(req) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/transport.go
pkg/server/service/transport.go
package service import ( "context" "crypto/tls" "crypto/x509" "errors" "fmt" "net" "net/http" "reflect" "slices" "strings" "sync" "time" "github.com/rs/zerolog/log" "github.com/spiffe/go-spiffe/v2/bundle/x509bundle" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/spiffe/go-spiffe/v2/spiffetls/tlsconfig" "github.com/spiffe/go-spiffe/v2/svid/x509svid" "github.com/traefik/traefik/v3/pkg/config/dynamic" traefiktls "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" ) // SpiffeX509Source allows to retrieve a x509 SVID and bundle. type SpiffeX509Source interface { x509svid.Source x509bundle.Source } // TransportManager handles transports for backend communication. type TransportManager struct { rtLock sync.RWMutex roundTrippers map[string]http.RoundTripper configs map[string]*dynamic.ServersTransport tlsConfigs map[string]*tls.Config spiffeX509Source SpiffeX509Source } // NewTransportManager creates a new TransportManager. func NewTransportManager(spiffeX509Source SpiffeX509Source) *TransportManager { return &TransportManager{ roundTrippers: make(map[string]http.RoundTripper), configs: make(map[string]*dynamic.ServersTransport), tlsConfigs: make(map[string]*tls.Config), spiffeX509Source: spiffeX509Source, } } // Update updates the transport configurations. func (t *TransportManager) Update(newConfigs map[string]*dynamic.ServersTransport) { t.rtLock.Lock() defer t.rtLock.Unlock() for configName, config := range t.configs { newConfig, ok := newConfigs[configName] if !ok { delete(t.configs, configName) delete(t.roundTrippers, configName) delete(t.tlsConfigs, configName) continue } if reflect.DeepEqual(newConfig, config) { continue } var err error var tlsConfig *tls.Config if tlsConfig, err = t.createTLSConfig(newConfig); err != nil { log.Error().Err(err).Msgf("Could not configure HTTP Transport %s TLS configuration, fallback on default TLS config", configName) } t.tlsConfigs[configName] = tlsConfig t.roundTrippers[configName], err = t.createRoundTripper(newConfig, tlsConfig) if err != nil { log.Error().Err(err).Msgf("Could not configure HTTP Transport %s, fallback on default transport", configName) t.roundTrippers[configName] = http.DefaultTransport } } for newConfigName, newConfig := range newConfigs { if _, ok := t.configs[newConfigName]; ok { continue } var err error var tlsConfig *tls.Config if tlsConfig, err = t.createTLSConfig(newConfig); err != nil { log.Error().Err(err).Msgf("Could not configure HTTP Transport %s TLS configuration, fallback on default TLS config", newConfigName) } t.tlsConfigs[newConfigName] = tlsConfig t.roundTrippers[newConfigName], err = t.createRoundTripper(newConfig, tlsConfig) if err != nil { log.Error().Err(err).Msgf("Could not configure HTTP Transport %s, fallback on default transport", newConfigName) t.roundTrippers[newConfigName] = http.DefaultTransport } } t.configs = newConfigs } // GetRoundTripper gets a roundtripper corresponding to the given transport name. func (t *TransportManager) GetRoundTripper(name string) (http.RoundTripper, error) { if len(name) == 0 { name = "default@internal" } t.rtLock.RLock() defer t.rtLock.RUnlock() if rt, ok := t.roundTrippers[name]; ok { return rt, nil } return nil, fmt.Errorf("servers transport not found %s", name) } // Get gets transport by name. func (t *TransportManager) Get(name string) (*dynamic.ServersTransport, error) { if len(name) == 0 { name = "default@internal" } t.rtLock.RLock() defer t.rtLock.RUnlock() if rt, ok := t.configs[name]; ok { return rt, nil } return nil, fmt.Errorf("servers transport not found %s", name) } // GetTLSConfig gets a TLS config corresponding to the given transport name. func (t *TransportManager) GetTLSConfig(name string) (*tls.Config, error) { if len(name) == 0 { name = "default@internal" } t.rtLock.RLock() defer t.rtLock.RUnlock() if rt, ok := t.tlsConfigs[name]; ok { return rt, nil } return nil, fmt.Errorf("tls config not found %s", name) } func (t *TransportManager) createTLSConfig(cfg *dynamic.ServersTransport) (*tls.Config, error) { var config *tls.Config if cfg.Spiffe != nil { if t.spiffeX509Source == nil { return nil, errors.New("SPIFFE is enabled for this transport, but not configured") } spiffeAuthorizer, err := buildSpiffeAuthorizer(cfg.Spiffe) if err != nil { return nil, fmt.Errorf("unable to build SPIFFE authorizer: %w", err) } config = tlsconfig.MTLSClientConfig(t.spiffeX509Source, t.spiffeX509Source, spiffeAuthorizer) } if cfg.InsecureSkipVerify || len(cfg.RootCAs) > 0 || len(cfg.ServerName) > 0 || len(cfg.Certificates) > 0 || cfg.PeerCertURI != "" { if config != nil { return nil, errors.New("TLS and SPIFFE configuration cannot be defined at the same time") } config = &tls.Config{ ServerName: cfg.ServerName, InsecureSkipVerify: cfg.InsecureSkipVerify, RootCAs: createRootCACertPool(cfg.RootCAs), Certificates: cfg.Certificates.GetCertificates(), } if cfg.PeerCertURI != "" { config.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error { return traefiktls.VerifyPeerCertificate(cfg.PeerCertURI, config, rawCerts) } } } return config, nil } // createRoundTripper creates an http.RoundTripper configured with the Transport configuration settings. // For the settings that can't be configured in Traefik it uses the default http.Transport settings. // An exception to this is the MaxIdleConns setting as we only provide the option MaxIdleConnsPerHost in Traefik at this point in time. // Setting this value to the default of 100 could lead to confusing behavior and backwards compatibility issues. func (t *TransportManager) createRoundTripper(cfg *dynamic.ServersTransport, tlsConfig *tls.Config) (http.RoundTripper, error) { if cfg == nil { return nil, errors.New("no transport configuration given") } dialer := &net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, } if cfg.ForwardingTimeouts != nil { dialer.Timeout = time.Duration(cfg.ForwardingTimeouts.DialTimeout) } transport := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: dialer.DialContext, MaxIdleConnsPerHost: cfg.MaxIdleConnsPerHost, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, ReadBufferSize: 64 * 1024, WriteBufferSize: 64 * 1024, TLSClientConfig: tlsConfig, } if cfg.ForwardingTimeouts != nil { transport.ResponseHeaderTimeout = time.Duration(cfg.ForwardingTimeouts.ResponseHeaderTimeout) transport.IdleConnTimeout = time.Duration(cfg.ForwardingTimeouts.IdleConnTimeout) } // Return directly HTTP/1.1 transport when HTTP/2 is disabled if cfg.DisableHTTP2 { return &kerberosRoundTripper{ OriginalRoundTripper: transport, new: func() http.RoundTripper { return transport.Clone() }, }, nil } rt, err := newSmartRoundTripper(transport, cfg.ForwardingTimeouts) if err != nil { return nil, err } return &kerberosRoundTripper{ OriginalRoundTripper: rt, new: func() http.RoundTripper { return rt.Clone() }, }, nil } type stickyRoundTripper struct { RoundTripper http.RoundTripper } type transportKeyType string var transportKey transportKeyType = "transport" func AddTransportOnContext(ctx context.Context) context.Context { return context.WithValue(ctx, transportKey, &stickyRoundTripper{}) } type kerberosRoundTripper struct { new func() http.RoundTripper OriginalRoundTripper http.RoundTripper } func (k *kerberosRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) { value, ok := request.Context().Value(transportKey).(*stickyRoundTripper) if !ok { return k.OriginalRoundTripper.RoundTrip(request) } if value.RoundTripper != nil { return value.RoundTripper.RoundTrip(request) } resp, err := k.OriginalRoundTripper.RoundTrip(request) // If we found that we are authenticating with Kerberos (Negotiate) or NTLM. // We put a dedicated roundTripper in the ConnContext. // This will stick the next calls to the same connection with the backend. if err == nil && containsNTLMorNegotiate(resp.Header.Values("WWW-Authenticate")) { value.RoundTripper = k.new() } return resp, err } func containsNTLMorNegotiate(h []string) bool { return slices.ContainsFunc(h, func(s string) bool { return strings.HasPrefix(s, "NTLM") || strings.HasPrefix(s, "Negotiate") }) } func createRootCACertPool(rootCAs []types.FileOrContent) *x509.CertPool { if len(rootCAs) == 0 { return nil } roots := x509.NewCertPool() for _, cert := range rootCAs { certContent, err := cert.Read() if err != nil { log.Error().Err(err).Msg("Error while read RootCAs") continue } roots.AppendCertsFromPEM(certContent) } return roots } func buildSpiffeAuthorizer(cfg *dynamic.Spiffe) (tlsconfig.Authorizer, error) { switch { case len(cfg.IDs) > 0: spiffeIDs := make([]spiffeid.ID, 0, len(cfg.IDs)) for _, rawID := range cfg.IDs { id, err := spiffeid.FromString(rawID) if err != nil { return nil, fmt.Errorf("invalid SPIFFE ID: %w", err) } spiffeIDs = append(spiffeIDs, id) } return tlsconfig.AuthorizeOneOf(spiffeIDs...), nil case cfg.TrustDomain != "": trustDomain, err := spiffeid.TrustDomainFromString(cfg.TrustDomain) if err != nil { return nil, fmt.Errorf("invalid SPIFFE trust domain: %w", err) } return tlsconfig.AuthorizeMemberOf(trustDomain), nil default: return tlsconfig.AuthorizeAny(), nil } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/tcp/service.go
pkg/server/service/tcp/service.go
package tcp import ( "context" "errors" "fmt" "maps" "math/rand" "net" "slices" "time" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/healthcheck" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/server/provider" "github.com/traefik/traefik/v3/pkg/tcp" ) // Manager is the TCPHandlers factory. type Manager struct { dialerManager *tcp.DialerManager configs map[string]*runtime.TCPServiceInfo rand *rand.Rand // For the initial shuffling of load-balancers. healthCheckers map[string]*healthcheck.ServiceTCPHealthChecker } // NewManager creates a new manager. func NewManager(conf *runtime.Configuration, dialerManager *tcp.DialerManager) *Manager { return &Manager{ dialerManager: dialerManager, healthCheckers: make(map[string]*healthcheck.ServiceTCPHealthChecker), configs: conf.TCPServices, rand: rand.New(rand.NewSource(time.Now().UnixNano())), } } // BuildTCP Creates a tcp.Handler for a service configuration. func (m *Manager) BuildTCP(rootCtx context.Context, serviceName string) (tcp.Handler, error) { serviceQualifiedName := provider.GetQualifiedName(rootCtx, serviceName) logger := log.Ctx(rootCtx).With().Str(logs.ServiceName, serviceQualifiedName).Logger() ctx := provider.AddInContext(rootCtx, serviceQualifiedName) conf, ok := m.configs[serviceQualifiedName] if !ok { return nil, fmt.Errorf("the service %q does not exist", serviceQualifiedName) } if conf.LoadBalancer != nil && conf.Weighted != nil { err := errors.New("cannot create service: multi-types service not supported, consider declaring two different pieces of service instead") conf.AddError(err, true) return nil, err } switch { case conf.LoadBalancer != nil: loadBalancer := tcp.NewWRRLoadBalancer(conf.LoadBalancer.HealthCheck != nil) if conf.LoadBalancer.TerminationDelay != nil { log.Ctx(ctx).Warn().Msgf("Service %q load balancer uses `TerminationDelay`, but this option is deprecated, please use ServersTransport configuration instead.", serviceName) } if conf.LoadBalancer.ProxyProtocol != nil { log.Ctx(ctx).Warn().Msgf("Service %q load balancer uses `ProxyProtocol`, but this option is deprecated, please use ServersTransport configuration instead.", serviceName) } if len(conf.LoadBalancer.ServersTransport) > 0 { conf.LoadBalancer.ServersTransport = provider.GetQualifiedName(ctx, conf.LoadBalancer.ServersTransport) } uniqHealthCheckTargets := make(map[string]healthcheck.TCPHealthCheckTarget, len(conf.LoadBalancer.Servers)) for index, server := range shuffle(conf.LoadBalancer.Servers, m.rand) { srvLogger := logger.With(). Int(logs.ServerIndex, index). Str("serverAddress", server.Address).Logger() if _, _, err := net.SplitHostPort(server.Address); err != nil { srvLogger.Error().Err(err).Msg("Failed to split host port") continue } dialer, err := m.dialerManager.Build(conf.LoadBalancer, server.TLS) if err != nil { return nil, err } handler, err := tcp.NewProxy(server.Address, dialer) if err != nil { srvLogger.Error().Err(err).Msg("Failed to create server") continue } loadBalancer.Add(server.Address, handler, nil) // Servers are considered UP by default. conf.UpdateServerStatus(server.Address, runtime.StatusUp) uniqHealthCheckTargets[server.Address] = healthcheck.TCPHealthCheckTarget{ Address: server.Address, TLS: server.TLS, Dialer: dialer, } logger.Debug().Msg("Creating TCP server") } if conf.LoadBalancer.HealthCheck != nil { m.healthCheckers[serviceName] = healthcheck.NewServiceTCPHealthChecker( ctx, conf.LoadBalancer.HealthCheck, loadBalancer, conf, slices.Collect(maps.Values(uniqHealthCheckTargets)), serviceQualifiedName) } return loadBalancer, nil case conf.Weighted != nil: loadBalancer := tcp.NewWRRLoadBalancer(conf.Weighted.HealthCheck != nil) for _, service := range shuffle(conf.Weighted.Services, m.rand) { handler, err := m.BuildTCP(ctx, service.Name) if err != nil { logger.Error().Err(err).Msg("Failed to build TCP handler") return nil, err } loadBalancer.Add(service.Name, handler, service.Weight) if conf.Weighted.HealthCheck == nil { continue } updater, ok := handler.(healthcheck.StatusUpdater) if !ok { return nil, fmt.Errorf("child service %v of %v not a healthcheck.StatusUpdater (%T)", service.Name, serviceName, handler) } if err := updater.RegisterStatusUpdater(func(up bool) { loadBalancer.SetStatus(ctx, service.Name, up) }); err != nil { return nil, fmt.Errorf("cannot register %v as updater for %v: %w", service.Name, serviceName, err) } log.Ctx(ctx).Debug().Str("parent", serviceName).Str("child", service.Name). Msg("Child service will update parent on status change") } return loadBalancer, nil default: err := fmt.Errorf("the service %q does not have any type defined", serviceQualifiedName) conf.AddError(err, true) return nil, err } } // LaunchHealthCheck launches the health checks. func (m *Manager) LaunchHealthCheck(ctx context.Context) { for serviceName, hc := range m.healthCheckers { logger := log.Ctx(ctx).With().Str(logs.ServiceName, serviceName).Logger() go hc.Launch(logger.WithContext(ctx)) } } func shuffle[T any](values []T, r *rand.Rand) []T { shuffled := make([]T, len(values)) copy(shuffled, values) r.Shuffle(len(shuffled), func(i, j int) { shuffled[i], shuffled[j] = shuffled[j], shuffled[i] }) return shuffled }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/tcp/service_test.go
pkg/server/service/tcp/service_test.go
package tcp import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/server/provider" "github.com/traefik/traefik/v3/pkg/tcp" ) func TestManager_BuildTCP(t *testing.T) { testCases := []struct { desc string serviceName string configs map[string]*runtime.TCPServiceInfo stConfigs map[string]*dynamic.TCPServersTransport providerName string expectedError string }{ { desc: "without configuration", serviceName: "test", configs: nil, expectedError: `the service "test" does not exist`, }, { desc: "missing lb configuration", serviceName: "test", configs: map[string]*runtime.TCPServiceInfo{ "test": { TCPService: &dynamic.TCPService{}, }, }, expectedError: `the service "test" does not have any type defined`, }, { desc: "no such host, server is skipped, error is logged", serviceName: "test", stConfigs: map[string]*dynamic.TCPServersTransport{"default@internal": {}}, configs: map[string]*runtime.TCPServiceInfo{ "test": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ {Address: "test:31"}, }, }, }, }, }, }, { desc: "invalid IP address, server is skipped, error is logged", serviceName: "test", configs: map[string]*runtime.TCPServiceInfo{ "test": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ {Address: "foobar"}, }, }, }, }, }, }, { desc: "Simple service name", serviceName: "serviceName", configs: map[string]*runtime.TCPServiceInfo{ "serviceName": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{}, }, }, }, }, { desc: "Service name with provider", serviceName: "serviceName@provider-1", configs: map[string]*runtime.TCPServiceInfo{ "serviceName@provider-1": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{}, }, }, }, }, { desc: "Service name with provider in context", serviceName: "serviceName", configs: map[string]*runtime.TCPServiceInfo{ "serviceName@provider-1": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{}, }, }, }, providerName: "provider-1", }, { desc: "Server with correct host:port as address", serviceName: "serviceName", stConfigs: map[string]*dynamic.TCPServersTransport{"default@internal": {}}, configs: map[string]*runtime.TCPServiceInfo{ "serviceName@provider-1": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "foobar.com:80", }, }, }, }, }, }, providerName: "provider-1", }, { desc: "Server with correct ip:port as address", serviceName: "serviceName", stConfigs: map[string]*dynamic.TCPServersTransport{"default@internal": {}}, configs: map[string]*runtime.TCPServiceInfo{ "serviceName@provider-1": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "192.168.0.12:80", }, }, }, }, }, }, providerName: "provider-1", }, { desc: "empty server address, server is skipped, error is logged", serviceName: "serviceName", configs: map[string]*runtime.TCPServiceInfo{ "serviceName@provider-1": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "", }, }, }, }, }, }, providerName: "provider-1", }, { desc: "missing port in address with hostname, server is skipped, error is logged", serviceName: "serviceName", configs: map[string]*runtime.TCPServiceInfo{ "serviceName@provider-1": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "foobar.com", }, }, }, }, }, }, providerName: "provider-1", }, { desc: "missing port in address with ip, server is skipped, error is logged", serviceName: "serviceName", configs: map[string]*runtime.TCPServiceInfo{ "serviceName@provider-1": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "192.168.0.12", }, }, }, }, }, }, providerName: "provider-1", }, { desc: "user defined serversTransport reference", serviceName: "serviceName", stConfigs: map[string]*dynamic.TCPServersTransport{"myServersTransport@provider-1": {}}, configs: map[string]*runtime.TCPServiceInfo{ "serviceName@provider-1": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "192.168.0.12:80", }, }, ServersTransport: "myServersTransport@provider-1", }, }, }, }, providerName: "provider-1", }, { desc: "user defined serversTransport reference not found", serviceName: "serviceName", configs: map[string]*runtime.TCPServiceInfo{ "serviceName@provider-1": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "192.168.0.12:80", }, }, ServersTransport: "myServersTransport@provider-1", }, }, }, }, providerName: "provider-1", expectedError: "no transport configuration found for \"myServersTransport@provider-1\"", }, { desc: "WRR with healthcheck enabled", stConfigs: map[string]*dynamic.TCPServersTransport{"default@internal": {}}, serviceName: "serviceName", configs: map[string]*runtime.TCPServiceInfo{ "serviceName@provider-1": { TCPService: &dynamic.TCPService{ Weighted: &dynamic.TCPWeightedRoundRobin{ Services: []dynamic.TCPWRRService{ {Name: "foobar@provider-1", Weight: new(int)}, {Name: "foobar2@provider-1", Weight: new(int)}, }, HealthCheck: &dynamic.HealthCheck{}, }, }, }, "foobar@provider-1": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "192.168.0.12:80", }, }, HealthCheck: &dynamic.TCPServerHealthCheck{}, }, }, }, "foobar2@provider-1": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "192.168.0.13:80", }, }, HealthCheck: &dynamic.TCPServerHealthCheck{}, }, }, }, }, providerName: "provider-1", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() dialerManager := tcp.NewDialerManager(nil) if test.stConfigs != nil { dialerManager.Update(test.stConfigs) } manager := NewManager(&runtime.Configuration{ TCPServices: test.configs, }, dialerManager) ctx := t.Context() if len(test.providerName) > 0 { ctx = provider.AddInContext(ctx, "foobar@"+test.providerName) } handler, err := manager.BuildTCP(ctx, test.serviceName) if test.expectedError != "" { assert.EqualError(t, err, test.expectedError) require.Nil(t, handler) } else { assert.NoError(t, err) require.NotNil(t, handler) } }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/udp/service.go
pkg/server/service/udp/service.go
package udp import ( "context" "errors" "fmt" "math/rand" "net" "time" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/server/provider" "github.com/traefik/traefik/v3/pkg/udp" ) // Manager handles UDP services creation. type Manager struct { configs map[string]*runtime.UDPServiceInfo rand *rand.Rand // For the initial shuffling of load-balancers. } // NewManager creates a new manager. func NewManager(conf *runtime.Configuration) *Manager { return &Manager{ configs: conf.UDPServices, rand: rand.New(rand.NewSource(time.Now().UnixNano())), } } // BuildUDP creates the UDP handler for the given service name. func (m *Manager) BuildUDP(rootCtx context.Context, serviceName string) (udp.Handler, error) { serviceQualifiedName := provider.GetQualifiedName(rootCtx, serviceName) logger := log.Ctx(rootCtx).With().Str(logs.ServiceName, serviceQualifiedName).Logger() ctx := provider.AddInContext(rootCtx, serviceQualifiedName) conf, ok := m.configs[serviceQualifiedName] if !ok { return nil, fmt.Errorf("the UDP service %q does not exist", serviceQualifiedName) } if conf.LoadBalancer != nil && conf.Weighted != nil { err := errors.New("cannot create service: multi-types service not supported, consider declaring two different pieces of service instead") conf.AddError(err, true) return nil, err } switch { case conf.LoadBalancer != nil: loadBalancer := udp.NewWRRLoadBalancer() for index, server := range shuffle(conf.LoadBalancer.Servers, m.rand) { srvLogger := logger.With(). Int(logs.ServerIndex, index). Str("serverAddress", server.Address).Logger() if _, _, err := net.SplitHostPort(server.Address); err != nil { srvLogger.Error().Err(err).Msg("Failed to split host port") continue } handler, err := udp.NewProxy(server.Address) if err != nil { srvLogger.Error().Err(err).Msg("Failed to create server") continue } loadBalancer.AddServer(handler) srvLogger.Debug().Msg("Creating UDP server") } return loadBalancer, nil case conf.Weighted != nil: loadBalancer := udp.NewWRRLoadBalancer() for _, service := range shuffle(conf.Weighted.Services, m.rand) { handler, err := m.BuildUDP(ctx, service.Name) if err != nil { logger.Error().Err(err).Msg("Failed to build UDP handler") return nil, err } loadBalancer.AddWeightedServer(handler, service.Weight) } return loadBalancer, nil default: err := fmt.Errorf("the UDP service %q does not have any type defined", serviceQualifiedName) conf.AddError(err, true) return nil, err } } func shuffle[T any](values []T, r *rand.Rand) []T { shuffled := make([]T, len(values)) copy(shuffled, values) r.Shuffle(len(shuffled), func(i, j int) { shuffled[i], shuffled[j] = shuffled[j], shuffled[i] }) return shuffled }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/udp/service_test.go
pkg/server/service/udp/service_test.go
package udp import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/server/provider" ) func TestManager_BuildUDP(t *testing.T) { testCases := []struct { desc string serviceName string configs map[string]*runtime.UDPServiceInfo providerName string expectedError string }{ { desc: "without configuration", serviceName: "test", configs: nil, expectedError: `the UDP service "test" does not exist`, }, { desc: "missing lb configuration", serviceName: "test", configs: map[string]*runtime.UDPServiceInfo{ "test": { UDPService: &dynamic.UDPService{}, }, }, expectedError: `the UDP service "test" does not have any type defined`, }, { desc: "no such host, server is skipped, error is logged", serviceName: "test", configs: map[string]*runtime.UDPServiceInfo{ "test": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ {Address: "test:31"}, }, }, }, }, }, }, { desc: "invalid IP address, server is skipped, error is logged", serviceName: "test", configs: map[string]*runtime.UDPServiceInfo{ "test": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ {Address: "foobar"}, }, }, }, }, }, }, { desc: "Simple service name", serviceName: "serviceName", configs: map[string]*runtime.UDPServiceInfo{ "serviceName": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{}, }, }, }, }, { desc: "Service name with provider", serviceName: "serviceName@provider-1", configs: map[string]*runtime.UDPServiceInfo{ "serviceName@provider-1": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{}, }, }, }, }, { desc: "Service name with provider in context", serviceName: "serviceName", configs: map[string]*runtime.UDPServiceInfo{ "serviceName@provider-1": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{}, }, }, }, providerName: "provider-1", }, { desc: "Server with correct host:port as address", serviceName: "serviceName", configs: map[string]*runtime.UDPServiceInfo{ "serviceName@provider-1": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "foobar.com:80", }, }, }, }, }, }, providerName: "provider-1", }, { desc: "Server with correct ip:port as address", serviceName: "serviceName", configs: map[string]*runtime.UDPServiceInfo{ "serviceName@provider-1": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "192.168.0.12:80", }, }, }, }, }, }, providerName: "provider-1", }, { desc: "missing port in address with hostname, server is skipped, error is logged", serviceName: "serviceName", configs: map[string]*runtime.UDPServiceInfo{ "serviceName@provider-1": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "foobar.com", }, }, }, }, }, }, providerName: "provider-1", }, { desc: "missing port in address with ip, server is skipped, error is logged", serviceName: "serviceName", configs: map[string]*runtime.UDPServiceInfo{ "serviceName@provider-1": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "192.168.0.12", }, }, }, }, }, }, providerName: "provider-1", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() manager := NewManager(&runtime.Configuration{ UDPServices: test.configs, }) ctx := t.Context() if len(test.providerName) > 0 { ctx = provider.AddInContext(ctx, "foobar@"+test.providerName) } handler, err := manager.BuildUDP(ctx, test.serviceName) if test.expectedError != "" { assert.EqualError(t, err, test.expectedError) require.Nil(t, handler) } else { assert.NoError(t, err) require.NotNil(t, handler) } }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/loadbalancer/sticky_test.go
pkg/server/service/loadbalancer/sticky_test.go
package loadbalancer import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) func pointer[T any](v T) *T { return &v } func TestSticky_StickyHandler(t *testing.T) { testCases := []struct { desc string handlers []string cookies []*http.Cookie wantHandler string wantRewrite bool }{ { desc: "No previous cookie", handlers: []string{"first"}, wantHandler: "", wantRewrite: false, }, { desc: "Wrong previous cookie", handlers: []string{"first"}, cookies: []*http.Cookie{ {Name: "test", Value: sha256Hash("foo")}, }, wantHandler: "", wantRewrite: false, }, { desc: "Sha256 previous cookie", handlers: []string{"first", "second"}, cookies: []*http.Cookie{ {Name: "test", Value: sha256Hash("first")}, }, wantHandler: "first", wantRewrite: false, }, { desc: "Raw previous cookie", handlers: []string{"first", "second"}, cookies: []*http.Cookie{ {Name: "test", Value: "first"}, }, wantHandler: "first", wantRewrite: true, }, { desc: "Fnv previous cookie", handlers: []string{"first", "second"}, cookies: []*http.Cookie{ {Name: "test", Value: fnvHash("first")}, }, wantHandler: "first", wantRewrite: true, }, { desc: "Double fnv previous cookie", handlers: []string{"first", "second"}, cookies: []*http.Cookie{ {Name: "test", Value: fnvHash("first")}, }, wantHandler: "first", wantRewrite: true, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() sticky := NewSticky(dynamic.Cookie{Name: "test"}) for _, handler := range test.handlers { sticky.AddHandler(handler, http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {})) } req := httptest.NewRequest(http.MethodGet, "/", nil) for _, cookie := range test.cookies { req.AddCookie(cookie) } h, rewrite, err := sticky.StickyHandler(req) require.NoError(t, err) if test.wantHandler != "" { assert.NotNil(t, h) assert.Equal(t, test.wantHandler, h.Name) } else { assert.Nil(t, h) } assert.Equal(t, test.wantRewrite, rewrite) }) } } func TestSticky_WriteStickyCookie(t *testing.T) { sticky := NewSticky(dynamic.Cookie{ Name: "test", Secure: true, HTTPOnly: true, SameSite: "none", MaxAge: 42, Path: pointer("/foo"), Domain: "foo.com", }) // Should return an error if the handler does not exist. res := httptest.NewRecorder() require.Error(t, sticky.WriteStickyCookie(res, "first")) // Should write the sticky cookie and use the sha256 hash. sticky.AddHandler("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {})) res = httptest.NewRecorder() require.NoError(t, sticky.WriteStickyCookie(res, "first")) assert.Len(t, res.Result().Cookies(), 1) cookie := res.Result().Cookies()[0] assert.Equal(t, sha256Hash("first"), cookie.Value) assert.Equal(t, "test", cookie.Name) assert.True(t, cookie.Secure) assert.True(t, cookie.HttpOnly) assert.Equal(t, http.SameSiteNoneMode, cookie.SameSite) assert.Equal(t, 42, cookie.MaxAge) assert.Equal(t, "/foo", cookie.Path) assert.Equal(t, "foo.com", cookie.Domain) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/loadbalancer/sticky.go
pkg/server/service/loadbalancer/sticky.go
package loadbalancer import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "hash/fnv" "net/http" "strconv" "sync" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) // NamedHandler is a http.Handler with a name. type NamedHandler struct { http.Handler Name string } // stickyCookie represents a sticky cookie. type stickyCookie struct { name string secure bool httpOnly bool sameSite http.SameSite maxAge int path string domain string } // Sticky ensures that client consistently interacts with the same HTTP handler by adding a sticky cookie to the response. // This cookie allows subsequent requests from the same client to be routed to the same handler, // enabling session persistence across multiple requests. type Sticky struct { // cookie is the sticky cookie configuration. cookie *stickyCookie // References all the handlers by name and also by the hashed value of the name. handlersMu sync.RWMutex hashMap map[string]string stickyMap map[string]*NamedHandler compatibilityStickyMap map[string]*NamedHandler } // NewSticky creates a new Sticky instance. func NewSticky(cookieConfig dynamic.Cookie) *Sticky { cookie := &stickyCookie{ name: cookieConfig.Name, secure: cookieConfig.Secure, httpOnly: cookieConfig.HTTPOnly, sameSite: convertSameSite(cookieConfig.SameSite), maxAge: cookieConfig.MaxAge, path: "/", domain: cookieConfig.Domain, } if cookieConfig.Path != nil { cookie.path = *cookieConfig.Path } return &Sticky{ cookie: cookie, hashMap: make(map[string]string), stickyMap: make(map[string]*NamedHandler), compatibilityStickyMap: make(map[string]*NamedHandler), } } // AddHandler adds a http.Handler to the sticky pool. func (s *Sticky) AddHandler(name string, h http.Handler) { s.handlersMu.Lock() defer s.handlersMu.Unlock() sha256HashedName := sha256Hash(name) s.hashMap[name] = sha256HashedName handler := &NamedHandler{ Handler: h, Name: name, } s.stickyMap[sha256HashedName] = handler s.compatibilityStickyMap[name] = handler hashedName := fnvHash(name) s.compatibilityStickyMap[hashedName] = handler // server.URL was fnv hashed in service.Manager // so we can have "double" fnv hash in already existing cookies hashedName = fnvHash(hashedName) s.compatibilityStickyMap[hashedName] = handler } // StickyHandler returns the NamedHandler corresponding to the sticky cookie if one. // It also returns a boolean which indicates if the sticky cookie has to be overwritten because it uses a deprecated hash algorithm. func (s *Sticky) StickyHandler(req *http.Request) (*NamedHandler, bool, error) { cookie, err := req.Cookie(s.cookie.name) if err != nil && errors.Is(err, http.ErrNoCookie) { return nil, false, nil } if err != nil { return nil, false, fmt.Errorf("reading cookie: %w", err) } s.handlersMu.RLock() handler, ok := s.stickyMap[cookie.Value] s.handlersMu.RUnlock() if ok && handler != nil { return handler, false, nil } s.handlersMu.RLock() handler, ok = s.compatibilityStickyMap[cookie.Value] s.handlersMu.RUnlock() return handler, ok, nil } // WriteStickyCookie writes a sticky cookie to the response to stick the client to the given handler name. func (s *Sticky) WriteStickyCookie(rw http.ResponseWriter, name string) error { s.handlersMu.RLock() hash, ok := s.hashMap[name] s.handlersMu.RUnlock() if !ok { return fmt.Errorf("no hash found for handler named %s", name) } cookie := &http.Cookie{ Name: s.cookie.name, Value: hash, Path: s.cookie.path, Domain: s.cookie.domain, HttpOnly: s.cookie.httpOnly, Secure: s.cookie.secure, SameSite: s.cookie.sameSite, MaxAge: s.cookie.maxAge, } http.SetCookie(rw, cookie) return nil } func convertSameSite(sameSite string) http.SameSite { switch sameSite { case "none": return http.SameSiteNoneMode case "lax": return http.SameSiteLaxMode case "strict": return http.SameSiteStrictMode default: return http.SameSiteDefaultMode } } // fnvHash returns the FNV-64 hash of the input string. func fnvHash(input string) string { hasher := fnv.New64() // We purposely ignore the error because the implementation always returns nil. _, _ = hasher.Write([]byte(input)) return strconv.FormatUint(hasher.Sum64(), 16) } // sha256 returns the SHA-256 hash, truncated to 16 characters, of the input string. func sha256Hash(input string) string { hash := sha256.New() // We purposely ignore the error because the implementation always returns nil. _, _ = hash.Write([]byte(input)) hashedInput := hex.EncodeToString(hash.Sum(nil)) if len(hashedInput) < 16 { return hashedInput } return hashedInput[:16] }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/loadbalancer/wrr/wrr.go
pkg/server/service/loadbalancer/wrr/wrr.go
package wrr import ( "container/heap" "context" "errors" "net/http" "sync" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/server/service/loadbalancer" ) var errNoAvailableServer = errors.New("no available server") type namedHandler struct { http.Handler name string weight float64 deadline float64 } // Balancer is a WeightedRoundRobin load balancer based on Earliest Deadline First (EDF). // (https://en.wikipedia.org/wiki/Earliest_deadline_first_scheduling) // Each pick from the schedule has the earliest deadline entry selected. // Entries have deadlines set at currentDeadline + 1 / weight, // providing weighted round-robin behavior with floating point weights and an O(log n) pick time. type Balancer struct { wantsHealthCheck bool // handlersMu is a mutex to protect the handlers slice, the status and the fenced maps. handlersMu sync.RWMutex handlers []*namedHandler // status is a record of which child services of the Balancer are healthy, keyed // by name of child service. A service is initially added to the map when it is // created via Add, and it is later removed or added to the map as needed, // through the SetStatus method. status map[string]struct{} // fenced is the list of terminating yet still serving child services. fenced map[string]struct{} // updaters is the list of hooks that are run (to update the Balancer // parent(s)), whenever the Balancer status changes. // No mutex is needed, as it is modified only during the configuration build. updaters []func(bool) sticky *loadbalancer.Sticky curDeadline float64 } // New creates a new load balancer. func New(sticky *dynamic.Sticky, wantsHealthCheck bool) *Balancer { balancer := &Balancer{ status: make(map[string]struct{}), fenced: make(map[string]struct{}), wantsHealthCheck: wantsHealthCheck, } if sticky != nil && sticky.Cookie != nil { balancer.sticky = loadbalancer.NewSticky(*sticky.Cookie) } return balancer } // Len implements heap.Interface/sort.Interface. func (b *Balancer) Len() int { return len(b.handlers) } // Less implements heap.Interface/sort.Interface. func (b *Balancer) Less(i, j int) bool { return b.handlers[i].deadline < b.handlers[j].deadline } // Swap implements heap.Interface/sort.Interface. func (b *Balancer) Swap(i, j int) { b.handlers[i], b.handlers[j] = b.handlers[j], b.handlers[i] } // Push implements heap.Interface for pushing an item into the heap. func (b *Balancer) Push(x interface{}) { h, ok := x.(*namedHandler) if !ok { return } b.handlers = append(b.handlers, h) } // Pop implements heap.Interface for popping an item from the heap. // It panics if b.Len() < 1. func (b *Balancer) Pop() interface{} { h := b.handlers[len(b.handlers)-1] b.handlers = b.handlers[0 : len(b.handlers)-1] return h } // SetStatus sets on the balancer that its given child is now of the given // status. childName is only needed for logging purposes. func (b *Balancer) SetStatus(ctx context.Context, childName string, up bool) { b.handlersMu.Lock() defer b.handlersMu.Unlock() upBefore := len(b.status) > 0 status := "DOWN" if up { status = "UP" } log.Ctx(ctx).Debug().Msgf("Setting status of %s to %v", childName, status) if up { b.status[childName] = struct{}{} } else { delete(b.status, childName) } upAfter := len(b.status) > 0 status = "DOWN" if upAfter { status = "UP" } // No Status Change if upBefore == upAfter { // We're still with the same status, no need to propagate log.Ctx(ctx).Debug().Msgf("Still %s, no need to propagate", status) return } // Status Change log.Ctx(ctx).Debug().Msgf("Propagating new %s status", status) for _, fn := range b.updaters { fn(upAfter) } } // RegisterStatusUpdater adds fn to the list of hooks that are run when the // status of the Balancer changes. // Not thread safe. func (b *Balancer) RegisterStatusUpdater(fn func(up bool)) error { if !b.wantsHealthCheck { return errors.New("healthCheck not enabled in config for this WRR service") } b.updaters = append(b.updaters, fn) return nil } func (b *Balancer) nextServer() (*namedHandler, error) { b.handlersMu.Lock() defer b.handlersMu.Unlock() if len(b.handlers) == 0 || len(b.status) == 0 || len(b.fenced) == len(b.handlers) { return nil, errNoAvailableServer } var handler *namedHandler for { // Pick handler with closest deadline. handler = heap.Pop(b).(*namedHandler) // curDeadline should be handler's deadline so that new added entry would have a fair competition environment with the old ones. b.curDeadline = handler.deadline handler.deadline += 1 / handler.weight heap.Push(b, handler) if _, ok := b.status[handler.name]; ok { if _, ok := b.fenced[handler.name]; !ok { // do not select a fenced handler. break } } } log.Debug().Msgf("Service selected by WRR: %s", handler.name) return handler, nil } func (b *Balancer) ServeHTTP(rw http.ResponseWriter, req *http.Request) { if b.sticky != nil { h, rewrite, err := b.sticky.StickyHandler(req) if err != nil { log.Error().Err(err).Msg("Error while getting sticky handler") } else if h != nil { b.handlersMu.RLock() _, ok := b.status[h.Name] b.handlersMu.RUnlock() if ok { if rewrite { if err := b.sticky.WriteStickyCookie(rw, h.Name); err != nil { log.Error().Err(err).Msg("Writing sticky cookie") } } h.ServeHTTP(rw, req) return } } } server, err := b.nextServer() if err != nil { if errors.Is(err, errNoAvailableServer) { http.Error(rw, errNoAvailableServer.Error(), http.StatusServiceUnavailable) } else { http.Error(rw, err.Error(), http.StatusInternalServerError) } return } if b.sticky != nil { if err := b.sticky.WriteStickyCookie(rw, server.name); err != nil { log.Error().Err(err).Msg("Error while writing sticky cookie") } } server.ServeHTTP(rw, req) } // AddServer adds a handler with a server. func (b *Balancer) AddServer(name string, handler http.Handler, server dynamic.Server) { b.Add(name, handler, server.Weight, server.Fenced) } // Add adds a handler. // A handler with a non-positive weight is ignored. func (b *Balancer) Add(name string, handler http.Handler, weight *int, fenced bool) { w := 1 if weight != nil { w = *weight } if w <= 0 { // non-positive weight is meaningless return } h := &namedHandler{Handler: handler, name: name, weight: float64(w)} b.handlersMu.Lock() h.deadline = b.curDeadline + 1/h.weight heap.Push(b, h) b.status[name] = struct{}{} if fenced { b.fenced[name] = struct{}{} } b.handlersMu.Unlock() if b.sticky != nil { b.sticky.AddHandler(name, handler) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/loadbalancer/wrr/wrr_test.go
pkg/server/service/loadbalancer/wrr/wrr_test.go
package wrr import ( "context" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) type key string const serviceName key = "serviceName" func pointer[T any](v T) *T { return &v } func TestBalancer(t *testing.T) { balancer := New(nil, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), pointer(3), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), pointer(1), false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 4 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 3, recorder.save["first"]) assert.Equal(t, 1, recorder.save["second"]) } func TestBalancerNoService(t *testing.T) { balancer := New(nil, false) recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, http.StatusServiceUnavailable, recorder.Result().StatusCode) } func TestBalancerOneServerZeroWeight(t *testing.T) { balancer := New(nil, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), pointer(0), false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 3 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 3, recorder.save["first"]) } func TestBalancerNoServiceUp(t *testing.T) { balancer := New(nil, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusInternalServerError) }), pointer(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusInternalServerError) }), pointer(1), false) balancer.SetStatus(context.WithValue(t.Context(), serviceName, "parent"), "first", false) balancer.SetStatus(context.WithValue(t.Context(), serviceName, "parent"), "second", false) recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, http.StatusServiceUnavailable, recorder.Result().StatusCode) } func TestBalancerOneServerDown(t *testing.T) { balancer := New(nil, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusInternalServerError) }), pointer(1), false) balancer.SetStatus(context.WithValue(t.Context(), serviceName, "parent"), "second", false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 3 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 3, recorder.save["first"]) } func TestBalancerDownThenUp(t *testing.T) { balancer := New(nil, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.SetStatus(context.WithValue(t.Context(), serviceName, "parent"), "second", false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 3 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 3, recorder.save["first"]) balancer.SetStatus(context.WithValue(t.Context(), serviceName, "parent"), "second", true) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 2 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 1, recorder.save["first"]) assert.Equal(t, 1, recorder.save["second"]) } func TestBalancerPropagate(t *testing.T) { balancer1 := New(nil, true) balancer1.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer1.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer2 := New(nil, true) balancer2.Add("third", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "third") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer2.Add("fourth", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "fourth") rw.WriteHeader(http.StatusOK) }), pointer(1), false) topBalancer := New(nil, true) topBalancer.Add("balancer1", balancer1, pointer(1), false) _ = balancer1.RegisterStatusUpdater(func(up bool) { topBalancer.SetStatus(context.WithValue(t.Context(), serviceName, "top"), "balancer1", up) // TODO(mpl): if test gets flaky, add channel or something here to signal that // propagation is done, and wait on it before sending request. }) topBalancer.Add("balancer2", balancer2, pointer(1), false) _ = balancer2.RegisterStatusUpdater(func(up bool) { topBalancer.SetStatus(context.WithValue(t.Context(), serviceName, "top"), "balancer2", up) }) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 8 { topBalancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 2, recorder.save["first"]) assert.Equal(t, 2, recorder.save["second"]) assert.Equal(t, 2, recorder.save["third"]) assert.Equal(t, 2, recorder.save["fourth"]) wantStatus := []int{200, 200, 200, 200, 200, 200, 200, 200} assert.Equal(t, wantStatus, recorder.status) // fourth gets downed, but balancer2 still up since third is still up. balancer2.SetStatus(context.WithValue(t.Context(), serviceName, "top"), "fourth", false) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 8 { topBalancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 2, recorder.save["first"]) assert.Equal(t, 2, recorder.save["second"]) assert.Equal(t, 4, recorder.save["third"]) assert.Equal(t, 0, recorder.save["fourth"]) wantStatus = []int{200, 200, 200, 200, 200, 200, 200, 200} assert.Equal(t, wantStatus, recorder.status) // third gets downed, and the propagation triggers balancer2 to be marked as // down as well for topBalancer. balancer2.SetStatus(context.WithValue(t.Context(), serviceName, "top"), "third", false) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 8 { topBalancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 4, recorder.save["first"]) assert.Equal(t, 4, recorder.save["second"]) assert.Equal(t, 0, recorder.save["third"]) assert.Equal(t, 0, recorder.save["fourth"]) wantStatus = []int{200, 200, 200, 200, 200, 200, 200, 200} assert.Equal(t, wantStatus, recorder.status) } func TestBalancerAllServersZeroWeight(t *testing.T) { balancer := New(nil, false) balancer.Add("test", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), pointer(0), false) balancer.Add("test2", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), pointer(0), false) recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, http.StatusServiceUnavailable, recorder.Result().StatusCode) } func TestBalancerAllServersFenced(t *testing.T) { balancer := New(nil, false) balancer.Add("test", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), pointer(1), true) balancer.Add("test2", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), pointer(1), true) recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, http.StatusServiceUnavailable, recorder.Result().StatusCode) } func TestSticky(t *testing.T) { balancer := New(&dynamic.Sticky{ Cookie: &dynamic.Cookie{ Name: "test", Secure: true, HTTPOnly: true, SameSite: "none", Domain: "foo.com", MaxAge: 42, Path: func(v string) *string { return &v }("/foo"), }, }, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), pointer(2), false) recorder := &responseRecorder{ ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}, cookies: make(map[string]*http.Cookie), } req := httptest.NewRequest(http.MethodGet, "/", nil) for range 3 { for _, cookie := range recorder.Result().Cookies() { assert.NotContains(t, "first", cookie.Value) assert.NotContains(t, "second", cookie.Value) req.AddCookie(cookie) } recorder.ResponseRecorder = httptest.NewRecorder() balancer.ServeHTTP(recorder, req) } assert.Equal(t, 0, recorder.save["first"]) assert.Equal(t, 3, recorder.save["second"]) assert.True(t, recorder.cookies["test"].HttpOnly) assert.True(t, recorder.cookies["test"].Secure) assert.Equal(t, "foo.com", recorder.cookies["test"].Domain) assert.Equal(t, http.SameSiteNoneMode, recorder.cookies["test"].SameSite) assert.Equal(t, 42, recorder.cookies["test"].MaxAge) assert.Equal(t, "/foo", recorder.cookies["test"].Path) } func TestSticky_Fallback(t *testing.T) { balancer := New(&dynamic.Sticky{ Cookie: &dynamic.Cookie{Name: "test"}, }, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), pointer(2), false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}, cookies: make(map[string]*http.Cookie)} req := httptest.NewRequest(http.MethodGet, "/", nil) req.AddCookie(&http.Cookie{Name: "test", Value: "second"}) for range 3 { recorder.ResponseRecorder = httptest.NewRecorder() balancer.ServeHTTP(recorder, req) } assert.Equal(t, 0, recorder.save["first"]) assert.Equal(t, 3, recorder.save["second"]) } // TestSticky_Fenced checks that fenced node receive traffic if their sticky cookie matches. func TestSticky_Fenced(t *testing.T) { balancer := New(&dynamic.Sticky{Cookie: &dynamic.Cookie{Name: "test"}}, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.Add("fenced", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "fenced") rw.WriteHeader(http.StatusOK) }), pointer(1), true) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}, cookies: make(map[string]*http.Cookie)} stickyReq := httptest.NewRequest(http.MethodGet, "/", nil) stickyReq.AddCookie(&http.Cookie{Name: "test", Value: "fenced"}) req := httptest.NewRequest(http.MethodGet, "/", nil) for range 4 { recorder.ResponseRecorder = httptest.NewRecorder() balancer.ServeHTTP(recorder, stickyReq) balancer.ServeHTTP(recorder, req) } assert.Equal(t, 4, recorder.save["fenced"]) assert.Equal(t, 2, recorder.save["first"]) assert.Equal(t, 2, recorder.save["second"]) } // TestBalancerBias makes sure that the WRR algorithm spreads elements evenly right from the start, // and that it does not "over-favor" the high-weighted ones with a biased start-up regime. func TestBalancerBias(t *testing.T) { balancer := New(nil, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "A") rw.WriteHeader(http.StatusOK) }), pointer(11), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "B") rw.WriteHeader(http.StatusOK) }), pointer(3), false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 14 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } wantSequence := []string{"A", "A", "A", "B", "A", "A", "A", "A", "B", "A", "A", "A", "B", "A"} assert.Equal(t, wantSequence, recorder.sequence) } type responseRecorder struct { *httptest.ResponseRecorder save map[string]int sequence []string status []int cookies map[string]*http.Cookie } func (r *responseRecorder) WriteHeader(statusCode int) { r.save[r.Header().Get("server")]++ r.sequence = append(r.sequence, r.Header().Get("server")) r.status = append(r.status, statusCode) for _, cookie := range r.Result().Cookies() { r.cookies[cookie.Name] = cookie } r.ResponseRecorder.WriteHeader(statusCode) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/loadbalancer/leasttime/leasttime.go
pkg/server/service/loadbalancer/leasttime/leasttime.go
package leasttime import ( "context" "errors" "math" "net/http" "net/http/httptrace" "sync" "sync/atomic" "time" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/server/service/loadbalancer" ) const sampleSize = 100 // Number of response time samples to track. var errNoAvailableServer = errors.New("no available server") // namedHandler wraps an HTTP handler with metrics and server information. // Tracks response time (TTFB) and inflight request count for load balancing decisions. type namedHandler struct { http.Handler name string weight float64 deadlineMu sync.RWMutex deadline float64 // WRR tie-breaking (EDF scheduling). inflightCount atomic.Int64 // Number of inflight requests. responseTimeMu sync.RWMutex responseTimes [sampleSize]float64 // Fixed-size ring buffer (TTFB measurements in ms). responseTimeIdx int // Current position in ring buffer. responseTimeSum float64 // Sum of all values in buffer. sampleCount int // Number of samples collected so far. } // updateResponseTime updates the average response time for this server using a ring buffer. func (s *namedHandler) updateResponseTime(elapsed time.Duration) { s.responseTimeMu.Lock() defer s.responseTimeMu.Unlock() ms := float64(elapsed.Milliseconds()) if s.sampleCount < sampleSize { // Still filling the buffer. s.responseTimes[s.responseTimeIdx] = ms s.responseTimeSum += ms s.sampleCount++ } else { // Buffer is full, replace oldest value. oldValue := s.responseTimes[s.responseTimeIdx] s.responseTimes[s.responseTimeIdx] = ms s.responseTimeSum = s.responseTimeSum - oldValue + ms } s.responseTimeIdx = (s.responseTimeIdx + 1) % sampleSize } // getAvgResponseTime returns the average response time in milliseconds. // Returns 0 if no samples have been collected yet (cold start). func (s *namedHandler) getAvgResponseTime() float64 { s.responseTimeMu.RLock() defer s.responseTimeMu.RUnlock() if s.sampleCount == 0 { return 0 } return s.responseTimeSum / float64(s.sampleCount) } func (s *namedHandler) getDeadline() float64 { s.deadlineMu.RLock() defer s.deadlineMu.RUnlock() return s.deadline } func (s *namedHandler) setDeadline(deadline float64) { s.deadlineMu.Lock() defer s.deadlineMu.Unlock() s.deadline = deadline } // Balancer implements the least-time load balancing algorithm. // It selects the server with the lowest average response time (TTFB) and fewest active connections. type Balancer struct { wantsHealthCheck bool // handlersMu protects the handlers slice, the status and the fenced maps. handlersMu sync.RWMutex handlers []*namedHandler // status is a record of which child services of the Balancer are healthy, keyed // by name of child service. A service is initially added to the map when it is // created via Add, and it is later removed or added to the map as needed, // through the SetStatus method. status map[string]struct{} // fenced is the list of terminating yet still serving child services. fenced map[string]struct{} // updaters is the list of hooks that are run (to update the Balancer // parent(s)), whenever the Balancer status changes. // No mutex is needed, as it is modified only during the configuration build. updaters []func(bool) sticky *loadbalancer.Sticky // deadlineMu protects EDF scheduling state (curDeadline and all handler deadline fields). // Separate from handlersMu to reduce lock contention during tie-breaking. curDeadlineMu sync.RWMutex // curDeadline is used for WRR tie-breaking (EDF scheduling). curDeadline float64 } // New creates a new least-time load balancer. func New(stickyConfig *dynamic.Sticky, wantsHealthCheck bool) *Balancer { balancer := &Balancer{ status: make(map[string]struct{}), fenced: make(map[string]struct{}), wantsHealthCheck: wantsHealthCheck, } if stickyConfig != nil && stickyConfig.Cookie != nil { balancer.sticky = loadbalancer.NewSticky(*stickyConfig.Cookie) } return balancer } // SetStatus sets on the balancer that its given child is now of the given // status. childName is only needed for logging purposes. func (b *Balancer) SetStatus(ctx context.Context, childName string, up bool) { b.handlersMu.Lock() defer b.handlersMu.Unlock() upBefore := len(b.status) > 0 status := "DOWN" if up { status = "UP" } log.Ctx(ctx).Debug().Msgf("Setting status of %s to %v", childName, status) if up { b.status[childName] = struct{}{} } else { delete(b.status, childName) } upAfter := len(b.status) > 0 status = "DOWN" if upAfter { status = "UP" } // No Status Change. if upBefore == upAfter { // We're still with the same status, no need to propagate. log.Ctx(ctx).Debug().Msgf("Still %s, no need to propagate", status) return } // Status Change. log.Ctx(ctx).Debug().Msgf("Propagating new %s status", status) for _, fn := range b.updaters { fn(upAfter) } } // RegisterStatusUpdater adds fn to the list of hooks that are run when the // status of the Balancer changes. // Not thread safe. func (b *Balancer) RegisterStatusUpdater(fn func(up bool)) error { if !b.wantsHealthCheck { return errors.New("healthCheck not enabled in config for this LeastTime service") } b.updaters = append(b.updaters, fn) return nil } // getHealthyServers returns the list of healthy, non-fenced servers. func (b *Balancer) getHealthyServers() []*namedHandler { b.handlersMu.RLock() defer b.handlersMu.RUnlock() var healthy []*namedHandler for _, h := range b.handlers { if _, ok := b.status[h.name]; ok { if _, fenced := b.fenced[h.name]; !fenced { healthy = append(healthy, h) } } } return healthy } // selectWRR selects a server from candidates using Weighted Round Robin (EDF scheduling). // This is used for tie-breaking when multiple servers have identical scores. func (b *Balancer) selectWRR(candidates []*namedHandler) *namedHandler { if len(candidates) == 0 { return nil } selected := candidates[0] minDeadline := math.MaxFloat64 // Find handler with earliest deadline. for _, h := range candidates { handlerDeadline := h.getDeadline() if handlerDeadline < minDeadline { minDeadline = handlerDeadline selected = h } } // Update deadline based on when this server was selected (minDeadline), // not the global curDeadline. This ensures proper weighted distribution. newDeadline := minDeadline + 1/selected.weight selected.setDeadline(newDeadline) // Track the maximum deadline assigned for initializing new servers. b.curDeadlineMu.Lock() if newDeadline > b.curDeadline { b.curDeadline = newDeadline } b.curDeadlineMu.Unlock() return selected } // Score = (avgResponseTime × (1 + inflightCount)) / weight. func (b *Balancer) nextServer() (*namedHandler, error) { healthy := b.getHealthyServers() if len(healthy) == 0 { return nil, errNoAvailableServer } if len(healthy) == 1 { return healthy[0], nil } // Calculate scores and find minimum. minScore := math.MaxFloat64 var candidates []*namedHandler for _, h := range healthy { avgRT := h.getAvgResponseTime() inflight := float64(h.inflightCount.Load()) score := (avgRT * (1 + inflight)) / h.weight if score < minScore { minScore = score candidates = []*namedHandler{h} } else if score == minScore { candidates = append(candidates, h) } } if len(candidates) == 1 { return candidates[0], nil } // Multiple servers with same score: use WRR (EDF) tie-breaking. selected := b.selectWRR(candidates) if selected == nil { return nil, errNoAvailableServer } return selected, nil } func (b *Balancer) ServeHTTP(rw http.ResponseWriter, req *http.Request) { // Handle sticky sessions first. if b.sticky != nil { h, rewrite, err := b.sticky.StickyHandler(req) if err != nil { log.Error().Err(err).Msg("Error while getting sticky handler") } else if h != nil { b.handlersMu.RLock() _, ok := b.status[h.Name] b.handlersMu.RUnlock() if ok { if rewrite { if err := b.sticky.WriteStickyCookie(rw, h.Name); err != nil { log.Error().Err(err).Msg("Writing sticky cookie") } } h.ServeHTTP(rw, req) return } } } server, err := b.nextServer() if err != nil { if errors.Is(err, errNoAvailableServer) { http.Error(rw, errNoAvailableServer.Error(), http.StatusServiceUnavailable) } else { http.Error(rw, err.Error(), http.StatusInternalServerError) } return } if b.sticky != nil { if err := b.sticky.WriteStickyCookie(rw, server.name); err != nil { log.Error().Err(err).Msg("Error while writing sticky cookie") } } // Track inflight requests. server.inflightCount.Add(1) defer server.inflightCount.Add(-1) startTime := time.Now() trace := &httptrace.ClientTrace{ GotFirstResponseByte: func() { // Update average response time (TTFB). server.updateResponseTime(time.Since(startTime)) }, } traceCtx := httptrace.WithClientTrace(req.Context(), trace) server.ServeHTTP(rw, req.WithContext(traceCtx)) } // AddServer adds a handler with a server. func (b *Balancer) AddServer(name string, handler http.Handler, server dynamic.Server) { b.Add(name, handler, server.Weight, server.Fenced) } // Add adds a handler. // A handler with a non-positive weight is ignored. func (b *Balancer) Add(name string, handler http.Handler, weight *int, fenced bool) { w := 1 if weight != nil { w = *weight } if w <= 0 { // non-positive weight is meaningless. return } h := &namedHandler{Handler: handler, name: name, weight: float64(w)} // Initialize deadline by adding 1/weight to current deadline. // This staggers servers to prevent all starting at the same time. var deadline float64 b.curDeadlineMu.RLock() deadline = b.curDeadline + 1/h.weight b.curDeadlineMu.RUnlock() h.setDeadline(deadline) // Update balancer's current deadline with the new server's deadline. b.curDeadlineMu.Lock() b.curDeadline = deadline b.curDeadlineMu.Unlock() b.handlersMu.Lock() b.handlers = append(b.handlers, h) b.status[name] = struct{}{} if fenced { b.fenced[name] = struct{}{} } b.handlersMu.Unlock() if b.sticky != nil { b.sticky.AddHandler(name, handler) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/loadbalancer/leasttime/leasttime_test.go
pkg/server/service/loadbalancer/leasttime/leasttime_test.go
package leasttime import ( "context" "net/http" "net/http/httptest" "net/http/httptrace" "sync" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) type key string const serviceName key = "serviceName" func pointer[T any](v T) *T { return &v } // responseRecorder tracks which servers handled requests. type responseRecorder struct { *httptest.ResponseRecorder save map[string]int } func (r *responseRecorder) WriteHeader(statusCode int) { server := r.Header().Get("server") if server != "" { r.save[server]++ } r.ResponseRecorder.WriteHeader(statusCode) } // TestBalancer tests basic server addition and least-time selection. func TestBalancer(t *testing.T) { balancer := New(nil, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { time.Sleep(5 * time.Millisecond) rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { time.Sleep(5 * time.Millisecond) rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), pointer(1), false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 10 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } // With least-time and equal response times, both servers should get some traffic. assert.Positive(t, recorder.save["first"]) assert.Positive(t, recorder.save["second"]) assert.Equal(t, 10, recorder.save["first"]+recorder.save["second"]) } // TestBalancerNoService tests behavior when no servers are configured. func TestBalancerNoService(t *testing.T) { balancer := New(nil, false) recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, http.StatusServiceUnavailable, recorder.Result().StatusCode) } // TestBalancerNoServiceUp tests behavior when all servers are marked down. func TestBalancerNoServiceUp(t *testing.T) { balancer := New(nil, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusInternalServerError) }), pointer(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusInternalServerError) }), pointer(1), false) balancer.SetStatus(context.WithValue(t.Context(), serviceName, "parent"), "first", false) balancer.SetStatus(context.WithValue(t.Context(), serviceName, "parent"), "second", false) recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, http.StatusServiceUnavailable, recorder.Result().StatusCode) } // TestBalancerOneServerDown tests that down servers are excluded from selection. func TestBalancerOneServerDown(t *testing.T) { balancer := New(nil, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusInternalServerError) }), pointer(1), false) balancer.SetStatus(context.WithValue(t.Context(), serviceName, "parent"), "second", false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 3 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 3, recorder.save["first"]) assert.Equal(t, 0, recorder.save["second"]) } // TestBalancerOneServerDownThenUp tests server status transitions. func TestBalancerOneServerDownThenUp(t *testing.T) { balancer := New(nil, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { time.Sleep(5 * time.Millisecond) rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { time.Sleep(5 * time.Millisecond) rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.SetStatus(context.WithValue(t.Context(), serviceName, "parent"), "second", false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 3 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 3, recorder.save["first"]) assert.Equal(t, 0, recorder.save["second"]) balancer.SetStatus(context.WithValue(t.Context(), serviceName, "parent"), "second", true) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 20 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } // Both servers should get some traffic. assert.Positive(t, recorder.save["first"]) assert.Positive(t, recorder.save["second"]) assert.Equal(t, 20, recorder.save["first"]+recorder.save["second"]) } // TestBalancerAllServersZeroWeight tests that all zero-weight servers result in no available server. func TestBalancerAllServersZeroWeight(t *testing.T) { balancer := New(nil, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), pointer(0), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), pointer(0), false) recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, http.StatusServiceUnavailable, recorder.Result().StatusCode) } // TestBalancerOneServerZeroWeight tests that zero-weight servers are ignored. func TestBalancerOneServerZeroWeight(t *testing.T) { balancer := New(nil, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), pointer(0), false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 3 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } // Only first server should receive traffic. assert.Equal(t, 3, recorder.save["first"]) assert.Equal(t, 0, recorder.save["second"]) } // TestBalancerPropagate tests status propagation to parent balancers. func TestBalancerPropagate(t *testing.T) { balancer1 := New(nil, true) balancer1.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer1.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer2 := New(nil, true) balancer2.Add("third", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "third") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer2.Add("fourth", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "fourth") rw.WriteHeader(http.StatusOK) }), pointer(1), false) topBalancer := New(nil, true) topBalancer.Add("balancer1", balancer1, pointer(1), false) topBalancer.Add("balancer2", balancer2, pointer(1), false) err := balancer1.RegisterStatusUpdater(func(up bool) { topBalancer.SetStatus(context.WithValue(t.Context(), serviceName, "top"), "balancer1", up) }) assert.NoError(t, err) err = balancer2.RegisterStatusUpdater(func(up bool) { topBalancer.SetStatus(context.WithValue(t.Context(), serviceName, "top"), "balancer2", up) }) assert.NoError(t, err) // Set all children of balancer1 to down, should propagate to top. balancer1.SetStatus(context.WithValue(t.Context(), serviceName, "top"), "first", false) balancer1.SetStatus(context.WithValue(t.Context(), serviceName, "top"), "second", false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 4 { topBalancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } // Only balancer2 should receive traffic. assert.Equal(t, 0, recorder.save["first"]) assert.Equal(t, 0, recorder.save["second"]) assert.Equal(t, 4, recorder.save["third"]+recorder.save["fourth"]) } // TestBalancerOneServerFenced tests that fenced servers are excluded from selection. func TestBalancerOneServerFenced(t *testing.T) { balancer := New(nil, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), pointer(1), true) // fenced recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 3 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } // Only first server should receive traffic. assert.Equal(t, 3, recorder.save["first"]) assert.Equal(t, 0, recorder.save["second"]) } // TestBalancerAllFencedServers tests that all fenced servers result in no available server. func TestBalancerAllFencedServers(t *testing.T) { balancer := New(nil, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), pointer(1), true) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), pointer(1), true) recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, http.StatusServiceUnavailable, recorder.Result().StatusCode) } // TestBalancerRegisterStatusUpdaterWithoutHealthCheck tests error when registering updater without health check. func TestBalancerRegisterStatusUpdaterWithoutHealthCheck(t *testing.T) { balancer := New(nil, false) err := balancer.RegisterStatusUpdater(func(up bool) {}) assert.Error(t, err) assert.Contains(t, err.Error(), "healthCheck not enabled") } // TestBalancerSticky tests sticky session support. func TestBalancerSticky(t *testing.T) { balancer := New(&dynamic.Sticky{ Cookie: &dynamic.Cookie{ Name: "test", }, }, false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), pointer(1), false) // First request should set cookie. recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) firstServer := recorder.Header().Get("server") assert.NotEmpty(t, firstServer) // Extract cookie from first response. cookies := recorder.Result().Cookies() assert.NotEmpty(t, cookies) // Second request with cookie should hit same server. req := httptest.NewRequest(http.MethodGet, "/", nil) for _, cookie := range cookies { req.AddCookie(cookie) } recorder2 := httptest.NewRecorder() balancer.ServeHTTP(recorder2, req) secondServer := recorder2.Header().Get("server") assert.Equal(t, firstServer, secondServer) } // TestBalancerStickyFallback tests that sticky sessions fallback to least-time when sticky server is down. func TestBalancerStickyFallback(t *testing.T) { balancer := New(&dynamic.Sticky{ Cookie: &dynamic.Cookie{ Name: "test", }, }, false) balancer.Add("server1", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { time.Sleep(50 * time.Millisecond) rw.Header().Set("server", "server1") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.Add("server2", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { time.Sleep(50 * time.Millisecond) rw.Header().Set("server", "server2") rw.WriteHeader(http.StatusOK) }), pointer(1), false) // Make initial request to establish sticky session with server1. recorder1 := httptest.NewRecorder() balancer.ServeHTTP(recorder1, httptest.NewRequest(http.MethodGet, "/", nil)) firstServer := recorder1.Header().Get("server") assert.NotEmpty(t, firstServer) // Extract cookie from first response. cookies := recorder1.Result().Cookies() assert.NotEmpty(t, cookies) // Mark the sticky server as DOWN balancer.SetStatus(context.WithValue(t.Context(), serviceName, "test"), firstServer, false) // Request with sticky cookie should fallback to the other server req2 := httptest.NewRequest(http.MethodGet, "/", nil) for _, cookie := range cookies { req2.AddCookie(cookie) } recorder2 := httptest.NewRecorder() balancer.ServeHTTP(recorder2, req2) fallbackServer := recorder2.Header().Get("server") assert.NotEqual(t, firstServer, fallbackServer) assert.NotEmpty(t, fallbackServer) // New sticky cookie should be written for the fallback server newCookies := recorder2.Result().Cookies() assert.NotEmpty(t, newCookies) // Verify sticky session persists with the fallback server req3 := httptest.NewRequest(http.MethodGet, "/", nil) for _, cookie := range newCookies { req3.AddCookie(cookie) } recorder3 := httptest.NewRecorder() balancer.ServeHTTP(recorder3, req3) assert.Equal(t, fallbackServer, recorder3.Header().Get("server")) // Bring original server back UP balancer.SetStatus(context.WithValue(t.Context(), serviceName, "test"), firstServer, true) // Request with fallback server cookie should still stick to fallback server req4 := httptest.NewRequest(http.MethodGet, "/", nil) for _, cookie := range newCookies { req4.AddCookie(cookie) } recorder4 := httptest.NewRecorder() balancer.ServeHTTP(recorder4, req4) assert.Equal(t, fallbackServer, recorder4.Header().Get("server")) } // TestBalancerStickyFenced tests that sticky sessions persist to fenced servers (graceful shutdown) // Fencing enables zero-downtime deployments: fenced servers reject NEW connections // but continue serving EXISTING sticky sessions until they complete. func TestBalancerStickyFenced(t *testing.T) { balancer := New(&dynamic.Sticky{ Cookie: &dynamic.Cookie{ Name: "test", }, }, false) balancer.Add("server1", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "server1") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.Add("server2", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "server2") rw.WriteHeader(http.StatusOK) }), pointer(1), false) // Establish sticky session with any server. recorder1 := httptest.NewRecorder() balancer.ServeHTTP(recorder1, httptest.NewRequest(http.MethodGet, "/", nil)) stickyServer := recorder1.Header().Get("server") assert.NotEmpty(t, stickyServer) cookies := recorder1.Result().Cookies() assert.NotEmpty(t, cookies) // Fence the sticky server (simulate graceful shutdown). balancer.handlersMu.Lock() balancer.fenced[stickyServer] = struct{}{} balancer.handlersMu.Unlock() // Existing sticky session should STILL work (graceful draining). req := httptest.NewRequest(http.MethodGet, "/", nil) for _, cookie := range cookies { req.AddCookie(cookie) } recorder2 := httptest.NewRecorder() balancer.ServeHTTP(recorder2, req) assert.Equal(t, stickyServer, recorder2.Header().Get("server")) // But NEW requests should NOT go to the fenced server. recorder3 := httptest.NewRecorder() balancer.ServeHTTP(recorder3, httptest.NewRequest(http.MethodGet, "/", nil)) newServer := recorder3.Header().Get("server") assert.NotEqual(t, stickyServer, newServer) assert.NotEmpty(t, newServer) } // TestRingBufferBasic tests basic ring buffer functionality with few samples. func TestRingBufferBasic(t *testing.T) { handler := &namedHandler{ Handler: http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), name: "test", weight: 1, } // Test cold start - no samples. avg := handler.getAvgResponseTime() assert.InDelta(t, 0.0, avg, 0) // Add one sample. handler.updateResponseTime(10 * time.Millisecond) avg = handler.getAvgResponseTime() assert.InDelta(t, 10.0, avg, 0) // Add more samples. handler.updateResponseTime(20 * time.Millisecond) handler.updateResponseTime(30 * time.Millisecond) avg = handler.getAvgResponseTime() assert.InDelta(t, 20.0, avg, 0) // (10 + 20 + 30) / 3 = 20 } // TestRingBufferWraparound tests ring buffer behavior when it wraps around func TestRingBufferWraparound(t *testing.T) { handler := &namedHandler{ Handler: http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), name: "test", weight: 1, } // Fill the buffer with 100 samples of 10ms each. for range sampleSize { handler.updateResponseTime(10 * time.Millisecond) } avg := handler.getAvgResponseTime() assert.InDelta(t, 10.0, avg, 0) // Add one more sample (should replace oldest). handler.updateResponseTime(20 * time.Millisecond) avg = handler.getAvgResponseTime() // Sum: 99*10 + 1*20 = 1010, avg = 1010/100 = 10.1 assert.InDelta(t, 10.1, avg, 0) // Add 10 more samples of 30ms. for range 10 { handler.updateResponseTime(30 * time.Millisecond) } avg = handler.getAvgResponseTime() // Sum: 89*10 + 1*20 + 10*30 = 890 + 20 + 300 = 1210, avg = 1210/100 = 12.1 assert.InDelta(t, 12.1, avg, 0) } // TestRingBufferLarge tests ring buffer with many samples (> 100). func TestRingBufferLarge(t *testing.T) { handler := &namedHandler{ Handler: http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), name: "test", weight: 1, } // Add 150 samples. for i := range 150 { handler.updateResponseTime(time.Duration(i+1) * time.Millisecond) } // Should only track last 100 samples: 51, 52, ..., 150 // Sum = (51 + 150) * 100 / 2 = 10050 // Avg = 10050 / 100 = 100.5 avg := handler.getAvgResponseTime() assert.InDelta(t, 100.5, avg, 0) } // TestInflightCounter tests inflight request tracking. func TestInflightCounter(t *testing.T) { balancer := New(nil, false) var inflightAtRequest atomic.Int64 balancer.Add("test", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { inflightAtRequest.Store(balancer.handlers[0].inflightCount.Load()) rw.Header().Set("server", "test") rw.WriteHeader(http.StatusOK) }), pointer(1), false) // Check that inflight count is 0 initially. balancer.handlersMu.RLock() handler := balancer.handlers[0] balancer.handlersMu.RUnlock() assert.Equal(t, int64(0), handler.inflightCount.Load()) // Make a request. recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) // During request, inflight should have been 1. assert.Equal(t, int64(1), inflightAtRequest.Load()) // After request completes, inflight should be back to 0. assert.Equal(t, int64(0), handler.inflightCount.Load()) } // TestConcurrentResponseTimeUpdates tests thread safety of response time updates. func TestConcurrentResponseTimeUpdates(t *testing.T) { handler := &namedHandler{ Handler: http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), name: "test", weight: 1, } // Concurrently update response times. var wg sync.WaitGroup numGoroutines := 10 updatesPerGoroutine := 20 for i := range numGoroutines { wg.Add(1) go func(id int) { defer wg.Done() for range updatesPerGoroutine { handler.updateResponseTime(time.Duration(id+1) * time.Millisecond) } }(i) } wg.Wait() // Should have exactly 100 samples (buffer size). assert.Equal(t, sampleSize, handler.sampleCount) } // TestConcurrentInflightTracking tests thread safety of inflight counter. func TestConcurrentInflightTracking(t *testing.T) { handler := &namedHandler{ Handler: http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { time.Sleep(10 * time.Millisecond) rw.WriteHeader(http.StatusOK) }), name: "test", weight: 1, } var maxInflight atomic.Int64 var wg sync.WaitGroup numRequests := 50 for range numRequests { wg.Add(1) go func() { defer wg.Done() handler.inflightCount.Add(1) defer handler.inflightCount.Add(-1) // Track maximum inflight count. current := handler.inflightCount.Load() for { maxLoad := maxInflight.Load() if current <= maxLoad || maxInflight.CompareAndSwap(maxLoad, current) { break } } time.Sleep(1 * time.Millisecond) }() } wg.Wait() // All requests completed, inflight should be 0. assert.Equal(t, int64(0), handler.inflightCount.Load()) // Max inflight should be > 1 (concurrent requests). assert.Greater(t, maxInflight.Load(), int64(1)) } // TestConcurrentRequestsRespectInflight tests that the load balancer dynamically // adapts to inflight request counts during concurrent request processing. func TestConcurrentRequestsRespectInflight(t *testing.T) { balancer := New(nil, false) // Use a channel to control when handlers start sleeping. // This ensures we can fill one server with inflight requests before routing new ones. blockChan := make(chan struct{}) // Add two servers with equal response times and weights. balancer.Add("server1", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { <-blockChan // Wait for signal to proceed. time.Sleep(10 * time.Millisecond) rw.Header().Set("server", "server1") rw.WriteHeader(http.StatusOK) }), pointer(1), false) balancer.Add("server2", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { <-blockChan // Wait for signal to proceed. time.Sleep(10 * time.Millisecond) rw.Header().Set("server", "server2") rw.WriteHeader(http.StatusOK) }), pointer(1), false) // Pre-warm both servers to establish equal average response times. for i := range sampleSize { balancer.handlers[0].responseTimes[i] = 10.0 } balancer.handlers[0].responseTimeSum = 10.0 * sampleSize balancer.handlers[0].sampleCount = sampleSize for i := range sampleSize { balancer.handlers[1].responseTimes[i] = 10.0 } balancer.handlers[1].responseTimeSum = 10.0 * sampleSize balancer.handlers[1].sampleCount = sampleSize // Phase 1: Launch concurrent requests to server1 that will block. var wg sync.WaitGroup inflightRequests := 5 for range inflightRequests { wg.Add(1) go func() { defer wg.Done() recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) }() } // Wait for goroutines to start and increment inflight counters. // They will block on the channel, keeping inflight count high. time.Sleep(50 * time.Millisecond) // Verify inflight counts before making new requests. server1Inflight := balancer.handlers[0].inflightCount.Load() server2Inflight := balancer.handlers[1].inflightCount.Load() assert.Equal(t, int64(5), server1Inflight+server2Inflight) // Phase 2: Make new requests while the initial requests are blocked. // These should see the high inflight counts and route to the less-loaded server. var saveMu sync.Mutex save := map[string]int{} newRequests := 50 // Launch new requests in background so they don't block. var newWg sync.WaitGroup for range newRequests { newWg.Add(1) go func() { defer newWg.Done() rec := httptest.NewRecorder() balancer.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) server := rec.Header().Get("server") if server != "" { saveMu.Lock() save[server]++ saveMu.Unlock() } }() } // Wait for new requests to start and see the inflight counts. time.Sleep(50 * time.Millisecond) close(blockChan) wg.Wait() newWg.Wait() saveMu.Lock() total := save["server1"] + save["server2"] server1Count := save["server1"] server2Count := save["server2"] saveMu.Unlock() assert.Equal(t, newRequests, total) // With inflight tracking, load should naturally balance toward equal distribution. // We allow variance due to concurrent execution and race windows in server selection. assert.InDelta(t, 25.0, float64(server1Count), 5.0) // 20-30 requests assert.InDelta(t, 25.0, float64(server2Count), 5.0) // 20-30 requests } // TestTTFBMeasurement tests TTFB measurement accuracy. func TestTTFBMeasurement(t *testing.T) { balancer := New(nil, false) // Add server with known delay. delay := 50 * time.Millisecond balancer.Add("slow", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { time.Sleep(delay) rw.Header().Set("server", "slow") rw.WriteHeader(http.StatusOK) httptrace.ContextClientTrace(req.Context()).GotFirstResponseByte() }), pointer(1), false) // Make multiple requests to build average. for range 5 { recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } // Check that average response time is approximately the delay. avg := balancer.handlers[0].getAvgResponseTime() // Allow 5ms tolerance for Go timing jitter and test environment variations. assert.InDelta(t, float64(delay.Milliseconds()), avg, 5.0) } // TestZeroSamplesReturnsZero tests that getAvgResponseTime returns 0 when no samples. func TestZeroSamplesReturnsZero(t *testing.T) { handler := &namedHandler{ Handler: http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), name: "test", weight: 1, } avg := handler.getAvgResponseTime() assert.InDelta(t, 0.0, avg, 0) } // TestScoreCalculationWithWeights tests that weights are properly considered in score calculation. func TestScoreCalculationWithWeights(t *testing.T) { balancer := New(nil, false) // Add two servers with same response time but different weights. // Server with higher weight should be preferred. balancer.Add("weighted", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { time.Sleep(50 * time.Millisecond) rw.Header().Set("server", "weighted") rw.WriteHeader(http.StatusOK) httptrace.ContextClientTrace(req.Context()).GotFirstResponseByte() }), pointer(3), false) // Weight 3 balancer.Add("normal", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { time.Sleep(50 * time.Millisecond) rw.Header().Set("server", "normal") rw.WriteHeader(http.StatusOK) httptrace.ContextClientTrace(req.Context()).GotFirstResponseByte() }), pointer(1), false) // Weight 1 // Make requests to build up response time averages. recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 2 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } // Score for weighted: (50 × (1 + 0)) / 3 = 16.67 // Score for normal: (50 × (1 + 0)) / 1 = 50 // After warmup, weighted server has 3x better score (16.67 vs 50) and should receive nearly all requests. recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 10 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 10, recorder.save["weighted"]) assert.Zero(t, recorder.save["normal"]) } // TestScoreCalculationWithInflight tests that inflight requests are considered in score calculation. func TestScoreCalculationWithInflight(t *testing.T) { balancer := New(nil, false) // We'll manually control the inflight counters to test the score calculation. // Add two servers with same response time. balancer.Add("server1", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { time.Sleep(10 * time.Millisecond) rw.Header().Set("server", "server1") rw.WriteHeader(http.StatusOK) httptrace.ContextClientTrace(req.Context()).GotFirstResponseByte() }), pointer(1), false) balancer.Add("server2", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { time.Sleep(10 * time.Millisecond) rw.Header().Set("server", "server2") rw.WriteHeader(http.StatusOK) httptrace.ContextClientTrace(req.Context()).GotFirstResponseByte() }), pointer(1), false) // Build up response time averages for both servers. for range 2 { recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } // Now manually set server1 to have high inflight count. balancer.handlers[0].inflightCount.Store(5) // Make requests - they should prefer server2 because: // Score for server1: (10 × (1 + 5)) / 1 = 60 // Score for server2: (10 × (1 + 0)) / 1 = 10 recorder := &responseRecorder{save: map[string]int{}} for range 5 { // Manually increment to simulate the ServeHTTP behavior. server, _ := balancer.nextServer() server.inflightCount.Add(1) if server.name == "server1" { recorder.save["server1"]++ } else { recorder.save["server2"]++ } } // Server2 should get all requests assert.Equal(t, 5, recorder.save["server2"]) assert.Zero(t, recorder.save["server1"]) } // TestScoreCalculationColdStart tests that new servers (0ms avg) get fair selection func TestScoreCalculationColdStart(t *testing.T) { balancer := New(nil, false) // Add a warm server with established response time balancer.Add("warm", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { time.Sleep(50 * time.Millisecond) rw.Header().Set("server", "warm") rw.WriteHeader(http.StatusOK) httptrace.ContextClientTrace(req.Context()).GotFirstResponseByte() }), pointer(1), false) // Warm up the first server for range 10 { recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } // Now add a cold server (new, no response time data) balancer.Add("cold", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { time.Sleep(10 * time.Millisecond) // Actually faster rw.Header().Set("server", "cold") rw.WriteHeader(http.StatusOK) httptrace.ContextClientTrace(req.Context()).GotFirstResponseByte() }), pointer(1), false) // Cold server should get selected because: // Score for warm: (50 × (1 + 0)) / 1 = 50 // Score for cold: (0 × (1 + 0)) / 1 = 0 recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 20 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } // Cold server should get all or most requests initially due to 0ms average assert.Greater(t, recorder.save["cold"], 10) // After cold server builds up its average, it should continue to get more traffic // because it's actually faster (10ms vs 50ms) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 20 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Greater(t, recorder.save["cold"], recorder.save["warm"]) } // TestFastServerGetsMoreTraffic verifies that servers with lower response times // receive proportionally more traffic in steady state (after cold start). // This tests the core selection bias of the least-time algorithm. func TestFastServerGetsMoreTraffic(t *testing.T) { balancer := New(nil, false) // Add two servers with different static response times. balancer.Add("fast", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { time.Sleep(20 * time.Millisecond) rw.Header().Set("server", "fast") rw.WriteHeader(http.StatusOK) httptrace.ContextClientTrace(req.Context()).GotFirstResponseByte() }), pointer(1), false) balancer.Add("slow", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { time.Sleep(100 * time.Millisecond) rw.Header().Set("server", "slow") rw.WriteHeader(http.StatusOK) httptrace.ContextClientTrace(req.Context()).GotFirstResponseByte() }), pointer(1), false) // After just 1 request to each server, the algorithm identifies the fastest server // and routes nearly all subsequent traffic there (converges in ~2 requests). recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 50 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Greater(t, recorder.save["fast"], recorder.save["slow"]) assert.Greater(t, recorder.save["fast"], 48) // Expect ~96-98% to fast server (48-49/50). } // TestTrafficShiftsWhenPerformanceDegrades verifies that the load balancer // adapts to changing server performance by shifting traffic away from degraded servers.
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/loadbalancer/failover/failover_test.go
pkg/server/service/loadbalancer/failover/failover_test.go
package failover import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) type responseRecorder struct { *httptest.ResponseRecorder save map[string]int sequence []string status []int } func (r *responseRecorder) WriteHeader(statusCode int) { r.save[r.Header().Get("server")]++ r.sequence = append(r.sequence, r.Header().Get("server")) r.status = append(r.status, statusCode) r.ResponseRecorder.WriteHeader(statusCode) } func TestFailover(t *testing.T) { failover := New(&dynamic.HealthCheck{}) status := true require.NoError(t, failover.RegisterStatusUpdater(func(up bool) { status = up })) failover.SetHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "handler") rw.WriteHeader(http.StatusOK) })) failover.SetFallbackHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "fallback") rw.WriteHeader(http.StatusOK) })) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} failover.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, 1, recorder.save["handler"]) assert.Equal(t, 0, recorder.save["fallback"]) assert.Equal(t, []int{200}, recorder.status) assert.True(t, status) failover.SetHandlerStatus(t.Context(), false) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} failover.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, 0, recorder.save["handler"]) assert.Equal(t, 1, recorder.save["fallback"]) assert.Equal(t, []int{200}, recorder.status) assert.True(t, status) failover.SetFallbackHandlerStatus(t.Context(), false) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} failover.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, 0, recorder.save["handler"]) assert.Equal(t, 0, recorder.save["fallback"]) assert.Equal(t, []int{503}, recorder.status) assert.False(t, status) } func TestFailoverDownThenUp(t *testing.T) { failover := New(nil) failover.SetHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "handler") rw.WriteHeader(http.StatusOK) })) failover.SetFallbackHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "fallback") rw.WriteHeader(http.StatusOK) })) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} failover.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, 1, recorder.save["handler"]) assert.Equal(t, 0, recorder.save["fallback"]) assert.Equal(t, []int{200}, recorder.status) failover.SetHandlerStatus(t.Context(), false) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} failover.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, 0, recorder.save["handler"]) assert.Equal(t, 1, recorder.save["fallback"]) assert.Equal(t, []int{200}, recorder.status) failover.SetHandlerStatus(t.Context(), true) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} failover.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, 1, recorder.save["handler"]) assert.Equal(t, 0, recorder.save["fallback"]) assert.Equal(t, []int{200}, recorder.status) } func TestFailoverPropagate(t *testing.T) { failover := New(&dynamic.HealthCheck{}) failover.SetHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "handler") rw.WriteHeader(http.StatusOK) })) failover.SetFallbackHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "fallback") rw.WriteHeader(http.StatusOK) })) topFailover := New(nil) topFailover.SetHandler(failover) topFailover.SetFallbackHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "topFailover") rw.WriteHeader(http.StatusOK) })) err := failover.RegisterStatusUpdater(func(up bool) { topFailover.SetHandlerStatus(t.Context(), up) }) require.NoError(t, err) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} topFailover.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, 1, recorder.save["handler"]) assert.Equal(t, 0, recorder.save["fallback"]) assert.Equal(t, 0, recorder.save["topFailover"]) assert.Equal(t, []int{200}, recorder.status) failover.SetHandlerStatus(t.Context(), false) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} topFailover.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, 0, recorder.save["handler"]) assert.Equal(t, 1, recorder.save["fallback"]) assert.Equal(t, 0, recorder.save["topFailover"]) assert.Equal(t, []int{200}, recorder.status) failover.SetFallbackHandlerStatus(t.Context(), false) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} topFailover.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, 0, recorder.save["handler"]) assert.Equal(t, 0, recorder.save["fallback"]) assert.Equal(t, 1, recorder.save["topFailover"]) assert.Equal(t, []int{200}, recorder.status) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/loadbalancer/failover/failover.go
pkg/server/service/loadbalancer/failover/failover.go
package failover import ( "context" "errors" "net/http" "sync" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) // Failover is an http.Handler that can forward requests to the fallback handler // when the main handler status is down. type Failover struct { wantsHealthCheck bool handler http.Handler fallbackHandler http.Handler // updaters is the list of hooks that are run (to update the Failover // parent(s)), whenever the Failover status changes. updaters []func(bool) handlerStatusMu sync.RWMutex handlerStatus bool fallbackStatusMu sync.RWMutex fallbackStatus bool } // New creates a new Failover handler. func New(hc *dynamic.HealthCheck) *Failover { return &Failover{ wantsHealthCheck: hc != nil, } } // RegisterStatusUpdater adds fn to the list of hooks that are run when the // status of the Failover changes. // Not thread safe. func (f *Failover) RegisterStatusUpdater(fn func(up bool)) error { if !f.wantsHealthCheck { return errors.New("healthCheck not enabled in config for this failover service") } f.updaters = append(f.updaters, fn) return nil } func (f *Failover) ServeHTTP(w http.ResponseWriter, req *http.Request) { f.handlerStatusMu.RLock() handlerStatus := f.handlerStatus f.handlerStatusMu.RUnlock() if handlerStatus { f.handler.ServeHTTP(w, req) return } f.fallbackStatusMu.RLock() fallbackStatus := f.fallbackStatus f.fallbackStatusMu.RUnlock() if fallbackStatus { f.fallbackHandler.ServeHTTP(w, req) return } http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable) } // SetHandler sets the main http.Handler. func (f *Failover) SetHandler(handler http.Handler) { f.handlerStatusMu.Lock() defer f.handlerStatusMu.Unlock() f.handler = handler f.handlerStatus = true } // SetHandlerStatus sets the main handler status. func (f *Failover) SetHandlerStatus(ctx context.Context, up bool) { f.handlerStatusMu.Lock() defer f.handlerStatusMu.Unlock() status := "DOWN" if up { status = "UP" } if up == f.handlerStatus { // We're still with the same status, no need to propagate. log.Ctx(ctx).Debug().Msgf("Still %s, no need to propagate", status) return } log.Ctx(ctx).Debug().Msgf("Propagating new %s status", status) f.handlerStatus = up for _, fn := range f.updaters { // Failover service status is set to DOWN // when main and fallback handlers have a DOWN status. fn(f.handlerStatus || f.fallbackStatus) } } // SetFallbackHandler sets the fallback http.Handler. func (f *Failover) SetFallbackHandler(handler http.Handler) { f.fallbackStatusMu.Lock() defer f.fallbackStatusMu.Unlock() f.fallbackHandler = handler f.fallbackStatus = true } // SetFallbackHandlerStatus sets the fallback handler status. func (f *Failover) SetFallbackHandlerStatus(ctx context.Context, up bool) { f.fallbackStatusMu.Lock() defer f.fallbackStatusMu.Unlock() status := "DOWN" if up { status = "UP" } if up == f.fallbackStatus { // We're still with the same status, no need to propagate. log.Ctx(ctx).Debug().Msgf("Still %s, no need to propagate", status) return } log.Ctx(ctx).Debug().Msgf("Propagating new %s status", status) f.fallbackStatus = up for _, fn := range f.updaters { // Failover service status is set to DOWN // when main and fallback handlers have a DOWN status. fn(f.handlerStatus || f.fallbackStatus) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/loadbalancer/hrw/hrw_test.go
pkg/server/service/loadbalancer/hrw/hrw_test.go
package hrw import ( "context" "encoding/binary" "math/rand" "net" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) // genIPAddress generate randomly an IP address as a string. func genIPAddress() string { buf := make([]byte, 4) ip := rand.Uint32() binary.LittleEndian.PutUint32(buf, ip) ipStr := net.IP(buf) return ipStr.String() } // initStatusArray initialize an array filled with status value for test assertions. func initStatusArray(size int, value int) []int { status := make([]int, 0, size) for i := 1; i <= size; i++ { status = append(status, value) } return status } // Tests evaluate load balancing of single and multiple clients. // Due to the randomness of IP Adresses, repartition between services is not perfect // The tests validate repartition using a margin of 10% of the number of requests func TestBalancer(t *testing.T) { balancer := New(false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), Int(4), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), Int(1), false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} req := httptest.NewRequest(http.MethodGet, "/", nil) for range 100 { req.RemoteAddr = genIPAddress() balancer.ServeHTTP(recorder, req) } assert.InDelta(t, 80, recorder.save["first"], 10) assert.InDelta(t, 20, recorder.save["second"], 10) } func TestBalancerNoService(t *testing.T) { balancer := New(false) recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, http.StatusServiceUnavailable, recorder.Result().StatusCode) } func TestBalancerOneServerZeroWeight(t *testing.T) { balancer := New(false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), Int(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), Int(0), false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 3 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 3, recorder.save["first"]) } type key string const serviceName key = "serviceName" func TestBalancerNoServiceUp(t *testing.T) { balancer := New(false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusInternalServerError) }), Int(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusInternalServerError) }), Int(1), false) balancer.SetStatus(context.WithValue(t.Context(), serviceName, "parent"), "first", false) balancer.SetStatus(context.WithValue(t.Context(), serviceName, "parent"), "second", false) recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, http.StatusServiceUnavailable, recorder.Result().StatusCode) } func TestBalancerOneServerDown(t *testing.T) { balancer := New(false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), Int(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusInternalServerError) }), Int(1), false) balancer.SetStatus(context.WithValue(t.Context(), serviceName, "parent"), "second", false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 3 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 3, recorder.save["first"]) } func TestBalancerDownThenUp(t *testing.T) { balancer := New(false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), Int(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), Int(1), false) balancer.SetStatus(context.WithValue(t.Context(), serviceName, "parent"), "second", false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} for range 3 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 3, recorder.save["first"]) balancer.SetStatus(context.WithValue(t.Context(), serviceName, "parent"), "second", true) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} req := httptest.NewRequest(http.MethodGet, "/", nil) for range 100 { req.RemoteAddr = genIPAddress() balancer.ServeHTTP(recorder, req) } assert.InDelta(t, 50, recorder.save["first"], 10) assert.InDelta(t, 50, recorder.save["second"], 10) } func TestBalancerPropagate(t *testing.T) { balancer1 := New(true) balancer1.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), Int(1), false) balancer1.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), Int(1), false) balancer2 := New(true) balancer2.Add("third", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "third") rw.WriteHeader(http.StatusOK) }), Int(1), false) balancer2.Add("fourth", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "fourth") rw.WriteHeader(http.StatusOK) }), Int(1), false) topBalancer := New(true) topBalancer.Add("balancer1", balancer1, Int(1), false) _ = balancer1.RegisterStatusUpdater(func(up bool) { topBalancer.SetStatus(context.WithValue(t.Context(), serviceName, "top"), "balancer1", up) // TODO(mpl): if test gets flaky, add channel or something here to signal that // propagation is done, and wait on it before sending request. }) topBalancer.Add("balancer2", balancer2, Int(1), false) _ = balancer2.RegisterStatusUpdater(func(up bool) { topBalancer.SetStatus(context.WithValue(t.Context(), serviceName, "top"), "balancer2", up) }) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} req := httptest.NewRequest(http.MethodGet, "/", nil) for range 100 { req.RemoteAddr = genIPAddress() topBalancer.ServeHTTP(recorder, req) } assert.InDelta(t, 25, recorder.save["first"], 10) assert.InDelta(t, 25, recorder.save["second"], 10) assert.InDelta(t, 25, recorder.save["third"], 10) assert.InDelta(t, 25, recorder.save["fourth"], 10) wantStatus := initStatusArray(100, 200) assert.Equal(t, wantStatus, recorder.status) // fourth gets downed, but balancer2 still up since third is still up. balancer2.SetStatus(context.WithValue(t.Context(), serviceName, "top"), "fourth", false) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} req = httptest.NewRequest(http.MethodGet, "/", nil) for range 100 { req.RemoteAddr = genIPAddress() topBalancer.ServeHTTP(recorder, req) } assert.InDelta(t, 25, recorder.save["first"], 10) assert.InDelta(t, 25, recorder.save["second"], 10) assert.InDelta(t, 50, recorder.save["third"], 10) assert.InDelta(t, 0, recorder.save["fourth"], 0) wantStatus = initStatusArray(100, 200) assert.Equal(t, wantStatus, recorder.status) // third gets downed, and the propagation triggers balancer2 to be marked as // down as well for topBalancer. balancer2.SetStatus(context.WithValue(t.Context(), serviceName, "top"), "third", false) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} req = httptest.NewRequest(http.MethodGet, "/", nil) for range 100 { req.RemoteAddr = genIPAddress() topBalancer.ServeHTTP(recorder, req) } assert.InDelta(t, 50, recorder.save["first"], 10) assert.InDelta(t, 50, recorder.save["second"], 10) assert.InDelta(t, 0, recorder.save["third"], 0) assert.InDelta(t, 0, recorder.save["fourth"], 0) wantStatus = initStatusArray(100, 200) assert.Equal(t, wantStatus, recorder.status) } func TestBalancerAllServersZeroWeight(t *testing.T) { balancer := New(false) balancer.Add("test", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), Int(0), false) balancer.Add("test2", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), Int(0), false) recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, http.StatusServiceUnavailable, recorder.Result().StatusCode) } func TestSticky(t *testing.T) { balancer := New(false) balancer.Add("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), Int(1), false) balancer.Add("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), Int(2), false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} req := httptest.NewRequest(http.MethodGet, "/", nil) req.RemoteAddr = genIPAddress() for range 10 { for _, cookie := range recorder.Result().Cookies() { req.AddCookie(cookie) } recorder.ResponseRecorder = httptest.NewRecorder() balancer.ServeHTTP(recorder, req) } assert.True(t, recorder.save["first"] == 0 || recorder.save["first"] == 10) assert.True(t, recorder.save["second"] == 0 || recorder.save["second"] == 10) // from one IP, the choice between server must be the same for the 10 requests // weight does not impose what would be chosen from 1 client } func Int(v int) *int { return &v } type responseRecorder struct { *httptest.ResponseRecorder save map[string]int sequence []string status []int } func (r *responseRecorder) WriteHeader(statusCode int) { r.save[r.Header().Get("server")]++ r.sequence = append(r.sequence, r.Header().Get("server")) r.status = append(r.status, statusCode) r.ResponseRecorder.WriteHeader(statusCode) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/loadbalancer/hrw/hrw.go
pkg/server/service/loadbalancer/hrw/hrw.go
package hrw import ( "context" "errors" "hash/fnv" "math" "net/http" "sync" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/ip" ) var errNoAvailableServer = errors.New("no available server") type namedHandler struct { http.Handler name string weight float64 } // Balancer implements the Rendezvous Hashing algorithm for load balancing. // The idea is to compute a score for each available backend using a hash of the client's // source (for example, IP) combined with the backend's identifier, and assign the client // to the backend with the highest score. This ensures that each client consistently // connects to the same backend while distributing load evenly across all backends. type Balancer struct { wantsHealthCheck bool strategy ip.RemoteAddrStrategy handlersMu sync.RWMutex // References all the handlers by name and also by the hashed value of the name. handlers []*namedHandler // status is a record of which child services of the Balancer are healthy, keyed // by name of child service. A service is initially added to the map when it is // created via Add, and it is later removed or added to the map as needed, // through the SetStatus method. status map[string]struct{} // updaters is the list of hooks that are run (to update the Balancer // parent(s)), whenever the Balancer status changes. // No mutex is needed, as it is modified only during the configuration build. updaters []func(bool) // fenced is the list of terminating yet still serving child services. fenced map[string]struct{} } // New creates a new load balancer. func New(wantHealthCheck bool) *Balancer { balancer := &Balancer{ status: make(map[string]struct{}), fenced: make(map[string]struct{}), wantsHealthCheck: wantHealthCheck, strategy: ip.RemoteAddrStrategy{}, } return balancer } // getNodeScore calculates the score of the couple of src and handler name. func getNodeScore(handler *namedHandler, src string) float64 { h := fnv.New64a() h.Write([]byte(src + handler.name)) sum := h.Sum64() score := float64(sum) / math.Pow(2, 64) logScore := 1.0 / -math.Log(score) return logScore * handler.weight } // SetStatus sets on the balancer that its given child is now of the given // status. balancerName is only needed for logging purposes. func (b *Balancer) SetStatus(ctx context.Context, childName string, up bool) { b.handlersMu.Lock() defer b.handlersMu.Unlock() upBefore := len(b.status) > 0 status := "DOWN" if up { status = "UP" } log.Ctx(ctx).Debug().Msgf("Setting status of %s to %v", childName, status) if up { b.status[childName] = struct{}{} } else { delete(b.status, childName) } upAfter := len(b.status) > 0 status = "DOWN" if upAfter { status = "UP" } // No Status Change if upBefore == upAfter { // We're still with the same status, no need to propagate log.Ctx(ctx).Debug().Msgf("Still %s, no need to propagate", status) return } // Status Change log.Ctx(ctx).Debug().Msgf("Propagating new %s status", status) for _, fn := range b.updaters { fn(upAfter) } } // RegisterStatusUpdater adds fn to the list of hooks that are run when the // status of the Balancer changes. // Not thread safe. func (b *Balancer) RegisterStatusUpdater(fn func(up bool)) error { if !b.wantsHealthCheck { return errors.New("healthCheck not enabled in config for this HRW service") } b.updaters = append(b.updaters, fn) return nil } func (b *Balancer) nextServer(ip string) (*namedHandler, error) { b.handlersMu.RLock() var healthy []*namedHandler for _, h := range b.handlers { if _, ok := b.status[h.name]; ok { if _, fenced := b.fenced[h.name]; !fenced { healthy = append(healthy, h) } } } b.handlersMu.RUnlock() if len(healthy) == 0 { return nil, errNoAvailableServer } var handler *namedHandler score := 0.0 for _, h := range healthy { s := getNodeScore(h, ip) if s > score { handler = h score = s } } log.Debug().Msgf("Service selected by HRW: %s", handler.name) return handler, nil } func (b *Balancer) ServeHTTP(w http.ResponseWriter, req *http.Request) { // give ip fetched to b.nextServer clientIP := b.strategy.GetIP(req) log.Debug().Msgf("ServeHTTP() clientIP=%s", clientIP) server, err := b.nextServer(clientIP) if err != nil { if errors.Is(err, errNoAvailableServer) { http.Error(w, errNoAvailableServer.Error(), http.StatusServiceUnavailable) } else { http.Error(w, err.Error(), http.StatusInternalServerError) } return } server.ServeHTTP(w, req) } // AddServer adds a handler with a server. func (b *Balancer) AddServer(name string, handler http.Handler, server dynamic.Server) { b.Add(name, handler, server.Weight, server.Fenced) } // Add adds a handler. // A handler with a non-positive weight is ignored. func (b *Balancer) Add(name string, handler http.Handler, weight *int, fenced bool) { w := 1 if weight != nil { w = *weight } if w <= 0 { // non-positive weight is meaningless return } h := &namedHandler{Handler: handler, name: name, weight: float64(w)} b.handlersMu.Lock() b.handlers = append(b.handlers, h) b.status[name] = struct{}{} if fenced { b.fenced[name] = struct{}{} } b.handlersMu.Unlock() }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/loadbalancer/p2c/p2c.go
pkg/server/service/loadbalancer/p2c/p2c.go
package p2c import ( "context" "errors" "math/rand" "net/http" "sync" "sync/atomic" "time" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/server/service/loadbalancer" ) var errNoAvailableServer = errors.New("no available server") type namedHandler struct { http.Handler // name is the handler name. name string // inflight is the number of inflight requests. // It is used to implement the "power-of-two-random-choices" algorithm. inflight atomic.Int64 } func (h *namedHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { h.inflight.Add(1) defer h.inflight.Add(-1) h.Handler.ServeHTTP(rw, req) } type rnd interface { Intn(n int) int } // Balancer implements the power-of-two-random-choices algorithm for load balancing. // The idea is to randomly select two of the available backends and choose the one with the fewest in-flight requests. // This algorithm balances the load more effectively than a round-robin approach, while maintaining a constant time for the selection: // The strategy also has more advantageous "herd" behavior than the "fewest connections" algorithm, especially when the load balancer // doesn't have perfect knowledge of the global number of connections to the backend, for example, when running in a distributed fashion. type Balancer struct { wantsHealthCheck bool // handlersMu is a mutex to protect the handlers slice, the status and the fenced maps. handlersMu sync.RWMutex handlers []*namedHandler // status is a record of which child services of the Balancer are healthy, keyed // by name of child service. A service is initially added to the map when it is // created via Add, and it is later removed or added to the map as needed, // through the SetStatus method. status map[string]struct{} // fenced is the list of terminating yet still serving child services. fenced map[string]struct{} // updaters is the list of hooks that are run (to update the Balancer // parent(s)), whenever the Balancer status changes. // No mutex is needed, as it is modified only during the configuration build. updaters []func(bool) sticky *loadbalancer.Sticky randMu sync.Mutex rand rnd } // New creates a new power-of-two-random-choices load balancer. func New(stickyConfig *dynamic.Sticky, wantsHealthCheck bool) *Balancer { balancer := &Balancer{ status: make(map[string]struct{}), fenced: make(map[string]struct{}), wantsHealthCheck: wantsHealthCheck, rand: rand.New(rand.NewSource(time.Now().UnixNano())), } if stickyConfig != nil && stickyConfig.Cookie != nil { balancer.sticky = loadbalancer.NewSticky(*stickyConfig.Cookie) } return balancer } // SetStatus sets on the balancer that its given child is now of the given // status. childName is only needed for logging purposes. func (b *Balancer) SetStatus(ctx context.Context, childName string, up bool) { b.handlersMu.Lock() defer b.handlersMu.Unlock() upBefore := len(b.status) > 0 status := "DOWN" if up { status = "UP" } log.Ctx(ctx).Debug().Msgf("Setting status of %s to %v", childName, status) if up { b.status[childName] = struct{}{} } else { delete(b.status, childName) } upAfter := len(b.status) > 0 status = "DOWN" if upAfter { status = "UP" } // No Status Change if upBefore == upAfter { // We're still with the same status, no need to propagate log.Ctx(ctx).Debug().Msgf("Still %s, no need to propagate", status) return } // Status Change log.Ctx(ctx).Debug().Msgf("Propagating new %s status", status) for _, fn := range b.updaters { fn(upAfter) } } // RegisterStatusUpdater adds fn to the list of hooks that are run when the // status of the Balancer changes. // Not thread safe. func (b *Balancer) RegisterStatusUpdater(fn func(up bool)) error { if !b.wantsHealthCheck { return errors.New("healthCheck not enabled in config for this P2C service") } b.updaters = append(b.updaters, fn) return nil } func (b *Balancer) nextServer() (*namedHandler, error) { // We kept the same representation (map) as in the WRR strategy to improve maintainability. // However, with the P2C strategy, we only need a slice of healthy servers. b.handlersMu.RLock() var healthy []*namedHandler for _, h := range b.handlers { if _, ok := b.status[h.name]; ok { if _, fenced := b.fenced[h.name]; !fenced { healthy = append(healthy, h) } } } b.handlersMu.RUnlock() if len(healthy) == 0 { return nil, errNoAvailableServer } // If there is only one healthy server, return it. if len(healthy) == 1 { return healthy[0], nil } // In order to not get the same backend twice, we make the second call to s.rand.Intn one fewer // than the length of the slice. We then have to shift over the second index if it is equal or // greater than the first index, wrapping round if needed. b.randMu.Lock() n1, n2 := b.rand.Intn(len(healthy)), b.rand.Intn(len(healthy)) b.randMu.Unlock() if n2 == n1 { n2 = (n2 + 1) % len(healthy) } h1, h2 := healthy[n1], healthy[n2] // Ensure h1 has fewer inflight requests than h2. if h2.inflight.Load() < h1.inflight.Load() { log.Debug().Msgf("Service selected by P2C: %s", h2.name) return h2, nil } log.Debug().Msgf("Service selected by P2C: %s", h1.name) return h1, nil } func (b *Balancer) ServeHTTP(rw http.ResponseWriter, req *http.Request) { if b.sticky != nil { h, rewrite, err := b.sticky.StickyHandler(req) if err != nil { log.Error().Err(err).Msg("Error while getting sticky handler") } else if h != nil { b.handlersMu.RLock() _, ok := b.status[h.Name] b.handlersMu.RUnlock() if ok { if rewrite { if err := b.sticky.WriteStickyCookie(rw, h.Name); err != nil { log.Error().Err(err).Msg("Writing sticky cookie") } } h.ServeHTTP(rw, req) return } } } server, err := b.nextServer() if err != nil { if errors.Is(err, errNoAvailableServer) { http.Error(rw, errNoAvailableServer.Error(), http.StatusServiceUnavailable) } else { http.Error(rw, err.Error(), http.StatusInternalServerError) } return } if b.sticky != nil { if err := b.sticky.WriteStickyCookie(rw, server.name); err != nil { log.Error().Err(err).Msg("Error while writing sticky cookie") } } server.ServeHTTP(rw, req) } // AddServer adds a handler with a server. func (b *Balancer) AddServer(name string, handler http.Handler, server dynamic.Server) { h := &namedHandler{Handler: handler, name: name} b.handlersMu.Lock() b.handlers = append(b.handlers, h) b.status[name] = struct{}{} if server.Fenced { b.fenced[name] = struct{}{} } b.handlersMu.Unlock() if b.sticky != nil { b.sticky.AddHandler(name, h) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/loadbalancer/p2c/p2c_test.go
pkg/server/service/loadbalancer/p2c/p2c_test.go
package p2c import ( "net/http" "net/http/httptest" "strconv" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) func TestP2C(t *testing.T) { testCases := []struct { desc string handlers []*namedHandler rand *mockRand expectedHandler string }{ { desc: "one healthy handler", handlers: testHandlers(0), rand: nil, expectedHandler: "0", }, { desc: "two handlers zero in flight", handlers: testHandlers(0, 0), rand: &mockRand{vals: []int{1, 0}}, expectedHandler: "1", }, { desc: "chooses lower of two", handlers: testHandlers(0, 1), rand: &mockRand{vals: []int{1, 0}}, expectedHandler: "0", }, { desc: "chooses lower of three", handlers: testHandlers(10, 90, 40), rand: &mockRand{vals: []int{1, 1}}, expectedHandler: "2", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() balancer := New(nil, false) balancer.rand = test.rand for _, h := range test.handlers { balancer.handlers = append(balancer.handlers, h) balancer.status[h.name] = struct{}{} } got, err := balancer.nextServer() require.NoError(t, err) assert.Equal(t, test.expectedHandler, got.name) }) } } func TestSticky(t *testing.T) { balancer := New(&dynamic.Sticky{ Cookie: &dynamic.Cookie{ Name: "test", Secure: true, HTTPOnly: true, SameSite: "none", MaxAge: 42, Path: func(v string) *string { return &v }("/foo"), }, }, false) balancer.rand = &mockRand{vals: []int{1, 0}} balancer.AddServer("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), dynamic.Server{}) balancer.AddServer("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), dynamic.Server{}) recorder := &responseRecorder{ ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}, cookies: make(map[string]*http.Cookie), } req := httptest.NewRequest(http.MethodGet, "/", nil) for range 3 { for _, cookie := range recorder.Result().Cookies() { assert.NotContains(t, "first", cookie.Value) assert.NotContains(t, "second", cookie.Value) req.AddCookie(cookie) } recorder.ResponseRecorder = httptest.NewRecorder() balancer.ServeHTTP(recorder, req) } assert.Equal(t, 0, recorder.save["first"]) assert.Equal(t, 3, recorder.save["second"]) assert.True(t, recorder.cookies["test"].HttpOnly) assert.True(t, recorder.cookies["test"].Secure) assert.Equal(t, http.SameSiteNoneMode, recorder.cookies["test"].SameSite) assert.Equal(t, 42, recorder.cookies["test"].MaxAge) assert.Equal(t, "/foo", recorder.cookies["test"].Path) } func TestSticky_Fallback(t *testing.T) { balancer := New(&dynamic.Sticky{ Cookie: &dynamic.Cookie{Name: "test"}, }, false) balancer.rand = &mockRand{vals: []int{1, 0}} balancer.AddServer("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), dynamic.Server{}) balancer.AddServer("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), dynamic.Server{}) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}, cookies: make(map[string]*http.Cookie)} req := httptest.NewRequest(http.MethodGet, "/", nil) req.AddCookie(&http.Cookie{Name: "test", Value: "second"}) for range 3 { recorder.ResponseRecorder = httptest.NewRecorder() balancer.ServeHTTP(recorder, req) } assert.Equal(t, 0, recorder.save["first"]) assert.Equal(t, 3, recorder.save["second"]) } // TestSticky_Fenced checks that fenced node receive traffic if their sticky cookie matches. func TestSticky_Fenced(t *testing.T) { balancer := New(&dynamic.Sticky{Cookie: &dynamic.Cookie{Name: "test"}}, false) balancer.rand = &mockRand{vals: []int{1, 0, 1, 0}} balancer.AddServer("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), dynamic.Server{}) balancer.AddServer("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), dynamic.Server{}) balancer.AddServer("fenced", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "fenced") rw.WriteHeader(http.StatusOK) }), dynamic.Server{Fenced: true}) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}, cookies: make(map[string]*http.Cookie)} stickyReq := httptest.NewRequest(http.MethodGet, "/", nil) stickyReq.AddCookie(&http.Cookie{Name: "test", Value: "fenced"}) req := httptest.NewRequest(http.MethodGet, "/", nil) for range 2 { recorder.ResponseRecorder = httptest.NewRecorder() balancer.ServeHTTP(recorder, stickyReq) balancer.ServeHTTP(recorder, req) } assert.Equal(t, 2, recorder.save["fenced"]) assert.Equal(t, 0, recorder.save["first"]) assert.Equal(t, 2, recorder.save["second"]) } func TestBalancerPropagate(t *testing.T) { balancer := New(nil, true) balancer.AddServer("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "first") rw.WriteHeader(http.StatusOK) }), dynamic.Server{}) balancer.AddServer("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("server", "second") rw.WriteHeader(http.StatusOK) }), dynamic.Server{}) var calls int err := balancer.RegisterStatusUpdater(func(up bool) { calls++ }) require.NoError(t, err) recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, http.StatusOK, recorder.Code) // two gets downed, but balancer still up since first is still up. balancer.SetStatus(t.Context(), "second", false) assert.Equal(t, 0, calls) recorder = httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, http.StatusOK, recorder.Code) assert.Equal(t, "first", recorder.Header().Get("server")) // first gets downed, balancer is down. balancer.SetStatus(t.Context(), "first", false) assert.Equal(t, 1, calls) recorder = httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, http.StatusServiceUnavailable, recorder.Code) // two gets up, balancer up. balancer.SetStatus(t.Context(), "second", true) assert.Equal(t, 2, calls) recorder = httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, http.StatusOK, recorder.Code) assert.Equal(t, "second", recorder.Header().Get("server")) } func TestBalancerAllServersFenced(t *testing.T) { balancer := New(nil, false) balancer.AddServer("test", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), dynamic.Server{Fenced: true}) balancer.AddServer("test2", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), dynamic.Server{Fenced: true}) recorder := httptest.NewRecorder() balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) assert.Equal(t, http.StatusServiceUnavailable, recorder.Result().StatusCode) } type responseRecorder struct { *httptest.ResponseRecorder save map[string]int sequence []string status []int cookies map[string]*http.Cookie } func (r *responseRecorder) WriteHeader(statusCode int) { r.save[r.Header().Get("server")]++ r.sequence = append(r.sequence, r.Header().Get("server")) r.status = append(r.status, statusCode) for _, cookie := range r.Result().Cookies() { r.cookies[cookie.Name] = cookie } r.ResponseRecorder.WriteHeader(statusCode) } type mockRand struct { vals []int calls int } func (m *mockRand) Intn(int) int { defer func() { m.calls++ }() return m.vals[m.calls] } func testHandlers(inflights ...int) []*namedHandler { var out []*namedHandler for i, inflight := range inflights { h := &namedHandler{ name: strconv.Itoa(i), } h.inflight.Store(int64(inflight)) out = append(out, h) } return out }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/loadbalancer/mirror/mirror.go
pkg/server/service/loadbalancer/mirror/mirror.go
package mirror import ( "bufio" "bytes" "context" "errors" "fmt" "io" "net" "net/http" "sync" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/healthcheck" "github.com/traefik/traefik/v3/pkg/middlewares/accesslog" "github.com/traefik/traefik/v3/pkg/safe" ) // Mirroring is an http.Handler that can mirror requests. type Mirroring struct { handler http.Handler mirrorHandlers []*mirrorHandler rw http.ResponseWriter routinePool *safe.Pool mirrorBody bool maxBodySize int64 wantsHealthCheck bool lock sync.RWMutex total uint64 } // New returns a new instance of *Mirroring. func New(handler http.Handler, pool *safe.Pool, mirrorBody bool, maxBodySize int64, hc *dynamic.HealthCheck) *Mirroring { return &Mirroring{ routinePool: pool, handler: handler, rw: blackHoleResponseWriter{}, mirrorBody: mirrorBody, maxBodySize: maxBodySize, wantsHealthCheck: hc != nil, } } func (m *Mirroring) inc() uint64 { m.lock.Lock() defer m.lock.Unlock() m.total++ return m.total } type mirrorHandler struct { http.Handler percent int lock sync.RWMutex count uint64 } func (m *Mirroring) getActiveMirrors() []http.Handler { total := m.inc() var mirrors []http.Handler for _, handler := range m.mirrorHandlers { handler.lock.Lock() if handler.count*100 < total*uint64(handler.percent) { handler.count++ handler.lock.Unlock() mirrors = append(mirrors, handler) } else { handler.lock.Unlock() } } return mirrors } func (m *Mirroring) ServeHTTP(rw http.ResponseWriter, req *http.Request) { mirrors := m.getActiveMirrors() if len(mirrors) == 0 { m.handler.ServeHTTP(rw, req) return } logger := log.Ctx(req.Context()) rr, bytesRead, err := newReusableRequest(req, m.mirrorBody, m.maxBodySize) if err != nil && !errors.Is(err, errBodyTooLarge) { http.Error(rw, fmt.Sprintf("%s: creating reusable request: %v", http.StatusText(http.StatusInternalServerError), err), http.StatusInternalServerError) return } if errors.Is(err, errBodyTooLarge) { req.Body = io.NopCloser(io.MultiReader(bytes.NewReader(bytesRead), req.Body)) m.handler.ServeHTTP(rw, req) logger.Debug().Msg("No mirroring, request body larger than allowed size") return } m.handler.ServeHTTP(rw, rr.clone(req.Context())) select { case <-req.Context().Done(): // No mirroring if request has been canceled during main handler ServeHTTP logger.Warn().Msg("No mirroring, request has been canceled during main handler ServeHTTP") return default: } m.routinePool.GoCtx(func(_ context.Context) { for _, handler := range mirrors { // prepare request, update body from buffer r := rr.clone(req.Context()) // In ServeHTTP, we rely on the presence of the accessLog datatable found in the request's context // to know whether we should mutate said datatable (and contribute some fields to the log). // In this instance, we do not want the mirrors mutating (i.e. changing the service name in) // the logs related to the mirrored server. // Especially since it would result in unguarded concurrent reads/writes on the datatable. // Therefore, we reset any potential datatable key in the new context that we pass around. ctx := context.WithValue(r.Context(), accesslog.DataTableKey, nil) // When a request served by m.handler is successful, req.Context will be canceled, // which would trigger a cancellation of the ongoing mirrored requests. // Therefore, we give a new, non-cancellable context to each of the mirrored calls, // so they can terminate by themselves. handler.ServeHTTP(m.rw, r.WithContext(contextStopPropagation{ctx})) } }) } // AddMirror adds an httpHandler to mirror to. func (m *Mirroring) AddMirror(handler http.Handler, percent int) error { if percent < 0 || percent > 100 { return errors.New("percent must be between 0 and 100") } m.mirrorHandlers = append(m.mirrorHandlers, &mirrorHandler{Handler: handler, percent: percent}) return nil } // RegisterStatusUpdater adds fn to the list of hooks that are run when the // status of handler of the Mirroring changes. // Not thread safe. func (m *Mirroring) RegisterStatusUpdater(fn func(up bool)) error { // Since the status propagation is completely transparent through the // mirroring (because of the recursion on the underlying service), we could maybe // skip that below, and even not add HealthCheck as a field of // dynamic.Mirroring. But I think it's easier to understand for the user // if the HealthCheck is required absolutely everywhere in the config. if !m.wantsHealthCheck { return errors.New("healthCheck not enabled in config for this mirroring service") } updater, ok := m.handler.(healthcheck.StatusUpdater) if !ok { return fmt.Errorf("service of mirroring %T not a healthcheck.StatusUpdater", m.handler) } if err := updater.RegisterStatusUpdater(fn); err != nil { return fmt.Errorf("cannot register service of mirroring as updater: %w", err) } return nil } type blackHoleResponseWriter struct{} func (b blackHoleResponseWriter) Flush() {} func (b blackHoleResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { return nil, nil, errors.New("connection on blackHoleResponseWriter cannot be hijacked") } func (b blackHoleResponseWriter) Header() http.Header { return http.Header{} } func (b blackHoleResponseWriter) Write(data []byte) (int, error) { return len(data), nil } func (b blackHoleResponseWriter) WriteHeader(_ int) {} type contextStopPropagation struct { context.Context } func (c contextStopPropagation) Done() <-chan struct{} { return make(chan struct{}) } // reusableRequest keeps in memory the body of the given request, // so that the request can be fully cloned by each mirror. type reusableRequest struct { req *http.Request body []byte } var errBodyTooLarge = errors.New("request body too large") // if the returned error is errBodyTooLarge, newReusableRequest also returns the // bytes that were already consumed from the request's body. func newReusableRequest(req *http.Request, mirrorBody bool, maxBodySize int64) (*reusableRequest, []byte, error) { if req == nil { return nil, nil, errors.New("nil input request") } if req.Body == nil || req.ContentLength == 0 || !mirrorBody { return &reusableRequest{req: req}, nil, nil } // unbounded body size if maxBodySize < 0 { body, err := io.ReadAll(req.Body) if err != nil { return nil, nil, err } return &reusableRequest{ req: req, body: body, }, nil, nil } // we purposefully try to read _more_ than maxBodySize to detect whether // the request body is larger than what we allow for the mirrors. body := make([]byte, maxBodySize+1) n, err := io.ReadFull(req.Body, body) if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) { return nil, nil, err } // we got an ErrUnexpectedEOF, which means there was less than maxBodySize data to read, // which permits us sending also to all the mirrors later. if errors.Is(err, io.ErrUnexpectedEOF) { return &reusableRequest{ req: req, body: body[:n], }, nil, nil } // err == nil , which means data size > maxBodySize return nil, body[:n], errBodyTooLarge } func (rr reusableRequest) clone(ctx context.Context) *http.Request { req := rr.req.Clone(ctx) if rr.body != nil { req.Body = io.NopCloser(bytes.NewReader(rr.body)) } return req }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/service/loadbalancer/mirror/mirror_test.go
pkg/server/service/loadbalancer/mirror/mirror_test.go
package mirror import ( "bytes" "io" "net/http" "net/http/httptest" "sync/atomic" "testing" "github.com/stretchr/testify/assert" "github.com/traefik/traefik/v3/pkg/safe" ) const defaultMaxBodySize int64 = -1 func TestMirroringOn100(t *testing.T) { var countMirror1, countMirror2 int32 handler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) }) pool := safe.NewPool(t.Context()) mirror := New(handler, pool, true, defaultMaxBodySize, nil) err := mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { atomic.AddInt32(&countMirror1, 1) }), 10) assert.NoError(t, err) err = mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { atomic.AddInt32(&countMirror2, 1) }), 50) assert.NoError(t, err) for range 100 { mirror.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) } pool.Stop() val1 := atomic.LoadInt32(&countMirror1) val2 := atomic.LoadInt32(&countMirror2) assert.Equal(t, 10, int(val1)) assert.Equal(t, 50, int(val2)) } func TestMirroringOn10(t *testing.T) { var countMirror1, countMirror2 int32 handler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) }) pool := safe.NewPool(t.Context()) mirror := New(handler, pool, true, defaultMaxBodySize, nil) err := mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { atomic.AddInt32(&countMirror1, 1) }), 10) assert.NoError(t, err) err = mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { atomic.AddInt32(&countMirror2, 1) }), 50) assert.NoError(t, err) for range 10 { mirror.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) } pool.Stop() val1 := atomic.LoadInt32(&countMirror1) val2 := atomic.LoadInt32(&countMirror2) assert.Equal(t, 1, int(val1)) assert.Equal(t, 5, int(val2)) } func TestInvalidPercent(t *testing.T) { mirror := New(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), safe.NewPool(t.Context()), true, defaultMaxBodySize, nil) err := mirror.AddMirror(nil, -1) assert.Error(t, err) err = mirror.AddMirror(nil, 101) assert.Error(t, err) err = mirror.AddMirror(nil, 100) assert.NoError(t, err) err = mirror.AddMirror(nil, 0) assert.NoError(t, err) } func TestHijack(t *testing.T) { handler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) }) pool := safe.NewPool(t.Context()) mirror := New(handler, pool, true, defaultMaxBodySize, nil) var mirrorRequest bool err := mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { hijacker, ok := rw.(http.Hijacker) assert.True(t, ok) _, _, err := hijacker.Hijack() assert.Error(t, err) mirrorRequest = true }), 100) assert.NoError(t, err) mirror.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) pool.Stop() assert.True(t, mirrorRequest) } func TestFlush(t *testing.T) { handler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusOK) }) pool := safe.NewPool(t.Context()) mirror := New(handler, pool, true, defaultMaxBodySize, nil) var mirrorRequest bool err := mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { hijacker, ok := rw.(http.Flusher) assert.True(t, ok) hijacker.Flush() mirrorRequest = true }), 100) assert.NoError(t, err) mirror.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) pool.Stop() assert.True(t, mirrorRequest) } func TestMirroringWithBody(t *testing.T) { const numMirrors = 10 var ( countMirror int32 body = []byte(`body`) ) pool := safe.NewPool(t.Context()) handler := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { assert.NotNil(t, r.Body) bb, err := io.ReadAll(r.Body) assert.NoError(t, err) assert.Equal(t, body, bb) rw.WriteHeader(http.StatusOK) }) mirror := New(handler, pool, true, defaultMaxBodySize, nil) for range numMirrors { err := mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { assert.NotNil(t, r.Body) bb, err := io.ReadAll(r.Body) assert.NoError(t, err) assert.Equal(t, body, bb) atomic.AddInt32(&countMirror, 1) }), 100) assert.NoError(t, err) } req := httptest.NewRequest(http.MethodPost, "/", bytes.NewBuffer(body)) mirror.ServeHTTP(httptest.NewRecorder(), req) pool.Stop() val := atomic.LoadInt32(&countMirror) assert.Equal(t, numMirrors, int(val)) } func TestMirroringWithIgnoredBody(t *testing.T) { const numMirrors = 10 var ( countMirror int32 body = []byte(`body`) emptyBody = []byte(``) ) pool := safe.NewPool(t.Context()) handler := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { assert.NotNil(t, r.Body) bb, err := io.ReadAll(r.Body) assert.NoError(t, err) assert.Equal(t, body, bb) rw.WriteHeader(http.StatusOK) }) mirror := New(handler, pool, false, defaultMaxBodySize, nil) for range numMirrors { err := mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { assert.NotNil(t, r.Body) bb, err := io.ReadAll(r.Body) assert.NoError(t, err) assert.Equal(t, emptyBody, bb) atomic.AddInt32(&countMirror, 1) }), 100) assert.NoError(t, err) } req := httptest.NewRequest(http.MethodPost, "/", bytes.NewBuffer(body)) mirror.ServeHTTP(httptest.NewRecorder(), req) pool.Stop() val := atomic.LoadInt32(&countMirror) assert.Equal(t, numMirrors, int(val)) } func TestCloneRequest(t *testing.T) { t.Run("http request body is nil", func(t *testing.T) { req, err := http.NewRequest(http.MethodPost, "/", nil) assert.NoError(t, err) ctx := req.Context() rr, _, err := newReusableRequest(req, true, defaultMaxBodySize) assert.NoError(t, err) // first call cloned := rr.clone(ctx) assert.Equal(t, cloned, req) assert.Nil(t, cloned.Body) // second call cloned = rr.clone(ctx) assert.Equal(t, cloned, req) assert.Nil(t, cloned.Body) }) t.Run("http request body is not nil", func(t *testing.T) { bb := []byte(`¯\_(ツ)_/¯`) contentLength := len(bb) buf := bytes.NewBuffer(bb) req, err := http.NewRequest(http.MethodPost, "/", buf) assert.NoError(t, err) ctx := req.Context() req.ContentLength = int64(contentLength) rr, _, err := newReusableRequest(req, true, defaultMaxBodySize) assert.NoError(t, err) // first call cloned := rr.clone(ctx) body, err := io.ReadAll(cloned.Body) assert.NoError(t, err) assert.Equal(t, bb, body) // second call cloned = rr.clone(ctx) body, err = io.ReadAll(cloned.Body) assert.NoError(t, err) assert.Equal(t, bb, body) }) t.Run("failed case", func(t *testing.T) { bb := []byte(`1234567890`) buf := bytes.NewBuffer(bb) req, err := http.NewRequest(http.MethodPost, "/", buf) assert.NoError(t, err) _, expectedBytes, err := newReusableRequest(req, true, 2) assert.Error(t, err) assert.Equal(t, expectedBytes, bb[:3]) }) t.Run("valid case with maxBodySize", func(t *testing.T) { bb := []byte(`1234567890`) buf := bytes.NewBuffer(bb) req, err := http.NewRequest(http.MethodPost, "/", buf) assert.NoError(t, err) rr, expectedBytes, err := newReusableRequest(req, true, 20) assert.NoError(t, err) assert.Nil(t, expectedBytes) assert.Len(t, rr.body, 10) }) t.Run("valid GET case with maxBodySize", func(t *testing.T) { buf := bytes.NewBuffer([]byte{}) req, err := http.NewRequest(http.MethodGet, "/", buf) assert.NoError(t, err) rr, expectedBytes, err := newReusableRequest(req, true, 20) assert.NoError(t, err) assert.Nil(t, expectedBytes) assert.Empty(t, rr.body) }) t.Run("no request given", func(t *testing.T) { _, _, err := newReusableRequest(nil, true, defaultMaxBodySize) assert.Error(t, err) }) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/middleware/middlewares_test.go
pkg/server/middleware/middlewares_test.go
package middleware import ( "errors" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/server/provider" ) func TestBuilder_BuildChainNilConfig(t *testing.T) { testConfig := map[string]*runtime.MiddlewareInfo{ "empty": {}, } middlewaresBuilder := NewBuilder(testConfig, nil, nil) chain := middlewaresBuilder.BuildChain(t.Context(), []string{"empty"}) _, err := chain.Then(nil) require.Error(t, err) } func TestBuilder_BuildChainNonExistentChain(t *testing.T) { testConfig := map[string]*runtime.MiddlewareInfo{ "foobar": {}, } middlewaresBuilder := NewBuilder(testConfig, nil, nil) chain := middlewaresBuilder.BuildChain(t.Context(), []string{"empty"}) _, err := chain.Then(nil) require.Error(t, err) } func TestBuilder_BuildChainWithContext(t *testing.T) { testCases := []struct { desc string buildChain []string configuration map[string]*dynamic.Middleware expected map[string]string contextProvider string expectedError error }{ { desc: "Simple middleware", buildChain: []string{"middleware-1"}, configuration: map[string]*dynamic.Middleware{ "middleware-1": { Headers: &dynamic.Headers{ CustomRequestHeaders: map[string]string{"middleware-1": "value-middleware-1"}, }, }, }, expected: map[string]string{"middleware-1": "value-middleware-1"}, }, { desc: "Middleware that references a chain", buildChain: []string{"middleware-chain-1"}, configuration: map[string]*dynamic.Middleware{ "middleware-1": { Headers: &dynamic.Headers{ CustomRequestHeaders: map[string]string{"middleware-1": "value-middleware-1"}, }, }, "middleware-chain-1": { Chain: &dynamic.Chain{ Middlewares: []string{"middleware-1"}, }, }, }, expected: map[string]string{"middleware-1": "value-middleware-1"}, }, { desc: "Should suffix the middlewareName with the provider in the context", buildChain: []string{"middleware-1"}, configuration: map[string]*dynamic.Middleware{ "middleware-1@provider-1": { Headers: &dynamic.Headers{ CustomRequestHeaders: map[string]string{"middleware-1@provider-1": "value-middleware-1"}, }, }, }, expected: map[string]string{"middleware-1@provider-1": "value-middleware-1"}, contextProvider: "provider-1", }, { desc: "Should not suffix a qualified middlewareName with the provider in the context", buildChain: []string{"middleware-1@provider-1"}, configuration: map[string]*dynamic.Middleware{ "middleware-1@provider-1": { Headers: &dynamic.Headers{ CustomRequestHeaders: map[string]string{"middleware-1@provider-1": "value-middleware-1"}, }, }, }, expected: map[string]string{"middleware-1@provider-1": "value-middleware-1"}, contextProvider: "provider-1", }, { desc: "Should be context aware if a chain references another middleware", buildChain: []string{"middleware-chain-1@provider-1"}, configuration: map[string]*dynamic.Middleware{ "middleware-1@provider-1": { Headers: &dynamic.Headers{ CustomRequestHeaders: map[string]string{"middleware-1": "value-middleware-1"}, }, }, "middleware-chain-1@provider-1": { Chain: &dynamic.Chain{ Middlewares: []string{"middleware-1"}, }, }, }, expected: map[string]string{"middleware-1": "value-middleware-1"}, }, { desc: "Should handle nested chains with different context", buildChain: []string{"middleware-chain-1@provider-1", "middleware-chain-1"}, configuration: map[string]*dynamic.Middleware{ "middleware-1@provider-1": { Headers: &dynamic.Headers{ CustomRequestHeaders: map[string]string{"middleware-1": "value-middleware-1"}, }, }, "middleware-2@provider-1": { Headers: &dynamic.Headers{ CustomRequestHeaders: map[string]string{"middleware-2": "value-middleware-2"}, }, }, "middleware-chain-1@provider-1": { Chain: &dynamic.Chain{ Middlewares: []string{"middleware-1"}, }, }, "middleware-chain-2@provider-1": { Chain: &dynamic.Chain{ Middlewares: []string{"middleware-2"}, }, }, "middleware-chain-1@provider-2": { Chain: &dynamic.Chain{ Middlewares: []string{"middleware-2@provider-1", "middleware-chain-2@provider-1"}, }, }, }, expected: map[string]string{"middleware-1": "value-middleware-1", "middleware-2": "value-middleware-2"}, contextProvider: "provider-2", }, { desc: "Detects recursion in Middleware chain", buildChain: []string{"m1"}, configuration: map[string]*dynamic.Middleware{ "ok": { Retry: &dynamic.Retry{}, }, "m1": { Chain: &dynamic.Chain{ Middlewares: []string{"m2"}, }, }, "m2": { Chain: &dynamic.Chain{ Middlewares: []string{"ok", "m3"}, }, }, "m3": { Chain: &dynamic.Chain{ Middlewares: []string{"m1"}, }, }, }, expectedError: errors.New("could not instantiate middleware m1: recursion detected in m1->m2->m3->m1"), }, { desc: "Detects recursion in Middleware chain", buildChain: []string{"m1@provider"}, configuration: map[string]*dynamic.Middleware{ "ok@provider2": { Retry: &dynamic.Retry{}, }, "m1@provider": { Chain: &dynamic.Chain{ Middlewares: []string{"m2@provider2"}, }, }, "m2@provider2": { Chain: &dynamic.Chain{ Middlewares: []string{"ok", "m3@provider"}, }, }, "m3@provider": { Chain: &dynamic.Chain{ Middlewares: []string{"m1"}, }, }, }, expectedError: errors.New("could not instantiate middleware m1@provider: recursion detected in m1@provider->m2@provider2->m3@provider->m1@provider"), }, { buildChain: []string{"ok", "m0"}, configuration: map[string]*dynamic.Middleware{ "ok": { Retry: &dynamic.Retry{}, }, "m0": { Chain: &dynamic.Chain{ Middlewares: []string{"m0"}, }, }, }, expectedError: errors.New("could not instantiate middleware m0: recursion detected in m0->m0"), }, { desc: "Detects MiddlewareChain that references a Chain that references a Chain with a missing middleware", buildChain: []string{"m0"}, configuration: map[string]*dynamic.Middleware{ "m0": { Chain: &dynamic.Chain{ Middlewares: []string{"m1"}, }, }, "m1": { Chain: &dynamic.Chain{ Middlewares: []string{"m2"}, }, }, "m2": { Chain: &dynamic.Chain{ Middlewares: []string{"m3"}, }, }, "m3": { Chain: &dynamic.Chain{ Middlewares: []string{"m2"}, }, }, }, expectedError: errors.New("could not instantiate middleware m2: recursion detected in m0->m1->m2->m3->m2"), }, { desc: "--", buildChain: []string{"m0"}, configuration: map[string]*dynamic.Middleware{ "m0": { Chain: &dynamic.Chain{ Middlewares: []string{"m0"}, }, }, }, expectedError: errors.New("could not instantiate middleware m0: recursion detected in m0->m0"), }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() ctx := t.Context() if len(test.contextProvider) > 0 { ctx = provider.AddInContext(ctx, "foobar@"+test.contextProvider) } rtConf := runtime.NewConfig(dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: test.configuration, }, }) builder := NewBuilder(rtConf.Middlewares, nil, nil) result := builder.BuildChain(ctx, test.buildChain) handlers, err := result.Then(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) if test.expectedError != nil { require.Error(t, err) require.Equal(t, test.expectedError.Error(), err.Error()) } else { require.NoError(t, err) recorder := httptest.NewRecorder() request, _ := http.NewRequest(http.MethodGet, "http://foo/", nil) handlers.ServeHTTP(recorder, request) for key, value := range test.expected { assert.Equal(t, value, request.Header.Get(key)) } } }) } } func TestBuilder_buildConstructor(t *testing.T) { testConfig := map[string]*dynamic.Middleware{ "cb-empty": { CircuitBreaker: &dynamic.CircuitBreaker{ Expression: "", }, }, "cb-foo": { CircuitBreaker: &dynamic.CircuitBreaker{ Expression: "NetworkErrorRatio() > 0.5", }, }, "ap-empty": { AddPrefix: &dynamic.AddPrefix{ Prefix: "", }, }, "ap-foo": { AddPrefix: &dynamic.AddPrefix{ Prefix: "foo/", }, }, "buff-foo": { Buffering: &dynamic.Buffering{ MaxRequestBodyBytes: 1, MemRequestBodyBytes: 2, MaxResponseBodyBytes: 3, MemResponseBodyBytes: 5, }, }, } rtConf := runtime.NewConfig(dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: testConfig, }, }) middlewaresBuilder := NewBuilder(rtConf.Middlewares, nil, nil) testCases := []struct { desc string middlewareID string expectedError bool }{ { desc: "Should fail at creating a circuit breaker with an empty expression", middlewareID: "cb-empty", expectedError: true, }, { desc: "Should create a circuit breaker with a valid expression", middlewareID: "cb-foo", expectedError: false, }, { desc: "Should create a buffering middleware", middlewareID: "buff-foo", expectedError: false, }, { desc: "Should not create an empty AddPrefix middleware when given an empty prefix", middlewareID: "ap-empty", expectedError: true, }, { desc: "Should create an AddPrefix middleware when given a valid configuration", middlewareID: "ap-foo", expectedError: false, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() constructor, err := middlewaresBuilder.buildConstructor(t.Context(), test.middlewareID) require.NoError(t, err) middleware, err2 := constructor(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {})) if test.expectedError { require.Error(t, err2) } else { require.NoError(t, err) require.NotNil(t, middleware) } }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/middleware/middlewares.go
pkg/server/middleware/middlewares.go
package middleware import ( "context" "errors" "fmt" "net/http" "reflect" "slices" "strings" "github.com/containous/alice" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/middlewares/addprefix" "github.com/traefik/traefik/v3/pkg/middlewares/auth" "github.com/traefik/traefik/v3/pkg/middlewares/buffering" "github.com/traefik/traefik/v3/pkg/middlewares/chain" "github.com/traefik/traefik/v3/pkg/middlewares/circuitbreaker" "github.com/traefik/traefik/v3/pkg/middlewares/compress" "github.com/traefik/traefik/v3/pkg/middlewares/contenttype" "github.com/traefik/traefik/v3/pkg/middlewares/customerrors" "github.com/traefik/traefik/v3/pkg/middlewares/gatewayapi/headermodifier" gapiredirect "github.com/traefik/traefik/v3/pkg/middlewares/gatewayapi/redirect" "github.com/traefik/traefik/v3/pkg/middlewares/gatewayapi/urlrewrite" "github.com/traefik/traefik/v3/pkg/middlewares/grpcweb" "github.com/traefik/traefik/v3/pkg/middlewares/headers" "github.com/traefik/traefik/v3/pkg/middlewares/inflightreq" "github.com/traefik/traefik/v3/pkg/middlewares/ipallowlist" "github.com/traefik/traefik/v3/pkg/middlewares/ipwhitelist" "github.com/traefik/traefik/v3/pkg/middlewares/observability" "github.com/traefik/traefik/v3/pkg/middlewares/passtlsclientcert" "github.com/traefik/traefik/v3/pkg/middlewares/ratelimiter" "github.com/traefik/traefik/v3/pkg/middlewares/redirect" "github.com/traefik/traefik/v3/pkg/middlewares/replacepath" "github.com/traefik/traefik/v3/pkg/middlewares/replacepathregex" "github.com/traefik/traefik/v3/pkg/middlewares/retry" "github.com/traefik/traefik/v3/pkg/middlewares/stripprefix" "github.com/traefik/traefik/v3/pkg/middlewares/stripprefixregex" "github.com/traefik/traefik/v3/pkg/server/provider" ) type middlewareStackType int const ( middlewareStackKey middlewareStackType = iota ) // Builder the middleware builder. type Builder struct { configs map[string]*runtime.MiddlewareInfo pluginBuilder PluginsBuilder serviceBuilder serviceBuilder } type serviceBuilder interface { BuildHTTP(ctx context.Context, serviceName string) (http.Handler, error) } // NewBuilder creates a new Builder. func NewBuilder(configs map[string]*runtime.MiddlewareInfo, serviceBuilder serviceBuilder, pluginBuilder PluginsBuilder) *Builder { return &Builder{configs: configs, serviceBuilder: serviceBuilder, pluginBuilder: pluginBuilder} } // BuildChain creates a middleware chain. func (b *Builder) BuildChain(ctx context.Context, middlewares []string) *alice.Chain { chain := alice.New() for _, name := range middlewares { middlewareName := provider.GetQualifiedName(ctx, name) chain = chain.Append(func(next http.Handler) (http.Handler, error) { constructorContext := provider.AddInContext(ctx, middlewareName) if midInf, ok := b.configs[middlewareName]; !ok || midInf.Middleware == nil { return nil, fmt.Errorf("middleware %q does not exist", middlewareName) } var err error if constructorContext, err = checkRecursion(constructorContext, middlewareName); err != nil { b.configs[middlewareName].AddError(err, true) return nil, err } constructor, err := b.buildConstructor(constructorContext, middlewareName) if err != nil { b.configs[middlewareName].AddError(err, true) return nil, err } handler, err := constructor(next) if err != nil { b.configs[middlewareName].AddError(err, true) return nil, err } return handler, nil }) } return &chain } func checkRecursion(ctx context.Context, middlewareName string) (context.Context, error) { currentStack, ok := ctx.Value(middlewareStackKey).([]string) if !ok { currentStack = []string{} } if slices.Contains(currentStack, middlewareName) { return ctx, fmt.Errorf("could not instantiate middleware %s: recursion detected in %s", middlewareName, strings.Join(append(currentStack, middlewareName), "->")) } return context.WithValue(ctx, middlewareStackKey, append(currentStack, middlewareName)), nil } // it is the responsibility of the caller to make sure that b.configs[middlewareName].Middleware exists. func (b *Builder) buildConstructor(ctx context.Context, middlewareName string) (alice.Constructor, error) { config := b.configs[middlewareName] if config == nil || config.Middleware == nil { return nil, fmt.Errorf("invalid middleware %q configuration", middlewareName) } var middleware alice.Constructor badConf := errors.New("cannot create middleware: multi-types middleware not supported, consider declaring two different pieces of middleware instead") // AddPrefix if config.AddPrefix != nil { middleware = func(next http.Handler) (http.Handler, error) { return addprefix.New(ctx, next, *config.AddPrefix, middlewareName) } } // BasicAuth if config.BasicAuth != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return auth.NewBasic(ctx, next, *config.BasicAuth, middlewareName) } } // Buffering if config.Buffering != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return buffering.New(ctx, next, *config.Buffering, middlewareName) } } // Chain if config.Chain != nil { if middleware != nil { return nil, badConf } var qualifiedNames []string for _, name := range config.Chain.Middlewares { qualifiedNames = append(qualifiedNames, provider.GetQualifiedName(ctx, name)) } config.Chain.Middlewares = qualifiedNames middleware = func(next http.Handler) (http.Handler, error) { return chain.New(ctx, next, *config.Chain, b, middlewareName) } } // CircuitBreaker if config.CircuitBreaker != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return circuitbreaker.New(ctx, next, *config.CircuitBreaker, middlewareName) } } // Compress if config.Compress != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return compress.New(ctx, next, *config.Compress, middlewareName) } } // ContentType if config.ContentType != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return contenttype.New(ctx, next, *config.ContentType, middlewareName) } } // CustomErrors if config.Errors != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return customerrors.New(ctx, next, *config.Errors, b.serviceBuilder, middlewareName) } } // DigestAuth if config.DigestAuth != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return auth.NewDigest(ctx, next, *config.DigestAuth, middlewareName) } } // ForwardAuth if config.ForwardAuth != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return auth.NewForward(ctx, next, *config.ForwardAuth, middlewareName) } } // GrpcWeb if config.GrpcWeb != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return grpcweb.New(ctx, next, *config.GrpcWeb, middlewareName), nil } } // Headers if config.Headers != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return headers.New(ctx, next, *config.Headers, middlewareName) } } // IPWhiteList if config.IPWhiteList != nil { qualifiedName := provider.GetQualifiedName(ctx, middlewareName) log.Warn().Msgf("Middleware %q of type IPWhiteList is deprecated, please use IPAllowList instead.", qualifiedName) if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return ipwhitelist.New(ctx, next, *config.IPWhiteList, middlewareName) } } // IPAllowList if config.IPAllowList != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return ipallowlist.New(ctx, next, *config.IPAllowList, middlewareName) } } // InFlightReq if config.InFlightReq != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return inflightreq.New(ctx, next, *config.InFlightReq, middlewareName) } } // PassTLSClientCert if config.PassTLSClientCert != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return passtlsclientcert.New(ctx, next, *config.PassTLSClientCert, middlewareName) } } // RateLimit if config.RateLimit != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return ratelimiter.New(ctx, next, *config.RateLimit, middlewareName) } } // RedirectRegex if config.RedirectRegex != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return redirect.NewRedirectRegex(ctx, next, *config.RedirectRegex, middlewareName) } } // RedirectScheme if config.RedirectScheme != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return redirect.NewRedirectScheme(ctx, next, *config.RedirectScheme, middlewareName) } } // ReplacePath if config.ReplacePath != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return replacepath.New(ctx, next, *config.ReplacePath, middlewareName) } } // ReplacePathRegex if config.ReplacePathRegex != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return replacepathregex.New(ctx, next, *config.ReplacePathRegex, middlewareName) } } // Retry if config.Retry != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { // TODO missing metrics / accessLog return retry.New(ctx, next, *config.Retry, retry.Listeners{}, middlewareName) } } // StripPrefix if config.StripPrefix != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return stripprefix.New(ctx, next, *config.StripPrefix, middlewareName) } } // StripPrefixRegex if config.StripPrefixRegex != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return stripprefixregex.New(ctx, next, *config.StripPrefixRegex, middlewareName) } } // Plugin if config.Plugin != nil && !reflect.ValueOf(b.pluginBuilder).IsNil() { // Using "reflect" because "b.pluginBuilder" is an interface. if middleware != nil { return nil, badConf } pluginType, rawPluginConfig, err := findPluginConfig(config.Plugin) if err != nil { return nil, fmt.Errorf("plugin: %w", err) } plug, err := b.pluginBuilder.Build(pluginType, rawPluginConfig, middlewareName) if err != nil { return nil, fmt.Errorf("plugin: %w", err) } middleware = func(next http.Handler) (http.Handler, error) { return newTraceablePlugin(ctx, middlewareName, plug, next) } } // Gateway API HTTPRoute filters middlewares. if config.RequestHeaderModifier != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return headermodifier.NewRequestHeaderModifier(ctx, next, *config.RequestHeaderModifier, middlewareName), nil } } if config.ResponseHeaderModifier != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return headermodifier.NewResponseHeaderModifier(ctx, next, *config.ResponseHeaderModifier, middlewareName), nil } } if config.RequestRedirect != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return gapiredirect.NewRequestRedirect(ctx, next, *config.RequestRedirect, middlewareName) } } if config.URLRewrite != nil { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { return urlrewrite.NewURLRewrite(ctx, next, *config.URLRewrite, middlewareName), nil } } if middleware == nil { return nil, fmt.Errorf("invalid middleware %q configuration: invalid middleware type or middleware does not exist", middlewareName) } return observability.WrapMiddleware(ctx, middleware), nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/middleware/plugins.go
pkg/server/middleware/plugins.go
package middleware import ( "context" "errors" "net/http" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/plugins" ) const typeName = "Plugin" // PluginsBuilder the plugin's builder interface. type PluginsBuilder interface { Build(pName string, config map[string]interface{}, middlewareName string) (plugins.Constructor, error) } func findPluginConfig(rawConfig map[string]dynamic.PluginConf) (string, map[string]interface{}, error) { if len(rawConfig) != 1 { return "", nil, errors.New("invalid configuration: no configuration or too many plugin definition") } var pluginType string var rawPluginConfig map[string]interface{} for pType, pConfig := range rawConfig { pluginType = pType rawPluginConfig = pConfig } if pluginType == "" { return "", nil, errors.New("missing plugin type") } return pluginType, rawPluginConfig, nil } type traceablePlugin struct { name string h http.Handler } func newTraceablePlugin(ctx context.Context, name string, plug plugins.Constructor, next http.Handler) (*traceablePlugin, error) { h, err := plug(ctx, next) if err != nil { return nil, err } return &traceablePlugin{name: name, h: h}, nil } func (s *traceablePlugin) ServeHTTP(rw http.ResponseWriter, req *http.Request) { s.h.ServeHTTP(rw, req) } func (s *traceablePlugin) GetTracingInformation() (string, string) { return s.name, typeName }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/middleware/observability.go
pkg/server/middleware/observability.go
package middleware import ( "context" "io" "net/http" "github.com/containous/alice" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/middlewares/accesslog" "github.com/traefik/traefik/v3/pkg/middlewares/capture" mmetrics "github.com/traefik/traefik/v3/pkg/middlewares/metrics" "github.com/traefik/traefik/v3/pkg/middlewares/observability" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/observability/metrics" "github.com/traefik/traefik/v3/pkg/observability/tracing" otypes "github.com/traefik/traefik/v3/pkg/observability/types" ) // ObservabilityMgr is a manager for observability (AccessLogs, Metrics and Tracing) enablement. type ObservabilityMgr struct { config static.Configuration accessLoggerMiddleware *accesslog.Handler metricsRegistry metrics.Registry semConvMetricRegistry *metrics.SemConvMetricsRegistry tracer *tracing.Tracer tracerCloser io.Closer } // NewObservabilityMgr creates a new ObservabilityMgr. func NewObservabilityMgr(config static.Configuration, metricsRegistry metrics.Registry, semConvMetricRegistry *metrics.SemConvMetricsRegistry, accessLoggerMiddleware *accesslog.Handler, tracer *tracing.Tracer, tracerCloser io.Closer) *ObservabilityMgr { return &ObservabilityMgr{ config: config, metricsRegistry: metricsRegistry, semConvMetricRegistry: semConvMetricRegistry, accessLoggerMiddleware: accessLoggerMiddleware, tracer: tracer, tracerCloser: tracerCloser, } } // BuildEPChain an observability middleware chain by entry point. func (o *ObservabilityMgr) BuildEPChain(ctx context.Context, entryPointName string, internal bool, config dynamic.RouterObservabilityConfig) alice.Chain { chain := alice.New() if o == nil { return chain } // Injection of the observability variables in the request context. // This injection must be the first step in order for other observability middlewares to rely on it. chain = chain.Append(func(next http.Handler) (http.Handler, error) { return o.observabilityContextHandler(next, internal, config), nil }) // Capture middleware for accessLogs or metrics. if o.shouldAccessLog(internal, config) || o.shouldMeter(internal, config) || o.shouldMeterSemConv(internal, config) { chain = chain.Append(capture.Wrap) } // As the Entry point observability middleware ensures that the tracing is added to the request and logger context, // it needs to be added before the access log middleware to ensure that the trace ID is logged. chain = chain.Append(observability.EntryPointHandler(ctx, o.tracer, entryPointName)) // Access log handlers. chain = chain.Append(o.accessLoggerMiddleware.AliceConstructor()) chain = chain.Append(func(next http.Handler) (http.Handler, error) { return accesslog.NewFieldHandler(next, logs.EntryPointName, entryPointName, accesslog.InitServiceFields), nil }) // Entrypoint metrics handler. metricsHandler := mmetrics.EntryPointMetricsHandler(ctx, o.metricsRegistry, entryPointName) chain = chain.Append(observability.WrapMiddleware(ctx, metricsHandler)) // Semantic convention server metrics handler. chain = chain.Append(observability.SemConvServerMetricsHandler(ctx, o.semConvMetricRegistry)) return chain } // MetricsRegistry is an accessor to the metrics registry. func (o *ObservabilityMgr) MetricsRegistry() metrics.Registry { if o == nil { return nil } return o.metricsRegistry } // SemConvMetricsRegistry is an accessor to the semantic conventions metrics registry. func (o *ObservabilityMgr) SemConvMetricsRegistry() *metrics.SemConvMetricsRegistry { if o == nil { return nil } return o.semConvMetricRegistry } // Close closes the accessLogger and tracer. func (o *ObservabilityMgr) Close() { if o == nil { return } if o.accessLoggerMiddleware != nil { if err := o.accessLoggerMiddleware.Close(); err != nil { log.Error().Err(err).Msg("Could not close the access log file") } } if o.tracerCloser != nil { if err := o.tracerCloser.Close(); err != nil { log.Error().Err(err).Msg("Could not close the tracer") } } } func (o *ObservabilityMgr) RotateAccessLogs() error { if o.accessLoggerMiddleware == nil { return nil } return o.accessLoggerMiddleware.Rotate() } func (o *ObservabilityMgr) observabilityContextHandler(next http.Handler, internal bool, config dynamic.RouterObservabilityConfig) http.Handler { return observability.WithObservabilityHandler(next, observability.Observability{ AccessLogsEnabled: o.shouldAccessLog(internal, config), MetricsEnabled: o.shouldMeter(internal, config), SemConvMetricsEnabled: o.shouldMeterSemConv(internal, config), TracingEnabled: o.shouldTrace(internal, config, otypes.MinimalVerbosity), DetailedTracingEnabled: o.shouldTrace(internal, config, otypes.DetailedVerbosity), }) } // shouldAccessLog returns whether the access logs should be enabled for the given serviceName and the observability config. func (o *ObservabilityMgr) shouldAccessLog(internal bool, observabilityConfig dynamic.RouterObservabilityConfig) bool { if o == nil { return false } if o.config.AccessLog == nil { return false } if internal && !o.config.AccessLog.AddInternals { return false } return observabilityConfig.AccessLogs == nil || *observabilityConfig.AccessLogs } // shouldMeter returns whether the metrics should be enabled for the given serviceName and the observability config. func (o *ObservabilityMgr) shouldMeter(internal bool, observabilityConfig dynamic.RouterObservabilityConfig) bool { if o == nil || o.metricsRegistry == nil { return false } if !o.metricsRegistry.IsEpEnabled() && !o.metricsRegistry.IsRouterEnabled() && !o.metricsRegistry.IsSvcEnabled() { return false } if o.config.Metrics == nil { return false } if internal && !o.config.Metrics.AddInternals { return false } return observabilityConfig.Metrics == nil || *observabilityConfig.Metrics } // shouldMeterSemConv returns whether the OTel semantic convention metrics should be enabled for the given serviceName and the observability config. func (o *ObservabilityMgr) shouldMeterSemConv(internal bool, observabilityConfig dynamic.RouterObservabilityConfig) bool { if o == nil || o.semConvMetricRegistry == nil { return false } if o.config.Metrics == nil { return false } if internal && !o.config.Metrics.AddInternals { return false } return observabilityConfig.Metrics == nil || *observabilityConfig.Metrics } // shouldTrace returns whether the tracing should be enabled for the given serviceName and the observability config. func (o *ObservabilityMgr) shouldTrace(internal bool, observabilityConfig dynamic.RouterObservabilityConfig, verbosity otypes.TracingVerbosity) bool { if o == nil { return false } if o.config.Tracing == nil { return false } if internal && !o.config.Tracing.AddInternals { return false } if !observabilityConfig.TraceVerbosity.Allows(verbosity) { return false } return observabilityConfig.Tracing == nil || *observabilityConfig.Tracing }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/middleware/tcp/middlewares.go
pkg/server/middleware/tcp/middlewares.go
package tcpmiddleware import ( "context" "fmt" "slices" "strings" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/middlewares/tcp/inflightconn" "github.com/traefik/traefik/v3/pkg/middlewares/tcp/ipallowlist" "github.com/traefik/traefik/v3/pkg/middlewares/tcp/ipwhitelist" "github.com/traefik/traefik/v3/pkg/server/provider" "github.com/traefik/traefik/v3/pkg/tcp" ) type middlewareStackType int const ( middlewareStackKey middlewareStackType = iota ) // Builder the middleware builder. type Builder struct { configs map[string]*runtime.TCPMiddlewareInfo } // NewBuilder creates a new Builder. func NewBuilder(configs map[string]*runtime.TCPMiddlewareInfo) *Builder { return &Builder{configs: configs} } // BuildChain creates a middleware chain. func (b *Builder) BuildChain(ctx context.Context, middlewares []string) *tcp.Chain { chain := tcp.NewChain() for _, name := range middlewares { middlewareName := provider.GetQualifiedName(ctx, name) chain = chain.Append(func(next tcp.Handler) (tcp.Handler, error) { constructorContext := provider.AddInContext(ctx, middlewareName) if midInf, ok := b.configs[middlewareName]; !ok || midInf.TCPMiddleware == nil { return nil, fmt.Errorf("middleware %q does not exist", middlewareName) } var err error if constructorContext, err = checkRecursion(constructorContext, middlewareName); err != nil { b.configs[middlewareName].AddError(err, true) return nil, err } constructor, err := b.buildConstructor(constructorContext, middlewareName) if err != nil { b.configs[middlewareName].AddError(err, true) return nil, err } handler, err := constructor(next) if err != nil { b.configs[middlewareName].AddError(err, true) return nil, err } return handler, nil }) } return &chain } func checkRecursion(ctx context.Context, middlewareName string) (context.Context, error) { currentStack, ok := ctx.Value(middlewareStackKey).([]string) if !ok { currentStack = []string{} } if slices.Contains(currentStack, middlewareName) { return ctx, fmt.Errorf("could not instantiate middleware %s: recursion detected in %s", middlewareName, strings.Join(append(currentStack, middlewareName), "->")) } return context.WithValue(ctx, middlewareStackKey, append(currentStack, middlewareName)), nil } func (b *Builder) buildConstructor(ctx context.Context, middlewareName string) (tcp.Constructor, error) { config := b.configs[middlewareName] if config == nil || config.TCPMiddleware == nil { return nil, fmt.Errorf("invalid middleware %q configuration", middlewareName) } var middleware tcp.Constructor // InFlightConn if config.InFlightConn != nil { middleware = func(next tcp.Handler) (tcp.Handler, error) { return inflightconn.New(ctx, next, *config.InFlightConn, middlewareName) } } // IPWhiteList if config.IPWhiteList != nil { log.Warn().Msg("IPWhiteList is deprecated, please use IPAllowList instead.") middleware = func(next tcp.Handler) (tcp.Handler, error) { return ipwhitelist.New(ctx, next, *config.IPWhiteList, middlewareName) } } // IPAllowList if config.IPAllowList != nil { middleware = func(next tcp.Handler) (tcp.Handler, error) { return ipallowlist.New(ctx, next, *config.IPAllowList, middlewareName) } } if middleware == nil { return nil, fmt.Errorf("invalid middleware %q configuration: invalid middleware type or middleware does not exist", middlewareName) } return middleware, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/cookie/cookie_test.go
pkg/server/cookie/cookie_test.go
package cookie import ( "testing" "github.com/stretchr/testify/assert" ) func TestGetName(t *testing.T) { testCases := []struct { desc string cookieName string backendName string expectedCookieName string }{ { desc: "with backend name, without cookie name", cookieName: "", backendName: "/my/BACKEND-v1.0~rc1", expectedCookieName: "_5f7bc", }, { desc: "without backend name, with cookie name", cookieName: "/my/BACKEND-v1.0~rc1", backendName: "", expectedCookieName: "_my_BACKEND-v1.0~rc1", }, { desc: "with backend name, with cookie name", cookieName: "cookie", backendName: "backend", expectedCookieName: "cookie", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() cookieName := GetName(test.cookieName, test.backendName) assert.Equal(t, test.expectedCookieName, cookieName) }) } } func Test_sanitizeName(t *testing.T) { testCases := []struct { desc string srcName string expectedName string }{ { desc: "with /", srcName: "/my/BACKEND-v1.0~rc1", expectedName: "_my_BACKEND-v1.0~rc1", }, { desc: "some chars", srcName: "!#$%&'()*+-./:<=>?@[]^_`{|}~", expectedName: "!#$%&'__*+-._________^_`_|_~", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() cookieName := sanitizeName(test.srcName) assert.Equal(t, test.expectedName, cookieName, "Cookie name") }) } } func TestGenerateName(t *testing.T) { cookieName := GenerateName("backend") assert.Len(t, "_76eb3", 6) assert.Equal(t, "_76eb3", cookieName) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/cookie/cookie.go
pkg/server/cookie/cookie.go
package cookie import ( "crypto/sha1" "fmt" "strings" "github.com/rs/zerolog/log" ) const cookieNameLength = 6 // GetName of a cookie. func GetName(cookieName, backendName string) string { if len(cookieName) != 0 { return sanitizeName(cookieName) } return GenerateName(backendName) } // GenerateName Generate a hashed name. func GenerateName(backendName string) string { data := []byte("_TRAEFIK_BACKEND_" + backendName) hash := sha1.New() _, err := hash.Write(data) if err != nil { // Impossible case log.Error().Err(err).Msg("Fail to create cookie name") } return fmt.Sprintf("_%x", hash.Sum(nil))[:cookieNameLength] } // sanitizeName According to [RFC 2616](https://www.ietf.org/rfc/rfc2616.txt) section 2.2. func sanitizeName(backend string) string { sanitizer := func(r rune) rune { switch r { case '!', '#', '$', '%', '&', '\'', '*', '+', '-', '.', '^', '`', '|', '~': return r } switch { case 'a' <= r && r <= 'z': fallthrough case 'A' <= r && r <= 'Z': fallthrough case '0' <= r && r <= '9': return r default: return '_' } } return strings.Map(sanitizer, backend) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/provider/provider.go
pkg/server/provider/provider.go
package provider import ( "context" "strings" "github.com/rs/zerolog/log" ) type contextKey int const ( key contextKey = iota ) // AddInContext Adds the provider name in the context. func AddInContext(ctx context.Context, elementName string) context.Context { parts := strings.Split(elementName, "@") if len(parts) == 1 { log.Ctx(ctx).Debug().Msgf("Could not find a provider for %s", elementName) return ctx } if name, ok := ctx.Value(key).(string); ok && name == parts[1] { return ctx } return context.WithValue(ctx, key, parts[1]) } // GetQualifiedName Gets the fully qualified name. func GetQualifiedName(ctx context.Context, elementName string) string { parts := strings.Split(elementName, "@") if len(parts) == 1 { if providerName, ok := ctx.Value(key).(string); ok { return MakeQualifiedName(providerName, parts[0]) } } return elementName } // MakeQualifiedName Creates a qualified name for an element. func MakeQualifiedName(providerName, elementName string) string { return elementName + "@" + providerName }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/provider/provider_test.go
pkg/server/provider/provider_test.go
package provider import ( "context" "testing" "github.com/stretchr/testify/assert" ) func TestAddInContext(t *testing.T) { testCases := []struct { desc string ctx context.Context name string expected string }{ { desc: "without provider information", ctx: t.Context(), name: "test", expected: "", }, { desc: "provider name embedded in element name", ctx: t.Context(), name: "test@foo", expected: "foo", }, { desc: "provider name in context", ctx: context.WithValue(t.Context(), key, "foo"), name: "test", expected: "foo", }, { desc: "provider name in context and different provider name embedded in element name", ctx: context.WithValue(t.Context(), key, "foo"), name: "test@fii", expected: "fii", }, { desc: "provider name in context and same provider name embedded in element name", ctx: context.WithValue(t.Context(), key, "foo"), name: "test@foo", expected: "foo", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() newCtx := AddInContext(test.ctx, test.name) var providerName string if name, ok := newCtx.Value(key).(string); ok { providerName = name } assert.Equal(t, test.expected, providerName) }) } } func TestGetQualifiedName(t *testing.T) { testCases := []struct { desc string ctx context.Context name string expected string }{ { desc: "empty name", ctx: t.Context(), name: "", expected: "", }, { desc: "without provider", ctx: t.Context(), name: "test", expected: "test", }, { desc: "with explicit provider", ctx: t.Context(), name: "test@foo", expected: "test@foo", }, { desc: "with provider in context", ctx: context.WithValue(t.Context(), key, "foo"), name: "test", expected: "test@foo", }, { desc: "with provider in context and explicit name", ctx: context.WithValue(t.Context(), key, "foo"), name: "test@fii", expected: "test@fii", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() qualifiedName := GetQualifiedName(test.ctx, test.name) assert.Equal(t, test.expected, qualifiedName) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/router/deny.go
pkg/server/router/deny.go
package router import ( "net/http" "strings" "github.com/rs/zerolog/log" ) // denyFragment rejects the request if the URL path contains a fragment (hash character). // When go receives an HTTP request, it assumes the absence of fragment URL. // However, it is still possible to send a fragment in the request. // In this case, Traefik will encode the '#' character, altering the request's intended meaning. // To avoid this behavior, the following function rejects requests that include a fragment in the URL. func denyFragment(h http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { if strings.Contains(req.URL.RawPath, "#") { log.Debug().Msgf("Rejecting request because it contains a fragment in the URL path: %s", req.URL.RawPath) rw.WriteHeader(http.StatusBadRequest) return } h.ServeHTTP(rw, req) }) } // denyEncodedPathCharacters reject the request if the escaped path contains encoded characters in the given list. func denyEncodedPathCharacters(encodedCharacters map[string]struct{}, h http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { if len(encodedCharacters) == 0 { h.ServeHTTP(rw, req) return } escapedPath := req.URL.EscapedPath() for i := 0; i < len(escapedPath); i++ { if escapedPath[i] != '%' { continue } // This should never happen as the standard library will reject requests containing invalid percent-encodings. // This discards URLs with a percent character at the end. if i+2 >= len(escapedPath) { rw.WriteHeader(http.StatusBadRequest) return } // This rejects a request with a path containing the given encoded characters. if _, exists := encodedCharacters[escapedPath[i:i+3]]; exists { log.Debug().Msgf("Rejecting request because it contains encoded character %s in the URL path: %s", escapedPath[i:i+3], escapedPath) rw.WriteHeader(http.StatusBadRequest) return } i += 2 } h.ServeHTTP(rw, req) }) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/router/router.go
pkg/server/router/router.go
package router import ( "context" "errors" "fmt" "math" "net/http" "slices" "sort" "strings" "github.com/containous/alice" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/middlewares/accesslog" "github.com/traefik/traefik/v3/pkg/middlewares/denyrouterrecursion" metricsMiddle "github.com/traefik/traefik/v3/pkg/middlewares/metrics" "github.com/traefik/traefik/v3/pkg/middlewares/observability" "github.com/traefik/traefik/v3/pkg/middlewares/recovery" httpmuxer "github.com/traefik/traefik/v3/pkg/muxer/http" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/server/middleware" "github.com/traefik/traefik/v3/pkg/server/provider" "github.com/traefik/traefik/v3/pkg/tls" ) const maxUserPriority = math.MaxInt - 1000 type middlewareBuilder interface { BuildChain(ctx context.Context, names []string) *alice.Chain } type serviceManager interface { BuildHTTP(rootCtx context.Context, serviceName string) (http.Handler, error) LaunchHealthCheck(ctx context.Context) } // Manager A route/router manager. type Manager struct { routerHandlers map[string]http.Handler serviceManager serviceManager observabilityMgr *middleware.ObservabilityMgr middlewaresBuilder middlewareBuilder conf *runtime.Configuration tlsManager *tls.Manager parser httpmuxer.SyntaxParser } // NewManager creates a new Manager. func NewManager(conf *runtime.Configuration, serviceManager serviceManager, middlewaresBuilder middlewareBuilder, observabilityMgr *middleware.ObservabilityMgr, tlsManager *tls.Manager, parser httpmuxer.SyntaxParser, ) *Manager { return &Manager{ routerHandlers: make(map[string]http.Handler), serviceManager: serviceManager, observabilityMgr: observabilityMgr, middlewaresBuilder: middlewaresBuilder, conf: conf, tlsManager: tlsManager, parser: parser, } } func (m *Manager) getHTTPRouters(ctx context.Context, entryPoints []string, tls bool) map[string]map[string]*runtime.RouterInfo { if m.conf != nil { return m.conf.GetRoutersByEntryPoints(ctx, entryPoints, tls) } return make(map[string]map[string]*runtime.RouterInfo) } // BuildHandlers Builds handler for all entry points. func (m *Manager) BuildHandlers(rootCtx context.Context, entryPoints []string, tls bool) map[string]http.Handler { entryPointHandlers := make(map[string]http.Handler) defaultObsConfig := dynamic.RouterObservabilityConfig{} defaultObsConfig.SetDefaults() for entryPointName, routers := range m.getHTTPRouters(rootCtx, entryPoints, tls) { logger := log.Ctx(rootCtx).With().Str(logs.EntryPointName, entryPointName).Logger() ctx := logger.WithContext(rootCtx) // TODO: Improve this part. Relying on models is a shortcut to get the entrypoint observability configuration. Maybe we should pass down the static configuration. // When the entry point has no observability configuration no model is produced, // and we need to create the default configuration is this case. epObsConfig := defaultObsConfig if model, ok := m.conf.Models[entryPointName+"@internal"]; ok && model != nil { epObsConfig = model.Observability } handler, err := m.buildEntryPointHandler(ctx, entryPointName, routers, epObsConfig) if err != nil { logger.Error().Err(err).Send() continue } entryPointHandlers[entryPointName] = handler } // Create default handlers. for _, entryPointName := range entryPoints { logger := log.Ctx(rootCtx).With().Str(logs.EntryPointName, entryPointName).Logger() ctx := logger.WithContext(rootCtx) handler, ok := entryPointHandlers[entryPointName] if ok || handler != nil { continue } // TODO: Improve this part. Relying on models is a shortcut to get the entrypoint observability configuration. Maybe we should pass down the static configuration. // When the entry point has no observability configuration no model is produced, // and we need to create the default configuration is this case. epObsConfig := defaultObsConfig if model, ok := m.conf.Models[entryPointName+"@internal"]; ok && model != nil { epObsConfig = model.Observability } defaultHandler, err := m.observabilityMgr.BuildEPChain(ctx, entryPointName, false, epObsConfig).Then(http.NotFoundHandler()) if err != nil { logger.Error().Err(err).Send() continue } entryPointHandlers[entryPointName] = defaultHandler } return entryPointHandlers } func (m *Manager) buildEntryPointHandler(ctx context.Context, entryPointName string, configs map[string]*runtime.RouterInfo, config dynamic.RouterObservabilityConfig) (http.Handler, error) { muxer := httpmuxer.NewMuxer(m.parser) defaultHandler, err := m.observabilityMgr.BuildEPChain(ctx, entryPointName, false, config).Then(http.NotFoundHandler()) if err != nil { return nil, err } muxer.SetDefaultHandler(defaultHandler) for routerName, routerConfig := range configs { logger := log.Ctx(ctx).With().Str(logs.RouterName, routerName).Logger() ctxRouter := logger.WithContext(provider.AddInContext(ctx, routerName)) if routerConfig.Priority == 0 { routerConfig.Priority = httpmuxer.GetRulePriority(routerConfig.Rule) } if routerConfig.Priority > maxUserPriority && !strings.HasSuffix(routerName, "@internal") { err = fmt.Errorf("the router priority %d exceeds the max user-defined priority %d", routerConfig.Priority, maxUserPriority) routerConfig.AddError(err, true) logger.Error().Err(err).Send() continue } // Only build handlers for root routers (routers without ParentRefs). // Routers with ParentRefs will be built as part of their parent router's muxer. if len(routerConfig.ParentRefs) > 0 { continue } handler, err := m.buildRouterHandler(ctxRouter, entryPointName, routerName, routerConfig) if err != nil { routerConfig.AddError(err, true) logger.Error().Err(err).Send() continue } if routerConfig.Observability != nil { config = *routerConfig.Observability } observabilityChain := m.observabilityMgr.BuildEPChain(ctxRouter, entryPointName, strings.HasSuffix(routerConfig.Service, "@internal"), config) handler, err = observabilityChain.Then(handler) if err != nil { routerConfig.AddError(err, true) logger.Error().Err(err).Send() continue } if err = muxer.AddRoute(routerConfig.Rule, routerConfig.RuleSyntax, routerConfig.Priority, handler); err != nil { routerConfig.AddError(err, true) logger.Error().Err(err).Send() continue } } chain := alice.New() chain = chain.Append(func(next http.Handler) (http.Handler, error) { return recovery.New(ctx, next) }) return chain.Then(muxer) } func (m *Manager) buildRouterHandler(ctx context.Context, entryPointName, routerName string, routerConfig *runtime.RouterInfo) (http.Handler, error) { if handler, ok := m.routerHandlers[routerName]; ok { return handler, nil } if routerConfig.TLS != nil { // Don't build the router if the TLSOptions configuration is invalid. tlsOptionsName := tls.DefaultTLSConfigName if len(routerConfig.TLS.Options) > 0 && routerConfig.TLS.Options != tls.DefaultTLSConfigName { tlsOptionsName = provider.GetQualifiedName(ctx, routerConfig.TLS.Options) } if _, err := m.tlsManager.Get(tls.DefaultTLSStoreName, tlsOptionsName); err != nil { return nil, fmt.Errorf("building router handler: %w", err) } } handler, err := m.buildHTTPHandler(ctx, routerConfig, entryPointName, routerName) if err != nil { return nil, err } m.routerHandlers[routerName] = handler return handler, nil } func (m *Manager) buildHTTPHandler(ctx context.Context, router *runtime.RouterInfo, entryPointName, routerName string) (http.Handler, error) { var qualifiedNames []string for _, name := range router.Middlewares { qualifiedNames = append(qualifiedNames, provider.GetQualifiedName(ctx, name)) } router.Middlewares = qualifiedNames chain := alice.New() if router.DefaultRule { chain = chain.Append(denyrouterrecursion.WrapHandler(routerName)) } var ( nextHandler http.Handler serviceName string err error ) // Check if this router has child routers or a service. switch { case len(router.ChildRefs) > 0: // This router routes to child routers - create a muxer for them nextHandler, err = m.buildChildRoutersMuxer(ctx, entryPointName, router.ChildRefs) if err != nil { return nil, fmt.Errorf("building child routers muxer: %w", err) } serviceName = fmt.Sprintf("%s-muxer", routerName) case router.Service != "": // This router routes to a service qualifiedService := provider.GetQualifiedName(ctx, router.Service) nextHandler, err = m.serviceManager.BuildHTTP(ctx, qualifiedService) if err != nil { return nil, err } serviceName = qualifiedService default: return nil, errors.New("router must have either a service or child routers") } // Access logs, metrics, and tracing middlewares are idempotent if the associated signal is disabled. chain = chain.Append(observability.WrapRouterHandler(ctx, routerName, router.Rule, serviceName)) metricsHandler := metricsMiddle.RouterMetricsHandler(ctx, m.observabilityMgr.MetricsRegistry(), routerName, serviceName) chain = chain.Append(observability.WrapMiddleware(ctx, metricsHandler)) chain = chain.Append(func(next http.Handler) (http.Handler, error) { return accesslog.NewConcatFieldHandler(next, accesslog.RouterName, routerName), nil }) // Here we are adding deny handlers for encoded path characters and fragment. // Deny handler are only added for root routers, child routers are protected by their parent router deny handlers. if len(router.ParentRefs) == 0 { chain = chain.Append(func(next http.Handler) (http.Handler, error) { return denyFragment(next), nil }) chain = chain.Append(func(next http.Handler) (http.Handler, error) { return denyEncodedPathCharacters(router.DeniedEncodedPathCharacters.Map(), next), nil }) } mHandler := m.middlewaresBuilder.BuildChain(ctx, router.Middlewares) return chain.Extend(*mHandler).Then(nextHandler) } // ParseRouterTree sets up router tree and validates router configuration. // This function performs the following operations in order: // // 1. Populate ChildRefs: Uses ParentRefs to build the parent-child relationship graph // 2. Root-first traversal: Starting from root routers (no ParentRefs), traverses the tree // 3. Cycle detection: Detects circular dependencies and removes cyclic links // 4. Reachability check: Marks routers unreachable from any root as disabled // 5. Dead-end detection: Marks routers with no service and no children as disabled // 6. Validation: Checks for configuration errors // // Router status is set during this process: // - Enabled: Reachable routers with valid configuration // - Disabled: Unreachable, dead-end, or routers with critical errors // - Warning: Routers with non-critical errors (like cycles) // // The function modifies router.Status, router.ChildRefs, and adds errors to router.Err. func (m *Manager) ParseRouterTree() { if m.conf == nil || m.conf.Routers == nil { return } // Populate ChildRefs based on ParentRefs and find root routers. var rootRouters []string for routerName, router := range m.conf.Routers { if len(router.ParentRefs) == 0 { rootRouters = append(rootRouters, routerName) continue } for _, parentName := range router.ParentRefs { if parentRouter, exists := m.conf.Routers[parentName]; exists { // Add this router as a child of its parent if !slices.Contains(parentRouter.ChildRefs, routerName) { parentRouter.ChildRefs = append(parentRouter.ChildRefs, routerName) } } else { router.AddError(fmt.Errorf("parent router %q does not exist", parentName), true) } } // Check for non-root router with TLS config. if router.TLS != nil { router.AddError(errors.New("non-root router cannot have TLS configuration"), true) continue } // Check for non-root router with Observability config. if router.Observability != nil { router.AddError(errors.New("non-root router cannot have Observability configuration"), true) continue } // Check for non-root router with Entrypoint config. if len(router.EntryPoints) > 0 { router.AddError(errors.New("non-root router cannot have Entrypoints configuration"), true) continue } } sort.Strings(rootRouters) // Root-first traversal with cycle detection. visited := make(map[string]bool) currentPath := make(map[string]bool) var path []string for _, rootName := range rootRouters { if !visited[rootName] { m.traverse(rootName, visited, currentPath, path) } } for routerName, router := range m.conf.Routers { // Set status for all routers based on reachability. if !visited[routerName] { router.AddError(errors.New("router is not reachable"), true) continue } // Detect dead-end routers (no service + no children) - AFTER cycle handling. if router.Service == "" && len(router.ChildRefs) == 0 { router.AddError(errors.New("router has no service and no child routers"), true) continue } // Check for router with service that is referenced as a parent. if router.Service != "" && len(router.ChildRefs) > 0 { router.AddError(errors.New("router has both a service and is referenced as a parent by other routers"), true) continue } } } // traverse performs a depth-first traversal starting from root routers, // detecting cycles and marking visited routers for reachability detection. func (m *Manager) traverse(routerName string, visited, currentPath map[string]bool, path []string) { if currentPath[routerName] { // Found a cycle - handle it properly. m.handleCycle(routerName, path) return } if visited[routerName] { return } router, exists := m.conf.Routers[routerName] // Since the ChildRefs population already guarantees router existence, this check is purely defensive. if !exists { visited[routerName] = true return } visited[routerName] = true currentPath[routerName] = true newPath := append(path, routerName) // Sort ChildRefs for deterministic behavior. sortedChildRefs := make([]string, len(router.ChildRefs)) copy(sortedChildRefs, router.ChildRefs) sort.Strings(sortedChildRefs) // Traverse children. for _, childName := range sortedChildRefs { m.traverse(childName, visited, currentPath, newPath) } currentPath[routerName] = false } // handleCycle handles cycle detection and removes the victim from guilty router's ChildRefs. func (m *Manager) handleCycle(victimRouter string, path []string) { // Find where the cycle starts in the path cycleStart := -1 for i, name := range path { if name == victimRouter { cycleStart = i break } } if cycleStart < 0 { return } // Build the cycle path: from cycle start to current + victim. cyclePath := append(path[cycleStart:], victimRouter) cycleRouters := strings.Join(cyclePath, " -> ") // The guilty router is the last one in the path (the one creating the cycle). if len(path) > 0 { guiltyRouterName := path[len(path)-1] guiltyRouter, exists := m.conf.Routers[guiltyRouterName] if !exists { return } // Add cycle error to guilty router. guiltyRouter.AddError(fmt.Errorf("cyclic reference detected in router tree: %s", cycleRouters), false) // Remove victim from guilty router's ChildRefs. for i, childRef := range guiltyRouter.ChildRefs { if childRef == victimRouter { guiltyRouter.ChildRefs = append(guiltyRouter.ChildRefs[:i], guiltyRouter.ChildRefs[i+1:]...) break } } } } // buildChildRoutersMuxer creates a muxer for child routers. func (m *Manager) buildChildRoutersMuxer(ctx context.Context, entryPointName string, childRefs []string) (http.Handler, error) { childMuxer := httpmuxer.NewMuxer(m.parser) // Set a default handler for the child muxer (404 Not Found). childMuxer.SetDefaultHandler(http.NotFoundHandler()) childCount := 0 for _, childName := range childRefs { childRouter, exists := m.conf.Routers[childName] if !exists { return nil, fmt.Errorf("child router %q does not exist", childName) } // Skip child routers with errors. if len(childRouter.Err) > 0 { continue } logger := log.Ctx(ctx).With().Str(logs.RouterName, childName).Logger() ctxChild := logger.WithContext(provider.AddInContext(ctx, childName)) // Set priority if not set. if childRouter.Priority == 0 { childRouter.Priority = httpmuxer.GetRulePriority(childRouter.Rule) } // Build the child router handler. childHandler, err := m.buildRouterHandler(ctxChild, entryPointName, childName, childRouter) if err != nil { childRouter.AddError(err, true) logger.Error().Err(err).Send() continue } // Add the child router to the muxer. if err = childMuxer.AddRoute(childRouter.Rule, childRouter.RuleSyntax, childRouter.Priority, childHandler); err != nil { childRouter.AddError(err, true) logger.Error().Err(err).Send() continue } childCount++ } // Prevent empty muxer. if childCount == 0 { return nil, fmt.Errorf("no child routers could be added to muxer (%d skipped)", len(childRefs)) } return childMuxer, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/router/router_test.go
pkg/server/router/router_test.go
package router import ( "context" "crypto/tls" "io" "math" "net/http" "net/http/httptest" "net/url" "strings" "testing" "time" "github.com/containous/alice" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/middlewares/requestdecorator" httpmuxer "github.com/traefik/traefik/v3/pkg/muxer/http" "github.com/traefik/traefik/v3/pkg/server/middleware" "github.com/traefik/traefik/v3/pkg/server/service" "github.com/traefik/traefik/v3/pkg/testhelpers" traefiktls "github.com/traefik/traefik/v3/pkg/tls" ) func TestRouterManager_Get(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) t.Cleanup(func() { server.Close() }) type expectedResult struct { StatusCode int RequestHeaders map[string]string } testCases := []struct { desc string routersConfig map[string]*dynamic.Router serviceConfig map[string]*dynamic.Service middlewaresConfig map[string]*dynamic.Middleware entryPoints []string expected expectedResult }{ { desc: "no middleware", routersConfig: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar`)", }, }, serviceConfig: map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: server.URL, }, }, }, }, }, entryPoints: []string{"web"}, expected: expectedResult{StatusCode: http.StatusOK}, }, { desc: "empty host", routersConfig: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(``)", }, }, serviceConfig: map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: server.URL, }, }, }, }, }, entryPoints: []string{"web"}, expected: expectedResult{StatusCode: http.StatusNotFound}, }, { desc: "no load balancer", routersConfig: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar`)", }, }, serviceConfig: map[string]*dynamic.Service{ "foo-service": {}, }, entryPoints: []string{"web"}, expected: expectedResult{StatusCode: http.StatusNotFound}, }, { desc: "no middleware, no matching", routersConfig: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`bar.bar`)", }, }, serviceConfig: map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: server.URL, }, }, }, }, }, entryPoints: []string{"web"}, expected: expectedResult{StatusCode: http.StatusNotFound}, }, { desc: "middleware: headers > auth", routersConfig: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Middlewares: []string{"headers-middle", "auth-middle"}, Service: "foo-service", Rule: "Host(`foo.bar`)", }, }, serviceConfig: map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: server.URL, }, }, }, }, }, middlewaresConfig: map[string]*dynamic.Middleware{ "auth-middle": { BasicAuth: &dynamic.BasicAuth{ Users: []string{"toto:titi"}, }, }, "headers-middle": { Headers: &dynamic.Headers{ CustomRequestHeaders: map[string]string{"X-Apero": "beer"}, }, }, }, entryPoints: []string{"web"}, expected: expectedResult{ StatusCode: http.StatusUnauthorized, RequestHeaders: map[string]string{ "X-Apero": "beer", }, }, }, { desc: "middleware: auth > header", routersConfig: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Middlewares: []string{"auth-middle", "headers-middle"}, Service: "foo-service", Rule: "Host(`foo.bar`)", }, }, serviceConfig: map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: server.URL, }, }, }, }, }, middlewaresConfig: map[string]*dynamic.Middleware{ "auth-middle": { BasicAuth: &dynamic.BasicAuth{ Users: []string{"toto:titi"}, }, }, "headers-middle": { Headers: &dynamic.Headers{ CustomRequestHeaders: map[string]string{"X-Apero": "beer"}, }, }, }, entryPoints: []string{"web"}, expected: expectedResult{ StatusCode: http.StatusUnauthorized, RequestHeaders: map[string]string{ "X-Apero": "", }, }, }, { desc: "no middleware with provider name", routersConfig: map[string]*dynamic.Router{ "foo@provider-1": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar`)", }, }, serviceConfig: map[string]*dynamic.Service{ "foo-service@provider-1": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: server.URL, }, }, }, }, }, entryPoints: []string{"web"}, expected: expectedResult{StatusCode: http.StatusOK}, }, { desc: "no middleware with specified provider name", routersConfig: map[string]*dynamic.Router{ "foo@provider-1": { EntryPoints: []string{"web"}, Service: "foo-service@provider-2", Rule: "Host(`foo.bar`)", }, }, serviceConfig: map[string]*dynamic.Service{ "foo-service@provider-2": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: server.URL, }, }, }, }, }, entryPoints: []string{"web"}, expected: expectedResult{StatusCode: http.StatusOK}, }, { desc: "middleware: chain with provider name", routersConfig: map[string]*dynamic.Router{ "foo@provider-1": { EntryPoints: []string{"web"}, Middlewares: []string{"chain-middle@provider-2", "headers-middle"}, Service: "foo-service", Rule: "Host(`foo.bar`)", }, }, serviceConfig: map[string]*dynamic.Service{ "foo-service@provider-1": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: server.URL, }, }, }, }, }, middlewaresConfig: map[string]*dynamic.Middleware{ "chain-middle@provider-2": { Chain: &dynamic.Chain{Middlewares: []string{"auth-middle"}}, }, "auth-middle@provider-2": { BasicAuth: &dynamic.BasicAuth{ Users: []string{"toto:titi"}, }, }, "headers-middle@provider-1": { Headers: &dynamic.Headers{ CustomRequestHeaders: map[string]string{"X-Apero": "beer"}, }, }, }, entryPoints: []string{"web"}, expected: expectedResult{ StatusCode: http.StatusUnauthorized, RequestHeaders: map[string]string{ "X-Apero": "", }, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() rtConf := runtime.NewConfig(dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Services: test.serviceConfig, Routers: test.routersConfig, Middlewares: test.middlewaresConfig, }, }) transportManager := service.NewTransportManager(nil) transportManager.Update(map[string]*dynamic.ServersTransport{"default@internal": {}}) serviceManager := service.NewManager(rtConf.Services, nil, nil, transportManager, proxyBuilderMock{}) middlewaresBuilder := middleware.NewBuilder(rtConf.Middlewares, serviceManager, nil) tlsManager := traefiktls.NewManager(nil) parser, err := httpmuxer.NewSyntaxParser() require.NoError(t, err) routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, nil, tlsManager, parser) handlers := routerManager.BuildHandlers(t.Context(), test.entryPoints, false) w := httptest.NewRecorder() req := testhelpers.MustNewRequest(http.MethodGet, "http://foo.bar/", nil) reqHost := requestdecorator.New(nil) reqHost.ServeHTTP(w, req, handlers["web"].ServeHTTP) assert.Equal(t, test.expected.StatusCode, w.Code) for key, value := range test.expected.RequestHeaders { assert.Equal(t, value, req.Header.Get(key)) } }) } } func TestRuntimeConfiguration(t *testing.T) { testCases := []struct { desc string serviceConfig map[string]*dynamic.Service routerConfig map[string]*dynamic.Router middlewareConfig map[string]*dynamic.Middleware tlsOptions map[string]traefiktls.Options expectedError int }{ { desc: "No error", serviceConfig: map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:8085", }, { URL: "http://127.0.0.1:8086", }, }, HealthCheck: &dynamic.ServerHealthCheck{ Interval: ptypes.Duration(500 * time.Millisecond), Path: "/health", }, }, }, }, routerConfig: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`bar.foo`)", }, "bar": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar`)", }, }, expectedError: 0, }, { desc: "One router with wrong rule", serviceConfig: map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, }, routerConfig: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "WrongRule(`bar.foo`)", }, "bar": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar`)", }, }, expectedError: 1, }, { desc: "All router with wrong rule", serviceConfig: map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, }, routerConfig: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "WrongRule(`bar.foo`)", }, "bar": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "WrongRule(`foo.bar`)", }, }, expectedError: 2, }, { desc: "Router with unknown service", serviceConfig: map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, }, routerConfig: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "wrong-service", Rule: "Host(`bar.foo`)", }, "bar": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar`)", }, }, expectedError: 1, }, { desc: "Router with broken service", serviceConfig: map[string]*dynamic.Service{ "foo-service": { LoadBalancer: nil, }, }, routerConfig: map[string]*dynamic.Router{ "bar": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar`)", }, }, expectedError: 2, }, { desc: "Router with middleware", serviceConfig: map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, }, middlewareConfig: map[string]*dynamic.Middleware{ "auth": { BasicAuth: &dynamic.BasicAuth{ Users: []string{"admin:admin"}, }, }, "addPrefixTest": { AddPrefix: &dynamic.AddPrefix{ Prefix: "/toto", }, }, }, routerConfig: map[string]*dynamic.Router{ "bar": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth", "addPrefixTest"}, }, "test": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar.other`)", Middlewares: []string{"addPrefixTest", "auth"}, }, }, }, { desc: "Router with unknown middleware", serviceConfig: map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, }, middlewareConfig: map[string]*dynamic.Middleware{ "auth": { BasicAuth: &dynamic.BasicAuth{ Users: []string{"admin:admin"}, }, }, }, routerConfig: map[string]*dynamic.Router{ "bar": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar`)", Middlewares: []string{"unknown"}, }, }, expectedError: 1, }, { desc: "Router with broken middleware", serviceConfig: map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, }, middlewareConfig: map[string]*dynamic.Middleware{ "auth": { BasicAuth: &dynamic.BasicAuth{ Users: []string{"foo"}, }, }, }, routerConfig: map[string]*dynamic.Router{ "bar": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth"}, }, }, expectedError: 2, }, { desc: "Router priority exceeding max user-defined priority", serviceConfig: map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, }, middlewareConfig: map[string]*dynamic.Middleware{}, routerConfig: map[string]*dynamic.Router{ "bar": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar`)", Priority: math.MaxInt, TLS: &dynamic.RouterTLSConfig{}, }, }, tlsOptions: map[string]traefiktls.Options{}, expectedError: 1, }, { desc: "Router with broken tlsOption", serviceConfig: map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, }, middlewareConfig: map[string]*dynamic.Middleware{}, routerConfig: map[string]*dynamic.Router{ "bar": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar`)", TLS: &dynamic.RouterTLSConfig{ Options: "broken-tlsOption", }, }, }, tlsOptions: map[string]traefiktls.Options{ "broken-tlsOption": { ClientAuth: traefiktls.ClientAuth{ ClientAuthType: "foobar", }, }, }, expectedError: 1, }, { desc: "Router with broken default tlsOption", serviceConfig: map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, }, middlewareConfig: map[string]*dynamic.Middleware{}, routerConfig: map[string]*dynamic.Router{ "bar": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar`)", TLS: &dynamic.RouterTLSConfig{}, }, }, tlsOptions: map[string]traefiktls.Options{ "default": { ClientAuth: traefiktls.ClientAuth{ ClientAuthType: "foobar", }, }, }, expectedError: 1, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() entryPoints := []string{"web"} rtConf := runtime.NewConfig(dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Services: test.serviceConfig, Routers: test.routerConfig, Middlewares: test.middlewareConfig, }, TLS: &dynamic.TLSConfiguration{ Options: test.tlsOptions, }, }) transportManager := service.NewTransportManager(nil) transportManager.Update(map[string]*dynamic.ServersTransport{"default@internal": {}}) serviceManager := service.NewManager(rtConf.Services, nil, nil, transportManager, proxyBuilderMock{}) middlewaresBuilder := middleware.NewBuilder(rtConf.Middlewares, serviceManager, nil) tlsManager := traefiktls.NewManager(nil) tlsManager.UpdateConfigs(t.Context(), nil, test.tlsOptions, nil) parser, err := httpmuxer.NewSyntaxParser() require.NoError(t, err) routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, nil, tlsManager, parser) _ = routerManager.BuildHandlers(t.Context(), entryPoints, false) _ = routerManager.BuildHandlers(t.Context(), entryPoints, true) // even though rtConf was passed by argument to the manager builders above, // it's ok to use it as the result we check, because everything worth checking // can be accessed by pointers in it. var allErrors int for _, v := range rtConf.Services { if v.Err != nil { allErrors++ } } for _, v := range rtConf.Routers { if len(v.Err) > 0 { allErrors++ } } for _, v := range rtConf.Middlewares { if v.Err != nil { allErrors++ } } assert.Equal(t, test.expectedError, allErrors) }) } } func TestProviderOnMiddlewares(t *testing.T) { entryPoints := []string{"web"} rtConf := runtime.NewConfig(dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Services: map[string]*dynamic.Service{ "test@file": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{}, }, }, }, Routers: map[string]*dynamic.Router{ "router@file": { EntryPoints: []string{"web"}, Rule: "Host(`test`)", Service: "test@file", Middlewares: []string{"chain@file", "m1"}, }, "router@docker": { EntryPoints: []string{"web"}, Rule: "Host(`test`)", Service: "test@file", Middlewares: []string{"chain", "m1@file"}, }, }, Middlewares: map[string]*dynamic.Middleware{ "chain@file": { Chain: &dynamic.Chain{Middlewares: []string{"m1", "m2", "m1@file"}}, }, "chain@docker": { Chain: &dynamic.Chain{Middlewares: []string{"m1", "m2", "m1@file"}}, }, "m1@file": {AddPrefix: &dynamic.AddPrefix{Prefix: "/m1"}}, "m2@file": {AddPrefix: &dynamic.AddPrefix{Prefix: "/m2"}}, "m1@docker": {AddPrefix: &dynamic.AddPrefix{Prefix: "/m1"}}, "m2@docker": {AddPrefix: &dynamic.AddPrefix{Prefix: "/m2"}}, }, }, }) transportManager := service.NewTransportManager(nil) transportManager.Update(map[string]*dynamic.ServersTransport{"default@internal": {}}) serviceManager := service.NewManager(rtConf.Services, nil, nil, transportManager, nil) middlewaresBuilder := middleware.NewBuilder(rtConf.Middlewares, serviceManager, nil) tlsManager := traefiktls.NewManager(nil) parser, err := httpmuxer.NewSyntaxParser() require.NoError(t, err) routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, nil, tlsManager, parser) _ = routerManager.BuildHandlers(t.Context(), entryPoints, false) assert.Equal(t, []string{"chain@file", "m1@file"}, rtConf.Routers["router@file"].Middlewares) assert.Equal(t, []string{"m1@file", "m2@file", "m1@file"}, rtConf.Middlewares["chain@file"].Chain.Middlewares) assert.Equal(t, []string{"chain@docker", "m1@file"}, rtConf.Routers["router@docker"].Middlewares) assert.Equal(t, []string{"m1@docker", "m2@docker", "m1@file"}, rtConf.Middlewares["chain@docker"].Chain.Middlewares) } func BenchmarkRouterServe(b *testing.B) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) b.Cleanup(func() { server.Close() }) res := &http.Response{ StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("")), } routersConfig := map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar`) && Path(`/`)", }, } serviceConfig := map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: server.URL, }, }, }, }, } entryPoints := []string{"web"} rtConf := runtime.NewConfig(dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Services: serviceConfig, Routers: routersConfig, Middlewares: map[string]*dynamic.Middleware{}, }, }) serviceManager := service.NewManager(rtConf.Services, nil, nil, staticTransportManager{res}, nil) middlewaresBuilder := middleware.NewBuilder(rtConf.Middlewares, serviceManager, nil) tlsManager := traefiktls.NewManager(nil) parser, err := httpmuxer.NewSyntaxParser() require.NoError(b, err) routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, nil, tlsManager, parser) handlers := routerManager.BuildHandlers(b.Context(), entryPoints, false) w := httptest.NewRecorder() req := testhelpers.MustNewRequest(http.MethodGet, "http://foo.bar/", nil) reqHost := requestdecorator.New(nil) b.ReportAllocs() for range b.N { reqHost.ServeHTTP(w, req, handlers["web"].ServeHTTP) } } func BenchmarkService(b *testing.B) { res := &http.Response{ StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("")), } serviceConfig := map[string]*dynamic.Service{ "foo-service": { LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "tchouk", }, }, }, }, } rtConf := runtime.NewConfig(dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Services: serviceConfig, }, }) serviceManager := service.NewManager(rtConf.Services, nil, nil, staticTransportManager{res}, nil) w := httptest.NewRecorder() req := testhelpers.MustNewRequest(http.MethodGet, "http://foo.bar/", nil) handler, _ := serviceManager.BuildHTTP(b.Context(), "foo-service") b.ReportAllocs() for range b.N { handler.ServeHTTP(w, req) } } func TestManager_ComputeMultiLayerRouting(t *testing.T) { testCases := []struct { desc string routers map[string]*dynamic.Router expectedStatuses map[string]string expectedChildRefs map[string][]string expectedErrors map[string][]string expectedErrorCounts map[string]int }{ { desc: "Simple router", routers: map[string]*dynamic.Router{ "A": { Service: "A-service", }, }, expectedStatuses: map[string]string{ "A": runtime.StatusEnabled, }, expectedChildRefs: map[string][]string{ "A": {}, }, }, { // A->B1 // ->B2 desc: "Router with two children", routers: map[string]*dynamic.Router{ "A": {}, "B1": { ParentRefs: []string{"A"}, Service: "B1-service", }, "B2": { ParentRefs: []string{"A"}, Service: "B2-service", }, }, expectedStatuses: map[string]string{ "A": runtime.StatusEnabled, "B1": runtime.StatusEnabled, "B2": runtime.StatusEnabled, }, expectedChildRefs: map[string][]string{ "A": {"B1", "B2"}, "B1": nil, "B2": nil, }, }, { desc: "Non-root router with TLS config", routers: map[string]*dynamic.Router{ "A": {}, "B": { ParentRefs: []string{"A"}, Service: "B-service", TLS: &dynamic.RouterTLSConfig{}, }, }, expectedStatuses: map[string]string{ "A": runtime.StatusEnabled, "B": runtime.StatusDisabled, }, expectedChildRefs: map[string][]string{ "A": {"B"}, "B": nil, }, expectedErrors: map[string][]string{ "B": {"non-root router cannot have TLS configuration"}, }, }, { desc: "Non-root router with observability config", routers: map[string]*dynamic.Router{ "A": {}, "B": { ParentRefs: []string{"A"}, Service: "B-service", Observability: &dynamic.RouterObservabilityConfig{}, }, }, expectedStatuses: map[string]string{ "A": runtime.StatusEnabled, "B": runtime.StatusDisabled, }, expectedChildRefs: map[string][]string{ "A": {"B"}, "B": nil, }, expectedErrors: map[string][]string{ "B": {"non-root router cannot have Observability configuration"}, }, }, { desc: "Non-root router with EntryPoints config", routers: map[string]*dynamic.Router{ "A": {}, "B": { ParentRefs: []string{"A"}, Service: "B-service", EntryPoints: []string{"web"}, }, }, expectedStatuses: map[string]string{ "A": runtime.StatusEnabled, "B": runtime.StatusDisabled, }, expectedChildRefs: map[string][]string{ "A": {"B"}, "B": nil, }, expectedErrors: map[string][]string{ "B": {"non-root router cannot have Entrypoints configuration"}, }, }, { desc: "Router with non-existing parent", routers: map[string]*dynamic.Router{ "B": { ParentRefs: []string{"A"}, Service: "B-service", }, }, expectedStatuses: map[string]string{ "B": runtime.StatusDisabled, }, expectedChildRefs: map[string][]string{ "B": nil, }, expectedErrors: map[string][]string{ "B": {"parent router \"A\" does not exist", "router is not reachable"}, }, }, { desc: "Dead-end router with no child and no service", routers: map[string]*dynamic.Router{ "A": {}, }, expectedStatuses: map[string]string{ "A": runtime.StatusDisabled, }, expectedChildRefs: map[string][]string{ "A": {}, }, expectedErrors: map[string][]string{ "A": {"router has no service and no child routers"}, }, }, { // A->B->A desc: "Router is not reachable", routers: map[string]*dynamic.Router{ "A": { ParentRefs: []string{"B"}, }, "B": { ParentRefs: []string{"A"}, }, }, expectedStatuses: map[string]string{ "A": runtime.StatusDisabled, "B": runtime.StatusDisabled, }, expectedChildRefs: map[string][]string{ "A": {"B"}, "B": {"A"}, }, // Cycle detection does not visit unreachable routers (it avoids computing the cycle dependency graph for unreachable routers). expectedErrors: map[string][]string{ "A": {"router is not reachable"}, "B": {"router is not reachable"}, }, }, { // A->B->C->D->B desc: "Router creating a cycle is a dead-end and should be disabled", routers: map[string]*dynamic.Router{ "A": {}, "B": { ParentRefs: []string{"A", "D"}, }, "C": { ParentRefs: []string{"B"}, }, "D": { ParentRefs: []string{"C"}, }, }, expectedStatuses: map[string]string{ "A": runtime.StatusEnabled, "B": runtime.StatusEnabled, "C": runtime.StatusEnabled, "D": runtime.StatusDisabled, // Dead-end router is disabled, because the cycle error broke the link with B. }, expectedChildRefs: map[string][]string{ "A": {"B"}, "B": {"C"}, "C": {"D"}, "D": {}, }, expectedErrors: map[string][]string{ "D": { "cyclic reference detected in router tree: B -> C -> D -> B", "router has no service and no child routers", }, }, }, { // A->B->C->D->B // ->E desc: "Router creating a cycle A->B->C->D->B but which is referenced elsewhere, must be set to warning status", routers: map[string]*dynamic.Router{ "A": {}, "B": { ParentRefs: []string{"A", "D"}, }, "C": { ParentRefs: []string{"B"}, }, "D": { ParentRefs: []string{"C"}, }, "E": { ParentRefs: []string{"D"}, Service: "E-service", }, }, expectedStatuses: map[string]string{ "A": runtime.StatusEnabled, "B": runtime.StatusEnabled, "C": runtime.StatusEnabled, "D": runtime.StatusWarning, "E": runtime.StatusEnabled, }, expectedChildRefs: map[string][]string{ "A": {"B"}, "B": {"C"}, "C": {"D"}, "D": {"E"}, }, expectedErrors: map[string][]string{ "D": {"cyclic reference detected in router tree: B -> C -> D -> B"}, }, }, { desc: "Parent router with all children having errors", routers: map[string]*dynamic.Router{ "parent": {}, "child-a": { ParentRefs: []string{"parent"}, Service: "child-a-service", TLS: &dynamic.RouterTLSConfig{}, // Invalid: non-root cannot have TLS }, "child-b": { ParentRefs: []string{"parent"}, Service: "child-b-service", TLS: &dynamic.RouterTLSConfig{}, // Invalid: non-root cannot have TLS }, }, expectedStatuses: map[string]string{ "parent": runtime.StatusEnabled, // Enabled during ParseRouterTree (no config errors). Would be disabled during handler building when empty muxer is detected. "child-a": runtime.StatusDisabled, "child-b": runtime.StatusDisabled, }, expectedChildRefs: map[string][]string{ "parent": {"child-a", "child-b"}, "child-a": nil, "child-b": nil, }, expectedErrors: map[string][]string{ "child-a": {"non-root router cannot have TLS configuration"}, "child-b": {"non-root router cannot have TLS configuration"}, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { // Create runtime routers runtimeRouters := make(map[string]*runtime.RouterInfo) for name, router := range test.routers { runtimeRouters[name] = &runtime.RouterInfo{ Router: router, Status: runtime.StatusEnabled, } } conf := &runtime.Configuration{ Routers: runtimeRouters, } manager := &Manager{ conf: conf, } // Execute the function we're testing manager.ParseRouterTree() // Verify ChildRefs are populated correctly for routerName, expectedChildren := range test.expectedChildRefs { router := runtimeRouters[routerName] assert.ElementsMatch(t, expectedChildren, router.ChildRefs) } // Verify statuses are set correctly var gotStatuses map[string]string for routerName, router := range runtimeRouters { if gotStatuses == nil { gotStatuses = make(map[string]string) } gotStatuses[routerName] = router.Status } assert.Equal(t, test.expectedStatuses, gotStatuses) // Verify errors are added correctly var gotErrors map[string][]string for routerName, router := range runtimeRouters { for _, err := range router.Err { if gotErrors == nil { gotErrors = make(map[string][]string) } gotErrors[routerName] = append(gotErrors[routerName], err) } } assert.Equal(t, test.expectedErrors, gotErrors) }) } } func TestManager_buildChildRoutersMuxer(t *testing.T) { testCases := []struct { desc string childRefs []string routers map[string]*dynamic.Router services map[string]*dynamic.Service
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/router/deny_test.go
pkg/server/router/deny_test.go
package router import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func Test_denyFragment(t *testing.T) { tests := []struct { name string url string wantStatus int }{ { name: "Rejects fragment character", url: "http://example.com/#", wantStatus: http.StatusBadRequest, }, { name: "Allows without fragment", url: "http://example.com/", wantStatus: http.StatusOK, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { t.Parallel() handler := denyFragment(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) req := httptest.NewRequest(http.MethodGet, test.url, nil) res := httptest.NewRecorder() handler.ServeHTTP(res, req) assert.Equal(t, test.wantStatus, res.Code) }) } } func Test_denyEncodedPathCharacters(t *testing.T) { tests := []struct { name string encoded map[string]struct{} url string wantStatus int }{ { name: "Rejects disallowed characters", encoded: map[string]struct{}{ "%0A": {}, "%0D": {}, }, url: "http://example.com/foo%0Abar", wantStatus: http.StatusBadRequest, }, { name: "Allows valid paths", encoded: map[string]struct{}{ "%0A": {}, "%0D": {}, }, url: "http://example.com/foo%20bar", wantStatus: http.StatusOK, }, { name: "Handles empty path", encoded: map[string]struct{}{ "%0A": {}, }, url: "http://example.com/", wantStatus: http.StatusOK, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { t.Parallel() handler := denyEncodedPathCharacters(test.encoded, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) req := httptest.NewRequest(http.MethodGet, test.url, nil) res := httptest.NewRecorder() handler.ServeHTTP(res, req) assert.Equal(t, test.wantStatus, res.Code) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/router/tcp/manager_test.go
pkg/server/router/tcp/manager_test.go
package tcp import ( "crypto/tls" "math" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" tcpmiddleware "github.com/traefik/traefik/v3/pkg/server/middleware/tcp" "github.com/traefik/traefik/v3/pkg/server/service/tcp" tcp2 "github.com/traefik/traefik/v3/pkg/tcp" traefiktls "github.com/traefik/traefik/v3/pkg/tls" ) func TestRuntimeConfiguration(t *testing.T) { testCases := []struct { desc string httpServiceConfig map[string]*runtime.ServiceInfo httpRouterConfig map[string]*runtime.RouterInfo tcpServiceConfig map[string]*runtime.TCPServiceInfo tcpRouterConfig map[string]*runtime.TCPRouterInfo expectedError int }{ { desc: "No error", tcpServiceConfig: map[string]*runtime.TCPServiceInfo{ "foo-service": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Port: "8085", Address: "127.0.0.1:8085", }, { Address: "127.0.0.1:8086", Port: "8086", }, }, }, }, }, }, tcpRouterConfig: map[string]*runtime.TCPRouterInfo{ "foo": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", Rule: "HostSNI(`bar.foo`)", TLS: &dynamic.RouterTCPTLSConfig{ Passthrough: false, Options: "foo", }, }, }, "bar": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", Rule: "HostSNI(`foo.bar`)", TLS: &dynamic.RouterTCPTLSConfig{ Passthrough: false, Options: "bar", }, }, }, }, expectedError: 0, }, { desc: "Non-ASCII domain error", tcpServiceConfig: map[string]*runtime.TCPServiceInfo{ "foo-service": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Port: "8085", Address: "127.0.0.1:8085", }, }, }, }, }, }, tcpRouterConfig: map[string]*runtime.TCPRouterInfo{ "foo": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", Rule: "HostSNI(`bàr.foo`)", TLS: &dynamic.RouterTCPTLSConfig{ Passthrough: false, Options: "foo", }, }, }, }, expectedError: 1, }, { desc: "HTTP routers with same domain but different TLS options", httpServiceConfig: map[string]*runtime.ServiceInfo{ "foo-service": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { Port: "8085", URL: "127.0.0.1:8085", }, { URL: "127.0.0.1:8086", Port: "8086", }, }, }, }, }, }, httpRouterConfig: map[string]*runtime.RouterInfo{ "foo": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`bar.foo`)", TLS: &dynamic.RouterTLSConfig{ Options: "foo", }, }, }, "bar": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`bar.foo`) && PathPrefix(`/path`)", TLS: &dynamic.RouterTLSConfig{ Options: "bar", }, }, }, }, expectedError: 2, }, { desc: "One router with wrong rule", tcpServiceConfig: map[string]*runtime.TCPServiceInfo{ "foo-service": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1:80", }, }, }, }, }, }, tcpRouterConfig: map[string]*runtime.TCPRouterInfo{ "foo": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", Rule: "WrongRule(`bar.foo`)", }, }, "bar": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", Rule: "HostSNI(`foo.bar`)", TLS: &dynamic.RouterTCPTLSConfig{}, }, }, }, expectedError: 1, }, { desc: "All router with wrong rule", tcpServiceConfig: map[string]*runtime.TCPServiceInfo{ "foo-service": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1:80", }, }, }, }, }, }, tcpRouterConfig: map[string]*runtime.TCPRouterInfo{ "foo": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", Rule: "WrongRule(`bar.foo`)", }, }, "bar": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", Rule: "WrongRule(`foo.bar`)", }, }, }, expectedError: 2, }, { desc: "Router with unknown service", tcpServiceConfig: map[string]*runtime.TCPServiceInfo{ "foo-service": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1:80", }, }, }, }, }, }, tcpRouterConfig: map[string]*runtime.TCPRouterInfo{ "foo": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "wrong-service", Rule: "HostSNI(`bar.foo`)", TLS: &dynamic.RouterTCPTLSConfig{}, }, }, "bar": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", Rule: "HostSNI(`foo.bar`)", TLS: &dynamic.RouterTCPTLSConfig{}, }, }, }, expectedError: 1, }, { desc: "Router with broken service", tcpServiceConfig: map[string]*runtime.TCPServiceInfo{ "foo-service": { TCPService: &dynamic.TCPService{ LoadBalancer: nil, }, }, }, tcpRouterConfig: map[string]*runtime.TCPRouterInfo{ "bar": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", Rule: "HostSNI(`foo.bar`)", TLS: &dynamic.RouterTCPTLSConfig{}, }, }, }, expectedError: 2, }, { desc: "Router with priority exceeding the max user-defined priority", tcpServiceConfig: map[string]*runtime.TCPServiceInfo{ "foo-service": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Port: "8085", Address: "127.0.0.1:8085", }, { Address: "127.0.0.1:8086", Port: "8086", }, }, }, }, }, }, tcpRouterConfig: map[string]*runtime.TCPRouterInfo{ "bar": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", Rule: "HostSNI(`foo.bar`)", TLS: &dynamic.RouterTCPTLSConfig{}, Priority: math.MaxInt, }, }, }, expectedError: 1, }, { desc: "Router with HostSNI but no TLS", tcpServiceConfig: map[string]*runtime.TCPServiceInfo{ "foo-service": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1:80", }, }, }, }, }, }, tcpRouterConfig: map[string]*runtime.TCPRouterInfo{ "foo": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", Rule: "HostSNI(`bar.foo`)", }, }, }, expectedError: 1, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() entryPoints := []string{"web"} conf := &runtime.Configuration{ Services: test.httpServiceConfig, Routers: test.httpRouterConfig, TCPServices: test.tcpServiceConfig, TCPRouters: test.tcpRouterConfig, } dialerManager := tcp2.NewDialerManager(nil) dialerManager.Update(map[string]*dynamic.TCPServersTransport{"default@internal": {}}) serviceManager := tcp.NewManager(conf, dialerManager) tlsManager := traefiktls.NewManager(nil) tlsManager.UpdateConfigs( t.Context(), map[string]traefiktls.Store{}, map[string]traefiktls.Options{ "default": { MinVersion: "VersionTLS10", }, "foo": { MinVersion: "VersionTLS12", }, "bar": { MinVersion: "VersionTLS11", }, }, []*traefiktls.CertAndStores{}) middlewaresBuilder := tcpmiddleware.NewBuilder(conf.TCPMiddlewares) routerManager := NewManager(conf, serviceManager, middlewaresBuilder, nil, nil, tlsManager) _ = routerManager.BuildHandlers(t.Context(), entryPoints) // even though conf was passed by argument to the manager builders above, // it's ok to use it as the result we check, because everything worth checking // can be accessed by pointers in it. var allErrors int for _, v := range conf.TCPServices { if v.Err != nil { allErrors++ } } for _, v := range conf.TCPRouters { if len(v.Err) > 0 { allErrors++ } } for _, v := range conf.Services { if v.Err != nil { allErrors++ } } for _, v := range conf.Routers { if len(v.Err) > 0 { allErrors++ } } assert.Equal(t, test.expectedError, allErrors) }) } } func TestDomainFronting(t *testing.T) { tlsOptionsBase := map[string]traefiktls.Options{ "default": { MinVersion: "VersionTLS10", }, "host1@file": { MinVersion: "VersionTLS12", }, "host1@crd": { MinVersion: "VersionTLS12", }, } entryPoints := []string{"web"} tests := []struct { desc string routers map[string]*runtime.RouterInfo tlsOptions map[string]traefiktls.Options host string ServerName string expectedStatus int }{ { desc: "Request is misdirected when TLS options are different", routers: map[string]*runtime.RouterInfo{ "router-1@file": { Router: &dynamic.Router{ EntryPoints: entryPoints, Rule: "Host(`host1.local`)", TLS: &dynamic.RouterTLSConfig{ Options: "host1", }, }, }, "router-2@file": { Router: &dynamic.Router{ EntryPoints: entryPoints, Rule: "Host(`host2.local`)", TLS: &dynamic.RouterTLSConfig{}, }, }, }, tlsOptions: tlsOptionsBase, host: "host1.local", ServerName: "host2.local", expectedStatus: http.StatusMisdirectedRequest, }, { desc: "Request is OK when TLS options are the same", routers: map[string]*runtime.RouterInfo{ "router-1@file": { Router: &dynamic.Router{ EntryPoints: entryPoints, Rule: "Host(`host1.local`)", TLS: &dynamic.RouterTLSConfig{ Options: "host1", }, }, }, "router-2@file": { Router: &dynamic.Router{ EntryPoints: entryPoints, Rule: "Host(`host2.local`)", TLS: &dynamic.RouterTLSConfig{ Options: "host1", }, }, }, }, tlsOptions: tlsOptionsBase, host: "host1.local", ServerName: "host2.local", expectedStatus: http.StatusOK, }, { desc: "Default TLS options is used when options are ambiguous for the same host", routers: map[string]*runtime.RouterInfo{ "router-1@file": { Router: &dynamic.Router{ EntryPoints: entryPoints, Rule: "Host(`host1.local`)", TLS: &dynamic.RouterTLSConfig{ Options: "host1", }, }, }, "router-2@file": { Router: &dynamic.Router{ EntryPoints: entryPoints, Rule: "Host(`host1.local`) && PathPrefix(`/foo`)", TLS: &dynamic.RouterTLSConfig{ Options: "default", }, }, }, "router-3@file": { Router: &dynamic.Router{ EntryPoints: entryPoints, Rule: "Host(`host2.local`)", TLS: &dynamic.RouterTLSConfig{ Options: "host1", }, }, }, }, tlsOptions: tlsOptionsBase, host: "host1.local", ServerName: "host2.local", expectedStatus: http.StatusMisdirectedRequest, }, { desc: "Default TLS options should not be used when options are the same for the same host", routers: map[string]*runtime.RouterInfo{ "router-1@file": { Router: &dynamic.Router{ EntryPoints: entryPoints, Rule: "Host(`host1.local`)", TLS: &dynamic.RouterTLSConfig{ Options: "host1", }, }, }, "router-2@file": { Router: &dynamic.Router{ EntryPoints: entryPoints, Rule: "Host(`host1.local`) && PathPrefix(`/bar`)", TLS: &dynamic.RouterTLSConfig{ Options: "host1", }, }, }, "router-3@file": { Router: &dynamic.Router{ EntryPoints: entryPoints, Rule: "Host(`host2.local`)", TLS: &dynamic.RouterTLSConfig{ Options: "host1", }, }, }, }, tlsOptions: tlsOptionsBase, host: "host1.local", ServerName: "host2.local", expectedStatus: http.StatusOK, }, { desc: "Request is misdirected when TLS options have the same name but from different providers", routers: map[string]*runtime.RouterInfo{ "router-1@file": { Router: &dynamic.Router{ EntryPoints: entryPoints, Rule: "Host(`host1.local`)", TLS: &dynamic.RouterTLSConfig{ Options: "host1", }, }, }, "router-2@crd": { Router: &dynamic.Router{ EntryPoints: entryPoints, Rule: "Host(`host2.local`)", TLS: &dynamic.RouterTLSConfig{ Options: "host1", }, }, }, }, tlsOptions: tlsOptionsBase, host: "host1.local", ServerName: "host2.local", expectedStatus: http.StatusMisdirectedRequest, }, { desc: "Request is OK when TLS options reference from a different provider is the same", routers: map[string]*runtime.RouterInfo{ "router-1@file": { Router: &dynamic.Router{ EntryPoints: entryPoints, Rule: "Host(`host1.local`)", TLS: &dynamic.RouterTLSConfig{ Options: "host1@crd", }, }, }, "router-2@crd": { Router: &dynamic.Router{ EntryPoints: entryPoints, Rule: "Host(`host2.local`)", TLS: &dynamic.RouterTLSConfig{ Options: "host1@crd", }, }, }, }, tlsOptions: tlsOptionsBase, host: "host1.local", ServerName: "host2.local", expectedStatus: http.StatusOK, }, { desc: "Request is misdirected when server name is empty and the host name is an FQDN, but router's rule is not", routers: map[string]*runtime.RouterInfo{ "router-1@file": { Router: &dynamic.Router{ EntryPoints: entryPoints, Rule: "Host(`host1.local`)", TLS: &dynamic.RouterTLSConfig{ Options: "host1@file", }, }, }, }, tlsOptions: map[string]traefiktls.Options{ "default": { MinVersion: "VersionTLS13", }, "host1@file": { MinVersion: "VersionTLS12", }, }, host: "host1.local.", expectedStatus: http.StatusMisdirectedRequest, }, { desc: "Request is misdirected when server name is empty and the host name is not FQDN, but router's rule is", routers: map[string]*runtime.RouterInfo{ "router-1@file": { Router: &dynamic.Router{ EntryPoints: entryPoints, Rule: "Host(`host1.local.`)", TLS: &dynamic.RouterTLSConfig{ Options: "host1@file", }, }, }, }, tlsOptions: map[string]traefiktls.Options{ "default": { MinVersion: "VersionTLS13", }, "host1@file": { MinVersion: "VersionTLS12", }, }, host: "host1.local", expectedStatus: http.StatusMisdirectedRequest, }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { conf := &runtime.Configuration{ Routers: test.routers, } serviceManager := tcp.NewManager(conf, tcp2.NewDialerManager(nil)) tlsManager := traefiktls.NewManager(nil) tlsManager.UpdateConfigs(t.Context(), map[string]traefiktls.Store{}, test.tlsOptions, []*traefiktls.CertAndStores{}) httpsHandler := map[string]http.Handler{ "web": http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {}), } middlewaresBuilder := tcpmiddleware.NewBuilder(conf.TCPMiddlewares) routerManager := NewManager(conf, serviceManager, middlewaresBuilder, nil, httpsHandler, tlsManager) routers := routerManager.BuildHandlers(t.Context(), entryPoints) router, ok := routers["web"] require.True(t, ok) req := httptest.NewRequest(http.MethodGet, "/", nil) req.Host = test.host req.TLS = &tls.ConnectionState{ ServerName: test.ServerName, } rw := httptest.NewRecorder() router.GetHTTPSHandler().ServeHTTP(rw, req) assert.Equal(t, test.expectedStatus, rw.Code) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/router/tcp/postgres.go
pkg/server/router/tcp/postgres.go
package tcp import ( "bufio" "bytes" "errors" "io" "net" "sync" "github.com/rs/zerolog/log" tcpmuxer "github.com/traefik/traefik/v3/pkg/muxer/tcp" "github.com/traefik/traefik/v3/pkg/tcp" ) var ( PostgresStartTLSMsg = []byte{0, 0, 0, 8, 4, 210, 22, 47} // int32(8) + int32(80877103) PostgresStartTLSReply = []byte{83} // S ) // isPostgres determines whether the buffer contains the Postgres STARTTLS message. func isPostgres(br *bufio.Reader) (bool, error) { // Peek the first 8 bytes individually to prevent blocking on peek // if the underlying conn does not send enough bytes. // It could happen if a protocol start by sending less than 8 bytes, // and expect a response before proceeding. for i := 1; i < len(PostgresStartTLSMsg)+1; i++ { peeked, err := br.Peek(i) if err != nil { var opErr *net.OpError if !errors.Is(err, io.EOF) && (!errors.As(err, &opErr) || !opErr.Timeout()) { log.Debug().Err(err).Msg("Error while peeking first bytes") } return false, err } if !bytes.Equal(peeked, PostgresStartTLSMsg[:i]) { return false, nil } } return true, nil } // servePostgres serves a connection with a Postgres client negotiating a STARTTLS session. // It handles TCP TLS routing, after accepting to start the STARTTLS session. func (r *Router) servePostgres(conn tcp.WriteCloser) { _, err := conn.Write(PostgresStartTLSReply) if err != nil { conn.Close() return } br := bufio.NewReader(conn) b := make([]byte, len(PostgresStartTLSMsg)) _, err = br.Read(b) if err != nil { conn.Close() return } hello, err := clientHelloInfo(br) if err != nil { conn.Close() return } if !hello.isTLS { conn.Close() return } connData, err := tcpmuxer.NewConnData(hello.serverName, conn, hello.protos) if err != nil { log.Error().Err(err).Msg("Error while reading TCP connection data") conn.Close() return } // Contains also TCP TLS passthrough routes. handlerTCPTLS, _ := r.muxerTCPTLS.Match(connData) if handlerTCPTLS == nil { conn.Close() return } // We are in TLS mode and if the handler is not TLSHandler, we are in passthrough. proxiedConn := r.GetConn(conn, hello.peeked) if _, ok := handlerTCPTLS.(*tcp.TLSHandler); !ok { proxiedConn = &postgresConn{WriteCloser: proxiedConn} } handlerTCPTLS.ServeTCP(proxiedConn) } // postgresConn is a tcp.WriteCloser that will negotiate a TLS session (STARTTLS), // before exchanging any data. // It enforces that the STARTTLS negotiation with the peer is successful. type postgresConn struct { tcp.WriteCloser starttlsMsgSent bool // whether we have already sent the STARTTLS handshake to the backend. starttlsReplyReceived bool // whether we have already received the STARTTLS handshake reply from the backend. // errChan makes sure that an error is returned if the first operation to ever // happen on a postgresConn is a Write (because it should instead be a Read). errChanMu sync.Mutex errChan chan error } // Read reads bytes from the underlying connection (tcp.WriteCloser). // On first call, it actually only injects the PostgresStartTLSMsg, // in order to behave as a Postgres TLS client that initiates a STARTTLS handshake. // Read does not support concurrent calls. func (c *postgresConn) Read(p []byte) (n int, err error) { if c.starttlsMsgSent { if err := <-c.errChan; err != nil { return 0, err } return c.WriteCloser.Read(p) } defer func() { c.starttlsMsgSent = true c.errChanMu.Lock() c.errChan = make(chan error) c.errChanMu.Unlock() }() copy(p, PostgresStartTLSMsg) return len(PostgresStartTLSMsg), nil } // Write writes bytes to the underlying connection (tcp.WriteCloser). // On first call, it checks that the bytes to write (the ones provided by the backend) // match the PostgresStartTLSReply, and if yes it drops them (as the STARTTLS // handshake between the client and traefik has already taken place). Otherwise, an // error is transmitted through c.errChan, so that the second Read call gets it and // returns it up the stack. // Write does not support concurrent calls. func (c *postgresConn) Write(p []byte) (n int, err error) { if c.starttlsReplyReceived { return c.WriteCloser.Write(p) } c.errChanMu.Lock() if c.errChan == nil { c.errChanMu.Unlock() return 0, errors.New("initial read never happened") } c.errChanMu.Unlock() defer func() { c.starttlsReplyReceived = true }() if len(p) != 1 || p[0] != PostgresStartTLSReply[0] { c.errChan <- errors.New("invalid response from Postgres server") return len(p), nil } close(c.errChan) return 1, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/router/tcp/router.go
pkg/server/router/tcp/router.go
package tcp import ( "bufio" "bytes" "crypto/tls" "errors" "io" "net" "net/http" "slices" "time" "github.com/go-acme/lego/v4/challenge/tlsalpn01" "github.com/rs/zerolog/log" tcpmuxer "github.com/traefik/traefik/v3/pkg/muxer/tcp" "github.com/traefik/traefik/v3/pkg/tcp" ) const defaultBufSize = 4096 // Router is a TCP router. type Router struct { acmeTLSPassthrough bool // Contains TCP routes. muxerTCP tcpmuxer.Muxer // Contains TCP TLS routes. muxerTCPTLS tcpmuxer.Muxer // Contains HTTPS routes. muxerHTTPS tcpmuxer.Muxer // Forwarder handlers. // httpForwarder handles all HTTP requests. httpForwarder tcp.Handler // httpsForwarder handles (indirectly through muxerHTTPS, or directly) all HTTPS requests. httpsForwarder tcp.Handler // Neither is used directly, but they are held here, and recreated on config reload, // so that they can be passed to the Switcher at the end of the config reload phase. httpHandler http.Handler httpsHandler http.Handler // TLS configs. httpsTLSConfig *tls.Config // default TLS config // hostHTTPTLSConfig contains TLS configs keyed by SNI. // A nil config is the hint to set up a brokenTLSRouter. hostHTTPTLSConfig map[string]*tls.Config // TLS configs keyed by SNI } // NewRouter returns a new TCP router. func NewRouter() (*Router, error) { muxTCP, err := tcpmuxer.NewMuxer() if err != nil { return nil, err } muxTCPTLS, err := tcpmuxer.NewMuxer() if err != nil { return nil, err } muxHTTPS, err := tcpmuxer.NewMuxer() if err != nil { return nil, err } return &Router{ muxerTCP: *muxTCP, muxerTCPTLS: *muxTCPTLS, muxerHTTPS: *muxHTTPS, }, nil } // GetTLSGetClientInfo is called after a ClientHello is received from a client. func (r *Router) GetTLSGetClientInfo() func(info *tls.ClientHelloInfo) (*tls.Config, error) { return func(info *tls.ClientHelloInfo) (*tls.Config, error) { if tlsConfig, ok := r.hostHTTPTLSConfig[info.ServerName]; ok { return tlsConfig, nil } return r.httpsTLSConfig, nil } } // ServeTCP forwards the connection to the right TCP/HTTP handler. func (r *Router) ServeTCP(conn tcp.WriteCloser) { // Handling Non-TLS TCP connection early if there is neither HTTP(S) nor TLS routers on the entryPoint, // and if there is at least one non-TLS TCP router. // In the case of a non-TLS TCP client (that does not "send" first), // we would block forever on clientHelloInfo, // which is why we want to detect and handle that case first and foremost. if r.muxerTCP.HasRoutes() && !r.muxerTCPTLS.HasRoutes() && !r.muxerHTTPS.HasRoutes() { connData, err := tcpmuxer.NewConnData("", conn, nil) if err != nil { log.Error().Err(err).Msg("Error while reading TCP connection data") conn.Close() return } handler, _ := r.muxerTCP.Match(connData) // If there is a handler matching the connection metadata, // we let it handle the connection. if handler != nil { // Remove read/write deadline and delegate this to underlying TCP server. if err := conn.SetDeadline(time.Time{}); err != nil { log.Error().Err(err).Msg("Error while setting deadline") } handler.ServeTCP(conn) return } // Otherwise, we keep going because: // 1) we could be in the case where we have HTTP routers. // 2) if it is an HTTPS request, even though we do not have any TLS routers, // we still need to reply with a 404. } // TODO -- Check if ProxyProtocol changes the first bytes of the request br := bufio.NewReader(conn) postgres, err := isPostgres(br) if err != nil { conn.Close() return } if postgres { // Remove read/write deadline and delegate this to underlying TCP server. if err := conn.SetDeadline(time.Time{}); err != nil { log.Error().Err(err).Msg("Error while setting deadline") } r.servePostgres(r.GetConn(conn, getPeeked(br))) return } hello, err := clientHelloInfo(br) if err != nil { conn.Close() return } // Remove read/write deadline and delegate this to underlying TCP server (for now only handled by HTTP Server) if err := conn.SetDeadline(time.Time{}); err != nil { log.Error().Err(err).Msg("Error while setting deadline") } connData, err := tcpmuxer.NewConnData(hello.serverName, conn, hello.protos) if err != nil { log.Error().Err(err).Msg("Error while reading TCP connection data") conn.Close() return } if !hello.isTLS { handler, _ := r.muxerTCP.Match(connData) switch { case handler != nil: handler.ServeTCP(r.GetConn(conn, hello.peeked)) case r.httpForwarder != nil: r.httpForwarder.ServeTCP(r.GetConn(conn, hello.peeked)) default: conn.Close() } return } // Handling ACME-TLS/1 challenges. if !r.acmeTLSPassthrough && slices.Contains(hello.protos, tlsalpn01.ACMETLS1Protocol) { r.acmeTLSALPNHandler().ServeTCP(r.GetConn(conn, hello.peeked)) return } // For real, the handler eventually used for HTTPS is (almost) always the same: // it is the httpsForwarder that is used for all HTTPS connections that match // (which is also incidentally the same used in the last block below for 404s). // The added value from doing Match is to find and use the specific TLS config // (wrapped inside the returned handler) requested for the given HostSNI. handlerHTTPS, catchAllHTTPS := r.muxerHTTPS.Match(connData) if handlerHTTPS != nil && !catchAllHTTPS { // In order not to depart from the behavior in 2.6, // we only allow an HTTPS router to take precedence over a TCP-TLS router if it is _not_ an HostSNI(*) router // (so basically any router that has a specific HostSNI based rule). handlerHTTPS.ServeTCP(r.GetConn(conn, hello.peeked)) return } // Contains also TCP TLS passthrough routes. handlerTCPTLS, catchAllTCPTLS := r.muxerTCPTLS.Match(connData) if handlerTCPTLS != nil && !catchAllTCPTLS { handlerTCPTLS.ServeTCP(r.GetConn(conn, hello.peeked)) return } // Fallback on HTTPS catchAll. // We end up here for e.g. an HTTPS router that only has a PathPrefix rule, // which under the scenes is counted as an HostSNI(*) rule. if handlerHTTPS != nil { handlerHTTPS.ServeTCP(r.GetConn(conn, hello.peeked)) return } // Fallback on TCP TLS catchAll. if handlerTCPTLS != nil { handlerTCPTLS.ServeTCP(r.GetConn(conn, hello.peeked)) return } // To handle 404s for HTTPS. if r.httpsForwarder != nil { r.httpsForwarder.ServeTCP(r.GetConn(conn, hello.peeked)) return } conn.Close() } // acmeTLSALPNHandler returns a special handler to solve ACME-TLS/1 challenges. func (r *Router) acmeTLSALPNHandler() tcp.Handler { if r.httpsTLSConfig == nil { return &brokenTLSRouter{} } return tcp.HandlerFunc(func(conn tcp.WriteCloser) { _ = tls.Server(conn, r.httpsTLSConfig).Handshake() }) } // AddTCPRoute defines a handler for the given rule. func (r *Router) AddTCPRoute(rule string, priority int, target tcp.Handler) error { return r.muxerTCP.AddRoute(rule, "", priority, target) } // AddHTTPTLSConfig defines a handler for a given sniHost and sets the matching tlsConfig. func (r *Router) AddHTTPTLSConfig(sniHost string, config *tls.Config) { if r.hostHTTPTLSConfig == nil { r.hostHTTPTLSConfig = map[string]*tls.Config{} } r.hostHTTPTLSConfig[sniHost] = config } // GetConn creates a connection proxy with a peeked string. func (r *Router) GetConn(conn tcp.WriteCloser, peeked string) tcp.WriteCloser { // TODO should it really be on Router ? conn = &Conn{ Peeked: []byte(peeked), WriteCloser: conn, } return conn } // GetHTTPHandler gets the attached http handler. func (r *Router) GetHTTPHandler() http.Handler { return r.httpHandler } // GetHTTPSHandler gets the attached https handler. func (r *Router) GetHTTPSHandler() http.Handler { return r.httpsHandler } // SetHTTPForwarder sets the tcp handler that will forward the connections to an http handler. func (r *Router) SetHTTPForwarder(handler tcp.Handler) { r.httpForwarder = handler } // brokenTLSRouter is associated to a Host(SNI) rule for which we know the TLS conf is broken. // It is used to make sure any attempt to connect to that hostname is closed, // since we cannot proceed with the intended TLS conf. type brokenTLSRouter struct{} // ServeTCP instantly closes the connection. func (t *brokenTLSRouter) ServeTCP(conn tcp.WriteCloser) { _ = conn.Close() } // SetHTTPSForwarder sets the tcp handler that will forward the TLS connections to an HTTP handler. // It also sets up each TLS handler (with its TLS config) for each Host(SNI) rule we previously kept track of. // It sets up a special handler that closes the connection if a TLS config is nil. func (r *Router) SetHTTPSForwarder(handler tcp.Handler) { for sniHost, tlsConf := range r.hostHTTPTLSConfig { var tcpHandler tcp.Handler if tlsConf == nil { tcpHandler = &brokenTLSRouter{} } else { tcpHandler = &tcp.TLSHandler{ Next: handler, Config: tlsConf, } } rule := "HostSNI(`" + sniHost + "`)" if err := r.muxerHTTPS.AddRoute(rule, "", tcpmuxer.GetRulePriority(rule), tcpHandler); err != nil { log.Error().Err(err).Msg("Error while adding route for host") } } if r.httpsTLSConfig == nil { r.httpsForwarder = &brokenTLSRouter{} return } r.httpsForwarder = &tcp.TLSHandler{ Next: handler, Config: r.httpsTLSConfig, } } // SetHTTPHandler attaches http handlers on the router. func (r *Router) SetHTTPHandler(handler http.Handler) { r.httpHandler = handler } // SetHTTPSHandler attaches https handlers on the router. func (r *Router) SetHTTPSHandler(handler http.Handler, config *tls.Config) { r.httpsHandler = handler r.httpsTLSConfig = config } func (r *Router) EnableACMETLSPassthrough() { r.acmeTLSPassthrough = true } // Conn is a connection proxy that handles Peeked bytes. type Conn struct { // Peeked are the bytes that have been read from Conn for the purposes of route matching, // but have not yet been consumed by Read calls. // It set to nil by Read when fully consumed. Peeked []byte // Conn is the underlying connection. // It can be type asserted against *net.TCPConn or other types as needed. // It should not be read from directly unless Peeked is nil. tcp.WriteCloser } // Read reads bytes from the connection (using the buffer prior to actually reading). func (c *Conn) Read(p []byte) (n int, err error) { if len(c.Peeked) > 0 { n = copy(p, c.Peeked) c.Peeked = c.Peeked[n:] if len(c.Peeked) == 0 { c.Peeked = nil } return n, nil } return c.WriteCloser.Read(p) } type clientHello struct { serverName string // SNI server name protos []string // ALPN protocols list isTLS bool // whether we are a TLS handshake peeked string // the bytes peeked from the hello while getting the info } // clientHelloInfo returns various data from the clientHello handshake, // without consuming any bytes from br. // It returns an error if it can't peek the first byte from the connection. func clientHelloInfo(br *bufio.Reader) (*clientHello, error) { hdr, err := br.Peek(1) if err != nil { var opErr *net.OpError if !errors.Is(err, io.EOF) && (!errors.As(err, &opErr) || !opErr.Timeout()) { log.Debug().Err(err).Msg("Error while peeking first byte") } return nil, err } // No valid TLS record has a type of 0x80, however SSLv2 handshakes start with an uint16 length // where the MSB is set and the first record is always < 256 bytes long. // Therefore, typ == 0x80 strongly suggests an SSLv2 client. const recordTypeSSLv2 = 0x80 const recordTypeHandshake = 0x16 if hdr[0] != recordTypeHandshake { if hdr[0] == recordTypeSSLv2 { // we consider SSLv2 as TLS, and it will be refused by real TLS handshake. return &clientHello{ isTLS: true, peeked: getPeeked(br), }, nil } return &clientHello{ peeked: getPeeked(br), }, nil // Not TLS. } const recordHeaderLen = 5 hdr, err = br.Peek(recordHeaderLen) if err != nil { log.Error().Err(err).Msg("Error while peeking client hello header") return &clientHello{ peeked: getPeeked(br), }, nil } recLen := int(hdr[3])<<8 | int(hdr[4]) // ignoring version in hdr[1:3] if recordHeaderLen+recLen > defaultBufSize { br = bufio.NewReaderSize(br, recordHeaderLen+recLen) } helloBytes, err := br.Peek(recordHeaderLen + recLen) if err != nil { log.Error().Err(err).Msg("Error while peeking client hello bytes") return &clientHello{ isTLS: true, peeked: getPeeked(br), }, nil } sni := "" var protos []string server := tls.Server(helloSniffConn{r: bytes.NewReader(helloBytes)}, &tls.Config{ GetConfigForClient: func(hello *tls.ClientHelloInfo) (*tls.Config, error) { sni = hello.ServerName protos = hello.SupportedProtos return nil, nil }, }) _ = server.Handshake() return &clientHello{ serverName: sni, isTLS: true, peeked: getPeeked(br), protos: protos, }, nil } func getPeeked(br *bufio.Reader) string { peeked, err := br.Peek(br.Buffered()) if err != nil { log.Error().Err(err).Msg("Error while peeking bytes") return "" } return string(peeked) } // helloSniffConn is a net.Conn that reads from r, fails on Writes, // and crashes otherwise. type helloSniffConn struct { r io.Reader net.Conn // nil; crash on any unexpected use } // Read reads from the underlying reader. func (c helloSniffConn) Read(p []byte) (int, error) { return c.r.Read(p) } // Write crashes all the time. func (helloSniffConn) Write(p []byte) (int, error) { return 0, io.EOF }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/router/tcp/router_test.go
pkg/server/router/tcp/router_test.go
package tcp import ( "bytes" "crypto/tls" "errors" "fmt" "io" "net" "net/http" "net/url" "strings" "testing" "time" "github.com/go-acme/lego/v4/challenge/tlsalpn01" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" tcpmiddleware "github.com/traefik/traefik/v3/pkg/server/middleware/tcp" "github.com/traefik/traefik/v3/pkg/server/service/tcp" tcp2 "github.com/traefik/traefik/v3/pkg/tcp" traefiktls "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/tls/generate" "github.com/traefik/traefik/v3/pkg/types" ) type applyRouter func(conf *runtime.Configuration) type checkRouter func(addr string, timeout time.Duration) error type httpForwarder struct { net.Listener connChan chan net.Conn errChan chan error } func newHTTPForwarder(ln net.Listener) *httpForwarder { return &httpForwarder{ Listener: ln, connChan: make(chan net.Conn), errChan: make(chan error), } } // Close closes the Listener. func (h *httpForwarder) Close() error { h.errChan <- http.ErrServerClosed return nil } // ServeTCP uses the connection to serve it later in "Accept". func (h *httpForwarder) ServeTCP(conn tcp2.WriteCloser) { h.connChan <- conn } // Accept retrieves a served connection in ServeTCP. func (h *httpForwarder) Accept() (net.Conn, error) { select { case conn := <-h.connChan: return conn, nil case err := <-h.errChan: return nil, err } } // Test_Routing aims to settle the behavior between routers of different types on the same TCP entryPoint. // It has been introduced as a regression test following a fix on the v2.7 TCP Muxer. // // The routing precedence is roughly as follows: // - TCP over HTTP // - HTTPS over TCP-TLS // // Discrepancies for server sending first bytes support: // - On v2.6, it is possible as long as you have one and only one TCP Non-TLS HostSNI(`*`) router (so called CatchAllNoTLS) defined. // - On v2.7, it is possible as long as you have zero TLS/HTTPS router defined. // // Discrepancies in routing precedence between TCP and HTTP routers: // - TCP HostSNI(`*`) and HTTP Host(`foobar`) // - On v2.6 and v2.7, the TCP one takes precedence. // // - TCP ClientIP(`[::]`) and HTTP Host(`foobar`) // - On v2.6, ClientIP matcher doesn't exist. // - On v2.7, the TCP one takes precedence. // // Routing precedence between TCP-TLS and HTTPS routers (considering a request/connection with the servername "foobar"): // - TCP-TLS HostSNI(`*`) and HTTPS Host(`foobar`) // - On v2.6 and v2.7, the HTTPS one takes precedence. // // - TCP-TLS HostSNI(`foobar`) and HTTPS Host(`foobar`) // - On v2.6 and v2.7, the HTTPS one takes precedence (overriding the TCP-TLS one in v2.6). // // - TCP-TLS HostSNI(`*`) and HTTPS PathPrefix(`/`) // - On v2.6 and v2.7, the HTTPS one takes precedence (overriding the TCP-TLS one in v2.6). // // - TCP-TLS HostSNI(`foobar`) and HTTPS PathPrefix(`/`) // - On v2.6 and v2.7, the TCP-TLS one takes precedence. func Test_Routing(t *testing.T) { // This listener simulates the backend service. // It is capable of switching into server first communication mode, // if the client takes to long to send the first bytes. tcpBackendListener, err := net.Listen("tcp", "127.0.0.1:0") require.NoError(t, err) // This allows the closing of the TCP backend listener to happen last. t.Cleanup(func() { tcpBackendListener.Close() }) go func() { for { conn, err := tcpBackendListener.Accept() if err != nil { var opErr *net.OpError if errors.As(err, &opErr) && opErr.Temporary() { continue } var urlErr *url.Error if errors.As(err, &urlErr) && urlErr.Temporary() { continue } return } err = conn.SetReadDeadline(time.Now().Add(200 * time.Millisecond)) if err != nil { return } buf := make([]byte, 100) _, err = conn.Read(buf) var opErr *net.OpError if err == nil { _, err = fmt.Fprint(conn, "TCP-CLIENT-FIRST") require.NoError(t, err) } else if errors.As(err, &opErr) && opErr.Timeout() { _, err = fmt.Fprint(conn, "TCP-SERVER-FIRST") require.NoError(t, err) } err = conn.Close() require.NoError(t, err) } }() // Configuration defining the TCP backend service, used by TCP routers later. conf := &runtime.Configuration{ TCPServices: map[string]*runtime.TCPServiceInfo{ "tcp": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: tcpBackendListener.Addr().String(), }, }, }, }, }, }, } dialerManager := tcp2.NewDialerManager(nil) dialerManager.Update(map[string]*dynamic.TCPServersTransport{"default@internal": {}}) serviceManager := tcp.NewManager(conf, dialerManager) certPEM, keyPEM, err := generate.KeyPair("foo.bar", time.Time{}) require.NoError(t, err) // Creates the tlsManager and defines the TLS 1.0 and 1.2 TLSOptions. tlsManager := traefiktls.NewManager(nil) tlsManager.UpdateConfigs( t.Context(), map[string]traefiktls.Store{ tlsalpn01.ACMETLS1Protocol: {}, }, map[string]traefiktls.Options{ "default": { MinVersion: "VersionTLS10", MaxVersion: "VersionTLS10", }, "tls10": { MinVersion: "VersionTLS10", MaxVersion: "VersionTLS10", }, "tls12": { MinVersion: "VersionTLS12", MaxVersion: "VersionTLS12", }, }, []*traefiktls.CertAndStores{{ Certificate: traefiktls.Certificate{CertFile: types.FileOrContent(certPEM), KeyFile: types.FileOrContent(keyPEM)}, Stores: []string{tlsalpn01.ACMETLS1Protocol}, }}) middlewaresBuilder := tcpmiddleware.NewBuilder(conf.TCPMiddlewares) manager := NewManager(conf, serviceManager, middlewaresBuilder, nil, nil, tlsManager) type checkCase struct { checkRouter desc string expectedError string timeout time.Duration } testCases := []struct { desc string routers []applyRouter checks []checkCase allowACMETLSPassthrough bool }{ { desc: "No routers", routers: []applyRouter{}, checks: []checkCase{ { desc: "ACME TLS Challenge", checkRouter: checkACMETLS, }, { desc: "TCP with client sending first bytes should fail", checkRouter: checkTCPClientFirst, expectedError: "i/o timeout", }, { desc: "TCP with server sending first bytes should fail", checkRouter: checkTCPServerFirst, expectedError: "i/o timeout", }, { desc: "HTTP request should be handled by HTTP service (404)", checkRouter: checkHTTP, }, { desc: "TCP TLS 1.0 connection should fail", checkRouter: checkTCPTLS10, expectedError: "i/o timeout", }, { desc: "TCP TLS 1.2 connection should fail", checkRouter: checkTCPTLS12, // The HTTPS forwarder catches the connection with the TLS 1.0 config, // because no matching routes are defined with the custom TLS Config. expectedError: "wrong TLS version", }, { desc: "HTTPS TLS 1.0 request should be handled by HTTPS (HTTPS forwarder with tls 1.0 config) (404)", checkRouter: checkHTTPSTLS10, }, { desc: "HTTPS TLS 1.2 request should fail", checkRouter: checkHTTPSTLS12, expectedError: "wrong TLS version", }, }, }, { desc: "TCP TLS passthrough does not catch ACME TLS", routers: []applyRouter{routerTCPTLSCatchAllPassthrough}, checks: []checkCase{ { desc: "ACME TLS Challenge", checkRouter: checkACMETLS, }, }, }, { desc: "TCP TLS passthrough catches ACME TLS", allowACMETLSPassthrough: true, routers: []applyRouter{routerTCPTLSCatchAllPassthrough}, checks: []checkCase{ { desc: "ACME TLS Challenge", checkRouter: checkACMETLS, expectedError: "tls: first record does not look like a TLS handshake", }, }, }, { desc: "Single TCP CatchAll router", routers: []applyRouter{routerTCPCatchAll}, checks: []checkCase{ { desc: "TCP with client sending first bytes should be handled by TCP service", checkRouter: checkTCPClientFirst, }, { desc: "TCP with server sending first bytes should be handled by TCP service", checkRouter: checkTCPServerFirst, }, }, }, { desc: "Single HTTP router", routers: []applyRouter{routerHTTP}, checks: []checkCase{ { desc: "HTTP request should be handled by HTTP service", checkRouter: checkHTTP, }, }, }, { desc: "Single TCP TLS router", routers: []applyRouter{routerTCPTLS}, checks: []checkCase{ { desc: "TCP TLS 1.0 connection should fail", checkRouter: checkTCPTLS10, expectedError: "wrong TLS version", }, { desc: "TCP TLS 1.2 connection should be handled by TCP service", checkRouter: checkTCPTLS12, }, }, }, { desc: "Single TCP TLS CatchAll router", routers: []applyRouter{routerTCPTLSCatchAll}, checks: []checkCase{ { desc: "TCP TLS 1.0 connection should be handled by TCP service", checkRouter: checkTCPTLS10, }, { desc: "TCP TLS 1.2 connection should fail", checkRouter: checkTCPTLS12, expectedError: "wrong TLS version", }, }, }, { desc: "Single HTTPS router", routers: []applyRouter{routerHTTPS}, checks: []checkCase{ { desc: "HTTPS TLS 1.0 request should fail", checkRouter: checkHTTPSTLS10, expectedError: "wrong TLS version", }, { desc: "HTTPS TLS 1.2 request should be handled by HTTPS service", checkRouter: checkHTTPSTLS12, }, }, }, { desc: "Single HTTPS PathPrefix router", routers: []applyRouter{routerHTTPSPathPrefix}, checks: []checkCase{ { desc: "HTTPS TLS 1.0 request should be handled by HTTPS service", checkRouter: checkHTTPSTLS10, }, { desc: "HTTPS TLS 1.2 request should fail", checkRouter: checkHTTPSTLS12, expectedError: "wrong TLS version", }, }, }, { desc: "TCP CatchAll router && HTTP router", routers: []applyRouter{routerTCPCatchAll, routerHTTP}, checks: []checkCase{ { desc: "TCP client sending first bytes should be handled by TCP service", checkRouter: checkTCPClientFirst, }, { desc: "TCP server sending first bytes should be handled by TCP service", checkRouter: checkTCPServerFirst, }, { desc: "HTTP request should fail, because handled by TCP service", checkRouter: checkHTTP, expectedError: "malformed HTTP response", }, }, }, { desc: "TCP TLS CatchAll router && HTTP router", routers: []applyRouter{routerTCPTLS, routerHTTP}, checks: []checkCase{ { desc: "TCP TLS 1.0 connection should fail", checkRouter: checkTCPTLS10, expectedError: "wrong TLS version", }, { desc: "TCP TLS 1.2 connection should be handled by TCP service", checkRouter: checkTCPTLS12, }, { desc: "HTTP request should be handled by HTTP service", checkRouter: checkHTTP, }, }, }, { desc: "TCP CatchAll router && HTTPS router", routers: []applyRouter{routerTCPCatchAll, routerHTTPS}, checks: []checkCase{ { desc: "TCP client sending first bytes should be handled by TCP service", checkRouter: checkTCPClientFirst, }, { desc: "TCP server sending first bytes should timeout on clientHello", checkRouter: checkTCPServerFirst, expectedError: "i/o timeout", }, { desc: "HTTP request should fail, because handled by TCP service", checkRouter: checkHTTP, expectedError: "malformed HTTP response", }, { desc: "HTTPS TLS 1.0 request should be handled by HTTPS service", checkRouter: checkHTTPSTLS10, expectedError: "wrong TLS version", }, { desc: "HTTPS TLS 1.2 request should be handled by HTTPS service", checkRouter: checkHTTPSTLS12, }, }, }, { // We show that a not CatchAll HTTPS router takes priority over a TCP-TLS router. desc: "TCP TLS router && HTTPS router", routers: []applyRouter{routerTCPTLS, routerHTTPS}, checks: []checkCase{ { desc: "TCP TLS 1.0 connection should fail", checkRouter: checkTCPTLS10, expectedError: "wrong TLS version", }, { desc: "TCP TLS 1.2 connection should fail", checkRouter: checkTCPTLS12, // The connection is handled by the HTTPS router, // which has the correct TLS config, // but the HTTP server is detecting a malformed request which ends with a timeout. expectedError: "i/o timeout", }, { desc: "HTTPS TLS 1.0 request should fail", checkRouter: checkHTTPSTLS10, expectedError: "wrong TLS version", }, { desc: "HTTPS TLS 1.2 request should be handled by HTTPS service", checkRouter: checkHTTPSTLS12, }, }, }, { // We show that a not CatchAll HTTPS router takes priority over a CatchAll TCP-TLS router. desc: "TCP TLS CatchAll router && HTTPS router", routers: []applyRouter{routerTCPCatchAll, routerHTTPS}, checks: []checkCase{ { desc: "TCP TLS 1.0 connection should fail", checkRouter: checkTCPTLS10, expectedError: "wrong TLS version", }, { desc: "TCP TLS 1.2 connection should fail", checkRouter: checkTCPTLS12, // The connection is handled by the HTTPS router, // which has the correct TLS config, // but the HTTP server is detecting a malformed request which ends with a timeout. expectedError: "i/o timeout", }, { desc: "HTTPS TLS 1.0 request should fail", checkRouter: checkHTTPSTLS10, expectedError: "wrong TLS version", }, { desc: "HTTPS TLS 1.2 request should be handled by HTTPS service", checkRouter: checkHTTPSTLS12, }, }, }, { // We show that TCP-TLS router (not CatchAll) takes priority over non-Host rule HTTPS router (CatchAll). desc: "TCP TLS router && HTTPS Path prefix router", routers: []applyRouter{routerTCPTLS, routerHTTPSPathPrefix}, checks: []checkCase{ { desc: "TCP TLS 1.0 connection should fail", checkRouter: checkTCPTLS10, expectedError: "wrong TLS version", }, { desc: "TCP TLS 1.2 connection should be handled by TCP service", checkRouter: checkTCPTLS12, }, { desc: "HTTPS TLS 1.0 request should fail", checkRouter: checkHTTPSTLS10, expectedError: "malformed HTTP response", }, { desc: "HTTPS TLS 1.2 should fail", checkRouter: checkHTTPSTLS12, expectedError: "malformed HTTP response", }, }, }, { desc: "TCP TLS router && TCP TLS CatchAll router", routers: []applyRouter{routerTCPTLS, routerTCPTLSCatchAll}, checks: []checkCase{ { desc: "TCP TLS 1.0 connection should fail", checkRouter: checkTCPTLS10, expectedError: "wrong TLS version", }, { desc: "TCP TLS 1.2 connection should be handled by TCP service", checkRouter: checkTCPTLS12, }, }, }, { desc: "HTTPS router && HTTPS CatchAll router", routers: []applyRouter{routerHTTPS, routerHTTPSPathPrefix}, checks: []checkCase{ { desc: "HTTPS TLS 1.0 request should fail", checkRouter: checkHTTPSTLS10, expectedError: "wrong TLS version", }, { desc: "HTTPS TLS 1.2 request should be handled by HTTPS service", checkRouter: checkHTTPSTLS12, }, }, }, { desc: "All routers, all checks", routers: []applyRouter{routerTCPCatchAll, routerHTTP, routerHTTPS, routerTCPTLS, routerTCPTLSCatchAll}, checks: []checkCase{ { desc: "TCP client sending first bytes should be handled by TCP service", checkRouter: checkTCPClientFirst, }, { desc: "TCP server sending first bytes should timeout on clientHello", checkRouter: checkTCPServerFirst, expectedError: "i/o timeout", }, { desc: "HTTP request should fail, because handled by TCP service", checkRouter: checkHTTP, expectedError: "malformed HTTP response", }, { desc: "HTTPS TLS 1.0 request should fail", checkRouter: checkHTTPSTLS10, expectedError: "wrong TLS version", }, { desc: "HTTPS TLS 1.2 request should be handled by HTTPS service", checkRouter: checkHTTPSTLS12, }, { desc: "TCP TLS 1.0 connection should fail", checkRouter: checkTCPTLS10, expectedError: "wrong TLS version", }, { desc: "TCP TLS 1.2 connection should fail", checkRouter: checkTCPTLS12, // The connection is handled by the HTTPS router, // witch have the correct TLS config, // but the HTTP server is detecting a malformed request which ends with a timeout. expectedError: "i/o timeout", }, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() dynConf := &runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{}, TCPRouters: map[string]*runtime.TCPRouterInfo{}, } for _, router := range test.routers { router(dynConf) } router, err := manager.buildEntryPointHandler(t.Context(), dynConf.TCPRouters, dynConf.Routers, nil, nil) require.NoError(t, err) if test.allowACMETLSPassthrough { router.EnableACMETLSPassthrough() } epListener, err := net.Listen("tcp", "127.0.0.1:0") require.NoError(t, err) // serverHTTP handler returns only the "HTTP" value as body for further checks. serverHTTP := &http.Server{ Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, err = fmt.Fprint(w, "HTTP") require.NoError(t, err) }), } stoppedHTTP := make(chan struct{}) forwarder := newHTTPForwarder(epListener) go func() { defer close(stoppedHTTP) _ = serverHTTP.Serve(forwarder) }() router.SetHTTPForwarder(forwarder) // serverHTTPS handler returns only the "HTTPS" value as body for further checks. serverHTTPS := &http.Server{ Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, err = fmt.Fprint(w, "HTTPS") require.NoError(t, err) }), } stoppedHTTPS := make(chan struct{}) httpsForwarder := newHTTPForwarder(epListener) go func() { defer close(stoppedHTTPS) _ = serverHTTPS.Serve(httpsForwarder) }() router.SetHTTPSForwarder(httpsForwarder) stoppedTCP := make(chan struct{}) go func() { defer close(stoppedTCP) for { conn, err := epListener.Accept() if err != nil { return } tcpConn, ok := conn.(*net.TCPConn) if !ok { t.Error("not a write closer") } router.ServeTCP(tcpConn) } }() for _, check := range test.checks { timeout := 2 * time.Second if check.timeout > 0 { timeout = check.timeout } err := check.checkRouter(epListener.Addr().String(), timeout) if check.expectedError != "" { require.Error(t, err, check.desc) assert.Contains(t, err.Error(), check.expectedError, check.desc) continue } assert.NoError(t, err, check.desc) } epListener.Close() <-stoppedTCP serverHTTP.Close() serverHTTPS.Close() <-stoppedHTTP <-stoppedHTTPS }) } } // routerTCPCatchAll configures a TCP CatchAll No TLS - HostSNI(`*`) router. func routerTCPCatchAll(conf *runtime.Configuration) { conf.TCPRouters["tcp-catchall"] = &runtime.TCPRouterInfo{ TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "tcp", Rule: "HostSNI(`*`)", }, } } // routerHTTP configures an HTTP - Host(`foo.bar`) router. func routerHTTP(conf *runtime.Configuration) { conf.Routers["http"] = &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "http", Rule: "Host(`foo.bar`)", }, } } // routerTCPTLSCatchAll a TCP TLS CatchAll - HostSNI(`*`) router with TLS 1.0 config. func routerTCPTLSCatchAll(conf *runtime.Configuration) { conf.TCPRouters["tcp-tls-catchall"] = &runtime.TCPRouterInfo{ TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "tcp", Rule: "HostSNI(`*`)", TLS: &dynamic.RouterTCPTLSConfig{ Options: "tls10", }, }, } } // routerTCPTLSCatchAllPassthrough a TCP TLS CatchAll Passthrough - HostSNI(`*`) router with TLS 1.2 config. func routerTCPTLSCatchAllPassthrough(conf *runtime.Configuration) { conf.TCPRouters["tcp-tls-catchall-passthrough"] = &runtime.TCPRouterInfo{ TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "tcp", Rule: "HostSNI(`*`)", TLS: &dynamic.RouterTCPTLSConfig{ Options: "tls12", Passthrough: true, }, }, } } // routerTCPTLS configures a TCP TLS - HostSNI(`foo.bar`) router with TLS 1.2 config. func routerTCPTLS(conf *runtime.Configuration) { conf.TCPRouters["tcp-tls"] = &runtime.TCPRouterInfo{ TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "tcp", Rule: "HostSNI(`foo.bar`)", TLS: &dynamic.RouterTCPTLSConfig{ Options: "tls12", }, }, } } // routerHTTPSPathPrefix configures an HTTPS - PathPrefix(`/`) router with TLS 1.0 config. func routerHTTPSPathPrefix(conf *runtime.Configuration) { conf.Routers["https"] = &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "http", Rule: "PathPrefix(`/`)", TLS: &dynamic.RouterTLSConfig{ Options: "tls10", }, }, } } // routerHTTPS configures an HTTPS - Host(`foo.bar`) router with TLS 1.2 config. func routerHTTPS(conf *runtime.Configuration) { conf.Routers["https-custom-tls"] = &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "http", Rule: "Host(`foo.bar`)", TLS: &dynamic.RouterTLSConfig{ Options: "tls12", }, }, } } // checkACMETLS simulates a ACME TLS Challenge client connection. // It returns an error if TLS handshake fails. func checkACMETLS(addr string, _ time.Duration) (err error) { tlsConfig := &tls.Config{ InsecureSkipVerify: true, ServerName: "foo.bar", MinVersion: tls.VersionTLS10, NextProtos: []string{tlsalpn01.ACMETLS1Protocol}, } conn, err := tls.Dial("tcp", addr, tlsConfig) if err != nil { return err } defer func() { closeErr := conn.Close() if closeErr != nil && err == nil { err = closeErr } }() if conn.ConnectionState().Version != tls.VersionTLS10 { return fmt.Errorf("wrong TLS version. wanted %X, got %X", tls.VersionTLS10, conn.ConnectionState().Version) } return nil } // checkTCPClientFirst simulates a TCP client sending first bytes first. // It returns an error if it doesn't receive the expected response. func checkTCPClientFirst(addr string, timeout time.Duration) (err error) { conn, err := net.Dial("tcp", addr) if err != nil { return err } defer func() { closeErr := conn.Close() if closeErr != nil && err == nil { err = closeErr } }() fmt.Fprint(conn, "HELLO") err = conn.SetReadDeadline(time.Now().Add(timeout)) if err != nil { return } var buf bytes.Buffer _, err = io.Copy(&buf, conn) if err != nil { return err } if !strings.HasPrefix(buf.String(), "TCP-CLIENT-FIRST") { return fmt.Errorf("unexpected response: %s", buf.String()) } return nil } // checkTCPServerFirst simulates a TCP client waiting for the server first bytes. // It returns an error if it doesn't receive the expected response. func checkTCPServerFirst(addr string, timeout time.Duration) (err error) { conn, err := net.Dial("tcp", addr) if err != nil { return err } defer func() { closeErr := conn.Close() if closeErr != nil && err == nil { err = closeErr } }() err = conn.SetReadDeadline(time.Now().Add(timeout)) if err != nil { return } var buf bytes.Buffer _, err = io.Copy(&buf, conn) if err != nil { return err } if !strings.HasPrefix(buf.String(), "TCP-SERVER-FIRST") { return fmt.Errorf("unexpected response: %s", buf.String()) } return nil } // checkHTTP simulates an HTTP client. // It returns an error if it doesn't receive the expected response. func checkHTTP(addr string, timeout time.Duration) error { httpClient := &http.Client{Timeout: timeout} req, err := http.NewRequest(http.MethodGet, "http://"+addr, nil) if err != nil { return err } req.Header.Set("Host", "foo.bar") resp, err := httpClient.Do(req) if err != nil { return err } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return err } if !strings.Contains(string(body), "HTTP") { return fmt.Errorf("unexpected response: %s", string(body)) } return nil } // checkTCPTLS simulates a TCP client connection. // It returns an error if it doesn't receive the expected response. func checkTCPTLS(addr string, timeout time.Duration, tlsVersion uint16) (err error) { tlsConfig := &tls.Config{ InsecureSkipVerify: true, ServerName: "foo.bar", MinVersion: tls.VersionTLS10, MaxVersion: tls.VersionTLS12, } conn, err := tls.Dial("tcp", addr, tlsConfig) if err != nil { return err } defer func() { closeErr := conn.Close() if closeErr != nil && err == nil { err = closeErr } }() if conn.ConnectionState().Version != tlsVersion { return fmt.Errorf("wrong TLS version. wanted %X, got %X", tlsVersion, conn.ConnectionState().Version) } fmt.Fprint(conn, "HELLO") err = conn.SetReadDeadline(time.Now().Add(timeout)) if err != nil { return err } var buf bytes.Buffer _, err = io.Copy(&buf, conn) if err != nil { return err } if !strings.HasPrefix(buf.String(), "TCP-CLIENT-FIRST") { return fmt.Errorf("unexpected response: %s", buf.String()) } return nil } // checkTCPTLS10 simulates a TCP client connection with TLS 1.0. // It returns an error if it doesn't receive the expected response. func checkTCPTLS10(addr string, timeout time.Duration) error { return checkTCPTLS(addr, timeout, tls.VersionTLS10) } // checkTCPTLS12 simulates a TCP client connection with TLS 1.2. // It returns an error if it doesn't receive the expected response. func checkTCPTLS12(addr string, timeout time.Duration) error { return checkTCPTLS(addr, timeout, tls.VersionTLS12) } // checkHTTPS makes an HTTPS request and checks the given TLS. // It returns an error if it doesn't receive the expected response. func checkHTTPS(addr string, timeout time.Duration, tlsVersion uint16) error { req, err := http.NewRequest(http.MethodGet, "https://"+addr, nil) if err != nil { return err } req.Header.Set("Host", "foo.bar") httpClient := &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, ServerName: "foo.bar", MinVersion: tls.VersionTLS10, MaxVersion: tls.VersionTLS12, }, }, Timeout: timeout, } resp, err := httpClient.Do(req) if err != nil { return err } if resp.TLS.Version != tlsVersion { return fmt.Errorf("wrong TLS version. wanted %X, got %X", tlsVersion, resp.TLS.Version) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return err } if !strings.Contains(string(body), "HTTPS") { return fmt.Errorf("unexpected response: %s", string(body)) } return nil } // checkHTTPSTLS10 makes an HTTP request with TLS version 1.0. // It returns an error if it doesn't receive the expected response. func checkHTTPSTLS10(addr string, timeout time.Duration) error { return checkHTTPS(addr, timeout, tls.VersionTLS10) } // checkHTTPSTLS12 makes an HTTP request with TLS version 1.2. // It returns an error if it doesn't receive the expected response. func checkHTTPSTLS12(addr string, timeout time.Duration) error { return checkHTTPS(addr, timeout, tls.VersionTLS12) } func TestPostgres(t *testing.T) { router, err := NewRouter() require.NoError(t, err) // This test requires to have a TLS route, but does not actually check the // content of the handler. It would require to code a TLS handshake to // check the SNI and content of the handlerFunc. err = router.muxerTCPTLS.AddRoute("HostSNI(`test.localhost`)", "", 0, nil) require.NoError(t, err) err = router.muxerTCP.AddRoute("HostSNI(`*`)", "", 0, tcp2.HandlerFunc(func(conn tcp2.WriteCloser) { _, _ = conn.Write([]byte("OK")) _ = conn.Close() })) require.NoError(t, err) mockConn := NewMockConn() go router.ServeTCP(mockConn) mockConn.dataRead <- PostgresStartTLSMsg b := <-mockConn.dataWrite require.Equal(t, PostgresStartTLSReply, b) mockConn = NewMockConn() go router.ServeTCP(mockConn) mockConn.dataRead <- []byte("HTTP") b = <-mockConn.dataWrite require.Equal(t, []byte("OK"), b) } func NewMockConn() *MockConn { return &MockConn{ dataRead: make(chan []byte), dataWrite: make(chan []byte), } } type MockConn struct { dataRead chan []byte dataWrite chan []byte } func (m *MockConn) Read(b []byte) (n int, err error) { temp := <-m.dataRead copy(b, temp) return len(temp), nil } func (m *MockConn) Write(b []byte) (n int, err error) { m.dataWrite <- b return len(b), nil } func (m *MockConn) Close() error { close(m.dataRead) close(m.dataWrite) return nil } func (m *MockConn) LocalAddr() net.Addr { return nil } func (m *MockConn) RemoteAddr() net.Addr { return &net.TCPAddr{} } func (m *MockConn) SetDeadline(t time.Time) error { return nil } func (m *MockConn) SetReadDeadline(t time.Time) error { return nil } func (m *MockConn) SetWriteDeadline(t time.Time) error { return nil } func (m *MockConn) CloseWrite() error { close(m.dataRead) close(m.dataWrite) return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/router/tcp/manager.go
pkg/server/router/tcp/manager.go
package tcp import ( "context" "crypto/tls" "errors" "fmt" "math" "net/http" "strings" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/middlewares/snicheck" httpmuxer "github.com/traefik/traefik/v3/pkg/muxer/http" tcpmuxer "github.com/traefik/traefik/v3/pkg/muxer/tcp" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/server/provider" tcpservice "github.com/traefik/traefik/v3/pkg/server/service/tcp" "github.com/traefik/traefik/v3/pkg/tcp" traefiktls "github.com/traefik/traefik/v3/pkg/tls" ) const maxUserPriority = math.MaxInt - 1000 type middlewareBuilder interface { BuildChain(ctx context.Context, names []string) *tcp.Chain } // NewManager Creates a new Manager. func NewManager(conf *runtime.Configuration, serviceManager *tcpservice.Manager, middlewaresBuilder middlewareBuilder, httpHandlers map[string]http.Handler, httpsHandlers map[string]http.Handler, tlsManager *traefiktls.Manager, ) *Manager { return &Manager{ serviceManager: serviceManager, middlewaresBuilder: middlewaresBuilder, httpHandlers: httpHandlers, httpsHandlers: httpsHandlers, tlsManager: tlsManager, conf: conf, } } // Manager is a route/router manager. type Manager struct { serviceManager *tcpservice.Manager middlewaresBuilder middlewareBuilder httpHandlers map[string]http.Handler httpsHandlers map[string]http.Handler tlsManager *traefiktls.Manager conf *runtime.Configuration } func (m *Manager) getTCPRouters(ctx context.Context, entryPoints []string) map[string]map[string]*runtime.TCPRouterInfo { if m.conf != nil { return m.conf.GetTCPRoutersByEntryPoints(ctx, entryPoints) } return make(map[string]map[string]*runtime.TCPRouterInfo) } func (m *Manager) getHTTPRouters(ctx context.Context, entryPoints []string, tls bool) map[string]map[string]*runtime.RouterInfo { if m.conf != nil { return m.conf.GetRoutersByEntryPoints(ctx, entryPoints, tls) } return make(map[string]map[string]*runtime.RouterInfo) } // BuildHandlers builds the handlers for the given entrypoints. func (m *Manager) BuildHandlers(rootCtx context.Context, entryPoints []string) map[string]*Router { entryPointsRouters := m.getTCPRouters(rootCtx, entryPoints) entryPointsRoutersHTTP := m.getHTTPRouters(rootCtx, entryPoints, true) entryPointHandlers := make(map[string]*Router) for _, entryPointName := range entryPoints { routers := entryPointsRouters[entryPointName] logger := log.Ctx(rootCtx).With().Str(logs.EntryPointName, entryPointName).Logger() ctx := logger.WithContext(rootCtx) handler, err := m.buildEntryPointHandler(ctx, routers, entryPointsRoutersHTTP[entryPointName], m.httpHandlers[entryPointName], m.httpsHandlers[entryPointName]) if err != nil { logger.Error().Err(err).Send() continue } entryPointHandlers[entryPointName] = handler } return entryPointHandlers } type nameAndConfig struct { routerName string // just so we have it as additional information when logging TLSConfig *tls.Config } func (m *Manager) buildEntryPointHandler(ctx context.Context, configs map[string]*runtime.TCPRouterInfo, configsHTTP map[string]*runtime.RouterInfo, handlerHTTP, handlerHTTPS http.Handler) (*Router, error) { // Build a new Router. router, err := NewRouter() if err != nil { return nil, err } router.SetHTTPHandler(handlerHTTP) // Even though the error is seemingly ignored (aside from logging it), // we actually rely later on the fact that a tls config is nil (which happens when an error is returned) to take special steps // when assigning a handler to a route. defaultTLSConf, err := m.tlsManager.Get(traefiktls.DefaultTLSStoreName, traefiktls.DefaultTLSConfigName) if err != nil { log.Ctx(ctx).Error().Err(err).Msg("Error during the build of the default TLS configuration") } // Keyed by domain. The source of truth for doing SNI checking (domain fronting). // As soon as there's (at least) two different tlsOptions found for the same domain, // we set the value to the default TLS conf. tlsOptionsForHost := map[string]string{} // Keyed by domain, then by options reference. // The actual source of truth for what TLS options will actually be used for the connection. // As opposed to tlsOptionsForHost, it keeps track of all the (different) TLS // options that occur for a given host name, so that later on we can set relevant // errors and logging for all the routers concerned (i.e. wrongly configured). tlsOptionsForHostSNI := map[string]map[string]nameAndConfig{} for routerHTTPName, routerHTTPConfig := range configsHTTP { if routerHTTPConfig.TLS == nil { continue } logger := log.Ctx(ctx).With().Str(logs.RouterName, routerHTTPName).Logger() ctxRouter := logger.WithContext(provider.AddInContext(ctx, routerHTTPName)) tlsOptionsName := traefiktls.DefaultTLSConfigName if len(routerHTTPConfig.TLS.Options) > 0 && routerHTTPConfig.TLS.Options != traefiktls.DefaultTLSConfigName { tlsOptionsName = provider.GetQualifiedName(ctxRouter, routerHTTPConfig.TLS.Options) } domains, err := httpmuxer.ParseDomains(routerHTTPConfig.Rule) if err != nil { routerErr := fmt.Errorf("invalid rule %s, error: %w", routerHTTPConfig.Rule, err) routerHTTPConfig.AddError(routerErr, true) logger.Error().Err(routerErr).Send() continue } if len(domains) == 0 { // Extra Host(*) rule, for HTTPS routers with no Host rule, // and for requests for which the SNI does not match _any_ of the other existing routers Host. // This is only about choosing the TLS configuration. // The actual routing will be done further on by the HTTPS handler. // See examples below. router.AddHTTPTLSConfig("*", defaultTLSConf) // The server name (from a Host(SNI) rule) is the only parameter (available in HTTP routing rules) on which we can map a TLS config, // because it is the only one accessible before decryption (we obtain it during the ClientHello). // Therefore, when a router has no Host rule, it does not make any sense to specify some TLS options. // Consequently, when it comes to deciding what TLS config will be used, // for a request that will match an HTTPS router with no Host rule, // the result will depend on the _others_ existing routers (their Host rule, to be precise), and the TLS options associated with them, // even though they don't match the incoming request. Consider the following examples: // # conf1 // httpRouter1: // rule: PathPrefix("/foo") // # Wherever the request comes from, the TLS config used will be the default one, because of the Host(*) fallback. // # conf2 // httpRouter1: // rule: PathPrefix("/foo") // // httpRouter2: // rule: Host("foo.com") && PathPrefix("/bar") // tlsoptions: myTLSOptions // # When a request for "/foo" comes, even though it won't be routed by httpRouter2, // # if its SNI is set to foo.com, myTLSOptions will be used for the TLS connection. // # Otherwise, it will fallback to the default TLS config. logger.Warn().Msgf("No domain found in rule %v, the TLS options applied for this router will depend on the SNI of each request", routerHTTPConfig.Rule) } // Even though the error is seemingly ignored (aside from logging it), // we actually rely later on the fact that a tls config is nil (which happens when an error is returned) to take special steps // when assigning a handler to a route. tlsConf, tlsConfErr := m.tlsManager.Get(traefiktls.DefaultTLSStoreName, tlsOptionsName) if tlsConfErr != nil { // Note: we do not call AddError here because we already did so when buildRouterHandler errored for the same reason. logger.Error().Err(tlsConfErr).Send() } for _, domain := range domains { // domain is already in lower case thanks to the domain parsing if tlsOptionsForHostSNI[domain] == nil { tlsOptionsForHostSNI[domain] = make(map[string]nameAndConfig) } tlsOptionsForHostSNI[domain][tlsOptionsName] = nameAndConfig{ routerName: routerHTTPName, TLSConfig: tlsConf, } if name, ok := tlsOptionsForHost[domain]; ok && name != tlsOptionsName { // Different tlsOptions on the same domain, so fallback to default tlsOptionsForHost[domain] = traefiktls.DefaultTLSConfigName } else { tlsOptionsForHost[domain] = tlsOptionsName } } } sniCheck := snicheck.New(tlsOptionsForHost, handlerHTTPS) // Keep in mind that defaultTLSConf might be nil here. router.SetHTTPSHandler(sniCheck, defaultTLSConf) logger := log.Ctx(ctx) for hostSNI, tlsConfigs := range tlsOptionsForHostSNI { if len(tlsConfigs) == 1 { var optionsName string var config *tls.Config for k, v := range tlsConfigs { optionsName = k config = v.TLSConfig break } if config == nil { // we use nil config as a signal to insert a handler // that enforces that TLS connection attempts to the corresponding (broken) router should fail. logger.Debug().Msgf("Adding special closing route for %s because broken TLS options %s", hostSNI, optionsName) router.AddHTTPTLSConfig(hostSNI, nil) continue } logger.Debug().Msgf("Adding route for %s with TLS options %s", hostSNI, optionsName) router.AddHTTPTLSConfig(hostSNI, config) continue } // multiple tlsConfigs routers := make([]string, 0, len(tlsConfigs)) for _, v := range tlsConfigs { configsHTTP[v.routerName].AddError(fmt.Errorf("found different TLS options for routers on the same host %v, so using the default TLS options instead", hostSNI), false) routers = append(routers, v.routerName) } logger.Warn().Msgf("Found different TLS options for routers on the same host %v, so using the default TLS options instead for these routers: %#v", hostSNI, routers) if defaultTLSConf == nil { logger.Debug().Msgf("Adding special closing route for %s because broken default TLS options", hostSNI) } router.AddHTTPTLSConfig(hostSNI, defaultTLSConf) } m.addTCPHandlers(ctx, configs, router) return router, nil } // addTCPHandlers creates the TCP handlers defined in configs, and adds them to router. func (m *Manager) addTCPHandlers(ctx context.Context, configs map[string]*runtime.TCPRouterInfo, router *Router) { for routerName, routerConfig := range configs { logger := log.Ctx(ctx).With().Str(logs.RouterName, routerName).Logger() ctxRouter := logger.WithContext(provider.AddInContext(ctx, routerName)) if routerConfig.Priority == 0 { routerConfig.Priority = tcpmuxer.GetRulePriority(routerConfig.Rule) } if routerConfig.Service == "" { err := errors.New("the service is missing on the router") routerConfig.AddError(err, true) logger.Error().Err(err).Send() continue } if routerConfig.Rule == "" { err := errors.New("router has no rule") routerConfig.AddError(err, true) logger.Error().Err(err).Send() continue } domains, err := tcpmuxer.ParseHostSNI(routerConfig.Rule) if err != nil { routerErr := fmt.Errorf("invalid rule: %q , %w", routerConfig.Rule, err) routerConfig.AddError(routerErr, true) logger.Error().Err(routerErr).Send() continue } // HostSNI Rule, but TLS not set on the router, which is an error. // However, we allow the HostSNI(*) exception. if len(domains) > 0 && routerConfig.TLS == nil && domains[0] != "*" { routerErr := fmt.Errorf("invalid rule: %q , has HostSNI matcher, but no TLS on router", routerConfig.Rule) routerConfig.AddError(routerErr, true) logger.Error().Err(routerErr).Send() continue } if routerConfig.Priority > maxUserPriority && !strings.HasSuffix(routerName, "@internal") { routerErr := fmt.Errorf("the router priority %d exceeds the max user-defined priority %d", routerConfig.Priority, maxUserPriority) routerConfig.AddError(routerErr, true) logger.Error().Err(routerErr).Send() continue } var handler tcp.Handler if routerConfig.TLS == nil || routerConfig.TLS.Passthrough { handler, err = m.buildTCPHandler(ctxRouter, routerConfig) if err != nil { routerConfig.AddError(err, true) logger.Error().Err(err).Send() continue } } if routerConfig.TLS == nil { logger.Debug().Msgf("Adding route for %q", routerConfig.Rule) if err := router.muxerTCP.AddRoute(routerConfig.Rule, routerConfig.RuleSyntax, routerConfig.Priority, handler); err != nil { routerConfig.AddError(err, true) logger.Error().Err(err).Send() } continue } if routerConfig.TLS.Passthrough { logger.Debug().Msgf("Adding Passthrough route for %q", routerConfig.Rule) if err := router.muxerTCPTLS.AddRoute(routerConfig.Rule, routerConfig.RuleSyntax, routerConfig.Priority, handler); err != nil { routerConfig.AddError(err, true) logger.Error().Err(err).Send() } continue } for _, domain := range domains { if httpmuxer.IsASCII(domain) { continue } asciiError := fmt.Errorf("invalid domain name value %q, non-ASCII characters are not allowed", domain) routerConfig.AddError(asciiError, true) logger.Error().Err(asciiError).Send() } tlsOptionsName := routerConfig.TLS.Options if len(tlsOptionsName) == 0 { tlsOptionsName = traefiktls.DefaultTLSConfigName } if tlsOptionsName != traefiktls.DefaultTLSConfigName { tlsOptionsName = provider.GetQualifiedName(ctxRouter, tlsOptionsName) } tlsConf, err := m.tlsManager.Get(traefiktls.DefaultTLSStoreName, tlsOptionsName) if err != nil { routerConfig.AddError(err, true) logger.Error().Err(err).Send() logger.Debug().Msgf("Adding special TLS closing route for %q because broken TLS options %s", routerConfig.Rule, tlsOptionsName) if err := router.muxerTCPTLS.AddRoute(routerConfig.Rule, routerConfig.RuleSyntax, routerConfig.Priority, &brokenTLSRouter{}); err != nil { routerConfig.AddError(err, true) logger.Error().Err(err).Send() } continue } // Now that the Rule is not just about the Host, we could theoretically have a config like: // router1: // rule: HostSNI(foo.com) && ClientIP(IP1) // tlsOption: tlsOne // router2: // rule: HostSNI(foo.com) && ClientIP(IP2) // tlsOption: tlsTwo // i.e. same HostSNI but different tlsOptions // This is only applicable if the muxer can decide about the routing _before_ telling the client about the tlsConf (i.e. before the TLS HandShake). // This seems to be the case so far with the existing matchers (HostSNI, and ClientIP), so it's all good. // Otherwise, we would have to do as for HTTPS, i.e. disallow different TLS configs for the same HostSNIs. handler, err = m.buildTCPHandler(ctxRouter, routerConfig) if err != nil { routerConfig.AddError(err, true) logger.Error().Err(err).Send() continue } handler = &tcp.TLSHandler{ Next: handler, Config: tlsConf, } logger.Debug().Msgf("Adding TLS route for %q", routerConfig.Rule) if err := router.muxerTCPTLS.AddRoute(routerConfig.Rule, routerConfig.RuleSyntax, routerConfig.Priority, handler); err != nil { routerConfig.AddError(err, true) logger.Error().Err(err).Send() continue } } } func (m *Manager) buildTCPHandler(ctx context.Context, router *runtime.TCPRouterInfo) (tcp.Handler, error) { var qualifiedNames []string for _, name := range router.Middlewares { qualifiedNames = append(qualifiedNames, provider.GetQualifiedName(ctx, name)) } router.Middlewares = qualifiedNames if router.Service == "" { return nil, errors.New("the service is missing on the router") } sHandler, err := m.serviceManager.BuildTCP(ctx, router.Service) if err != nil { return nil, err } mHandler := m.middlewaresBuilder.BuildChain(ctx, router.Middlewares) return tcp.NewChain().Extend(*mHandler).Then(sHandler) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/router/udp/router.go
pkg/server/router/udp/router.go
package udp import ( "context" "errors" "sort" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/server/provider" udpservice "github.com/traefik/traefik/v3/pkg/server/service/udp" "github.com/traefik/traefik/v3/pkg/udp" ) // NewManager Creates a new Manager. func NewManager(conf *runtime.Configuration, serviceManager *udpservice.Manager, ) *Manager { return &Manager{ serviceManager: serviceManager, conf: conf, } } // Manager is a route/router manager. type Manager struct { serviceManager *udpservice.Manager conf *runtime.Configuration } func (m *Manager) getUDPRouters(ctx context.Context, entryPoints []string) map[string]map[string]*runtime.UDPRouterInfo { if m.conf != nil { return m.conf.GetUDPRoutersByEntryPoints(ctx, entryPoints) } return make(map[string]map[string]*runtime.UDPRouterInfo) } // BuildHandlers builds the handlers for the given entrypoints. func (m *Manager) BuildHandlers(rootCtx context.Context, entryPoints []string) map[string]udp.Handler { entryPointsRouters := m.getUDPRouters(rootCtx, entryPoints) entryPointHandlers := make(map[string]udp.Handler) for _, entryPointName := range entryPoints { routers := entryPointsRouters[entryPointName] logger := log.Ctx(rootCtx).With().Str(logs.EntryPointName, entryPointName).Logger() ctx := logger.WithContext(rootCtx) if len(routers) > 1 { logger.Warn().Msg("Config has more than one udp router for a given entrypoint.") } handlers := m.buildEntryPointHandlers(ctx, routers) if len(handlers) > 0 { // As UDP support only one router per entrypoint, we only take the first one. entryPointHandlers[entryPointName] = handlers[0] } } return entryPointHandlers } func (m *Manager) buildEntryPointHandlers(ctx context.Context, configs map[string]*runtime.UDPRouterInfo) []udp.Handler { var rtNames []string for routerName := range configs { rtNames = append(rtNames, routerName) } sort.Slice(rtNames, func(i, j int) bool { return rtNames[i] > rtNames[j] }) var handlers []udp.Handler for _, routerName := range rtNames { routerConfig := configs[routerName] logger := log.Ctx(ctx).With().Str(logs.RouterName, routerName).Logger() ctxRouter := logger.WithContext(provider.AddInContext(ctx, routerName)) if routerConfig.Service == "" { err := errors.New("the service is missing on the udp router") routerConfig.AddError(err, true) logger.Error().Err(err).Send() continue } handler, err := m.serviceManager.BuildUDP(ctxRouter, routerConfig.Service) if err != nil { routerConfig.AddError(err, true) logger.Error().Err(err).Send() continue } handlers = append(handlers, handler) } return handlers }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/server/router/udp/router_test.go
pkg/server/router/udp/router_test.go
package udp import ( "testing" "github.com/stretchr/testify/assert" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/server/service/udp" ) func TestRuntimeConfiguration(t *testing.T) { testCases := []struct { desc string serviceConfig map[string]*runtime.UDPServiceInfo routerConfig map[string]*runtime.UDPRouterInfo expectedError int }{ { desc: "No error", serviceConfig: map[string]*runtime.UDPServiceInfo{ "foo-service": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Port: "8085", Address: "127.0.0.1:8085", }, { Address: "127.0.0.1:8086", Port: "8086", }, }, }, }, }, }, routerConfig: map[string]*runtime.UDPRouterInfo{ "foo": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", }, }, "bar": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", }, }, }, expectedError: 0, }, { desc: "Router with unknown service", serviceConfig: map[string]*runtime.UDPServiceInfo{ "foo-service": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "127.0.0.1:80", }, }, }, }, }, }, routerConfig: map[string]*runtime.UDPRouterInfo{ "foo": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "wrong-service", }, }, "bar": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", }, }, }, expectedError: 1, }, { desc: "Router with broken service", serviceConfig: map[string]*runtime.UDPServiceInfo{ "foo-service": { UDPService: &dynamic.UDPService{ LoadBalancer: nil, }, }, }, routerConfig: map[string]*runtime.UDPRouterInfo{ "bar": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", }, }, }, expectedError: 2, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() entryPoints := []string{"web"} conf := &runtime.Configuration{ UDPServices: test.serviceConfig, UDPRouters: test.routerConfig, } serviceManager := udp.NewManager(conf) routerManager := NewManager(conf, serviceManager) _ = routerManager.BuildHandlers(t.Context(), entryPoints) // even though conf was passed by argument to the manager builders above, // it's ok to use it as the result we check, because everything worth checking // can be accessed by pointers in it. var allErrors int for _, v := range conf.UDPServices { if v.Err != nil { allErrors++ } } for _, v := range conf.UDPRouters { if len(v.Err) > 0 { allErrors++ } } assert.Equal(t, test.expectedError, allErrors) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/static/experimental.go
pkg/config/static/experimental.go
package static import "github.com/traefik/traefik/v3/pkg/plugins" // Experimental experimental Traefik features. type Experimental struct { Plugins map[string]plugins.Descriptor `description:"Plugins configuration." json:"plugins,omitempty" toml:"plugins,omitempty" yaml:"plugins,omitempty" export:"true"` LocalPlugins map[string]plugins.LocalDescriptor `description:"Local plugins configuration." json:"localPlugins,omitempty" toml:"localPlugins,omitempty" yaml:"localPlugins,omitempty" export:"true"` AbortOnPluginFailure bool `description:"Defines whether all plugins must be loaded successfully for Traefik to start." json:"abortOnPluginFailure,omitempty" toml:"abortOnPluginFailure,omitempty" yaml:"abortOnPluginFailure,omitempty" export:"true"` FastProxy *FastProxyConfig `description:"Enables the FastProxy implementation." json:"fastProxy,omitempty" toml:"fastProxy,omitempty" yaml:"fastProxy,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` OTLPLogs bool `description:"Enables the OpenTelemetry logs integration." json:"otlplogs,omitempty" toml:"otlplogs,omitempty" yaml:"otlplogs,omitempty" export:"true"` Knative bool `description:"Allow the Knative provider usage." json:"knative,omitempty" toml:"knative,omitempty" yaml:"knative,omitempty" export:"true"` // Deprecated: KubernetesIngressNGINX provider is not an experimental feature starting with v3.6.2. Please remove its usage from the static configuration. KubernetesIngressNGINX bool `description:"Allow the Kubernetes Ingress NGINX provider usage." json:"kubernetesIngressNGINX,omitempty" toml:"kubernetesIngressNGINX,omitempty" yaml:"kubernetesIngressNGINX,omitempty" export:"true"` // Deprecated: KubernetesGateway provider is not an experimental feature starting with v3.1. Please remove its usage from the static configuration. KubernetesGateway bool `description:"(Deprecated) Allow the Kubernetes gateway api provider usage." json:"kubernetesGateway,omitempty" toml:"kubernetesGateway,omitempty" yaml:"kubernetesGateway,omitempty" export:"true"` } // FastProxyConfig holds the FastProxy configuration. type FastProxyConfig struct { Debug bool `description:"Enable debug mode for the FastProxy implementation." json:"debug,omitempty" toml:"debug,omitempty" yaml:"debug,omitempty" export:"true"` }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/static/entrypoints_test.go
pkg/config/static/entrypoints_test.go
package static import ( "testing" "github.com/stretchr/testify/require" ) func TestEntryPointProtocol(t *testing.T) { tests := []struct { name string address string expectedAddress string expectedProtocol string expectedError bool }{ { name: "Without protocol", address: "127.0.0.1:8080", expectedAddress: "127.0.0.1:8080", expectedProtocol: "tcp", expectedError: false, }, { name: "With TCP protocol in upper case", address: "127.0.0.1:8080/TCP", expectedAddress: "127.0.0.1:8080", expectedProtocol: "tcp", expectedError: false, }, { name: "With UDP protocol in upper case", address: "127.0.0.1:8080/UDP", expectedAddress: "127.0.0.1:8080", expectedProtocol: "udp", expectedError: false, }, { name: "With UDP protocol in weird case", address: "127.0.0.1:8080/uDp", expectedAddress: "127.0.0.1:8080", expectedProtocol: "udp", expectedError: false, }, { name: "With invalid protocol", address: "127.0.0.1:8080/toto/tata", expectedError: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ep := EntryPoint{ Address: tt.address, } protocol, err := ep.GetProtocol() if tt.expectedError { require.Error(t, err) return } require.NoError(t, err) require.Equal(t, tt.expectedProtocol, protocol) require.Equal(t, tt.expectedAddress, ep.GetAddress()) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/static/static_config_test.go
pkg/config/static/static_config_test.go
package static import ( "testing" "github.com/stretchr/testify/assert" "github.com/traefik/traefik/v3/pkg/provider/acme" ) func pointer[T any](v T) *T { return &v } func TestHasEntrypoint(t *testing.T) { tests := []struct { desc string entryPoints map[string]*EntryPoint assert assert.BoolAssertionFunc }{ { desc: "no user defined entryPoints", assert: assert.False, }, { desc: "user defined entryPoints", entryPoints: map[string]*EntryPoint{ "foo": {}, }, assert: assert.True, }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { t.Parallel() cfg := &Configuration{ EntryPoints: test.entryPoints, } test.assert(t, cfg.hasUserDefinedEntrypoint()) }) } } func TestConfiguration_SetEffectiveConfiguration(t *testing.T) { testCases := []struct { desc string conf *Configuration expected *Configuration }{ { desc: "empty", conf: &Configuration{ Providers: &Providers{}, }, expected: &Configuration{ EntryPoints: EntryPoints{"http": &EntryPoint{ Address: ":80", AllowACMEByPass: false, ReusePort: false, AsDefault: false, Transport: &EntryPointsTransport{ LifeCycle: &LifeCycle{ GraceTimeOut: 10000000000, }, RespondingTimeouts: &RespondingTimeouts{ ReadTimeout: 60000000000, IdleTimeout: 180000000000, }, }, ProxyProtocol: nil, ForwardedHeaders: &ForwardedHeaders{}, HTTP: HTTPConfig{ SanitizePath: pointer(true), MaxHeaderBytes: 1048576, }, HTTP2: &HTTP2Config{ MaxConcurrentStreams: 250, MaxDecoderHeaderTableSize: 4096, MaxEncoderHeaderTableSize: 4096, }, HTTP3: nil, UDP: &UDPConfig{ Timeout: 3000000000, }, }}, Providers: &Providers{}, }, }, { desc: "ACME simple", conf: &Configuration{ Providers: &Providers{}, CertificatesResolvers: map[string]CertificateResolver{ "foo": { ACME: &acme.Configuration{ DNSChallenge: &acme.DNSChallenge{ Provider: "bar", }, }, }, }, }, expected: &Configuration{ EntryPoints: EntryPoints{"http": &EntryPoint{ Address: ":80", AllowACMEByPass: false, ReusePort: false, AsDefault: false, Transport: &EntryPointsTransport{ LifeCycle: &LifeCycle{ GraceTimeOut: 10000000000, }, RespondingTimeouts: &RespondingTimeouts{ ReadTimeout: 60000000000, IdleTimeout: 180000000000, }, }, ProxyProtocol: nil, ForwardedHeaders: &ForwardedHeaders{}, HTTP: HTTPConfig{ SanitizePath: pointer(true), MaxHeaderBytes: 1048576, }, HTTP2: &HTTP2Config{ MaxConcurrentStreams: 250, MaxDecoderHeaderTableSize: 4096, MaxEncoderHeaderTableSize: 4096, }, HTTP3: nil, UDP: &UDPConfig{ Timeout: 3000000000, }, }}, Providers: &Providers{}, CertificatesResolvers: map[string]CertificateResolver{ "foo": { ACME: &acme.Configuration{ CAServer: "https://acme-v02.api.letsencrypt.org/directory", DNSChallenge: &acme.DNSChallenge{ Provider: "bar", }, }, }, }, }, }, { desc: "ACME deprecation DelayBeforeCheck", conf: &Configuration{ Providers: &Providers{}, CertificatesResolvers: map[string]CertificateResolver{ "foo": { ACME: &acme.Configuration{ DNSChallenge: &acme.DNSChallenge{ Provider: "bar", DelayBeforeCheck: 123, }, }, }, }, }, expected: &Configuration{ EntryPoints: EntryPoints{"http": &EntryPoint{ Address: ":80", AllowACMEByPass: false, ReusePort: false, AsDefault: false, Transport: &EntryPointsTransport{ LifeCycle: &LifeCycle{ GraceTimeOut: 10000000000, }, RespondingTimeouts: &RespondingTimeouts{ ReadTimeout: 60000000000, IdleTimeout: 180000000000, }, }, ProxyProtocol: nil, ForwardedHeaders: &ForwardedHeaders{}, HTTP: HTTPConfig{ SanitizePath: pointer(true), MaxHeaderBytes: 1048576, }, HTTP2: &HTTP2Config{ MaxConcurrentStreams: 250, MaxDecoderHeaderTableSize: 4096, MaxEncoderHeaderTableSize: 4096, }, HTTP3: nil, UDP: &UDPConfig{ Timeout: 3000000000, }, }}, Providers: &Providers{}, CertificatesResolvers: map[string]CertificateResolver{ "foo": { ACME: &acme.Configuration{ CAServer: "https://acme-v02.api.letsencrypt.org/directory", DNSChallenge: &acme.DNSChallenge{ Provider: "bar", DelayBeforeCheck: 123, Propagation: &acme.Propagation{ DelayBeforeChecks: 123, }, }, }, }, }, }, }, { desc: "ACME deprecation DisablePropagationCheck", conf: &Configuration{ Providers: &Providers{}, CertificatesResolvers: map[string]CertificateResolver{ "foo": { ACME: &acme.Configuration{ DNSChallenge: &acme.DNSChallenge{ Provider: "bar", DisablePropagationCheck: true, }, }, }, }, }, expected: &Configuration{ EntryPoints: EntryPoints{"http": &EntryPoint{ Address: ":80", AllowACMEByPass: false, ReusePort: false, AsDefault: false, Transport: &EntryPointsTransport{ LifeCycle: &LifeCycle{ GraceTimeOut: 10000000000, }, RespondingTimeouts: &RespondingTimeouts{ ReadTimeout: 60000000000, IdleTimeout: 180000000000, }, }, ProxyProtocol: nil, ForwardedHeaders: &ForwardedHeaders{}, HTTP: HTTPConfig{ SanitizePath: pointer(true), MaxHeaderBytes: 1048576, }, HTTP2: &HTTP2Config{ MaxConcurrentStreams: 250, MaxDecoderHeaderTableSize: 4096, MaxEncoderHeaderTableSize: 4096, }, HTTP3: nil, UDP: &UDPConfig{ Timeout: 3000000000, }, }}, Providers: &Providers{}, CertificatesResolvers: map[string]CertificateResolver{ "foo": { ACME: &acme.Configuration{ CAServer: "https://acme-v02.api.letsencrypt.org/directory", DNSChallenge: &acme.DNSChallenge{ Provider: "bar", DisablePropagationCheck: true, Propagation: &acme.Propagation{ DisableChecks: true, }, }, }, }, }, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() test.conf.SetEffectiveConfiguration() assert.Equal(t, test.expected, test.conf) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/static/plugins.go
pkg/config/static/plugins.go
package static // PluginConf holds the plugin configuration. type PluginConf map[string]interface{}
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/static/entrypoints.go
pkg/config/static/entrypoints.go
package static import ( "fmt" "math" "net/http" "strings" ptypes "github.com/traefik/paerser/types" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "github.com/traefik/traefik/v3/pkg/types" ) // EntryPoint holds the entry point configuration. type EntryPoint struct { Address string `description:"Entry point address." json:"address,omitempty" toml:"address,omitempty" yaml:"address,omitempty"` AllowACMEByPass bool `description:"Enables handling of ACME TLS and HTTP challenges with custom routers." json:"allowACMEByPass,omitempty" toml:"allowACMEByPass,omitempty" yaml:"allowACMEByPass,omitempty"` ReusePort bool `description:"Enables EntryPoints from the same or different processes listening on the same TCP/UDP port." json:"reusePort,omitempty" toml:"reusePort,omitempty" yaml:"reusePort,omitempty"` AsDefault bool `description:"Adds this EntryPoint to the list of default EntryPoints to be used on routers that don't have any Entrypoint defined." json:"asDefault,omitempty" toml:"asDefault,omitempty" yaml:"asDefault,omitempty"` Transport *EntryPointsTransport `description:"Configures communication between clients and Traefik." json:"transport,omitempty" toml:"transport,omitempty" yaml:"transport,omitempty" export:"true"` ProxyProtocol *ProxyProtocol `description:"Proxy-Protocol configuration." json:"proxyProtocol,omitempty" toml:"proxyProtocol,omitempty" yaml:"proxyProtocol,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` ForwardedHeaders *ForwardedHeaders `description:"Trust client forwarding headers." json:"forwardedHeaders,omitempty" toml:"forwardedHeaders,omitempty" yaml:"forwardedHeaders,omitempty" export:"true"` HTTP HTTPConfig `description:"HTTP configuration." json:"http,omitempty" toml:"http,omitempty" yaml:"http,omitempty" export:"true"` HTTP2 *HTTP2Config `description:"HTTP/2 configuration." json:"http2,omitempty" toml:"http2,omitempty" yaml:"http2,omitempty" export:"true"` HTTP3 *HTTP3Config `description:"HTTP/3 configuration." json:"http3,omitempty" toml:"http3,omitempty" yaml:"http3,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` UDP *UDPConfig `description:"UDP configuration." json:"udp,omitempty" toml:"udp,omitempty" yaml:"udp,omitempty"` Observability *ObservabilityConfig `description:"Observability configuration." json:"observability,omitempty" toml:"observability,omitempty" yaml:"observability,omitempty" export:"true"` } // GetAddress strips any potential protocol part of the address field of the // entry point, in order to return the actual address. func (ep *EntryPoint) GetAddress() string { splitN := strings.SplitN(ep.Address, "/", 2) return splitN[0] } // GetProtocol returns the protocol part of the address field of the entry point. // If none is specified, it defaults to "tcp". func (ep *EntryPoint) GetProtocol() (string, error) { splitN := strings.SplitN(ep.Address, "/", 2) if len(splitN) < 2 { return "tcp", nil } protocol := strings.ToLower(splitN[1]) if protocol == "tcp" || protocol == "udp" { return protocol, nil } return "", fmt.Errorf("invalid protocol: %s", splitN[1]) } // SetDefaults sets the default values. func (ep *EntryPoint) SetDefaults() { ep.Transport = &EntryPointsTransport{} ep.Transport.SetDefaults() ep.ForwardedHeaders = &ForwardedHeaders{} ep.UDP = &UDPConfig{} ep.UDP.SetDefaults() ep.HTTP = HTTPConfig{} ep.HTTP.SetDefaults() ep.HTTP2 = &HTTP2Config{} ep.HTTP2.SetDefaults() } // HTTPConfig is the HTTP configuration of an entry point. type HTTPConfig struct { Redirections *Redirections `description:"Set of redirection" json:"redirections,omitempty" toml:"redirections,omitempty" yaml:"redirections,omitempty" export:"true"` Middlewares []string `description:"Default middlewares for the routers linked to the entry point." json:"middlewares,omitempty" toml:"middlewares,omitempty" yaml:"middlewares,omitempty" export:"true"` TLS *TLSConfig `description:"Default TLS configuration for the routers linked to the entry point." json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` EncodedCharacters *EncodedCharacters `description:"Defines which encoded characters are allowed in the request path." json:"encodedCharacters,omitempty" toml:"encodedCharacters,omitempty" yaml:"encodedCharacters,omitempty" export:"true"` EncodeQuerySemicolons bool `description:"Defines whether request query semicolons should be URLEncoded." json:"encodeQuerySemicolons,omitempty" toml:"encodeQuerySemicolons,omitempty" yaml:"encodeQuerySemicolons,omitempty" export:"true"` SanitizePath *bool `description:"Defines whether to enable request path sanitization (removal of /./, /../ and multiple slash sequences)." json:"sanitizePath,omitempty" toml:"sanitizePath,omitempty" yaml:"sanitizePath,omitempty" export:"true"` MaxHeaderBytes int `description:"Maximum size of request headers in bytes." json:"maxHeaderBytes,omitempty" toml:"maxHeaderBytes,omitempty" yaml:"maxHeaderBytes,omitempty" export:"true"` } // SetDefaults sets the default values. func (c *HTTPConfig) SetDefaults() { sanitizePath := true c.SanitizePath = &sanitizePath c.MaxHeaderBytes = http.DefaultMaxHeaderBytes } // EncodedCharacters configures which encoded characters are allowed in the request path. type EncodedCharacters struct { AllowEncodedSlash bool `description:"Defines whether requests with encoded slash characters in the path are allowed." json:"allowEncodedSlash,omitempty" toml:"allowEncodedSlash,omitempty" yaml:"allowEncodedSlash,omitempty" export:"true"` AllowEncodedBackSlash bool `description:"Defines whether requests with encoded back slash characters in the path are allowed." json:"allowEncodedBackSlash,omitempty" toml:"allowEncodedBackSlash,omitempty" yaml:"allowEncodedBackSlash,omitempty" export:"true"` AllowEncodedNullCharacter bool `description:"Defines whether requests with encoded null characters in the path are allowed." json:"allowEncodedNullCharacter,omitempty" toml:"allowEncodedNullCharacter,omitempty" yaml:"allowEncodedNullCharacter,omitempty" export:"true"` AllowEncodedSemicolon bool `description:"Defines whether requests with encoded semicolon characters in the path are allowed." json:"allowEncodedSemicolon,omitempty" toml:"allowEncodedSemicolon,omitempty" yaml:"allowEncodedSemicolon,omitempty" export:"true"` AllowEncodedPercent bool `description:"Defines whether requests with encoded percent characters in the path are allowed." json:"allowEncodedPercent,omitempty" toml:"allowEncodedPercent,omitempty" yaml:"allowEncodedPercent,omitempty" export:"true"` AllowEncodedQuestionMark bool `description:"Defines whether requests with encoded question mark characters in the path are allowed." json:"allowEncodedQuestionMark,omitempty" toml:"allowEncodedQuestionMark,omitempty" yaml:"allowEncodedQuestionMark,omitempty" export:"true"` AllowEncodedHash bool `description:"Defines whether requests with encoded hash characters in the path are allowed." json:"allowEncodedHash,omitempty" toml:"allowEncodedHash,omitempty" yaml:"allowEncodedHash,omitempty" export:"true"` } // HTTP2Config is the HTTP2 configuration of an entry point. type HTTP2Config struct { MaxConcurrentStreams int32 `description:"Specifies the number of concurrent streams per connection that each client is allowed to initiate." json:"maxConcurrentStreams,omitempty" toml:"maxConcurrentStreams,omitempty" yaml:"maxConcurrentStreams,omitempty" export:"true"` MaxDecoderHeaderTableSize int32 `description:"Specifies the maximum size of the HTTP2 HPACK header table on the decoding (receiving from client) side." json:"maxDecoderHeaderTableSize,omitempty" toml:"maxDecoderHeaderTableSize,omitempty" yaml:"maxDecoderHeaderTableSize,omitempty" export:"true"` MaxEncoderHeaderTableSize int32 `description:"Specifies the maximum size of the HTTP2 HPACK header table on the encoding (sending to client) side." json:"maxEncoderHeaderTableSize,omitempty" toml:"maxEncoderHeaderTableSize,omitempty" yaml:"maxEncoderHeaderTableSize,omitempty" export:"true"` } // SetDefaults sets the default values. func (c *HTTP2Config) SetDefaults() { c.MaxConcurrentStreams = 250 // https://cs.opensource.google/go/x/net/+/cd36cc07:http2/server.go;l=58 c.MaxDecoderHeaderTableSize = 4096 // https://cs.opensource.google/go/x/net/+/0e478a2a:http2/server.go;l=105 c.MaxEncoderHeaderTableSize = 4096 // https://cs.opensource.google/go/x/net/+/0e478a2a:http2/server.go;l=111 } // HTTP3Config is the HTTP3 configuration of an entry point. type HTTP3Config struct { AdvertisedPort int `description:"UDP port to advertise, on which HTTP/3 is available." json:"advertisedPort,omitempty" toml:"advertisedPort,omitempty" yaml:"advertisedPort,omitempty" export:"true"` } // Redirections is a set of redirection for an entry point. type Redirections struct { EntryPoint *RedirectEntryPoint `description:"Set of redirection for an entry point." json:"entryPoint,omitempty" toml:"entryPoint,omitempty" yaml:"entryPoint,omitempty" export:"true"` } // RedirectEntryPoint is the definition of an entry point redirection. type RedirectEntryPoint struct { To string `description:"Targeted entry point of the redirection." json:"to,omitempty" toml:"to,omitempty" yaml:"to,omitempty" export:"true"` Scheme string `description:"Scheme used for the redirection." json:"scheme,omitempty" toml:"scheme,omitempty" yaml:"scheme,omitempty" export:"true"` Permanent bool `description:"Applies a permanent redirection." json:"permanent,omitempty" toml:"permanent,omitempty" yaml:"permanent,omitempty" export:"true"` Priority int `description:"Priority of the generated router." json:"priority,omitempty" toml:"priority,omitempty" yaml:"priority,omitempty" export:"true"` } // SetDefaults sets the default values. func (r *RedirectEntryPoint) SetDefaults() { r.Scheme = "https" r.Permanent = true r.Priority = math.MaxInt - 1 } // TLSConfig is the default TLS configuration for all the routers associated to the concerned entry point. type TLSConfig struct { Options string `description:"Default TLS options for the routers linked to the entry point." json:"options,omitempty" toml:"options,omitempty" yaml:"options,omitempty" export:"true"` CertResolver string `description:"Default certificate resolver for the routers linked to the entry point." json:"certResolver,omitempty" toml:"certResolver,omitempty" yaml:"certResolver,omitempty" export:"true"` Domains []types.Domain `description:"Default TLS domains for the routers linked to the entry point." json:"domains,omitempty" toml:"domains,omitempty" yaml:"domains,omitempty" export:"true"` } // ForwardedHeaders Trust client forwarding headers. type ForwardedHeaders struct { Insecure bool `description:"Trust all forwarded headers." json:"insecure,omitempty" toml:"insecure,omitempty" yaml:"insecure,omitempty" export:"true"` TrustedIPs []string `description:"Trust only forwarded headers from selected IPs." json:"trustedIPs,omitempty" toml:"trustedIPs,omitempty" yaml:"trustedIPs,omitempty"` Connection []string `description:"List of Connection headers that are allowed to pass through the middleware chain before being removed." json:"connection,omitempty" toml:"connection,omitempty" yaml:"connection,omitempty"` NotAppendXForwardedFor bool `description:"Disable appending RemoteAddr to X-Forwarded-For header. Defaults to false (appending is enabled)." json:"notAppendXForwardedFor,omitempty" toml:"notAppendXForwardedFor,omitempty" yaml:"notAppendXForwardedFor,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` } // ProxyProtocol contains Proxy-Protocol configuration. type ProxyProtocol struct { Insecure bool `description:"Trust all." json:"insecure,omitempty" toml:"insecure,omitempty" yaml:"insecure,omitempty" export:"true"` TrustedIPs []string `description:"Trust only selected IPs." json:"trustedIPs,omitempty" toml:"trustedIPs,omitempty" yaml:"trustedIPs,omitempty"` } // EntryPoints holds the HTTP entry point list. type EntryPoints map[string]*EntryPoint // EntryPointsTransport configures communication between clients and Traefik. type EntryPointsTransport struct { LifeCycle *LifeCycle `description:"Timeouts influencing the server life cycle." json:"lifeCycle,omitempty" toml:"lifeCycle,omitempty" yaml:"lifeCycle,omitempty" export:"true"` RespondingTimeouts *RespondingTimeouts `description:"Timeouts for incoming requests to the Traefik instance." json:"respondingTimeouts,omitempty" toml:"respondingTimeouts,omitempty" yaml:"respondingTimeouts,omitempty" export:"true"` KeepAliveMaxTime ptypes.Duration `description:"Maximum duration before closing a keep-alive connection." json:"keepAliveMaxTime,omitempty" toml:"keepAliveMaxTime,omitempty" yaml:"keepAliveMaxTime,omitempty" export:"true"` KeepAliveMaxRequests int `description:"Maximum number of requests before closing a keep-alive connection." json:"keepAliveMaxRequests,omitempty" toml:"keepAliveMaxRequests,omitempty" yaml:"keepAliveMaxRequests,omitempty" export:"true"` } // SetDefaults sets the default values. func (t *EntryPointsTransport) SetDefaults() { t.LifeCycle = &LifeCycle{} t.LifeCycle.SetDefaults() t.RespondingTimeouts = &RespondingTimeouts{} t.RespondingTimeouts.SetDefaults() } // UDPConfig is the UDP configuration of an entry point. type UDPConfig struct { Timeout ptypes.Duration `description:"Timeout defines how long to wait on an idle session before releasing the related resources." json:"timeout,omitempty" toml:"timeout,omitempty" yaml:"timeout,omitempty"` } // SetDefaults sets the default values. func (u *UDPConfig) SetDefaults() { u.Timeout = ptypes.Duration(DefaultUDPTimeout) } // ObservabilityConfig holds the observability configuration for an entry point. type ObservabilityConfig struct { AccessLogs *bool `description:"Enables access-logs for this entryPoint." json:"accessLogs,omitempty" toml:"accessLogs,omitempty" yaml:"accessLogs,omitempty" export:"true"` Metrics *bool `description:"Enables metrics for this entryPoint." json:"metrics,omitempty" toml:"metrics,omitempty" yaml:"metrics,omitempty" export:"true"` Tracing *bool `description:"Enables tracing for this entryPoint." json:"tracing,omitempty" toml:"tracing,omitempty" yaml:"tracing,omitempty" export:"true"` TraceVerbosity otypes.TracingVerbosity `description:"Defines the tracing verbosity level for this entryPoint." json:"traceVerbosity,omitempty" toml:"traceVerbosity,omitempty" yaml:"traceVerbosity,omitempty" export:"true"` } // SetDefaults sets the default values. func (o *ObservabilityConfig) SetDefaults() { defaultValue := true o.AccessLogs = &defaultValue o.Metrics = &defaultValue o.Tracing = &defaultValue o.TraceVerbosity = otypes.MinimalVerbosity }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/static/static_config.go
pkg/config/static/static_config.go
package static import ( "errors" "fmt" "path" "strings" "time" legolog "github.com/go-acme/lego/v4/log" "github.com/rs/zerolog" "github.com/rs/zerolog/log" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/observability/logs" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "github.com/traefik/traefik/v3/pkg/ping" acmeprovider "github.com/traefik/traefik/v3/pkg/provider/acme" "github.com/traefik/traefik/v3/pkg/provider/consulcatalog" "github.com/traefik/traefik/v3/pkg/provider/docker" "github.com/traefik/traefik/v3/pkg/provider/ecs" "github.com/traefik/traefik/v3/pkg/provider/file" "github.com/traefik/traefik/v3/pkg/provider/http" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/crd" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/gateway" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/ingress" ingressnginx "github.com/traefik/traefik/v3/pkg/provider/kubernetes/ingress-nginx" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/knative" "github.com/traefik/traefik/v3/pkg/provider/kv/consul" "github.com/traefik/traefik/v3/pkg/provider/kv/etcd" "github.com/traefik/traefik/v3/pkg/provider/kv/redis" "github.com/traefik/traefik/v3/pkg/provider/kv/zk" "github.com/traefik/traefik/v3/pkg/provider/nomad" "github.com/traefik/traefik/v3/pkg/provider/rest" "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" ) const ( // DefaultInternalEntryPointName the name of the default internal entry point. DefaultInternalEntryPointName = "traefik" // DefaultGraceTimeout controls how long Traefik serves pending requests // prior to shutting down. DefaultGraceTimeout = 10 * time.Second // DefaultIdleTimeout before closing an idle connection. DefaultIdleTimeout = 180 * time.Second // DefaultReadTimeout defines the default maximum duration for reading the entire request, including the body. DefaultReadTimeout = 60 * time.Second // DefaultAcmeCAServer is the default ACME API endpoint. DefaultAcmeCAServer = "https://acme-v02.api.letsencrypt.org/directory" // DefaultUDPTimeout defines how long to wait by default on an idle session, // before releasing all resources related to that session. DefaultUDPTimeout = 3 * time.Second ) // Configuration is the static configuration. type Configuration struct { Global *Global `description:"Global configuration options" json:"global,omitempty" toml:"global,omitempty" yaml:"global,omitempty" export:"true"` ServersTransport *ServersTransport `description:"Servers default transport." json:"serversTransport,omitempty" toml:"serversTransport,omitempty" yaml:"serversTransport,omitempty" export:"true"` TCPServersTransport *TCPServersTransport `description:"TCP servers default transport." json:"tcpServersTransport,omitempty" toml:"tcpServersTransport,omitempty" yaml:"tcpServersTransport,omitempty" export:"true"` EntryPoints EntryPoints `description:"Entry points definition." json:"entryPoints,omitempty" toml:"entryPoints,omitempty" yaml:"entryPoints,omitempty" export:"true"` Providers *Providers `description:"Providers configuration." json:"providers,omitempty" toml:"providers,omitempty" yaml:"providers,omitempty" export:"true"` API *API `description:"Enable api/dashboard." json:"api,omitempty" toml:"api,omitempty" yaml:"api,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` Metrics *otypes.Metrics `description:"Enable a metrics exporter." json:"metrics,omitempty" toml:"metrics,omitempty" yaml:"metrics,omitempty" export:"true"` Ping *ping.Handler `description:"Enable ping." json:"ping,omitempty" toml:"ping,omitempty" yaml:"ping,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` Log *otypes.TraefikLog `description:"Traefik log settings." json:"log,omitempty" toml:"log,omitempty" yaml:"log,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` AccessLog *otypes.AccessLog `description:"Access log settings." json:"accessLog,omitempty" toml:"accessLog,omitempty" yaml:"accessLog,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` Tracing *Tracing `description:"Tracing configuration." json:"tracing,omitempty" toml:"tracing,omitempty" yaml:"tracing,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` HostResolver *types.HostResolverConfig `description:"Enable CNAME Flattening." json:"hostResolver,omitempty" toml:"hostResolver,omitempty" yaml:"hostResolver,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` CertificatesResolvers map[string]CertificateResolver `description:"Certificates resolvers configuration." json:"certificatesResolvers,omitempty" toml:"certificatesResolvers,omitempty" yaml:"certificatesResolvers,omitempty" export:"true"` Experimental *Experimental `description:"Experimental features." json:"experimental,omitempty" toml:"experimental,omitempty" yaml:"experimental,omitempty" export:"true"` // Deprecated: Please do not use this field. Core *Core `description:"Core controls." json:"core,omitempty" toml:"core,omitempty" yaml:"core,omitempty" export:"true"` Spiffe *SpiffeClientConfig `description:"SPIFFE integration configuration." json:"spiffe,omitempty" toml:"spiffe,omitempty" yaml:"spiffe,omitempty" export:"true"` OCSP *tls.OCSPConfig `description:"OCSP configuration." json:"ocsp,omitempty" toml:"ocsp,omitempty" yaml:"ocsp,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` } // Core configures Traefik core behavior. type Core struct { // Deprecated: Please do not use this field and rewrite the router rules to use the v3 syntax. DefaultRuleSyntax string `description:"Defines the rule parser default syntax (v2 or v3)" json:"defaultRuleSyntax,omitempty" toml:"defaultRuleSyntax,omitempty" yaml:"defaultRuleSyntax,omitempty"` } // SetDefaults sets the default values. func (c *Core) SetDefaults() { c.DefaultRuleSyntax = "v3" } // SpiffeClientConfig defines the SPIFFE client configuration. type SpiffeClientConfig struct { WorkloadAPIAddr string `description:"Defines the workload API address." json:"workloadAPIAddr,omitempty" toml:"workloadAPIAddr,omitempty" yaml:"workloadAPIAddr,omitempty"` } // CertificateResolver contains the configuration for the different types of certificates resolver. type CertificateResolver struct { ACME *acmeprovider.Configuration `description:"Enables ACME (Let's Encrypt) automatic SSL." json:"acme,omitempty" toml:"acme,omitempty" yaml:"acme,omitempty" export:"true"` Tailscale *struct{} `description:"Enables Tailscale certificate resolution." json:"tailscale,omitempty" toml:"tailscale,omitempty" yaml:"tailscale,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` } // Global holds the global configuration. type Global struct { CheckNewVersion bool `description:"Periodically check if a new version has been released." json:"checkNewVersion,omitempty" toml:"checkNewVersion,omitempty" yaml:"checkNewVersion,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` SendAnonymousUsage bool `description:"Periodically send anonymous usage statistics. If the option is not specified, it will be disabled by default." json:"sendAnonymousUsage,omitempty" toml:"sendAnonymousUsage,omitempty" yaml:"sendAnonymousUsage,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` NotAppendXForwardedFor bool `description:"Disable appending RemoteAddr to X-Forwarded-For header. Defaults to false (appending is enabled)." json:"notAppendXForwardedFor,omitempty" toml:"notAppendXForwardedFor,omitempty" yaml:"notAppendXForwardedFor,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` } // ServersTransport options to configure communication between Traefik and the servers. type ServersTransport struct { InsecureSkipVerify bool `description:"Disable SSL certificate verification." json:"insecureSkipVerify,omitempty" toml:"insecureSkipVerify,omitempty" yaml:"insecureSkipVerify,omitempty" export:"true"` RootCAs []types.FileOrContent `description:"Add cert file for self-signed certificate." json:"rootCAs,omitempty" toml:"rootCAs,omitempty" yaml:"rootCAs,omitempty"` MaxIdleConnsPerHost int `description:"If non-zero, controls the maximum idle (keep-alive) to keep per-host. If zero, DefaultMaxIdleConnsPerHost is used. If negative, disables connection reuse." json:"maxIdleConnsPerHost,omitempty" toml:"maxIdleConnsPerHost,omitempty" yaml:"maxIdleConnsPerHost,omitempty" export:"true"` ForwardingTimeouts *ForwardingTimeouts `description:"Timeouts for requests forwarded to the backend servers." json:"forwardingTimeouts,omitempty" toml:"forwardingTimeouts,omitempty" yaml:"forwardingTimeouts,omitempty" export:"true"` Spiffe *Spiffe `description:"Defines the SPIFFE configuration." json:"spiffe,omitempty" toml:"spiffe,omitempty" yaml:"spiffe,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` } // Spiffe holds the SPIFFE configuration. type Spiffe struct { IDs []string `description:"Defines the allowed SPIFFE IDs (takes precedence over the SPIFFE TrustDomain)." json:"ids,omitempty" toml:"ids,omitempty" yaml:"ids,omitempty"` TrustDomain string `description:"Defines the allowed SPIFFE trust domain." json:"trustDomain,omitempty" toml:"trustDomain,omitempty" yaml:"trustDomain,omitempty"` } // TCPServersTransport options to configure communication between Traefik and the servers. type TCPServersTransport struct { DialKeepAlive ptypes.Duration `description:"Defines the interval between keep-alive probes for an active network connection. If zero, keep-alive probes are sent with a default value (currently 15 seconds), if supported by the protocol and operating system. Network protocols or operating systems that do not support keep-alives ignore this field. If negative, keep-alive probes are disabled" json:"dialKeepAlive,omitempty" toml:"dialKeepAlive,omitempty" yaml:"dialKeepAlive,omitempty" export:"true"` DialTimeout ptypes.Duration `description:"Defines the amount of time to wait until a connection to a backend server can be established. If zero, no timeout exists." json:"dialTimeout,omitempty" toml:"dialTimeout,omitempty" yaml:"dialTimeout,omitempty" export:"true"` // TerminationDelay, corresponds to the deadline that the proxy sets, after one // of its connected peers indicates it has closed the writing capability of its // connection, to close the reading capability as well, hence fully terminating the // connection. It is a duration in milliseconds, defaulting to 100. A negative value // means an infinite deadline (i.e. the reading capability is never closed). TerminationDelay ptypes.Duration `description:"Defines the delay to wait before fully terminating the connection, after one connected peer has closed its writing capability." json:"terminationDelay,omitempty" toml:"terminationDelay,omitempty" yaml:"terminationDelay,omitempty" export:"true"` TLS *TLSClientConfig `description:"Defines the TLS configuration." json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" label:"allowEmpty" file:"allowEmpty" kv:"allowEmpty" export:"true"` } // TLSClientConfig options to configure TLS communication between Traefik and the servers. type TLSClientConfig struct { InsecureSkipVerify bool `description:"Disables SSL certificate verification." json:"insecureSkipVerify,omitempty" toml:"insecureSkipVerify,omitempty" yaml:"insecureSkipVerify,omitempty" export:"true"` RootCAs []types.FileOrContent `description:"Defines a list of CA secret used to validate self-signed certificate" json:"rootCAs,omitempty" toml:"rootCAs,omitempty" yaml:"rootCAs,omitempty"` Spiffe *Spiffe `description:"Defines the SPIFFE TLS configuration." json:"spiffe,omitempty" toml:"spiffe,omitempty" yaml:"spiffe,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` } // API holds the API configuration. type API struct { BasePath string `description:"Defines the base path where the API and Dashboard will be exposed." json:"basePath,omitempty" toml:"basePath,omitempty" yaml:"basePath,omitempty" export:"true"` Insecure bool `description:"Activate API directly on the entryPoint named traefik." json:"insecure,omitempty" toml:"insecure,omitempty" yaml:"insecure,omitempty" export:"true"` Dashboard bool `description:"Activate dashboard." json:"dashboard,omitempty" toml:"dashboard,omitempty" yaml:"dashboard,omitempty" export:"true"` Debug bool `description:"Enable additional endpoints for debugging and profiling." json:"debug,omitempty" toml:"debug,omitempty" yaml:"debug,omitempty" export:"true"` DisableDashboardAd bool `description:"Disable ad in the dashboard." json:"disableDashboardAd,omitempty" toml:"disableDashboardAd,omitempty" yaml:"disableDashboardAd,omitempty" export:"true"` DashboardName string `description:"Custom name for the dashboard." json:"dashboardName,omitempty" toml:"dashboardName,omitempty" yaml:"dashboardName,omitempty" export:"true"` // TODO: Re-enable statistics // Statistics *types.Statistics `description:"Enable more detailed statistics." json:"statistics,omitempty" toml:"statistics,omitempty" yaml:"statistics,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` } // SetDefaults sets the default values. func (a *API) SetDefaults() { a.BasePath = "/" a.Dashboard = true a.DashboardName = "" } // RespondingTimeouts contains timeout configurations for incoming requests to the Traefik instance. type RespondingTimeouts struct { ReadTimeout ptypes.Duration `description:"ReadTimeout is the maximum duration for reading the entire request, including the body. If zero, no timeout is set." json:"readTimeout,omitempty" toml:"readTimeout,omitempty" yaml:"readTimeout,omitempty" export:"true"` WriteTimeout ptypes.Duration `description:"WriteTimeout is the maximum duration before timing out writes of the response. If zero, no timeout is set." json:"writeTimeout,omitempty" toml:"writeTimeout,omitempty" yaml:"writeTimeout,omitempty" export:"true"` IdleTimeout ptypes.Duration `description:"IdleTimeout is the maximum amount duration an idle (keep-alive) connection will remain idle before closing itself. If zero, no timeout is set." json:"idleTimeout,omitempty" toml:"idleTimeout,omitempty" yaml:"idleTimeout,omitempty" export:"true"` } // SetDefaults sets the default values. func (a *RespondingTimeouts) SetDefaults() { a.ReadTimeout = ptypes.Duration(DefaultReadTimeout) a.IdleTimeout = ptypes.Duration(DefaultIdleTimeout) } // ForwardingTimeouts contains timeout configurations for forwarding requests to the backend servers. type ForwardingTimeouts struct { DialTimeout ptypes.Duration `description:"The amount of time to wait until a connection to a backend server can be established. If zero, no timeout exists." json:"dialTimeout,omitempty" toml:"dialTimeout,omitempty" yaml:"dialTimeout,omitempty" export:"true"` ResponseHeaderTimeout ptypes.Duration `description:"The amount of time to wait for a server's response headers after fully writing the request (including its body, if any). If zero, no timeout exists." json:"responseHeaderTimeout,omitempty" toml:"responseHeaderTimeout,omitempty" yaml:"responseHeaderTimeout,omitempty" export:"true"` IdleConnTimeout ptypes.Duration `description:"The maximum period for which an idle HTTP keep-alive connection will remain open before closing itself" json:"idleConnTimeout,omitempty" toml:"idleConnTimeout,omitempty" yaml:"idleConnTimeout,omitempty" export:"true"` } // SetDefaults sets the default values. func (f *ForwardingTimeouts) SetDefaults() { f.DialTimeout = ptypes.Duration(30 * time.Second) f.IdleConnTimeout = ptypes.Duration(90 * time.Second) } // LifeCycle contains configurations relevant to the lifecycle (such as the shutdown phase) of Traefik. type LifeCycle struct { RequestAcceptGraceTimeout ptypes.Duration `description:"Duration to keep accepting requests before Traefik initiates the graceful shutdown procedure." json:"requestAcceptGraceTimeout,omitempty" toml:"requestAcceptGraceTimeout,omitempty" yaml:"requestAcceptGraceTimeout,omitempty" export:"true"` GraceTimeOut ptypes.Duration `description:"Duration to give active requests a chance to finish before Traefik stops." json:"graceTimeOut,omitempty" toml:"graceTimeOut,omitempty" yaml:"graceTimeOut,omitempty" export:"true"` } // SetDefaults sets the default values. func (a *LifeCycle) SetDefaults() { a.GraceTimeOut = ptypes.Duration(DefaultGraceTimeout) } // Tracing holds the tracing configuration. type Tracing struct { ServiceName string `description:"Defines the service name resource attribute." json:"serviceName,omitempty" toml:"serviceName,omitempty" yaml:"serviceName,omitempty" export:"true"` ResourceAttributes map[string]string `description:"Defines additional resource attributes (key:value)." json:"resourceAttributes,omitempty" toml:"resourceAttributes,omitempty" yaml:"resourceAttributes,omitempty" export:"true"` CapturedRequestHeaders []string `description:"Request headers to add as attributes for server and client spans." json:"capturedRequestHeaders,omitempty" toml:"capturedRequestHeaders,omitempty" yaml:"capturedRequestHeaders,omitempty" export:"true"` CapturedResponseHeaders []string `description:"Response headers to add as attributes for server and client spans." json:"capturedResponseHeaders,omitempty" toml:"capturedResponseHeaders,omitempty" yaml:"capturedResponseHeaders,omitempty" export:"true"` SafeQueryParams []string `description:"Query params to not redact." json:"safeQueryParams,omitempty" toml:"safeQueryParams,omitempty" yaml:"safeQueryParams,omitempty" export:"true"` SampleRate float64 `description:"Sets the rate between 0.0 and 1.0 of requests to trace." json:"sampleRate,omitempty" toml:"sampleRate,omitempty" yaml:"sampleRate,omitempty" export:"true"` AddInternals bool `description:"Enables tracing for internal services (ping, dashboard, etc...)." json:"addInternals,omitempty" toml:"addInternals,omitempty" yaml:"addInternals,omitempty" export:"true"` OTLP *otypes.OTelTracing `description:"Settings for OpenTelemetry." json:"otlp,omitempty" toml:"otlp,omitempty" yaml:"otlp,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` // Deprecated: please use ResourceAttributes instead. GlobalAttributes map[string]string `description:"(Deprecated) Defines additional resource attributes (key:value)." json:"globalAttributes,omitempty" toml:"globalAttributes,omitempty" yaml:"globalAttributes,omitempty" export:"true"` } // SetDefaults sets the default values. func (t *Tracing) SetDefaults() { t.ServiceName = "traefik" t.SampleRate = 1.0 t.OTLP = &otypes.OTelTracing{} t.OTLP.SetDefaults() } // Providers contains providers configuration. type Providers struct { ProvidersThrottleDuration ptypes.Duration `description:"Backends throttle duration: minimum duration between 2 events from providers before applying a new configuration. It avoids unnecessary reloads if multiples events are sent in a short amount of time." json:"providersThrottleDuration,omitempty" toml:"providersThrottleDuration,omitempty" yaml:"providersThrottleDuration,omitempty" export:"true"` Docker *docker.Provider `description:"Enables Docker provider." json:"docker,omitempty" toml:"docker,omitempty" yaml:"docker,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` Swarm *docker.SwarmProvider `description:"Enables Docker Swarm provider." json:"swarm,omitempty" toml:"swarm,omitempty" yaml:"swarm,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` File *file.Provider `description:"Enables File provider." json:"file,omitempty" toml:"file,omitempty" yaml:"file,omitempty" export:"true"` KubernetesIngress *ingress.Provider `description:"Enables Kubernetes Ingress provider." json:"kubernetesIngress,omitempty" toml:"kubernetesIngress,omitempty" yaml:"kubernetesIngress,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` KubernetesIngressNGINX *ingressnginx.Provider `description:"Enables Kubernetes Ingress NGINX provider." json:"kubernetesIngressNGINX,omitempty" toml:"kubernetesIngressNGINX,omitempty" yaml:"kubernetesIngressNGINX,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` KubernetesCRD *crd.Provider `description:"Enables Kubernetes CRD provider." json:"kubernetesCRD,omitempty" toml:"kubernetesCRD,omitempty" yaml:"kubernetesCRD,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` KubernetesGateway *gateway.Provider `description:"Enables Kubernetes Gateway API provider." json:"kubernetesGateway,omitempty" toml:"kubernetesGateway,omitempty" yaml:"kubernetesGateway,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` Knative *knative.Provider `description:"Enables Knative provider." json:"knative,omitempty" toml:"knative,omitempty" yaml:"knative,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` Rest *rest.Provider `description:"Enables Rest provider." json:"rest,omitempty" toml:"rest,omitempty" yaml:"rest,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` ConsulCatalog *consulcatalog.ProviderBuilder `description:"Enables Consul Catalog provider." json:"consulCatalog,omitempty" toml:"consulCatalog,omitempty" yaml:"consulCatalog,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` Nomad *nomad.ProviderBuilder `description:"Enables Nomad provider." json:"nomad,omitempty" toml:"nomad,omitempty" yaml:"nomad,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` Ecs *ecs.Provider `description:"Enables AWS ECS provider." json:"ecs,omitempty" toml:"ecs,omitempty" yaml:"ecs,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` Consul *consul.ProviderBuilder `description:"Enables Consul provider." json:"consul,omitempty" toml:"consul,omitempty" yaml:"consul,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` Etcd *etcd.Provider `description:"Enables Etcd provider." json:"etcd,omitempty" toml:"etcd,omitempty" yaml:"etcd,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` ZooKeeper *zk.Provider `description:"Enables ZooKeeper provider." json:"zooKeeper,omitempty" toml:"zooKeeper,omitempty" yaml:"zooKeeper,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` Redis *redis.Provider `description:"Enables Redis provider." json:"redis,omitempty" toml:"redis,omitempty" yaml:"redis,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` HTTP *http.Provider `description:"Enables HTTP provider." json:"http,omitempty" toml:"http,omitempty" yaml:"http,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` Plugin map[string]PluginConf `description:"Plugins configuration." json:"plugin,omitempty" toml:"plugin,omitempty" yaml:"plugin,omitempty"` } // SetEffectiveConfiguration adds missing configuration parameters derived from existing ones. // It also takes care of maintaining backwards compatibility. func (c *Configuration) SetEffectiveConfiguration() { // Creates the default entry point if needed if !c.hasUserDefinedEntrypoint() { ep := &EntryPoint{Address: ":80"} ep.SetDefaults() // TODO: double check this tomorrow if c.EntryPoints == nil { c.EntryPoints = make(EntryPoints) } c.EntryPoints["http"] = ep } // Creates the internal traefik entry point if needed if (c.API != nil && c.API.Insecure) || (c.Ping != nil && !c.Ping.ManualRouting && c.Ping.EntryPoint == DefaultInternalEntryPointName) || (c.Metrics != nil && c.Metrics.Prometheus != nil && !c.Metrics.Prometheus.ManualRouting && c.Metrics.Prometheus.EntryPoint == DefaultInternalEntryPointName) || (c.Providers != nil && c.Providers.Rest != nil && c.Providers.Rest.Insecure) { if _, ok := c.EntryPoints[DefaultInternalEntryPointName]; !ok { ep := &EntryPoint{Address: ":8080"} ep.SetDefaults() c.EntryPoints[DefaultInternalEntryPointName] = ep } } if c.Tracing != nil && c.Tracing.GlobalAttributes != nil && c.Tracing.ResourceAttributes == nil { c.Tracing.ResourceAttributes = c.Tracing.GlobalAttributes } if c.Providers.Docker != nil { if c.Providers.Docker.HTTPClientTimeout < 0 { c.Providers.Docker.HTTPClientTimeout = 0 } } if c.Providers.Swarm != nil { if c.Providers.Swarm.RefreshSeconds <= 0 { c.Providers.Swarm.RefreshSeconds = ptypes.Duration(15 * time.Second) } if c.Providers.Swarm.HTTPClientTimeout < 0 { c.Providers.Swarm.HTTPClientTimeout = 0 } } // Configure Gateway API provider if c.Providers.KubernetesGateway != nil { entryPoints := make(map[string]gateway.Entrypoint) for epName, entryPoint := range c.EntryPoints { entryPoints[epName] = gateway.Entrypoint{Address: entryPoint.GetAddress(), HasHTTPTLSConf: entryPoint.HTTP.TLS != nil} } if c.Providers.KubernetesCRD != nil { c.Providers.KubernetesCRD.FillExtensionBuilderRegistry(c.Providers.KubernetesGateway) } c.Providers.KubernetesGateway.EntryPoints = entryPoints } // Defines the default rule syntax for the Kubernetes Ingress Provider. // This allows the provider to adapt the matcher syntax to the desired rule syntax version. if c.Core != nil && c.Providers.KubernetesIngress != nil { c.Providers.KubernetesIngress.DefaultRuleSyntax = c.Core.DefaultRuleSyntax } for _, resolver := range c.CertificatesResolvers { if resolver.ACME == nil { continue } if resolver.ACME.DNSChallenge == nil { continue } switch resolver.ACME.DNSChallenge.Provider { case "googledomains", "cloudxns", "brandit": log.Warn().Msgf("%s DNS provider is deprecated.", resolver.ACME.DNSChallenge.Provider) case "dnspod": log.Warn().Msgf("%s provider is deprecated, please use 'tencentcloud' provider instead.", resolver.ACME.DNSChallenge.Provider) case "azure": log.Warn().Msgf("%s provider is deprecated, please use 'azuredns' provider instead.", resolver.ACME.DNSChallenge.Provider) } if resolver.ACME.DNSChallenge.DisablePropagationCheck { log.Warn().Msgf("disablePropagationCheck is now deprecated, please use propagation.disableChecks instead.") if resolver.ACME.DNSChallenge.Propagation == nil { resolver.ACME.DNSChallenge.Propagation = &acmeprovider.Propagation{} } resolver.ACME.DNSChallenge.Propagation.DisableChecks = true } if resolver.ACME.DNSChallenge.DelayBeforeCheck > 0 { log.Warn().Msgf("delayBeforeCheck is now deprecated, please use propagation.delayBeforeChecks instead.") if resolver.ACME.DNSChallenge.Propagation == nil { resolver.ACME.DNSChallenge.Propagation = &acmeprovider.Propagation{} } resolver.ACME.DNSChallenge.Propagation.DelayBeforeChecks = resolver.ACME.DNSChallenge.DelayBeforeCheck } } for _, resolver := range c.CertificatesResolvers { if resolver.ACME == nil { continue } if resolver.ACME.DNSChallenge == nil { continue } switch resolver.ACME.DNSChallenge.Provider { case "googledomains", "cloudxns", "brandit": log.Warn().Msgf("%s DNS provider is deprecated.", resolver.ACME.DNSChallenge.Provider) case "dnspod": log.Warn().Msgf("%s provider is deprecated, please use 'tencentcloud' provider instead.", resolver.ACME.DNSChallenge.Provider) case "azure": log.Warn().Msgf("%s provider is deprecated, please use 'azuredns' provider instead.", resolver.ACME.DNSChallenge.Provider) } } c.initACMEProvider() } func (c *Configuration) hasUserDefinedEntrypoint() bool { return len(c.EntryPoints) != 0 } func (c *Configuration) initACMEProvider() { for _, resolver := range c.CertificatesResolvers { if resolver.ACME != nil { resolver.ACME.CAServer = getSafeACMECAServer(resolver.ACME.CAServer) } } logger := logs.NoLevel(log.Logger, zerolog.DebugLevel).With().Str("lib", "lego").Logger() legolog.Logger = logs.NewLogrusWrapper(logger) } // ValidateConfiguration validate that configuration is coherent. func (c *Configuration) ValidateConfiguration() error { for name, resolver := range c.CertificatesResolvers { if resolver.ACME != nil && resolver.Tailscale != nil { return fmt.Errorf("unable to initialize certificates resolver %q, as ACME and Tailscale providers are mutually exclusive", name) } if resolver.ACME == nil { continue } if len(resolver.ACME.Storage) == 0 { return fmt.Errorf("unable to initialize certificates resolver %q with no storage location for the certificates", name) } } if c.Core != nil { switch c.Core.DefaultRuleSyntax { case "v3": // NOOP case "v2": // TODO: point to migration guide. log.Warn().Msgf("v2 rules syntax is now deprecated, please use v3 instead...") default: return fmt.Errorf("unsupported default rule syntax configuration: %q", c.Core.DefaultRuleSyntax) } } if c.Providers != nil && c.Providers.KubernetesIngressNGINX != nil { if c.Providers.KubernetesIngressNGINX.WatchNamespace != "" && c.Providers.KubernetesIngressNGINX.WatchNamespaceSelector != "" { return errors.New("watchNamespace and watchNamespaceSelector options are mutually exclusive") } } if c.Providers != nil && c.Providers.Knative != nil { if c.Experimental == nil || !c.Experimental.Knative { return errors.New("the experimental Knative feature must be enabled to use the Knative provider") } } if c.AccessLog != nil && c.AccessLog.OTLP != nil { if c.Experimental == nil || !c.Experimental.OTLPLogs { return errors.New("the experimental OTLPLogs feature must be enabled to use OTLP access logging") } if c.AccessLog.OTLP.GRPC != nil && c.AccessLog.OTLP.GRPC.TLS != nil && c.AccessLog.OTLP.GRPC.Insecure { return errors.New("access logs OTLP GRPC: TLS and Insecure options are mutually exclusive") } } if c.Log != nil && c.Log.OTLP != nil { if c.Experimental == nil || !c.Experimental.OTLPLogs { return errors.New("the experimental OTLPLogs feature must be enabled to use OTLP logging") } if c.Log.OTLP.GRPC != nil && c.Log.OTLP.GRPC.TLS != nil && c.Log.OTLP.GRPC.Insecure { return errors.New("logs OTLP GRPC: TLS and Insecure options are mutually exclusive") } } if c.Tracing != nil && c.Tracing.OTLP != nil { if c.Tracing.OTLP.GRPC != nil && c.Tracing.OTLP.GRPC.TLS != nil && c.Tracing.OTLP.GRPC.Insecure { return errors.New("tracing OTLP GRPC: TLS and Insecure options are mutually exclusive") } } if c.Metrics != nil && c.Metrics.OTLP != nil { if c.Metrics.OTLP.GRPC != nil && c.Metrics.OTLP.GRPC.TLS != nil && c.Metrics.OTLP.GRPC.Insecure { return errors.New("metrics OTLP GRPC: TLS and Insecure options are mutually exclusive") } } if c.API != nil && !path.IsAbs(c.API.BasePath) { return errors.New("API basePath must be a valid absolute path") } if c.OCSP != nil { for responderURL, url := range c.OCSP.ResponderOverrides { if url == "" { return fmt.Errorf("OCSP responder override value for %s cannot be empty", responderURL) } } } return nil } func getSafeACMECAServer(caServerSrc string) string { if len(caServerSrc) == 0 { return DefaultAcmeCAServer } if strings.HasPrefix(caServerSrc, "https://acme-v01.api.letsencrypt.org") { caServer := strings.Replace(caServerSrc, "v01", "v02", 1) log.Warn().Msgf("The CA server %[1]q refers to a v01 endpoint of the ACME API, please change to %[2]q. Fallback to %[2]q.", caServerSrc, caServer) return caServer } if strings.HasPrefix(caServerSrc, "https://acme-staging.api.letsencrypt.org") { caServer := strings.Replace(caServerSrc, "https://acme-staging.api.letsencrypt.org", "https://acme-staging-v02.api.letsencrypt.org", 1) log.Warn().Msgf("The CA server %[1]q refers to a v01 endpoint of the ACME API, please change to %[2]q. Fallback to %[2]q.", caServerSrc, caServer) return caServer } return caServerSrc }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/dynamic/middleware_test.go
pkg/config/dynamic/middleware_test.go
package dynamic import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func Test_GetStrategy_ipv6Subnet(t *testing.T) { testCases := []struct { desc string expectError bool ipv6Subnet *int }{ { desc: "Nil subnet", }, { desc: "Zero subnet", expectError: true, ipv6Subnet: intPtr(0), }, { desc: "Subnet greater that 128", expectError: true, ipv6Subnet: intPtr(129), }, { desc: "Valid subnet", ipv6Subnet: intPtr(128), }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() strategy := IPStrategy{ IPv6Subnet: test.ipv6Subnet, } get, err := strategy.Get() if test.expectError { require.Error(t, err) assert.Nil(t, get) } else { require.NoError(t, err) assert.NotNil(t, get) } }) } } func intPtr(value int) *int { return &value }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/dynamic/zz_generated.deepcopy.go
pkg/config/dynamic/zz_generated.deepcopy.go
//go:build !ignore_autogenerated // +build !ignore_autogenerated /* The MIT License (MIT) Copyright (c) 2016-2020 Containous SAS; 2020-2026 Traefik Labs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Code generated by deepcopy-gen. DO NOT EDIT. package dynamic import ( paersertypes "github.com/traefik/paerser/types" tls "github.com/traefik/traefik/v3/pkg/tls" types "github.com/traefik/traefik/v3/pkg/types" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AddPrefix) DeepCopyInto(out *AddPrefix) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AddPrefix. func (in *AddPrefix) DeepCopy() *AddPrefix { if in == nil { return nil } out := new(AddPrefix) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *BasicAuth) DeepCopyInto(out *BasicAuth) { *out = *in if in.Users != nil { in, out := &in.Users, &out.Users *out = make(Users, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BasicAuth. func (in *BasicAuth) DeepCopy() *BasicAuth { if in == nil { return nil } out := new(BasicAuth) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Buffering) DeepCopyInto(out *Buffering) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Buffering. func (in *Buffering) DeepCopy() *Buffering { if in == nil { return nil } out := new(Buffering) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Chain) DeepCopyInto(out *Chain) { *out = *in if in.Middlewares != nil { in, out := &in.Middlewares, &out.Middlewares *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Chain. func (in *Chain) DeepCopy() *Chain { if in == nil { return nil } out := new(Chain) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CircuitBreaker) DeepCopyInto(out *CircuitBreaker) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CircuitBreaker. func (in *CircuitBreaker) DeepCopy() *CircuitBreaker { if in == nil { return nil } out := new(CircuitBreaker) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ClientTLS) DeepCopyInto(out *ClientTLS) { *out = *in if in.CAOptional != nil { in, out := &in.CAOptional, &out.CAOptional *out = new(bool) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClientTLS. func (in *ClientTLS) DeepCopy() *ClientTLS { if in == nil { return nil } out := new(ClientTLS) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Compress) DeepCopyInto(out *Compress) { *out = *in if in.ExcludedContentTypes != nil { in, out := &in.ExcludedContentTypes, &out.ExcludedContentTypes *out = make([]string, len(*in)) copy(*out, *in) } if in.IncludedContentTypes != nil { in, out := &in.IncludedContentTypes, &out.IncludedContentTypes *out = make([]string, len(*in)) copy(*out, *in) } if in.Encodings != nil { in, out := &in.Encodings, &out.Encodings *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Compress. func (in *Compress) DeepCopy() *Compress { if in == nil { return nil } out := new(Compress) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Configuration) DeepCopyInto(out *Configuration) { *out = *in if in.HTTP != nil { in, out := &in.HTTP, &out.HTTP *out = new(HTTPConfiguration) (*in).DeepCopyInto(*out) } if in.TCP != nil { in, out := &in.TCP, &out.TCP *out = new(TCPConfiguration) (*in).DeepCopyInto(*out) } if in.UDP != nil { in, out := &in.UDP, &out.UDP *out = new(UDPConfiguration) (*in).DeepCopyInto(*out) } if in.TLS != nil { in, out := &in.TLS, &out.TLS *out = new(TLSConfiguration) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Configuration. func (in *Configuration) DeepCopy() *Configuration { if in == nil { return nil } out := new(Configuration) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in Configurations) DeepCopyInto(out *Configurations) { { in := &in *out = make(Configurations, len(*in)) for key, val := range *in { var outVal *Configuration if val == nil { (*out)[key] = nil } else { in, out := &val, &outVal *out = new(Configuration) (*in).DeepCopyInto(*out) } (*out)[key] = outVal } return } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Configurations. func (in Configurations) DeepCopy() Configurations { if in == nil { return nil } out := new(Configurations) in.DeepCopyInto(out) return *out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ContentType) DeepCopyInto(out *ContentType) { *out = *in if in.AutoDetect != nil { in, out := &in.AutoDetect, &out.AutoDetect *out = new(bool) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContentType. func (in *ContentType) DeepCopy() *ContentType { if in == nil { return nil } out := new(ContentType) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Cookie) DeepCopyInto(out *Cookie) { *out = *in if in.Path != nil { in, out := &in.Path, &out.Path *out = new(string) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Cookie. func (in *Cookie) DeepCopy() *Cookie { if in == nil { return nil } out := new(Cookie) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DigestAuth) DeepCopyInto(out *DigestAuth) { *out = *in if in.Users != nil { in, out := &in.Users, &out.Users *out = make(Users, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DigestAuth. func (in *DigestAuth) DeepCopy() *DigestAuth { if in == nil { return nil } out := new(DigestAuth) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ErrorPage) DeepCopyInto(out *ErrorPage) { *out = *in if in.Status != nil { in, out := &in.Status, &out.Status *out = make([]string, len(*in)) copy(*out, *in) } if in.StatusRewrites != nil { in, out := &in.StatusRewrites, &out.StatusRewrites *out = make(map[string]int, len(*in)) for key, val := range *in { (*out)[key] = val } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ErrorPage. func (in *ErrorPage) DeepCopy() *ErrorPage { if in == nil { return nil } out := new(ErrorPage) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Failover) DeepCopyInto(out *Failover) { *out = *in if in.HealthCheck != nil { in, out := &in.HealthCheck, &out.HealthCheck *out = new(HealthCheck) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Failover. func (in *Failover) DeepCopy() *Failover { if in == nil { return nil } out := new(Failover) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ForwardAuth) DeepCopyInto(out *ForwardAuth) { *out = *in if in.TLS != nil { in, out := &in.TLS, &out.TLS *out = new(ClientTLS) (*in).DeepCopyInto(*out) } if in.AuthResponseHeaders != nil { in, out := &in.AuthResponseHeaders, &out.AuthResponseHeaders *out = make([]string, len(*in)) copy(*out, *in) } if in.AuthRequestHeaders != nil { in, out := &in.AuthRequestHeaders, &out.AuthRequestHeaders *out = make([]string, len(*in)) copy(*out, *in) } if in.AddAuthCookiesToResponse != nil { in, out := &in.AddAuthCookiesToResponse, &out.AddAuthCookiesToResponse *out = make([]string, len(*in)) copy(*out, *in) } if in.MaxBodySize != nil { in, out := &in.MaxBodySize, &out.MaxBodySize *out = new(int64) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ForwardAuth. func (in *ForwardAuth) DeepCopy() *ForwardAuth { if in == nil { return nil } out := new(ForwardAuth) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ForwardingTimeouts) DeepCopyInto(out *ForwardingTimeouts) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ForwardingTimeouts. func (in *ForwardingTimeouts) DeepCopy() *ForwardingTimeouts { if in == nil { return nil } out := new(ForwardingTimeouts) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GRPCStatus) DeepCopyInto(out *GRPCStatus) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GRPCStatus. func (in *GRPCStatus) DeepCopy() *GRPCStatus { if in == nil { return nil } out := new(GRPCStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GrpcWeb) DeepCopyInto(out *GrpcWeb) { *out = *in if in.AllowOrigins != nil { in, out := &in.AllowOrigins, &out.AllowOrigins *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GrpcWeb. func (in *GrpcWeb) DeepCopy() *GrpcWeb { if in == nil { return nil } out := new(GrpcWeb) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HRWService) DeepCopyInto(out *HRWService) { *out = *in if in.Weight != nil { in, out := &in.Weight, &out.Weight *out = new(int) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HRWService. func (in *HRWService) DeepCopy() *HRWService { if in == nil { return nil } out := new(HRWService) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HTTPConfiguration) DeepCopyInto(out *HTTPConfiguration) { *out = *in if in.Routers != nil { in, out := &in.Routers, &out.Routers *out = make(map[string]*Router, len(*in)) for key, val := range *in { var outVal *Router if val == nil { (*out)[key] = nil } else { in, out := &val, &outVal *out = new(Router) (*in).DeepCopyInto(*out) } (*out)[key] = outVal } } if in.Services != nil { in, out := &in.Services, &out.Services *out = make(map[string]*Service, len(*in)) for key, val := range *in { var outVal *Service if val == nil { (*out)[key] = nil } else { in, out := &val, &outVal *out = new(Service) (*in).DeepCopyInto(*out) } (*out)[key] = outVal } } if in.Middlewares != nil { in, out := &in.Middlewares, &out.Middlewares *out = make(map[string]*Middleware, len(*in)) for key, val := range *in { var outVal *Middleware if val == nil { (*out)[key] = nil } else { in, out := &val, &outVal *out = new(Middleware) (*in).DeepCopyInto(*out) } (*out)[key] = outVal } } if in.Models != nil { in, out := &in.Models, &out.Models *out = make(map[string]*Model, len(*in)) for key, val := range *in { var outVal *Model if val == nil { (*out)[key] = nil } else { in, out := &val, &outVal *out = new(Model) (*in).DeepCopyInto(*out) } (*out)[key] = outVal } } if in.ServersTransports != nil { in, out := &in.ServersTransports, &out.ServersTransports *out = make(map[string]*ServersTransport, len(*in)) for key, val := range *in { var outVal *ServersTransport if val == nil { (*out)[key] = nil } else { in, out := &val, &outVal *out = new(ServersTransport) (*in).DeepCopyInto(*out) } (*out)[key] = outVal } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPConfiguration. func (in *HTTPConfiguration) DeepCopy() *HTTPConfiguration { if in == nil { return nil } out := new(HTTPConfiguration) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HeaderModifier) DeepCopyInto(out *HeaderModifier) { *out = *in if in.Set != nil { in, out := &in.Set, &out.Set *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.Add != nil { in, out := &in.Add, &out.Add *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.Remove != nil { in, out := &in.Remove, &out.Remove *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HeaderModifier. func (in *HeaderModifier) DeepCopy() *HeaderModifier { if in == nil { return nil } out := new(HeaderModifier) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Headers) DeepCopyInto(out *Headers) { *out = *in if in.CustomRequestHeaders != nil { in, out := &in.CustomRequestHeaders, &out.CustomRequestHeaders *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.CustomResponseHeaders != nil { in, out := &in.CustomResponseHeaders, &out.CustomResponseHeaders *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.AccessControlAllowHeaders != nil { in, out := &in.AccessControlAllowHeaders, &out.AccessControlAllowHeaders *out = make([]string, len(*in)) copy(*out, *in) } if in.AccessControlAllowMethods != nil { in, out := &in.AccessControlAllowMethods, &out.AccessControlAllowMethods *out = make([]string, len(*in)) copy(*out, *in) } if in.AccessControlAllowOriginList != nil { in, out := &in.AccessControlAllowOriginList, &out.AccessControlAllowOriginList *out = make([]string, len(*in)) copy(*out, *in) } if in.AccessControlAllowOriginListRegex != nil { in, out := &in.AccessControlAllowOriginListRegex, &out.AccessControlAllowOriginListRegex *out = make([]string, len(*in)) copy(*out, *in) } if in.AccessControlExposeHeaders != nil { in, out := &in.AccessControlExposeHeaders, &out.AccessControlExposeHeaders *out = make([]string, len(*in)) copy(*out, *in) } if in.AllowedHosts != nil { in, out := &in.AllowedHosts, &out.AllowedHosts *out = make([]string, len(*in)) copy(*out, *in) } if in.HostsProxyHeaders != nil { in, out := &in.HostsProxyHeaders, &out.HostsProxyHeaders *out = make([]string, len(*in)) copy(*out, *in) } if in.SSLProxyHeaders != nil { in, out := &in.SSLProxyHeaders, &out.SSLProxyHeaders *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.FeaturePolicy != nil { in, out := &in.FeaturePolicy, &out.FeaturePolicy *out = new(string) **out = **in } if in.SSLRedirect != nil { in, out := &in.SSLRedirect, &out.SSLRedirect *out = new(bool) **out = **in } if in.SSLTemporaryRedirect != nil { in, out := &in.SSLTemporaryRedirect, &out.SSLTemporaryRedirect *out = new(bool) **out = **in } if in.SSLHost != nil { in, out := &in.SSLHost, &out.SSLHost *out = new(string) **out = **in } if in.SSLForceHost != nil { in, out := &in.SSLForceHost, &out.SSLForceHost *out = new(bool) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Headers. func (in *Headers) DeepCopy() *Headers { if in == nil { return nil } out := new(Headers) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HealthCheck) DeepCopyInto(out *HealthCheck) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HealthCheck. func (in *HealthCheck) DeepCopy() *HealthCheck { if in == nil { return nil } out := new(HealthCheck) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HighestRandomWeight) DeepCopyInto(out *HighestRandomWeight) { *out = *in if in.Services != nil { in, out := &in.Services, &out.Services *out = make([]HRWService, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.HealthCheck != nil { in, out := &in.HealthCheck, &out.HealthCheck *out = new(HealthCheck) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HighestRandomWeight. func (in *HighestRandomWeight) DeepCopy() *HighestRandomWeight { if in == nil { return nil } out := new(HighestRandomWeight) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IPAllowList) DeepCopyInto(out *IPAllowList) { *out = *in if in.SourceRange != nil { in, out := &in.SourceRange, &out.SourceRange *out = make([]string, len(*in)) copy(*out, *in) } if in.IPStrategy != nil { in, out := &in.IPStrategy, &out.IPStrategy *out = new(IPStrategy) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IPAllowList. func (in *IPAllowList) DeepCopy() *IPAllowList { if in == nil { return nil } out := new(IPAllowList) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IPStrategy) DeepCopyInto(out *IPStrategy) { *out = *in if in.ExcludedIPs != nil { in, out := &in.ExcludedIPs, &out.ExcludedIPs *out = make([]string, len(*in)) copy(*out, *in) } if in.IPv6Subnet != nil { in, out := &in.IPv6Subnet, &out.IPv6Subnet *out = new(int) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IPStrategy. func (in *IPStrategy) DeepCopy() *IPStrategy { if in == nil { return nil } out := new(IPStrategy) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IPWhiteList) DeepCopyInto(out *IPWhiteList) { *out = *in if in.SourceRange != nil { in, out := &in.SourceRange, &out.SourceRange *out = make([]string, len(*in)) copy(*out, *in) } if in.IPStrategy != nil { in, out := &in.IPStrategy, &out.IPStrategy *out = new(IPStrategy) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IPWhiteList. func (in *IPWhiteList) DeepCopy() *IPWhiteList { if in == nil { return nil } out := new(IPWhiteList) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *InFlightReq) DeepCopyInto(out *InFlightReq) { *out = *in if in.SourceCriterion != nil { in, out := &in.SourceCriterion, &out.SourceCriterion *out = new(SourceCriterion) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new InFlightReq. func (in *InFlightReq) DeepCopy() *InFlightReq { if in == nil { return nil } out := new(InFlightReq) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Message) DeepCopyInto(out *Message) { *out = *in if in.Configuration != nil { in, out := &in.Configuration, &out.Configuration *out = new(Configuration) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Message. func (in *Message) DeepCopy() *Message { if in == nil { return nil } out := new(Message) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Middleware) DeepCopyInto(out *Middleware) { *out = *in if in.AddPrefix != nil { in, out := &in.AddPrefix, &out.AddPrefix *out = new(AddPrefix) **out = **in } if in.StripPrefix != nil { in, out := &in.StripPrefix, &out.StripPrefix *out = new(StripPrefix) (*in).DeepCopyInto(*out) } if in.StripPrefixRegex != nil { in, out := &in.StripPrefixRegex, &out.StripPrefixRegex *out = new(StripPrefixRegex) (*in).DeepCopyInto(*out) } if in.ReplacePath != nil { in, out := &in.ReplacePath, &out.ReplacePath *out = new(ReplacePath) **out = **in } if in.ReplacePathRegex != nil { in, out := &in.ReplacePathRegex, &out.ReplacePathRegex *out = new(ReplacePathRegex) **out = **in } if in.Chain != nil { in, out := &in.Chain, &out.Chain *out = new(Chain) (*in).DeepCopyInto(*out) } if in.IPWhiteList != nil { in, out := &in.IPWhiteList, &out.IPWhiteList *out = new(IPWhiteList) (*in).DeepCopyInto(*out) } if in.IPAllowList != nil { in, out := &in.IPAllowList, &out.IPAllowList *out = new(IPAllowList) (*in).DeepCopyInto(*out) } if in.Headers != nil { in, out := &in.Headers, &out.Headers *out = new(Headers) (*in).DeepCopyInto(*out) } if in.Errors != nil { in, out := &in.Errors, &out.Errors *out = new(ErrorPage) (*in).DeepCopyInto(*out) } if in.RateLimit != nil { in, out := &in.RateLimit, &out.RateLimit *out = new(RateLimit) (*in).DeepCopyInto(*out) } if in.RedirectRegex != nil { in, out := &in.RedirectRegex, &out.RedirectRegex *out = new(RedirectRegex) **out = **in } if in.RedirectScheme != nil { in, out := &in.RedirectScheme, &out.RedirectScheme *out = new(RedirectScheme) **out = **in } if in.BasicAuth != nil { in, out := &in.BasicAuth, &out.BasicAuth *out = new(BasicAuth) (*in).DeepCopyInto(*out) } if in.DigestAuth != nil { in, out := &in.DigestAuth, &out.DigestAuth *out = new(DigestAuth) (*in).DeepCopyInto(*out) } if in.ForwardAuth != nil { in, out := &in.ForwardAuth, &out.ForwardAuth *out = new(ForwardAuth) (*in).DeepCopyInto(*out) } if in.InFlightReq != nil { in, out := &in.InFlightReq, &out.InFlightReq *out = new(InFlightReq) (*in).DeepCopyInto(*out) } if in.Buffering != nil { in, out := &in.Buffering, &out.Buffering *out = new(Buffering) **out = **in } if in.CircuitBreaker != nil { in, out := &in.CircuitBreaker, &out.CircuitBreaker *out = new(CircuitBreaker) **out = **in } if in.Compress != nil { in, out := &in.Compress, &out.Compress *out = new(Compress) (*in).DeepCopyInto(*out) } if in.PassTLSClientCert != nil { in, out := &in.PassTLSClientCert, &out.PassTLSClientCert *out = new(PassTLSClientCert) (*in).DeepCopyInto(*out) } if in.Retry != nil { in, out := &in.Retry, &out.Retry *out = new(Retry) **out = **in } if in.ContentType != nil { in, out := &in.ContentType, &out.ContentType *out = new(ContentType) (*in).DeepCopyInto(*out) } if in.GrpcWeb != nil { in, out := &in.GrpcWeb, &out.GrpcWeb *out = new(GrpcWeb) (*in).DeepCopyInto(*out) } if in.Plugin != nil { in, out := &in.Plugin, &out.Plugin *out = make(map[string]PluginConf, len(*in)) for key, val := range *in { (*out)[key] = *val.DeepCopy() } } if in.RequestHeaderModifier != nil { in, out := &in.RequestHeaderModifier, &out.RequestHeaderModifier *out = new(HeaderModifier) (*in).DeepCopyInto(*out) } if in.ResponseHeaderModifier != nil { in, out := &in.ResponseHeaderModifier, &out.ResponseHeaderModifier *out = new(HeaderModifier) (*in).DeepCopyInto(*out) } if in.RequestRedirect != nil { in, out := &in.RequestRedirect, &out.RequestRedirect *out = new(RequestRedirect) (*in).DeepCopyInto(*out) } if in.URLRewrite != nil { in, out := &in.URLRewrite, &out.URLRewrite *out = new(URLRewrite) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Middleware. func (in *Middleware) DeepCopy() *Middleware { if in == nil { return nil } out := new(Middleware) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MirrorService) DeepCopyInto(out *MirrorService) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MirrorService. func (in *MirrorService) DeepCopy() *MirrorService { if in == nil { return nil } out := new(MirrorService) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Mirroring) DeepCopyInto(out *Mirroring) { *out = *in if in.MirrorBody != nil { in, out := &in.MirrorBody, &out.MirrorBody *out = new(bool) **out = **in } if in.MaxBodySize != nil { in, out := &in.MaxBodySize, &out.MaxBodySize *out = new(int64) **out = **in } if in.Mirrors != nil { in, out := &in.Mirrors, &out.Mirrors *out = make([]MirrorService, len(*in)) copy(*out, *in) } if in.HealthCheck != nil { in, out := &in.HealthCheck, &out.HealthCheck *out = new(HealthCheck) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Mirroring. func (in *Mirroring) DeepCopy() *Mirroring { if in == nil { return nil } out := new(Mirroring) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Model) DeepCopyInto(out *Model) { *out = *in if in.Middlewares != nil { in, out := &in.Middlewares, &out.Middlewares *out = make([]string, len(*in)) copy(*out, *in) } if in.TLS != nil { in, out := &in.TLS, &out.TLS *out = new(RouterTLSConfig) (*in).DeepCopyInto(*out) } in.Observability.DeepCopyInto(&out.Observability) if in.DeniedEncodedPathCharacters != nil { in, out := &in.DeniedEncodedPathCharacters, &out.DeniedEncodedPathCharacters *out = new(RouterDeniedEncodedPathCharacters) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Model. func (in *Model) DeepCopy() *Model { if in == nil { return nil } out := new(Model) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PassTLSClientCert) DeepCopyInto(out *PassTLSClientCert) { *out = *in if in.Info != nil { in, out := &in.Info, &out.Info *out = new(TLSClientCertificateInfo) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PassTLSClientCert. func (in *PassTLSClientCert) DeepCopy() *PassTLSClientCert { if in == nil { return nil } out := new(PassTLSClientCert) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PassiveServerHealthCheck) DeepCopyInto(out *PassiveServerHealthCheck) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PassiveServerHealthCheck. func (in *PassiveServerHealthCheck) DeepCopy() *PassiveServerHealthCheck { if in == nil { return nil } out := new(PassiveServerHealthCheck) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ProxyProtocol) DeepCopyInto(out *ProxyProtocol) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProxyProtocol. func (in *ProxyProtocol) DeepCopy() *ProxyProtocol { if in == nil { return nil } out := new(ProxyProtocol) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RateLimit) DeepCopyInto(out *RateLimit) { *out = *in if in.SourceCriterion != nil { in, out := &in.SourceCriterion, &out.SourceCriterion *out = new(SourceCriterion) (*in).DeepCopyInto(*out) } if in.Redis != nil { in, out := &in.Redis, &out.Redis *out = new(Redis) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RateLimit. func (in *RateLimit) DeepCopy() *RateLimit { if in == nil { return nil } out := new(RateLimit) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RedirectRegex) DeepCopyInto(out *RedirectRegex) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RedirectRegex. func (in *RedirectRegex) DeepCopy() *RedirectRegex { if in == nil { return nil } out := new(RedirectRegex) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RedirectScheme) DeepCopyInto(out *RedirectScheme) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RedirectScheme. func (in *RedirectScheme) DeepCopy() *RedirectScheme { if in == nil { return nil } out := new(RedirectScheme) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true