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/chain/chain.go | pkg/middlewares/chain/chain.go | package chain
import (
"context"
"net/http"
"github.com/containous/alice"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
)
const (
typeName = "Chain"
)
type chainBuilder interface {
BuildChain(ctx context.Context, middlewares []string) *alice.Chain
}
// New creates a chain middleware.
func New(ctx context.Context, next http.Handler, config dynamic.Chain, builder chainBuilder, name string) (http.Handler, error) {
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
middlewareChain := builder.BuildChain(ctx, config.Middlewares)
return middlewareChain.Then(next)
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/auth/connectionheader_test.go | pkg/middlewares/auth/connectionheader_test.go | package auth
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRemover(t *testing.T) {
testCases := []struct {
desc string
reqHeaders map[string]string
expected http.Header
}{
{
desc: "simple remove",
reqHeaders: map[string]string{
"Foo": "bar",
connectionHeader: "foo",
},
expected: http.Header{},
},
{
desc: "remove and Upgrade",
reqHeaders: map[string]string{
upgradeHeader: "test",
"Foo": "bar",
connectionHeader: "Upgrade,foo",
},
expected: http.Header{
upgradeHeader: []string{"test"},
connectionHeader: []string{"Upgrade"},
},
},
{
desc: "no remove",
reqHeaders: map[string]string{
"Foo": "bar",
connectionHeader: "fii",
},
expected: http.Header{
"Foo": []string{"bar"},
},
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
req := httptest.NewRequest(http.MethodGet, "https://localhost", nil)
for k, v := range test.reqHeaders {
req.Header.Set(k, v)
}
RemoveConnectionHeaders(req)
assert.Equal(t, test.expected, req.Header)
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/auth/forward.go | pkg/middlewares/auth/forward.go | package auth
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/middlewares/accesslog"
"github.com/traefik/traefik/v3/pkg/middlewares/observability"
"github.com/traefik/traefik/v3/pkg/observability/tracing"
"github.com/traefik/traefik/v3/pkg/proxy/httputil"
"github.com/traefik/traefik/v3/pkg/types"
"github.com/vulcand/oxy/v2/forward"
"github.com/vulcand/oxy/v2/utils"
"go.opentelemetry.io/otel/trace"
)
const typeNameForward = "ForwardAuth"
const (
xForwardedURI = "X-Forwarded-Uri"
xForwardedMethod = "X-Forwarded-Method"
)
// hopHeaders Hop-by-hop headers to be removed in the authentication request.
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
// Proxy-Authorization header is forwarded to the authentication server (see https://tools.ietf.org/html/rfc7235#section-4.4).
var hopHeaders = []string{
forward.Connection,
forward.KeepAlive,
forward.Te, // canonicalized version of "TE"
forward.Trailers,
forward.TransferEncoding,
forward.Upgrade,
}
type forwardAuth struct {
address string
authResponseHeaders []string
authResponseHeadersRegex *regexp.Regexp
next http.Handler
name string
client http.Client
trustForwardHeader bool
authRequestHeaders []string
addAuthCookiesToResponse map[string]struct{}
headerField string
forwardBody bool
maxBodySize int64
preserveLocationHeader bool
preserveRequestMethod bool
}
// NewForward creates a forward auth middleware.
func NewForward(ctx context.Context, next http.Handler, config dynamic.ForwardAuth, name string) (http.Handler, error) {
logger := middlewares.GetLogger(ctx, name, typeNameForward)
logger.Debug().Msg("Creating middleware")
addAuthCookiesToResponse := make(map[string]struct{})
for _, cookieName := range config.AddAuthCookiesToResponse {
addAuthCookiesToResponse[cookieName] = struct{}{}
}
fa := &forwardAuth{
address: config.Address,
authResponseHeaders: config.AuthResponseHeaders,
next: next,
name: name,
trustForwardHeader: config.TrustForwardHeader,
authRequestHeaders: config.AuthRequestHeaders,
addAuthCookiesToResponse: addAuthCookiesToResponse,
headerField: config.HeaderField,
forwardBody: config.ForwardBody,
maxBodySize: dynamic.ForwardAuthDefaultMaxBodySize,
preserveLocationHeader: config.PreserveLocationHeader,
preserveRequestMethod: config.PreserveRequestMethod,
}
if config.MaxBodySize != nil {
fa.maxBodySize = *config.MaxBodySize
} else if fa.forwardBody {
logger.Warn().Msgf("ForwardAuth 'maxBodySize' is not configured with 'forwardBody: true', allowing unlimited request body size which can lead to DoS attacks and memory exhaustion. Please set an appropriate limit.")
}
// Ensure our request client does not follow redirects
fa.client = http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Timeout: 30 * time.Second,
}
if config.TLS != nil {
if config.TLS.CAOptional != nil {
logger.Warn().Msg("CAOptional option is deprecated, TLS client authentication is a server side option, please remove any usage of this option.")
}
clientTLS := &types.ClientTLS{
CA: config.TLS.CA,
Cert: config.TLS.Cert,
Key: config.TLS.Key,
InsecureSkipVerify: config.TLS.InsecureSkipVerify,
}
tlsConfig, err := clientTLS.CreateTLSConfig(ctx)
if err != nil {
return nil, fmt.Errorf("unable to create client TLS configuration: %w", err)
}
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.TLSClientConfig = tlsConfig
fa.client.Transport = tr
}
if config.AuthResponseHeadersRegex != "" {
re, err := regexp.Compile(config.AuthResponseHeadersRegex)
if err != nil {
return nil, fmt.Errorf("error compiling regular expression %s: %w", config.AuthResponseHeadersRegex, err)
}
fa.authResponseHeadersRegex = re
}
return fa, nil
}
func (fa *forwardAuth) GetTracingInformation() (string, string) {
return fa.name, typeNameForward
}
func (fa *forwardAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
logger := middlewares.GetLogger(req.Context(), fa.name, typeNameForward)
forwardReqMethod := http.MethodGet
if fa.preserveRequestMethod {
forwardReqMethod = req.Method
}
forwardReq, err := http.NewRequestWithContext(req.Context(), forwardReqMethod, fa.address, nil)
if err != nil {
logger.Debug().Err(err).Msgf("Error calling %s", fa.address)
observability.SetStatusErrorf(req.Context(), "Error calling %s. Cause %s", fa.address, err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
if fa.forwardBody {
bodyBytes, err := fa.readBodyBytes(req)
if errors.Is(err, errBodyTooLarge) {
logger.Debug().Msgf("Request body is too large, maxBodySize: %d", fa.maxBodySize)
observability.SetStatusErrorf(req.Context(), "Request body is too large, maxBodySize: %d", fa.maxBodySize)
rw.WriteHeader(http.StatusUnauthorized)
return
}
if err != nil {
logger.Debug().Err(err).Msg("Error while reading body")
observability.SetStatusErrorf(req.Context(), "Error while reading Body: %s", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
// bodyBytes is nil when the request has no body.
if bodyBytes != nil {
req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
forwardReq.Body = io.NopCloser(bytes.NewReader(bodyBytes))
}
}
writeHeader(req, forwardReq, fa.trustForwardHeader, fa.authRequestHeaders)
var forwardSpan trace.Span
var tracer *tracing.Tracer
if tracer = tracing.TracerFromContext(req.Context()); tracer != nil && observability.TracingEnabled(req.Context()) {
var tracingCtx context.Context
tracingCtx, forwardSpan = tracer.Start(req.Context(), "AuthRequest", trace.WithSpanKind(trace.SpanKindClient))
defer forwardSpan.End()
forwardReq = forwardReq.WithContext(tracingCtx)
tracing.InjectContextIntoCarrier(forwardReq)
tracer.CaptureClientRequest(forwardSpan, forwardReq)
}
forwardResponse, forwardErr := fa.client.Do(forwardReq)
if forwardErr != nil {
logger.Error().Err(forwardErr).Msgf("Error calling %s", fa.address)
observability.SetStatusErrorf(req.Context(), "Error calling %s. Cause: %s", fa.address, forwardErr)
statusCode := http.StatusInternalServerError
if errors.Is(forwardErr, context.Canceled) {
statusCode = httputil.StatusClientClosedRequest
}
rw.WriteHeader(statusCode)
return
}
defer forwardResponse.Body.Close()
body, readError := io.ReadAll(forwardResponse.Body)
if readError != nil {
logger.Debug().Err(readError).Msgf("Error reading body %s", fa.address)
observability.SetStatusErrorf(req.Context(), "Error reading body %s. Cause: %s", fa.address, readError)
rw.WriteHeader(http.StatusInternalServerError)
return
}
// Ending the forward request span as soon as the response is handled.
// If any errors happen earlier, this span will be close by the defer instruction.
if forwardSpan != nil {
forwardSpan.End()
}
if fa.headerField != "" {
if elems := forwardResponse.Header[http.CanonicalHeaderKey(fa.headerField)]; len(elems) > 0 {
logData := accesslog.GetLogData(req)
if logData != nil {
logData.Core[accesslog.ClientUsername] = elems[0]
}
}
}
// Pass the forward response's body and selected headers if it
// didn't return a response within the range of [200, 300).
if forwardResponse.StatusCode < http.StatusOK || forwardResponse.StatusCode >= http.StatusMultipleChoices {
logger.Debug().Msgf("Remote error %s. StatusCode: %d", fa.address, forwardResponse.StatusCode)
utils.CopyHeaders(rw.Header(), forwardResponse.Header)
utils.RemoveHeaders(rw.Header(), hopHeaders...)
redirectURL, err := fa.redirectURL(forwardResponse)
if err != nil {
if !errors.Is(err, http.ErrNoLocation) {
logger.Debug().Err(err).Msgf("Error reading response location header %s", fa.address)
observability.SetStatusErrorf(req.Context(), "Error reading response location header %s. Cause: %s", fa.address, err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
} else if redirectURL.String() != "" {
// Set the location in our response if one was sent back.
rw.Header().Set("Location", redirectURL.String())
}
tracer.CaptureResponse(forwardSpan, forwardResponse.Header, forwardResponse.StatusCode, trace.SpanKindClient)
rw.WriteHeader(forwardResponse.StatusCode)
if _, err = rw.Write(body); err != nil {
logger.Error().Err(err).Send()
}
return
}
for _, headerName := range fa.authResponseHeaders {
headerKey := http.CanonicalHeaderKey(headerName)
req.Header.Del(headerKey)
if len(forwardResponse.Header[headerKey]) > 0 {
req.Header[headerKey] = append([]string(nil), forwardResponse.Header[headerKey]...)
}
}
if fa.authResponseHeadersRegex != nil {
for headerKey := range req.Header {
if fa.authResponseHeadersRegex.MatchString(headerKey) {
req.Header.Del(headerKey)
}
}
for headerKey, headerValues := range forwardResponse.Header {
if fa.authResponseHeadersRegex.MatchString(headerKey) {
req.Header[headerKey] = append([]string(nil), headerValues...)
}
}
}
tracer.CaptureResponse(forwardSpan, forwardResponse.Header, forwardResponse.StatusCode, trace.SpanKindClient)
req.RequestURI = req.URL.RequestURI()
authCookies := forwardResponse.Cookies()
if len(authCookies) == 0 {
fa.next.ServeHTTP(rw, req)
return
}
fa.next.ServeHTTP(middlewares.NewResponseModifier(rw, req, fa.buildModifier(authCookies)), req)
}
func (fa *forwardAuth) redirectURL(forwardResponse *http.Response) (*url.URL, error) {
if !fa.preserveLocationHeader {
return forwardResponse.Location()
}
// Preserve the Location header if it exists.
if lv := forwardResponse.Header.Get("Location"); lv != "" {
return url.Parse(lv)
}
return nil, http.ErrNoLocation
}
func (fa *forwardAuth) buildModifier(authCookies []*http.Cookie) func(res *http.Response) error {
return func(res *http.Response) error {
cookies := res.Cookies()
res.Header.Del("Set-Cookie")
for _, cookie := range cookies {
if _, found := fa.addAuthCookiesToResponse[cookie.Name]; !found {
res.Header.Add("Set-Cookie", cookie.String())
}
}
for _, cookie := range authCookies {
if _, found := fa.addAuthCookiesToResponse[cookie.Name]; found {
res.Header.Add("Set-Cookie", cookie.String())
}
}
return nil
}
}
var errBodyTooLarge = errors.New("request body too large")
func (fa *forwardAuth) readBodyBytes(req *http.Request) ([]byte, error) {
if fa.maxBodySize < 0 {
return io.ReadAll(req.Body)
}
body := make([]byte, fa.maxBodySize+1)
n, err := io.ReadFull(req.Body, body)
if errors.Is(err, io.EOF) {
return nil, nil
}
if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) {
return nil, fmt.Errorf("reading body bytes: %w", err)
}
if errors.Is(err, io.ErrUnexpectedEOF) {
return body[:n], nil
}
return nil, errBodyTooLarge
}
func writeHeader(req, forwardReq *http.Request, trustForwardHeader bool, allowedHeaders []string) {
utils.CopyHeaders(forwardReq.Header, req.Header)
RemoveConnectionHeaders(forwardReq)
utils.RemoveHeaders(forwardReq.Header, hopHeaders...)
forwardReq.Header = filterForwardRequestHeaders(forwardReq.Header, allowedHeaders)
if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
if trustForwardHeader {
if prior, ok := req.Header[forward.XForwardedFor]; ok {
clientIP = strings.Join(prior, ", ") + ", " + clientIP
}
}
forwardReq.Header.Set(forward.XForwardedFor, clientIP)
}
xMethod := req.Header.Get(xForwardedMethod)
switch {
case xMethod != "" && trustForwardHeader:
forwardReq.Header.Set(xForwardedMethod, xMethod)
case req.Method != "":
forwardReq.Header.Set(xForwardedMethod, req.Method)
default:
forwardReq.Header.Del(xForwardedMethod)
}
xfp := req.Header.Get(forward.XForwardedProto)
switch {
case xfp != "" && trustForwardHeader:
forwardReq.Header.Set(forward.XForwardedProto, xfp)
case req.TLS != nil:
forwardReq.Header.Set(forward.XForwardedProto, "https")
default:
forwardReq.Header.Set(forward.XForwardedProto, "http")
}
if xfp := req.Header.Get(forward.XForwardedPort); xfp != "" && trustForwardHeader {
forwardReq.Header.Set(forward.XForwardedPort, xfp)
}
xfh := req.Header.Get(forward.XForwardedHost)
switch {
case xfh != "" && trustForwardHeader:
forwardReq.Header.Set(forward.XForwardedHost, xfh)
case req.Host != "":
forwardReq.Header.Set(forward.XForwardedHost, req.Host)
default:
forwardReq.Header.Del(forward.XForwardedHost)
}
xfURI := req.Header.Get(xForwardedURI)
switch {
case xfURI != "" && trustForwardHeader:
forwardReq.Header.Set(xForwardedURI, xfURI)
case req.URL.RequestURI() != "":
forwardReq.Header.Set(xForwardedURI, req.URL.RequestURI())
default:
forwardReq.Header.Del(xForwardedURI)
}
}
func filterForwardRequestHeaders(forwardRequestHeaders http.Header, allowedHeaders []string) http.Header {
if len(allowedHeaders) == 0 {
return forwardRequestHeaders
}
filteredHeaders := http.Header{}
for _, headerName := range allowedHeaders {
values := forwardRequestHeaders.Values(headerName)
if len(values) > 0 {
filteredHeaders[http.CanonicalHeaderKey(headerName)] = append([]string(nil), values...)
}
}
return filteredHeaders
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/auth/digest_auth_test.go | pkg/middlewares/auth/digest_auth_test.go | package auth
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"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/testhelpers"
)
func TestDigestAuthError(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "traefik")
})
auth := dynamic.DigestAuth{
Users: []string{"test"},
}
_, err := NewDigest(t.Context(), next, auth, "authName")
assert.Error(t, err)
}
func TestDigestAuthFail(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "traefik")
})
auth := dynamic.DigestAuth{
Users: []string{"test:traefik:a2688e031edb4be6a3797f3882655c05"},
}
authMiddleware, err := NewDigest(t.Context(), next, auth, "authName")
require.NoError(t, err)
assert.NotNil(t, authMiddleware, "this should not be nil")
ts := httptest.NewServer(authMiddleware)
defer ts.Close()
client := http.DefaultClient
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
req.SetBasicAuth("test", "test")
res, err := client.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusUnauthorized, res.StatusCode)
}
func TestDigestAuthUsersFromFile(t *testing.T) {
testCases := []struct {
desc string
userFileContent string
expectedUsers map[string]string
givenUsers []string
realm string
}{
{
desc: "Finds the users in the file",
userFileContent: "test:traefik:a2688e031edb4be6a3797f3882655c05\ntest2:traefik:518845800f9e2bfb1f1f740ec24f074e\n",
givenUsers: []string{},
expectedUsers: map[string]string{"test": "test", "test2": "test2"},
},
{
desc: "Merges given users with users from the file",
userFileContent: "test:traefik:a2688e031edb4be6a3797f3882655c05\n",
givenUsers: []string{"test2:traefik:518845800f9e2bfb1f1f740ec24f074e", "test3:traefik:c8e9f57ce58ecb4424407f665a91646c"},
expectedUsers: map[string]string{"test": "test", "test2": "test2", "test3": "test3"},
},
{
desc: "Given users have priority over users in the file",
userFileContent: "test:traefik:a2688e031edb4be6a3797f3882655c05\ntest2:traefik:518845800f9e2bfb1f1f740ec24f074e\n",
givenUsers: []string{"test2:traefik:8de60a1c52da68ccf41f0c0ffb7c51a0"},
expectedUsers: map[string]string{"test": "test", "test2": "overridden"},
},
{
desc: "Should authenticate the correct user based on the realm",
userFileContent: "test:traefik:a2688e031edb4be6a3797f3882655c05\ntest:traefiker:a3d334dff2645b914918de78bec50bf4\n",
givenUsers: []string{},
expectedUsers: map[string]string{"test": "test2"},
realm: "traefiker",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
// Creates the temporary configuration file with the users
usersFile, err := os.CreateTemp(t.TempDir(), "auth-users")
require.NoError(t, err)
_, err = usersFile.WriteString(test.userFileContent)
require.NoError(t, err)
// Creates the configuration for our Authenticator
authenticatorConfiguration := dynamic.DigestAuth{
Users: test.givenUsers,
UsersFile: usersFile.Name(),
Realm: test.realm,
}
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "traefik")
})
authenticator, err := NewDigest(t.Context(), next, authenticatorConfiguration, "authName")
require.NoError(t, err)
ts := httptest.NewServer(authenticator)
defer ts.Close()
for userName, userPwd := range test.expectedUsers {
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
digestRequest := newDigestRequest(userName, userPwd, http.DefaultClient)
var res *http.Response
res, err = digestRequest.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusOK, res.StatusCode, "Cannot authenticate user "+userName)
var body []byte
body, err = io.ReadAll(res.Body)
require.NoError(t, err)
err = res.Body.Close()
require.NoError(t, err)
require.Equal(t, "traefik\n", string(body))
}
// Checks that user foo doesn't work
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
digestRequest := newDigestRequest("foo", "foo", http.DefaultClient)
var res *http.Response
res, err = digestRequest.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusUnauthorized, res.StatusCode)
var body []byte
body, err = io.ReadAll(res.Body)
require.NoError(t, err)
err = res.Body.Close()
require.NoError(t, err)
require.NotContains(t, "traefik", string(body))
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/auth/digest_auth.go | pkg/middlewares/auth/digest_auth.go | package auth
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
goauth "github.com/abbot/go-http-auth"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/middlewares/accesslog"
"github.com/traefik/traefik/v3/pkg/middlewares/observability"
)
const (
typeNameDigest = "digestAuth"
)
type digestAuth struct {
next http.Handler
auth *goauth.DigestAuth
users map[string]string
headerField string
removeHeader bool
name string
}
// NewDigest creates a digest auth middleware.
func NewDigest(ctx context.Context, next http.Handler, authConfig dynamic.DigestAuth, name string) (http.Handler, error) {
middlewares.GetLogger(ctx, name, typeNameDigest).Debug().Msg("Creating middleware")
users, err := getUsers(authConfig.UsersFile, authConfig.Users, digestUserParser)
if err != nil {
return nil, err
}
da := &digestAuth{
next: next,
users: users,
headerField: authConfig.HeaderField,
removeHeader: authConfig.RemoveHeader,
name: name,
}
realm := defaultRealm
if len(authConfig.Realm) > 0 {
realm = authConfig.Realm
}
da.auth = goauth.NewDigestAuthenticator(realm, da.secretDigest)
return da, nil
}
func (d *digestAuth) GetTracingInformation() (string, string) {
return d.name, typeNameDigest
}
func (d *digestAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
logger := middlewares.GetLogger(req.Context(), d.name, typeNameDigest)
username, authinfo := d.auth.CheckAuth(req)
if username == "" {
headerField := d.headerField
if d.headerField == "" {
headerField = "Authorization"
}
auth := goauth.DigestAuthParams(req.Header.Get(headerField))
if auth["username"] != "" {
logData := accesslog.GetLogData(req)
if logData != nil {
logData.Core[accesslog.ClientUsername] = auth["username"]
}
}
if authinfo != nil && *authinfo == "stale" {
logger.Debug().Msg("Digest authentication failed, possibly because out of order requests")
observability.SetStatusErrorf(req.Context(), "Digest authentication failed, possibly because out of order requests")
d.auth.RequireAuthStale(rw, req)
return
}
logger.Debug().Msg("Digest authentication failed")
observability.SetStatusErrorf(req.Context(), "Digest authentication failed")
d.auth.RequireAuth(rw, req)
return
}
logger.Debug().Msg("Digest authentication succeeded")
req.URL.User = url.User(username)
logData := accesslog.GetLogData(req)
if logData != nil {
logData.Core[accesslog.ClientUsername] = username
}
if d.headerField != "" {
req.Header[d.headerField] = []string{username}
}
if d.removeHeader {
logger.Debug().Msg("Removing the Authorization header")
req.Header.Del(authorizationHeader)
}
d.next.ServeHTTP(rw, req)
}
func (d *digestAuth) secretDigest(user, realm string) string {
if secret, ok := d.users[user+":"+realm]; ok {
return secret
}
return ""
}
func digestUserParser(user string) (string, string, error) {
split := strings.Split(user, ":")
if len(split) != 3 {
return "", "", fmt.Errorf("error parsing DigestUser: %v", user)
}
return split[0] + ":" + split[1], split[2], nil
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/auth/digest_auth_request_test.go | pkg/middlewares/auth/digest_auth_request_test.go | package auth
import (
"crypto/md5"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"net/http"
"strings"
)
const (
algorithm = "algorithm"
authorization = "Authorization"
nonce = "nonce"
opaque = "opaque"
qop = "qop"
realm = "realm"
wwwAuthenticate = "Www-Authenticate"
)
// DigestRequest is a client for digest authentication requests.
type digestRequest struct {
client *http.Client
username, password string
nonceCount nonceCount
}
type nonceCount int
func (nc nonceCount) String() string {
return fmt.Sprintf("%08x", int(nc))
}
var wanted = []string{algorithm, nonce, opaque, qop, realm}
// New makes a DigestRequest instance.
func newDigestRequest(username, password string, client *http.Client) *digestRequest {
return &digestRequest{
client: client,
username: username,
password: password,
}
}
// Do does requests as http.Do does.
func (r *digestRequest) Do(req *http.Request) (*http.Response, error) {
parts, err := r.makeParts(req)
if err != nil {
return nil, err
}
if parts != nil {
req.Header.Set(authorization, r.makeAuthorization(req, parts))
}
return r.client.Do(req)
}
func (r *digestRequest) makeParts(req *http.Request) (map[string]string, error) {
authReq, err := http.NewRequest(req.Method, req.URL.String(), nil)
if err != nil {
return nil, err
}
resp, err := r.client.Do(authReq)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
return nil, nil
}
if len(resp.Header[wwwAuthenticate]) == 0 {
return nil, fmt.Errorf("headers do not have %s", wwwAuthenticate)
}
headers := strings.Split(resp.Header[wwwAuthenticate][0], ",")
parts := make(map[string]string, len(wanted))
for _, r := range headers {
for _, w := range wanted {
if strings.Contains(r, w) {
parts[w] = strings.Split(r, `"`)[1]
}
}
}
if len(parts) != len(wanted) {
return nil, fmt.Errorf("header is invalid: %+v", parts)
}
return parts, nil
}
func getMD5(texts []string) string {
h := md5.New()
_, _ = io.WriteString(h, strings.Join(texts, ":"))
return hex.EncodeToString(h.Sum(nil))
}
func (r *digestRequest) getNonceCount() string {
r.nonceCount++
return r.nonceCount.String()
}
func (r *digestRequest) makeAuthorization(req *http.Request, parts map[string]string) string {
ha1 := getMD5([]string{r.username, parts[realm], r.password})
ha2 := getMD5([]string{req.Method, req.URL.String()})
cnonce := generateRandom(16)
nc := r.getNonceCount()
response := getMD5([]string{
ha1,
parts[nonce],
nc,
cnonce,
parts[qop],
ha2,
})
return fmt.Sprintf(
`Digest username="%s", realm="%s", nonce="%s", uri="%s", algorithm=%s, qop=%s, nc=%s, cnonce="%s", response="%s", opaque="%s"`,
r.username,
parts[realm],
parts[nonce],
req.URL.String(),
parts[algorithm],
parts[qop],
nc,
cnonce,
response,
parts[opaque],
)
}
// GenerateRandom generates random string.
func generateRandom(n int) string {
b := make([]byte, 8)
_, _ = io.ReadFull(rand.Reader, b)
return hex.EncodeToString(b)[:n]
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/auth/connectionheader.go | pkg/middlewares/auth/connectionheader.go | package auth
import (
"net/http"
"net/textproto"
"strings"
"golang.org/x/net/http/httpguts"
)
const (
connectionHeader = "Connection"
upgradeHeader = "Upgrade"
)
// RemoveConnectionHeaders removes hop-by-hop headers listed in the "Connection" header.
// See RFC 7230, section 6.1.
func RemoveConnectionHeaders(req *http.Request) {
var reqUpType string
if httpguts.HeaderValuesContainsToken(req.Header[connectionHeader], upgradeHeader) {
reqUpType = req.Header.Get(upgradeHeader)
}
for _, f := range req.Header[connectionHeader] {
for _, sf := range strings.Split(f, ",") {
if sf = textproto.TrimString(sf); sf != "" {
req.Header.Del(sf)
}
}
}
if reqUpType != "" {
req.Header.Set(connectionHeader, upgradeHeader)
req.Header.Set(upgradeHeader, reqUpType)
} else {
req.Header.Del(connectionHeader)
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/auth/basic_auth_test.go | pkg/middlewares/auth/basic_auth_test.go | package auth
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"sync"
"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/testhelpers"
)
func TestBasicAuthFail(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "traefik")
})
auth := dynamic.BasicAuth{
Users: []string{"test"},
}
_, err := NewBasic(t.Context(), next, auth, "authName")
require.Error(t, err)
auth2 := dynamic.BasicAuth{
Users: []string{"test:test"},
}
authMiddleware, err := NewBasic(t.Context(), next, auth2, "authTest")
require.NoError(t, err)
ts := httptest.NewServer(authMiddleware)
defer ts.Close()
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
req.SetBasicAuth("test", "test")
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusUnauthorized, res.StatusCode, "they should be equal")
}
func TestBasicAuthSuccess(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "traefik")
})
auth := dynamic.BasicAuth{
Users: []string{"test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/"},
}
authMiddleware, err := NewBasic(t.Context(), next, auth, "authName")
require.NoError(t, err)
ts := httptest.NewServer(authMiddleware)
defer ts.Close()
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
req.SetBasicAuth("test", "test")
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode, "they should be equal")
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
defer res.Body.Close()
assert.Equal(t, "traefik\n", string(body), "they should be equal")
}
func TestBasicAuthUserHeader(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "test", r.Header["X-Webauth-User"][0], "auth user should be set")
fmt.Fprintln(w, "traefik")
})
auth := dynamic.BasicAuth{
Users: []string{"test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/"},
HeaderField: "X-Webauth-User",
}
middleware, err := NewBasic(t.Context(), next, auth, "authName")
require.NoError(t, err)
ts := httptest.NewServer(middleware)
defer ts.Close()
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
req.SetBasicAuth("test", "test")
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
defer res.Body.Close()
assert.Equal(t, "traefik\n", string(body))
}
func TestBasicAuthHeaderRemoved(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Empty(t, r.Header.Get(authorizationHeader))
fmt.Fprintln(w, "traefik")
})
auth := dynamic.BasicAuth{
RemoveHeader: true,
Users: []string{"test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/"},
}
middleware, err := NewBasic(t.Context(), next, auth, "authName")
require.NoError(t, err)
ts := httptest.NewServer(middleware)
defer ts.Close()
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
req.SetBasicAuth("test", "test")
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
err = res.Body.Close()
require.NoError(t, err)
assert.Equal(t, "traefik\n", string(body))
}
func TestBasicAuthHeaderPresent(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.NotEmpty(t, r.Header.Get(authorizationHeader))
fmt.Fprintln(w, "traefik")
})
auth := dynamic.BasicAuth{
Users: []string{"test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/"},
}
middleware, err := NewBasic(t.Context(), next, auth, "authName")
require.NoError(t, err)
ts := httptest.NewServer(middleware)
defer ts.Close()
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
req.SetBasicAuth("test", "test")
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
err = res.Body.Close()
require.NoError(t, err)
assert.Equal(t, "traefik\n", string(body))
}
func TestBasicAuthConcurrentHashOnce(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "traefik")
})
auth := dynamic.BasicAuth{
Users: []string{"test:$2a$04$.8sTYfcxbSplCtoxt5TdJOgpBYkarKtZYsYfYxQ1edbYRuO1DNi0e"},
}
authMiddleware, err := NewBasic(t.Context(), next, auth, "authName")
require.NoError(t, err)
hashCount := 0
ba := authMiddleware.(*basicAuth)
ba.checkSecret = func(password, secret string) bool {
hashCount++
// delay to ensure the second request arrives
time.Sleep(time.Millisecond)
return true
}
ts := httptest.NewServer(authMiddleware)
defer ts.Close()
var wg sync.WaitGroup
wg.Add(2)
for range 2 {
go func() {
defer wg.Done()
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
req.SetBasicAuth("test", "test")
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer res.Body.Close()
assert.Equal(t, http.StatusOK, res.StatusCode, "they should be equal")
}()
}
wg.Wait()
assert.Equal(t, 1, hashCount)
}
func TestBasicAuthUsersFromFile(t *testing.T) {
testCases := []struct {
desc string
userFileContent string
expectedUsers map[string]string
givenUsers []string
realm string
}{
{
desc: "Finds the users in the file",
userFileContent: "test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/\ntest2:$apr1$d9hr9HBB$4HxwgUir3HP4EsggP/QNo0\n",
givenUsers: []string{},
expectedUsers: map[string]string{"test": "test", "test2": "test2"},
},
{
desc: "Merges given users with users from the file",
userFileContent: "test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/\n",
givenUsers: []string{"test2:$apr1$d9hr9HBB$4HxwgUir3HP4EsggP/QNo0", "test3:$apr1$3rJbDP0q$RfzJiorTk78jQ1EcKqWso0"},
expectedUsers: map[string]string{"test": "test", "test2": "test2", "test3": "test3"},
},
{
desc: "Given users have priority over users in the file",
userFileContent: "test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/\ntest2:$apr1$d9hr9HBB$4HxwgUir3HP4EsggP/QNo0\n",
givenUsers: []string{"test2:$apr1$mK.GtItK$ncnLYvNLek0weXdxo68690"},
expectedUsers: map[string]string{"test": "test", "test2": "overridden"},
},
{
desc: "Should authenticate the correct user based on the realm",
userFileContent: "test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/\ntest2:$apr1$d9hr9HBB$4HxwgUir3HP4EsggP/QNo0\n",
givenUsers: []string{"test2:$apr1$mK.GtItK$ncnLYvNLek0weXdxo68690"},
expectedUsers: map[string]string{"test": "test", "test2": "overridden"},
realm: "traefik",
},
{
desc: "Should skip comments",
userFileContent: "#Comment\ntest:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/\ntest2:$apr1$d9hr9HBB$4HxwgUir3HP4EsggP/QNo0\n",
givenUsers: []string{},
expectedUsers: map[string]string{"test": "test", "test2": "test2"},
realm: "traefiker",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
// Creates the temporary configuration file with the users
usersFile, err := os.CreateTemp(t.TempDir(), "auth-users")
require.NoError(t, err)
_, err = usersFile.WriteString(test.userFileContent)
require.NoError(t, err)
// Creates the configuration for our Authenticator
authenticatorConfiguration := dynamic.BasicAuth{
Users: test.givenUsers,
UsersFile: usersFile.Name(),
Realm: test.realm,
}
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "traefik")
})
authenticator, err := NewBasic(t.Context(), next, authenticatorConfiguration, "authName")
require.NoError(t, err)
ts := httptest.NewServer(authenticator)
defer ts.Close()
for userName, userPwd := range test.expectedUsers {
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
req.SetBasicAuth(userName, userPwd)
var res *http.Response
res, err = http.DefaultClient.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusOK, res.StatusCode, "Cannot authenticate user "+userName)
var body []byte
body, err = io.ReadAll(res.Body)
require.NoError(t, err)
err = res.Body.Close()
require.NoError(t, err)
require.Equal(t, "traefik\n", string(body))
}
// Checks that user foo doesn't work
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
req.SetBasicAuth("foo", "foo")
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusUnauthorized, res.StatusCode)
if len(test.realm) > 0 {
require.Equal(t, `Basic realm="`+test.realm+`"`, res.Header.Get("WWW-Authenticate"))
}
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
err = res.Body.Close()
require.NoError(t, err)
require.NotContains(t, "traefik", string(body))
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/auth/auth.go | pkg/middlewares/auth/auth.go | package auth
import (
"os"
"strings"
)
// UserParser Parses a string and return a userName/userHash. An error if the format of the string is incorrect.
type UserParser func(user string) (string, string, error)
const (
defaultRealm = "traefik"
authorizationHeader = "Authorization"
)
func getUsers(fileName string, appendUsers []string, parser UserParser) (map[string]string, error) {
users, err := loadUsers(fileName, appendUsers)
if err != nil {
return nil, err
}
userMap := make(map[string]string)
for _, user := range users {
userName, userHash, err := parser(user)
if err != nil {
return nil, err
}
userMap[userName] = userHash
}
return userMap, nil
}
func loadUsers(fileName string, appendUsers []string) ([]string, error) {
var users []string
var err error
if fileName != "" {
users, err = getLinesFromFile(fileName)
if err != nil {
return nil, err
}
}
return append(users, appendUsers...), nil
}
func getLinesFromFile(filename string) ([]string, error) {
dat, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
// Trim lines and filter out blanks
rawLines := strings.Split(string(dat), "\n")
var filteredLines []string
for _, rawLine := range rawLines {
line := strings.TrimSpace(rawLine)
if line != "" && !strings.HasPrefix(line, "#") {
filteredLines = append(filteredLines, line)
}
}
return filteredLines, nil
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/auth/basic_auth.go | pkg/middlewares/auth/basic_auth.go | package auth
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
goauth "github.com/abbot/go-http-auth"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/middlewares/accesslog"
"github.com/traefik/traefik/v3/pkg/middlewares/observability"
"golang.org/x/sync/singleflight"
)
const (
typeNameBasic = "BasicAuth"
)
type basicAuth struct {
next http.Handler
auth *goauth.BasicAuth
users map[string]string
headerField string
removeHeader bool
name string
checkSecret func(password, secret string) bool
singleflightGroup *singleflight.Group
}
// NewBasic creates a basicAuth middleware.
func NewBasic(ctx context.Context, next http.Handler, authConfig dynamic.BasicAuth, name string) (http.Handler, error) {
middlewares.GetLogger(ctx, name, typeNameBasic).Debug().Msg("Creating middleware")
users, err := getUsers(authConfig.UsersFile, authConfig.Users, basicUserParser)
if err != nil {
return nil, err
}
ba := &basicAuth{
next: next,
users: users,
headerField: authConfig.HeaderField,
removeHeader: authConfig.RemoveHeader,
name: name,
checkSecret: goauth.CheckSecret,
singleflightGroup: new(singleflight.Group),
}
realm := defaultRealm
if len(authConfig.Realm) > 0 {
realm = authConfig.Realm
}
ba.auth = &goauth.BasicAuth{Realm: realm, Secrets: ba.secretBasic}
return ba, nil
}
func (b *basicAuth) GetTracingInformation() (string, string) {
return b.name, typeNameBasic
}
func (b *basicAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
logger := middlewares.GetLogger(req.Context(), b.name, typeNameBasic)
user, password, ok := req.BasicAuth()
if ok {
ok = b.checkPassword(user, password)
}
logData := accesslog.GetLogData(req)
if logData != nil {
logData.Core[accesslog.ClientUsername] = user
}
if !ok {
logger.Debug().Msg("Authentication failed")
observability.SetStatusErrorf(req.Context(), "Authentication failed")
b.auth.RequireAuth(rw, req)
return
}
logger.Debug().Msg("Authentication succeeded")
req.URL.User = url.User(user)
if b.headerField != "" {
req.Header[b.headerField] = []string{user}
}
if b.removeHeader {
logger.Debug().Msg("Removing authorization header")
req.Header.Del(authorizationHeader)
}
b.next.ServeHTTP(rw, req)
}
func (b *basicAuth) checkPassword(user, password string) bool {
secret := b.auth.Secrets(user, b.auth.Realm)
if secret == "" {
return false
}
key := password + secret
match, _, _ := b.singleflightGroup.Do(key, func() (any, error) {
return b.checkSecret(password, secret), nil
})
return match.(bool)
}
func (b *basicAuth) secretBasic(user, realm string) string {
if secret, ok := b.users[user]; ok {
return secret
}
return ""
}
func basicUserParser(user string) (string, string, error) {
split := strings.Split(user, ":")
if len(split) != 2 {
return "", "", fmt.Errorf("error parsing BasicUser: %v", user)
}
return split[0], split[1], nil
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/auth/forward_test.go | pkg/middlewares/auth/forward_test.go | package auth
import (
"bytes"
"context"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"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/middlewares/observability"
"github.com/traefik/traefik/v3/pkg/observability/tracing"
"github.com/traefik/traefik/v3/pkg/proxy/httputil"
"github.com/traefik/traefik/v3/pkg/testhelpers"
"github.com/vulcand/oxy/v2/forward"
"go.opentelemetry.io/contrib/propagators/autoprop"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/trace/embedded"
)
func TestForwardAuthFail(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "traefik")
})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(forward.ProxyAuthenticate, "test")
http.Error(w, "Forbidden", http.StatusForbidden)
}))
t.Cleanup(server.Close)
middleware, err := NewForward(t.Context(), next, dynamic.ForwardAuth{
Address: server.URL,
}, "authTest")
require.NoError(t, err)
ts := httptest.NewServer(middleware)
t.Cleanup(ts.Close)
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusForbidden, res.StatusCode)
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
err = res.Body.Close()
require.NoError(t, err)
assert.Equal(t, "test", res.Header.Get(forward.ProxyAuthenticate))
assert.Equal(t, "Forbidden\n", string(body))
}
func TestForwardAuthSuccess(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Auth-User", "user@example.com")
w.Header().Set("X-Auth-Secret", "secret")
w.Header().Add("X-Auth-Group", "group1")
w.Header().Add("X-Auth-Group", "group2")
w.Header().Add("Foo-Bar", "auth-value")
w.Header().Add("Set-Cookie", "authCookie=Auth")
w.Header().Add("Set-Cookie", "authCookieNotAdded=Auth")
fmt.Fprintln(w, "Success")
}))
t.Cleanup(server.Close)
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "user@example.com", r.Header.Get("X-Auth-User"))
assert.Empty(t, r.Header.Get("X-Auth-Secret"))
assert.Equal(t, []string{"group1", "group2"}, r.Header["X-Auth-Group"])
assert.Equal(t, "auth-value", r.Header.Get("Foo-Bar"))
assert.Empty(t, r.Header.Get("Foo-Baz"))
w.Header().Add("Set-Cookie", "authCookie=Backend")
w.Header().Add("Set-Cookie", "backendCookie=Backend")
w.Header().Add("Other-Header", "BackendHeaderValue")
fmt.Fprintln(w, "traefik")
})
auth := dynamic.ForwardAuth{
Address: server.URL,
AuthResponseHeaders: []string{"X-Auth-User", "X-Auth-Group"},
AuthResponseHeadersRegex: "^Foo-",
AddAuthCookiesToResponse: []string{"authCookie"},
}
middleware, err := NewForward(t.Context(), next, auth, "authTest")
require.NoError(t, err)
ts := httptest.NewServer(middleware)
t.Cleanup(ts.Close)
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
req.Header.Set("X-Auth-Group", "admin_group")
req.Header.Set("Foo-Bar", "client-value")
req.Header.Set("Foo-Baz", "client-value")
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, []string{"backendCookie=Backend", "authCookie=Auth"}, res.Header["Set-Cookie"])
assert.Equal(t, []string{"BackendHeaderValue"}, res.Header["Other-Header"])
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
err = res.Body.Close()
require.NoError(t, err)
assert.Equal(t, "traefik\n", string(body))
}
func TestForwardAuthForwardBody(t *testing.T) {
data := []byte("forwardBodyTest")
var serverCallCount int
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
serverCallCount++
forwardedData, err := io.ReadAll(req.Body)
require.NoError(t, err)
assert.Equal(t, data, forwardedData)
}))
t.Cleanup(server.Close)
var nextCallCount int
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
nextCallCount++
})
maxBodySize := int64(len(data))
auth := dynamic.ForwardAuth{Address: server.URL, ForwardBody: true, MaxBodySize: &maxBodySize}
middleware, err := NewForward(t.Context(), next, auth, "authTest")
require.NoError(t, err)
ts := httptest.NewServer(middleware)
t.Cleanup(ts.Close)
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, bytes.NewReader(data))
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, 1, serverCallCount)
assert.Equal(t, 1, nextCallCount)
}
func TestForwardAuthForwardBodyEmptyBody(t *testing.T) {
var serverCallCount int
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
serverCallCount++
forwardedData, err := io.ReadAll(req.Body)
require.NoError(t, err)
assert.Empty(t, forwardedData)
}))
t.Cleanup(server.Close)
var nextCallCount int
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
nextCallCount++
})
auth := dynamic.ForwardAuth{Address: server.URL, ForwardBody: true}
middleware, err := NewForward(t.Context(), next, auth, "authTest")
require.NoError(t, err)
ts := httptest.NewServer(middleware)
t.Cleanup(ts.Close)
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, http.NoBody)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, 1, serverCallCount)
assert.Equal(t, 1, nextCallCount)
}
func TestForwardAuthForwardBodySizeLimit(t *testing.T) {
data := []byte("forwardBodyTest")
var serverCallCount int
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
serverCallCount++
forwardedData, err := io.ReadAll(req.Body)
require.NoError(t, err)
assert.Equal(t, data, forwardedData)
}))
t.Cleanup(server.Close)
var nextCallCount int
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
nextCallCount++
})
maxBodySize := int64(len(data)) - 1
auth := dynamic.ForwardAuth{Address: server.URL, ForwardBody: true, MaxBodySize: &maxBodySize}
middleware, err := NewForward(t.Context(), next, auth, "authTest")
require.NoError(t, err)
ts := httptest.NewServer(middleware)
t.Cleanup(ts.Close)
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, bytes.NewReader(data))
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusUnauthorized, res.StatusCode)
assert.Equal(t, 0, serverCallCount)
assert.Equal(t, 0, nextCallCount)
}
func TestForwardAuthNotForwardBody(t *testing.T) {
data := []byte("forwardBodyTest")
var serverCallCount int
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
serverCallCount++
forwardedData, err := io.ReadAll(req.Body)
require.NoError(t, err)
assert.Empty(t, forwardedData)
}))
t.Cleanup(server.Close)
var nextCallCount int
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
nextCallCount++
})
auth := dynamic.ForwardAuth{Address: server.URL}
middleware, err := NewForward(t.Context(), next, auth, "authTest")
require.NoError(t, err)
ts := httptest.NewServer(middleware)
t.Cleanup(ts.Close)
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, bytes.NewReader(data))
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, 1, serverCallCount)
assert.Equal(t, 1, nextCallCount)
}
func TestForwardAuthRedirect(t *testing.T) {
authTs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "http://example.com/redirect-test", http.StatusFound)
}))
t.Cleanup(authTs.Close)
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "traefik")
})
auth := dynamic.ForwardAuth{Address: authTs.URL}
authMiddleware, err := NewForward(t.Context(), next, auth, "authTest")
require.NoError(t, err)
ts := httptest.NewServer(authMiddleware)
t.Cleanup(ts.Close)
client := &http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
res, err := client.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusFound, res.StatusCode)
location, err := res.Location()
require.NoError(t, err)
assert.Equal(t, "http://example.com/redirect-test", location.String())
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
err = res.Body.Close()
require.NoError(t, err)
assert.NotEmpty(t, string(body))
}
func TestForwardAuthRemoveHopByHopHeaders(t *testing.T) {
authTs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
headers := w.Header()
for _, header := range hopHeaders {
if header == forward.TransferEncoding {
headers.Set(header, "chunked")
} else {
headers.Add(header, "test")
}
}
http.Redirect(w, r, "http://example.com/redirect-test", http.StatusFound)
}))
t.Cleanup(authTs.Close)
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "traefik")
})
auth := dynamic.ForwardAuth{Address: authTs.URL}
authMiddleware, err := NewForward(t.Context(), next, auth, "authTest")
require.NoError(t, err)
ts := httptest.NewServer(authMiddleware)
t.Cleanup(ts.Close)
client := &http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
res, err := client.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusFound, res.StatusCode, "they should be equal")
for _, header := range forward.HopHeaders {
assert.Empty(t, res.Header.Get(header), "hop-by-hop header '%s' mustn't be set", header)
}
location, err := res.Location()
require.NoError(t, err)
assert.Equal(t, "http://example.com/redirect-test", location.String(), "they should be equal")
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
assert.NotEmpty(t, string(body), "there should be something in the body")
}
func TestForwardAuthFailResponseHeaders(t *testing.T) {
authTs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie := &http.Cookie{Name: "example", Value: "testing", Path: "/"}
http.SetCookie(w, cookie)
w.Header().Add("X-Foo", "bar")
http.Error(w, "Forbidden", http.StatusForbidden)
}))
t.Cleanup(authTs.Close)
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "traefik")
})
auth := dynamic.ForwardAuth{
Address: authTs.URL,
}
authMiddleware, err := NewForward(t.Context(), next, auth, "authTest")
require.NoError(t, err)
ts := httptest.NewServer(authMiddleware)
t.Cleanup(ts.Close)
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusForbidden, res.StatusCode)
require.Len(t, res.Cookies(), 1)
for _, cookie := range res.Cookies() {
assert.Equal(t, "testing", cookie.Value)
}
expectedHeaders := http.Header{
"Content-Length": []string{"10"},
"Content-Type": []string{"text/plain; charset=utf-8"},
"X-Foo": []string{"bar"},
"Set-Cookie": []string{"example=testing; Path=/"},
"X-Content-Type-Options": []string{"nosniff"},
}
assert.Len(t, res.Header, 6)
for key, value := range expectedHeaders {
assert.Equal(t, value, res.Header[key])
}
body, err := io.ReadAll(res.Body)
require.NoError(t, err)
err = res.Body.Close()
require.NoError(t, err)
assert.Equal(t, "Forbidden\n", string(body))
}
func TestForwardAuthClientClosedRequest(t *testing.T) {
requestStarted := make(chan struct{})
requestCancelled := make(chan struct{})
responseComplete := make(chan struct{})
authTs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
close(requestStarted)
<-requestCancelled
}))
t.Cleanup(authTs.Close)
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// next should not be called.
t.Fail()
})
auth := dynamic.ForwardAuth{
Address: authTs.URL,
}
authMiddleware, err := NewForward(t.Context(), next, auth, "authTest")
require.NoError(t, err)
ctx, cancel := context.WithCancel(t.Context())
req := httptest.NewRequestWithContext(ctx, "GET", "http://foo", http.NoBody)
recorder := httptest.NewRecorder()
go func() {
authMiddleware.ServeHTTP(recorder, req)
close(responseComplete)
}()
<-requestStarted
cancel()
close(requestCancelled)
<-responseComplete
assert.Equal(t, httputil.StatusClientClosedRequest, recorder.Result().StatusCode)
}
func TestForwardAuthForwardError(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// next should not be called.
t.Fail()
})
auth := dynamic.ForwardAuth{
Address: "http://non-existing-server",
}
authMiddleware, err := NewForward(t.Context(), next, auth, "authTest")
require.NoError(t, err)
ctx, cancel := context.WithTimeout(t.Context(), 1*time.Microsecond)
defer cancel()
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "http://foo", nil)
recorder := httptest.NewRecorder()
responseComplete := make(chan struct{})
go func() {
authMiddleware.ServeHTTP(recorder, req)
close(responseComplete)
}()
<-responseComplete
assert.Equal(t, http.StatusInternalServerError, recorder.Result().StatusCode)
}
func Test_writeHeader(t *testing.T) {
testCases := []struct {
name string
headers map[string]string
authRequestHeaders []string
trustForwardHeader bool
emptyHost bool
expectedHeaders map[string]string
checkForUnexpectedHeaders bool
}{
{
name: "trust Forward Header",
headers: map[string]string{
"Accept": "application/json",
"X-Forwarded-Host": "fii.bir",
},
trustForwardHeader: true,
expectedHeaders: map[string]string{
"Accept": "application/json",
"X-Forwarded-Host": "fii.bir",
},
},
{
name: "not trust Forward Header",
headers: map[string]string{
"Accept": "application/json",
"X-Forwarded-Host": "fii.bir",
},
trustForwardHeader: false,
expectedHeaders: map[string]string{
"Accept": "application/json",
"X-Forwarded-Host": "foo.bar",
},
},
{
name: "trust Forward Header with empty Host",
headers: map[string]string{
"Accept": "application/json",
"X-Forwarded-Host": "fii.bir",
},
trustForwardHeader: true,
emptyHost: true,
expectedHeaders: map[string]string{
"Accept": "application/json",
"X-Forwarded-Host": "fii.bir",
},
},
{
name: "not trust Forward Header with empty Host",
headers: map[string]string{
"Accept": "application/json",
"X-Forwarded-Host": "fii.bir",
},
trustForwardHeader: false,
emptyHost: true,
expectedHeaders: map[string]string{
"Accept": "application/json",
"X-Forwarded-Host": "",
},
},
{
name: "trust Forward Header with forwarded URI",
headers: map[string]string{
"Accept": "application/json",
"X-Forwarded-Host": "fii.bir",
"X-Forwarded-Uri": "/forward?q=1",
},
trustForwardHeader: true,
expectedHeaders: map[string]string{
"Accept": "application/json",
"X-Forwarded-Host": "fii.bir",
"X-Forwarded-Uri": "/forward?q=1",
},
},
{
name: "not trust Forward Header with forward requested URI",
headers: map[string]string{
"Accept": "application/json",
"X-Forwarded-Host": "fii.bir",
"X-Forwarded-Uri": "/forward?q=1",
},
trustForwardHeader: false,
expectedHeaders: map[string]string{
"Accept": "application/json",
"X-Forwarded-Host": "foo.bar",
"X-Forwarded-Uri": "/path?q=1",
},
},
{
name: "trust Forward Header with forwarded request Method",
headers: map[string]string{
"X-Forwarded-Method": "OPTIONS",
},
trustForwardHeader: true,
expectedHeaders: map[string]string{
"X-Forwarded-Method": "OPTIONS",
},
},
{
name: "not trust Forward Header with forward request Method",
headers: map[string]string{
"X-Forwarded-Method": "OPTIONS",
},
trustForwardHeader: false,
expectedHeaders: map[string]string{
"X-Forwarded-Method": "GET",
},
},
{
name: "remove hop-by-hop headers",
headers: map[string]string{
forward.Connection: "Connection",
forward.KeepAlive: "KeepAlive",
forward.ProxyAuthenticate: "ProxyAuthenticate",
forward.ProxyAuthorization: "ProxyAuthorization",
forward.Te: "Te",
forward.Trailers: "Trailers",
forward.TransferEncoding: "TransferEncoding",
forward.Upgrade: "Upgrade",
"X-CustomHeader": "CustomHeader",
},
trustForwardHeader: false,
expectedHeaders: map[string]string{
"X-CustomHeader": "CustomHeader",
"X-Forwarded-Proto": "http",
"X-Forwarded-Host": "foo.bar",
"X-Forwarded-Uri": "/path?q=1",
"X-Forwarded-Method": "GET",
forward.ProxyAuthenticate: "ProxyAuthenticate",
forward.ProxyAuthorization: "ProxyAuthorization",
},
checkForUnexpectedHeaders: true,
},
{
name: "filter forward request headers",
headers: map[string]string{
"X-CustomHeader": "CustomHeader",
"Content-Type": "multipart/form-data; boundary=---123456",
},
authRequestHeaders: []string{
"X-CustomHeader",
},
trustForwardHeader: false,
expectedHeaders: map[string]string{
"x-customHeader": "CustomHeader",
"X-Forwarded-Proto": "http",
"X-Forwarded-Host": "foo.bar",
"X-Forwarded-Uri": "/path?q=1",
"X-Forwarded-Method": "GET",
},
checkForUnexpectedHeaders: true,
},
{
name: "filter forward request headers doesn't add new headers",
headers: map[string]string{
"X-CustomHeader": "CustomHeader",
"Content-Type": "multipart/form-data; boundary=---123456",
},
authRequestHeaders: []string{
"X-CustomHeader",
"X-Non-Exists-Header",
},
trustForwardHeader: false,
expectedHeaders: map[string]string{
"X-CustomHeader": "CustomHeader",
"X-Forwarded-Proto": "http",
"X-Forwarded-Host": "foo.bar",
"X-Forwarded-Uri": "/path?q=1",
"X-Forwarded-Method": "GET",
},
checkForUnexpectedHeaders: true,
},
}
for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
req := testhelpers.MustNewRequest(http.MethodGet, "http://foo.bar/path?q=1", nil)
for key, value := range test.headers {
req.Header.Set(key, value)
}
if test.emptyHost {
req.Host = ""
}
forwardReq := testhelpers.MustNewRequest(http.MethodGet, "http://foo.bar/path?q=1", nil)
writeHeader(req, forwardReq, test.trustForwardHeader, test.authRequestHeaders)
actualHeaders := forwardReq.Header
expectedHeaders := test.expectedHeaders
for key, value := range expectedHeaders {
assert.Equal(t, value, actualHeaders.Get(key))
actualHeaders.Del(key)
}
if test.checkForUnexpectedHeaders {
for key := range actualHeaders {
assert.Fail(t, "Unexpected header found", key)
}
}
})
}
}
func TestForwardAuthTracing(t *testing.T) {
type expected struct {
name string
attributes []attribute.KeyValue
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Traceparent") == "" {
t.Errorf("expected Traceparent header to be present in request")
}
w.Header().Set("X-Bar", "foo")
w.Header().Add("X-Bar", "bar")
w.WriteHeader(http.StatusNotFound)
}))
t.Cleanup(server.Close)
parse, err := url.Parse(server.URL)
require.NoError(t, err)
_, serverPort, err := net.SplitHostPort(parse.Host)
require.NoError(t, err)
serverPortInt, err := strconv.Atoi(serverPort)
require.NoError(t, err)
testCases := []struct {
desc string
expected []expected
}{
{
desc: "basic test",
expected: []expected{
{
name: "initial",
attributes: []attribute.KeyValue{
attribute.String("span.kind", "unspecified"),
},
},
{
name: "AuthRequest",
attributes: []attribute.KeyValue{
attribute.String("span.kind", "client"),
attribute.String("http.request.method", "GET"),
attribute.String("network.protocol.version", "1.1"),
attribute.String("url.full", server.URL),
attribute.String("url.scheme", "http"),
attribute.String("user_agent.original", ""),
attribute.String("network.peer.address", "127.0.0.1"),
attribute.Int64("network.peer.port", int64(serverPortInt)),
attribute.String("server.address", "127.0.0.1"),
attribute.Int64("server.port", int64(serverPortInt)),
attribute.StringSlice("http.request.header.x-foo", []string{"foo", "bar"}),
attribute.Int64("http.response.status_code", int64(404)),
attribute.StringSlice("http.response.header.x-bar", []string{"foo", "bar"}),
},
},
},
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
next := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
auth := dynamic.ForwardAuth{
Address: server.URL,
AuthRequestHeaders: []string{"X-Foo"},
}
next, err := NewForward(t.Context(), next, auth, "authTest")
require.NoError(t, err)
next = observability.WithObservabilityHandler(next, observability.Observability{
TracingEnabled: true,
})
req := httptest.NewRequest(http.MethodGet, "http://www.test.com/search?q=Opentelemetry", nil)
req.RemoteAddr = "10.0.0.1:1234"
req.Header.Set("User-Agent", "forward-test")
req.Header.Set("X-Forwarded-Proto", "http")
req.Header.Set("X-Foo", "foo")
req.Header.Add("X-Foo", "bar")
otel.SetTextMapPropagator(autoprop.NewTextMapPropagator())
mockTracer := &mockTracer{}
tracer := tracing.NewTracer(mockTracer, []string{"X-Foo"}, []string{"X-Bar"}, []string{"q"})
initialCtx, initialSpan := tracer.Start(req.Context(), "initial")
defer initialSpan.End()
req = req.WithContext(initialCtx)
recorder := httptest.NewRecorder()
next.ServeHTTP(recorder, req)
for i, span := range mockTracer.spans {
assert.Equal(t, test.expected[i].name, span.name)
assert.Equal(t, test.expected[i].attributes, span.attributes)
}
})
}
}
func TestForwardAuthPreserveLocationHeader(t *testing.T) {
relativeURL := "/index.html"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Location", relativeURL)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}))
t.Cleanup(server.Close)
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
auth := dynamic.ForwardAuth{
Address: server.URL,
PreserveLocationHeader: true,
}
middleware, err := NewForward(t.Context(), next, auth, "authTest")
require.NoError(t, err)
ts := httptest.NewServer(middleware)
t.Cleanup(ts.Close)
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusUnauthorized, res.StatusCode)
assert.Equal(t, relativeURL, res.Header.Get("Location"))
}
func TestForwardAuthPreserveRequestMethod(t *testing.T) {
testCases := []struct {
name string
preserveRequestMethod bool
originalReqMethod string
expectedReqMethodInAuthServer string
}{
{
name: "preserve request method",
preserveRequestMethod: true,
originalReqMethod: http.MethodPost,
expectedReqMethodInAuthServer: http.MethodPost,
},
{
name: "do not preserve request method",
preserveRequestMethod: false,
originalReqMethod: http.MethodPost,
expectedReqMethodInAuthServer: http.MethodGet,
},
}
for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
reqReachesAuthServer := false
authServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
reqReachesAuthServer = true
assert.Equal(t, test.expectedReqMethodInAuthServer, req.Method)
}))
t.Cleanup(authServer.Close)
reqReachesNextServer := false
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqReachesNextServer = true
assert.Equal(t, test.originalReqMethod, r.Method)
})
auth := dynamic.ForwardAuth{
Address: authServer.URL,
PreserveRequestMethod: test.preserveRequestMethod,
}
middleware, err := NewForward(t.Context(), next, auth, "authTest")
require.NoError(t, err)
ts := httptest.NewServer(middleware)
t.Cleanup(ts.Close)
req := testhelpers.MustNewRequest(test.originalReqMethod, ts.URL, nil)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.True(t, reqReachesAuthServer)
assert.True(t, reqReachesNextServer)
})
}
}
type mockTracer struct {
embedded.Tracer
spans []*mockSpan
}
var _ trace.Tracer = &mockTracer{}
func (t *mockTracer) Start(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) {
config := trace.NewSpanStartConfig(opts...)
span := &mockSpan{}
span.SetName(name)
span.SetAttributes(attribute.String("span.kind", config.SpanKind().String()))
span.SetAttributes(config.Attributes()...)
t.spans = append(t.spans, span)
return trace.ContextWithSpan(ctx, span), span
}
// mockSpan is an implementation of Span that preforms no operations.
type mockSpan struct {
embedded.Span
name string
attributes []attribute.KeyValue
}
var _ trace.Span = &mockSpan{}
func (*mockSpan) SpanContext() trace.SpanContext {
return trace.NewSpanContext(trace.SpanContextConfig{TraceID: trace.TraceID{1}, SpanID: trace.SpanID{1}})
}
func (*mockSpan) IsRecording() bool { return false }
func (s *mockSpan) SetStatus(_ codes.Code, _ string) {}
func (s *mockSpan) SetAttributes(kv ...attribute.KeyValue) {
s.attributes = append(s.attributes, kv...)
}
func (s *mockSpan) End(...trace.SpanEndOption) {}
func (s *mockSpan) RecordError(_ error, _ ...trace.EventOption) {}
func (s *mockSpan) AddEvent(_ string, _ ...trace.EventOption) {}
func (s *mockSpan) AddLink(_ trace.Link) {}
func (s *mockSpan) SetName(name string) { s.name = name }
func (s *mockSpan) TracerProvider() trace.TracerProvider {
return nil
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/ratelimiter/redis_limiter.go | pkg/middlewares/ratelimiter/redis_limiter.go | package ratelimiter
import (
"context"
"fmt"
"strconv"
"time"
"github.com/redis/go-redis/v9"
"github.com/rs/zerolog"
ptypes "github.com/traefik/paerser/types"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"golang.org/x/time/rate"
)
const redisPrefix = "rate:"
type redisLimiter struct {
rate rate.Limit // reqs/s
burst int64
maxDelay time.Duration
period ptypes.Duration
logger *zerolog.Logger
ttl int
client Rediser
}
func newRedisLimiter(ctx context.Context, rate rate.Limit, burst int64, maxDelay time.Duration, ttl int, config dynamic.RateLimit, logger *zerolog.Logger) (limiter, error) {
options := &redis.UniversalOptions{
Addrs: config.Redis.Endpoints,
Username: config.Redis.Username,
Password: config.Redis.Password,
DB: config.Redis.DB,
PoolSize: config.Redis.PoolSize,
MinIdleConns: config.Redis.MinIdleConns,
MaxActiveConns: config.Redis.MaxActiveConns,
}
if config.Redis.DialTimeout != nil && *config.Redis.DialTimeout > 0 {
options.DialTimeout = time.Duration(*config.Redis.DialTimeout)
}
if config.Redis.ReadTimeout != nil {
if *config.Redis.ReadTimeout > 0 {
options.ReadTimeout = time.Duration(*config.Redis.ReadTimeout)
} else {
options.ReadTimeout = -1
}
}
if config.Redis.WriteTimeout != nil {
if *config.Redis.ReadTimeout > 0 {
options.WriteTimeout = time.Duration(*config.Redis.WriteTimeout)
} else {
options.WriteTimeout = -1
}
}
if config.Redis.TLS != nil {
var err error
options.TLSConfig, err = config.Redis.TLS.CreateTLSConfig(ctx)
if err != nil {
return nil, fmt.Errorf("creating TLS config: %w", err)
}
}
return &redisLimiter{
rate: rate,
burst: burst,
period: config.Period,
maxDelay: maxDelay,
logger: logger,
ttl: ttl,
client: redis.NewUniversalClient(options),
}, nil
}
func (r *redisLimiter) Allow(ctx context.Context, source string) (*time.Duration, error) {
ok, delay, err := r.evaluateScript(ctx, source)
if err != nil {
return nil, fmt.Errorf("evaluating script: %w", err)
}
if !ok {
return nil, nil
}
return delay, nil
}
func (r *redisLimiter) evaluateScript(ctx context.Context, key string) (bool, *time.Duration, error) {
if r.rate == rate.Inf {
return true, nil, nil
}
params := []interface{}{
float64(r.rate / 1000000),
r.burst,
r.ttl,
time.Now().UnixMicro(),
r.maxDelay.Microseconds(),
}
v, err := AllowTokenBucketScript.Run(ctx, r.client, []string{redisPrefix + key}, params...).Result()
if err != nil {
return false, nil, fmt.Errorf("running script: %w", err)
}
values := v.([]interface{})
ok, err := strconv.ParseBool(values[0].(string))
if err != nil {
return false, nil, fmt.Errorf("parsing ok value from redis rate lua script: %w", err)
}
delay, err := strconv.ParseFloat(values[1].(string), 64)
if err != nil {
return false, nil, fmt.Errorf("parsing delay value from redis rate lua script: %w", err)
}
microDelay := time.Duration(delay * float64(time.Microsecond))
return ok, µDelay, nil
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/ratelimiter/rate_limiter.go | pkg/middlewares/ratelimiter/rate_limiter.go | // Package ratelimiter implements a rate limiting and traffic shaping middleware with a set of token buckets.
package ratelimiter
import (
"context"
"fmt"
"math"
"net/http"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/middlewares/observability"
"github.com/vulcand/oxy/v2/utils"
"golang.org/x/time/rate"
)
const (
typeName = "RateLimiter"
maxSources = 65536
)
type limiter interface {
Allow(ctx context.Context, token string) (*time.Duration, error)
}
// rateLimiter implements rate limiting and traffic shaping with a set of token buckets;
// one for each traffic source. The same parameters are applied to all the buckets.
type rateLimiter struct {
name string
rate rate.Limit // reqs/s
// maxDelay is the maximum duration we're willing to wait for a bucket reservation to become effective, in nanoseconds.
// For now it is somewhat arbitrarily set to 1/(2*rate).
maxDelay time.Duration
sourceMatcher utils.SourceExtractor
next http.Handler
logger *zerolog.Logger
limiter limiter
}
// New returns a rate limiter middleware.
func New(ctx context.Context, next http.Handler, config dynamic.RateLimit, name string) (http.Handler, error) {
logger := middlewares.GetLogger(ctx, name, typeName)
logger.Debug().Msg("Creating middleware")
ctxLog := logger.WithContext(ctx)
if config.SourceCriterion == nil ||
config.SourceCriterion.IPStrategy == nil &&
config.SourceCriterion.RequestHeaderName == "" && !config.SourceCriterion.RequestHost {
config.SourceCriterion = &dynamic.SourceCriterion{
IPStrategy: &dynamic.IPStrategy{},
}
}
sourceMatcher, err := middlewares.GetSourceExtractor(ctxLog, config.SourceCriterion)
if err != nil {
return nil, fmt.Errorf("getting source extractor: %w", err)
}
burst := config.Burst
if burst < 1 {
burst = 1
}
period := time.Duration(config.Period)
if period < 0 {
return nil, fmt.Errorf("negative value not valid for period: %v", period)
}
if period == 0 {
period = time.Second
}
// Initialized at rate.Inf to enforce no rate limiting when config.Average == 0
rtl := float64(rate.Inf)
// No need to set any particular value for maxDelay as the reservation's delay
// will be <= 0 in the Inf case (i.e. the average == 0 case).
var maxDelay time.Duration
if config.Average > 0 {
rtl = float64(config.Average*int64(time.Second)) / float64(period)
// maxDelay does not scale well for rates below 1,
// so we just cap it to the corresponding value, i.e. 0.5s, in order to keep the effective rate predictable.
// One alternative would be to switch to a no-reservation mode (Allow() method) whenever we are in such a low rate regime.
if rtl < 1 {
maxDelay = 500 * time.Millisecond
} else {
maxDelay = time.Second / (time.Duration(rtl) * 2)
}
}
// Make the ttl inversely proportional to how often a rate limiter is supposed to see any activity (when maxed out),
// for low rate limiters.
// Otherwise just make it a second for all the high rate limiters.
// Add an extra second in both cases for continuity between the two cases.
ttl := 1
if rtl >= 1 {
ttl++
} else if rtl > 0 {
ttl += int(1 / rtl)
}
var limiter limiter
if config.Redis != nil {
limiter, err = newRedisLimiter(ctx, rate.Limit(rtl), burst, maxDelay, ttl, config, logger)
if err != nil {
return nil, fmt.Errorf("creating redis limiter: %w", err)
}
} else {
limiter, err = newInMemoryRateLimiter(rate.Limit(rtl), burst, maxDelay, ttl, logger)
if err != nil {
return nil, fmt.Errorf("creating in-memory limiter: %w", err)
}
}
return &rateLimiter{
logger: logger,
name: name,
rate: rate.Limit(rtl),
maxDelay: maxDelay,
next: next,
sourceMatcher: sourceMatcher,
limiter: limiter,
}, nil
}
func (rl *rateLimiter) GetTracingInformation() (string, string) {
return rl.name, typeName
}
func (rl *rateLimiter) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
logger := middlewares.GetLogger(req.Context(), rl.name, typeName)
ctx := logger.WithContext(req.Context())
source, amount, err := rl.sourceMatcher.Extract(req)
if err != nil {
logger.Error().Err(err).Msg("Could not extract source of request")
http.Error(rw, "could not extract source of request", http.StatusInternalServerError)
return
}
if amount != 1 {
logger.Info().Msgf("ignoring token bucket amount > 1: %d", amount)
}
// Each rate limiter has its own source space,
// ensuring independence between rate limiters,
// i.e., rate limit rules are only applied based on traffic
// where the rate limiter is active.
rlSource := fmt.Sprintf("%s:%s", rl.name, source)
delay, err := rl.limiter.Allow(ctx, rlSource)
if err != nil {
rl.logger.Error().Err(err).Msg("Could not insert/update bucket")
observability.SetStatusErrorf(ctx, "Could not insert/update bucket")
http.Error(rw, "Could not insert/update bucket", http.StatusInternalServerError)
return
}
if delay == nil {
observability.SetStatusErrorf(ctx, "No bursty traffic allowed")
http.Error(rw, "No bursty traffic allowed", http.StatusTooManyRequests)
return
}
if *delay > rl.maxDelay {
rl.serveDelayError(ctx, rw, *delay)
return
}
select {
case <-ctx.Done():
observability.SetStatusErrorf(ctx, "Context canceled")
http.Error(rw, "context canceled", http.StatusInternalServerError)
return
case <-time.After(*delay):
}
rl.next.ServeHTTP(rw, req)
}
func (rl *rateLimiter) serveDelayError(ctx context.Context, w http.ResponseWriter, delay time.Duration) {
w.Header().Set("Retry-After", fmt.Sprintf("%.0f", math.Ceil(delay.Seconds())))
w.Header().Set("X-Retry-In", delay.String())
w.WriteHeader(http.StatusTooManyRequests)
if _, err := w.Write([]byte(http.StatusText(http.StatusTooManyRequests))); err != nil {
log.Ctx(ctx).Error().Err(err).Msg("Could not serve 429")
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/ratelimiter/rate_limiter_test.go | pkg/middlewares/ratelimiter/rate_limiter_test.go | package ratelimiter
import (
"context"
"errors"
"fmt"
"math/rand"
"net/http"
"net/http/httptest"
"os"
"strconv"
"testing"
"time"
"github.com/mailgun/ttlmap"
"github.com/redis/go-redis/v9"
"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/testhelpers"
"github.com/vulcand/oxy/v2/utils"
lua "github.com/yuin/gopher-lua"
"golang.org/x/time/rate"
)
const delta float64 = 1e-10
func TestNewRateLimiter(t *testing.T) {
testCases := []struct {
desc string
config dynamic.RateLimit
expectedMaxDelay time.Duration
expectedSourceIP string
requestHeader string
expectedError string
expectedRTL rate.Limit
}{
{
desc: "no ratelimit on Average == 0",
config: dynamic.RateLimit{
Average: 0,
Burst: 10,
},
expectedRTL: rate.Inf,
},
{
desc: "maxDelay computation",
config: dynamic.RateLimit{
Average: 200,
Burst: 10,
},
expectedMaxDelay: 2500 * time.Microsecond,
},
{
desc: "maxDelay computation, low rate regime",
config: dynamic.RateLimit{
Average: 2,
Period: ptypes.Duration(10 * time.Second),
Burst: 10,
},
expectedMaxDelay: 500 * time.Millisecond,
},
{
desc: "default SourceMatcher is remote address ip strategy",
config: dynamic.RateLimit{
Average: 200,
Burst: 10,
},
expectedSourceIP: "127.0.0.1",
},
{
desc: "SourceCriterion in config is respected",
config: dynamic.RateLimit{
Average: 200,
Burst: 10,
SourceCriterion: &dynamic.SourceCriterion{
RequestHeaderName: "Foo",
},
},
requestHeader: "bar",
},
{
desc: "SourceCriteria are mutually exclusive",
config: dynamic.RateLimit{
Average: 200,
Burst: 10,
SourceCriterion: &dynamic.SourceCriterion{
IPStrategy: &dynamic.IPStrategy{},
RequestHeaderName: "Foo",
},
},
expectedError: "getting source extractor: iPStrategy and RequestHeaderName are mutually exclusive",
},
{
desc: "Use Redis",
config: dynamic.RateLimit{
Average: 200,
Burst: 10,
Redis: &dynamic.Redis{
Endpoints: []string{"localhost:6379"},
},
},
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
h, err := New(t.Context(), next, test.config, "rate-limiter")
if test.expectedError != "" {
assert.EqualError(t, err, test.expectedError)
} else {
require.NoError(t, err)
}
rtl, _ := h.(*rateLimiter)
if test.expectedMaxDelay != 0 {
assert.Equal(t, test.expectedMaxDelay, rtl.maxDelay)
}
if test.expectedSourceIP != "" {
extractor, ok := rtl.sourceMatcher.(utils.ExtractorFunc)
require.True(t, ok, "Not an ExtractorFunc")
req := http.Request{
RemoteAddr: fmt.Sprintf("%s:1234", test.expectedSourceIP),
}
ip, _, err := extractor(&req)
assert.NoError(t, err)
assert.Equal(t, test.expectedSourceIP, ip)
}
if test.requestHeader != "" {
extractor, ok := rtl.sourceMatcher.(utils.ExtractorFunc)
require.True(t, ok, "Not an ExtractorFunc")
req := http.Request{
Header: map[string][]string{
test.config.SourceCriterion.RequestHeaderName: {test.requestHeader},
},
}
hd, _, err := extractor(&req)
assert.NoError(t, err)
assert.Equal(t, test.requestHeader, hd)
}
if test.expectedRTL != 0 {
assert.InDelta(t, float64(test.expectedRTL), float64(rtl.rate), delta)
}
})
}
}
func TestInMemoryRateLimit(t *testing.T) {
testCases := []struct {
desc string
config dynamic.RateLimit
loadDuration time.Duration
incomingLoad int // in reqs/s
burst int
}{
{
desc: "Average is respected",
config: dynamic.RateLimit{
Average: 100,
Burst: 1,
},
loadDuration: 2 * time.Second,
incomingLoad: 400,
},
{
desc: "burst allowed, no bursty traffic",
config: dynamic.RateLimit{
Average: 100,
Burst: 100,
},
loadDuration: 2 * time.Second,
incomingLoad: 200,
},
{
desc: "burst allowed, initial burst, under capacity",
config: dynamic.RateLimit{
Average: 100,
Burst: 100,
},
loadDuration: 2 * time.Second,
incomingLoad: 200,
burst: 50,
},
{
desc: "burst allowed, initial burst, over capacity",
config: dynamic.RateLimit{
Average: 100,
Burst: 100,
},
loadDuration: 2 * time.Second,
incomingLoad: 200,
burst: 150,
},
{
desc: "burst over average, initial burst, over capacity",
config: dynamic.RateLimit{
Average: 100,
Burst: 200,
},
loadDuration: 2 * time.Second,
incomingLoad: 200,
burst: 300,
},
{
desc: "lower than 1/s",
config: dynamic.RateLimit{
Average: 5,
Period: ptypes.Duration(10 * time.Second),
},
loadDuration: 2 * time.Second,
incomingLoad: 100,
burst: 0,
},
{
desc: "lower than 1/s, longer",
config: dynamic.RateLimit{
Average: 5,
Period: ptypes.Duration(10 * time.Second),
},
loadDuration: time.Minute,
incomingLoad: 100,
burst: 0,
},
{
desc: "lower than 1/s, longer, harsher",
config: dynamic.RateLimit{
Average: 1,
Period: ptypes.Duration(time.Minute),
},
loadDuration: time.Minute,
incomingLoad: 100,
burst: 0,
},
{
desc: "period below 1 second",
config: dynamic.RateLimit{
Average: 50,
Period: ptypes.Duration(500 * time.Millisecond),
},
loadDuration: 2 * time.Second,
incomingLoad: 300,
burst: 0,
},
// TODO Try to disambiguate when it fails if it is because of too high a load.
// {
// desc: "Zero average ==> no rate limiting",
// config: dynamic.RateLimit{
// Average: 0,
// Burst: 1,
// },
// incomingLoad: 1000,
// loadDuration: time.Second,
// },
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
if test.loadDuration >= time.Minute && testing.Short() {
t.Skip("skipping test in short mode.")
}
t.Parallel()
reqCount := 0
dropped := 0
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqCount++
})
h, err := New(t.Context(), next, test.config, "rate-limiter")
require.NoError(t, err)
loadPeriod := time.Duration(1e9 / test.incomingLoad)
start := time.Now()
end := start.Add(test.loadDuration)
ticker := time.NewTicker(loadPeriod)
defer ticker.Stop()
for !time.Now().After(end) {
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost", nil)
req.RemoteAddr = "127.0.0.1:1234"
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
if w.Result().StatusCode != http.StatusOK {
dropped++
}
if test.burst > 0 && reqCount < test.burst {
// if a burst is defined we first hammer the server with test.burst requests as fast as possible
continue
}
<-ticker.C
}
stop := time.Now()
elapsed := stop.Sub(start)
burst := test.config.Burst
if burst < 1 {
// actual default value
burst = 1
}
period := time.Duration(test.config.Period)
if period == 0 {
period = time.Second
}
if test.config.Average == 0 {
if reqCount < 75*test.incomingLoad/100 {
t.Fatalf("we (arbitrarily) expect at least 75%% of the requests to go through with no rate limiting, and yet only %d/%d went through", reqCount, test.incomingLoad)
}
if dropped != 0 {
t.Fatalf("no request should have been dropped if rate limiting is disabled, and yet %d were", dropped)
}
return
}
// Note that even when there is no bursty traffic,
// we take into account the configured burst,
// because it also helps absorbing non-bursty traffic.
rate := float64(test.config.Average) / float64(period)
wantCount := int(int64(rate*float64(test.loadDuration)) + burst)
// Allow for a 2% leeway
maxCount := wantCount * 102 / 100
// With very high CPU loads,
// we can expect some extra delay in addition to the rate limiting we already do,
// so we allow for some extra leeway there.
// Feel free to adjust wrt to the load on e.g. the CI.
minCount := computeMinCount(wantCount)
if reqCount < minCount {
t.Fatalf("rate was slower than expected: %d requests (wanted > %d) (dropped %d) in %v", reqCount, minCount, dropped, elapsed)
}
if reqCount > maxCount {
t.Fatalf("rate was faster than expected: %d requests (wanted < %d) (dropped %d) in %v", reqCount, maxCount, dropped, elapsed)
}
})
}
}
func TestRedisRateLimit(t *testing.T) {
testCases := []struct {
desc string
config dynamic.RateLimit
loadDuration time.Duration
incomingLoad int // in reqs/s
burst int
}{
{
desc: "Average is respected",
config: dynamic.RateLimit{
Average: 100,
Burst: 1,
},
loadDuration: 2 * time.Second,
incomingLoad: 400,
},
{
desc: "burst allowed, no bursty traffic",
config: dynamic.RateLimit{
Average: 100,
Burst: 100,
},
loadDuration: 2 * time.Second,
incomingLoad: 200,
},
{
desc: "burst allowed, initial burst, under capacity",
config: dynamic.RateLimit{
Average: 100,
Burst: 100,
},
loadDuration: 2 * time.Second,
incomingLoad: 200,
burst: 50,
},
{
desc: "burst allowed, initial burst, over capacity",
config: dynamic.RateLimit{
Average: 100,
Burst: 100,
},
loadDuration: 2 * time.Second,
incomingLoad: 200,
burst: 150,
},
{
desc: "burst over average, initial burst, over capacity",
config: dynamic.RateLimit{
Average: 100,
Burst: 200,
},
loadDuration: 2 * time.Second,
incomingLoad: 200,
burst: 300,
},
{
desc: "lower than 1/s",
config: dynamic.RateLimit{
// Bug on gopher-lua on parsing the string to number "5e-07" => 0.0000005
// See https://github.com/yuin/gopher-lua/issues/491
// Average: 5,
Average: 1,
Period: ptypes.Duration(10 * time.Second),
},
loadDuration: 2 * time.Second,
incomingLoad: 100,
burst: 0,
},
{
desc: "lower than 1/s, longer",
config: dynamic.RateLimit{
// Bug on gopher-lua on parsing the string to number "5e-07" => 0.0000005
// See https://github.com/yuin/gopher-lua/issues/491
// Average: 5,
Average: 1,
Period: ptypes.Duration(10 * time.Second),
},
loadDuration: time.Minute,
incomingLoad: 100,
burst: 0,
},
{
desc: "lower than 1/s, longer, harsher",
config: dynamic.RateLimit{
Average: 1,
Period: ptypes.Duration(time.Minute),
},
loadDuration: time.Minute,
incomingLoad: 100,
burst: 0,
},
{
desc: "period below 1 second",
config: dynamic.RateLimit{
Average: 50,
Period: ptypes.Duration(500 * time.Millisecond),
},
loadDuration: 2 * time.Second,
incomingLoad: 300,
burst: 0,
},
// TODO Try to disambiguate when it fails if it is because of too high a load.
// {
// desc: "Zero average ==> no rate limiting",
// config: dynamic.RateLimit{
// Average: 0,
// Burst: 1,
// },
// incomingLoad: 1000,
// loadDuration: time.Second,
// },
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
randPort := rand.Int()
if test.loadDuration >= time.Minute && testing.Short() {
t.Skip("skipping test in short mode.")
}
t.Parallel()
reqCount := 0
dropped := 0
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqCount++
})
test.config.Redis = &dynamic.Redis{
Endpoints: []string{"localhost:6379"},
}
h, err := New(t.Context(), next, test.config, "rate-limiter")
require.NoError(t, err)
l := h.(*rateLimiter)
limiter := l.limiter.(*redisLimiter)
limiter.client = newMockRedisClient(limiter.ttl)
h = l
loadPeriod := time.Duration(1e9 / test.incomingLoad)
start := time.Now()
end := start.Add(test.loadDuration)
ticker := time.NewTicker(loadPeriod)
defer ticker.Stop()
for !time.Now().After(end) {
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost", nil)
req.RemoteAddr = "127.0.0." + strconv.Itoa(randPort) + ":" + strconv.Itoa(randPort)
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
if w.Result().StatusCode != http.StatusOK {
dropped++
}
if test.burst > 0 && reqCount < test.burst {
// if a burst is defined we first hammer the server with test.burst requests as fast as possible
continue
}
<-ticker.C
}
stop := time.Now()
elapsed := stop.Sub(start)
burst := test.config.Burst
if burst < 1 {
// actual default value
burst = 1
}
period := time.Duration(test.config.Period)
if period == 0 {
period = time.Second
}
if test.config.Average == 0 {
if reqCount < 75*test.incomingLoad/100 {
t.Fatalf("we (arbitrarily) expect at least 75%% of the requests to go through with no rate limiting, and yet only %d/%d went through", reqCount, test.incomingLoad)
}
if dropped != 0 {
t.Fatalf("no request should have been dropped if rate limiting is disabled, and yet %d were", dropped)
}
return
}
// Note that even when there is no bursty traffic,
// we take into account the configured burst,
// because it also helps absorbing non-bursty traffic.
rate := float64(test.config.Average) / float64(period)
wantCount := int(int64(rate*float64(test.loadDuration)) + burst)
// Allow for a 2% leeway
maxCount := wantCount * 102 / 100
// With very high CPU loads,
// we can expect some extra delay in addition to the rate limiting we already do,
// so we allow for some extra leeway there.
// Feel free to adjust wrt to the load on e.g. the CI.
minCount := computeMinCount(wantCount)
if reqCount < minCount {
t.Fatalf("rate was slower than expected: %d requests (wanted > %d) (dropped %d) in %v", reqCount, minCount, dropped, elapsed)
}
if reqCount > maxCount {
t.Fatalf("rate was faster than expected: %d requests (wanted < %d) (dropped %d) in %v", reqCount, maxCount, dropped, elapsed)
}
})
}
}
type mockRedisClient struct {
ttl int
keys *ttlmap.TtlMap
}
func newMockRedisClient(ttl int) Rediser {
buckets, _ := ttlmap.NewConcurrent(65536)
return &mockRedisClient{
ttl: ttl,
keys: buckets,
}
}
func (m *mockRedisClient) EvalSha(ctx context.Context, _ string, keys []string, args ...interface{}) *redis.Cmd {
state := lua.NewState()
defer state.Close()
tableKeys := state.NewTable()
for _, key := range keys {
tableKeys.Append(lua.LString(key))
}
state.SetGlobal("KEYS", tableKeys)
tableArgv := state.NewTable()
for _, arg := range args {
tableArgv.Append(lua.LString(fmt.Sprint(arg)))
}
state.SetGlobal("ARGV", tableArgv)
mod := state.SetFuncs(state.NewTable(), map[string]lua.LGFunction{
"call": func(state *lua.LState) int {
switch state.Get(1).String() {
case "hset":
key := state.Get(2).String()
keyLast := state.Get(3).String()
last := state.Get(4).String()
keyTokens := state.Get(5).String()
tokens := state.Get(6).String()
table := []string{keyLast, last, keyTokens, tokens}
_ = m.keys.Set(key, table, m.ttl)
case "hgetall":
key := state.Get(2).String()
value, ok := m.keys.Get(key)
table := state.NewTable()
if !ok {
state.Push(table)
} else {
switch v := value.(type) {
case []string:
if len(v) != 4 {
break
}
for i := range v {
table.Append(lua.LString(v[i]))
}
default:
fmt.Printf("Unknown type: %T\n", v)
}
state.Push(table)
}
case "expire":
default:
return 0
}
return 1
},
})
state.SetGlobal("redis", mod)
state.Push(mod)
cmd := redis.NewCmd(ctx)
if err := state.DoString(AllowTokenBucketRaw); err != nil {
cmd.SetErr(err)
return cmd
}
result := state.Get(2)
resultTable, ok := result.(*lua.LTable)
if !ok {
cmd.SetErr(errors.New("unexpected response type: " + result.String()))
return cmd
}
var resultSlice []interface{}
resultTable.ForEach(func(_ lua.LValue, value lua.LValue) {
valueNbr, ok := value.(lua.LNumber)
if !ok {
valueStr, ok := value.(lua.LString)
if !ok {
cmd.SetErr(errors.New("unexpected response value type " + value.String()))
}
resultSlice = append(resultSlice, string(valueStr))
return
}
resultSlice = append(resultSlice, int64(valueNbr))
})
cmd.SetVal(resultSlice)
return cmd
}
func (m *mockRedisClient) Eval(ctx context.Context, script string, keys []string, args ...interface{}) *redis.Cmd {
return m.EvalSha(ctx, script, keys, args...)
}
func (m *mockRedisClient) ScriptExists(ctx context.Context, hashes ...string) *redis.BoolSliceCmd {
return nil
}
func (m *mockRedisClient) ScriptLoad(ctx context.Context, script string) *redis.StringCmd {
return nil
}
func (m *mockRedisClient) Del(ctx context.Context, keys ...string) *redis.IntCmd {
return nil
}
func (m *mockRedisClient) EvalRO(ctx context.Context, script string, keys []string, args ...interface{}) *redis.Cmd {
return nil
}
func (m *mockRedisClient) EvalShaRO(ctx context.Context, sha1 string, keys []string, args ...interface{}) *redis.Cmd {
return nil
}
func computeMinCount(wantCount int) int {
if os.Getenv("CI") != "" {
return wantCount * 60 / 100
}
return wantCount * 95 / 100
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/ratelimiter/in_memory_limiter.go | pkg/middlewares/ratelimiter/in_memory_limiter.go | package ratelimiter
import (
"context"
"fmt"
"time"
"github.com/mailgun/ttlmap"
"github.com/rs/zerolog"
"golang.org/x/time/rate"
)
type inMemoryRateLimiter struct {
rate rate.Limit // reqs/s
burst int64
// maxDelay is the maximum duration we're willing to wait for a bucket reservation to become effective, in nanoseconds.
// For now it is somewhat arbitrarily set to 1/(2*rate).
maxDelay time.Duration
// Each rate limiter for a given source is stored in the buckets ttlmap.
// To keep this ttlmap constrained in size,
// each ratelimiter is "garbage collected" when it is considered expired.
// It is considered expired after it hasn't been used for ttl seconds.
ttl int
buckets *ttlmap.TtlMap // actual buckets, keyed by source.
logger *zerolog.Logger
}
func newInMemoryRateLimiter(rate rate.Limit, burst int64, maxDelay time.Duration, ttl int, logger *zerolog.Logger) (*inMemoryRateLimiter, error) {
buckets, err := ttlmap.NewConcurrent(maxSources)
if err != nil {
return nil, fmt.Errorf("creating ttlmap: %w", err)
}
return &inMemoryRateLimiter{
rate: rate,
burst: burst,
maxDelay: maxDelay,
ttl: ttl,
logger: logger,
buckets: buckets,
}, nil
}
func (i *inMemoryRateLimiter) Allow(_ context.Context, source string) (*time.Duration, error) {
// Get bucket which contains limiter information.
var bucket *rate.Limiter
if rlSource, exists := i.buckets.Get(source); exists {
bucket = rlSource.(*rate.Limiter)
} else {
bucket = rate.NewLimiter(i.rate, int(i.burst))
}
// We Set even in the case where the source already exists,
// because we want to update the expiryTime everytime we get the source,
// as the expiryTime is supposed to reflect the activity (or lack thereof) on that source.
if err := i.buckets.Set(source, bucket, i.ttl); err != nil {
return nil, fmt.Errorf("setting buckets: %w", err)
}
res := bucket.Reserve()
if !res.OK() {
return nil, nil
}
delay := res.Delay()
if delay > i.maxDelay {
res.Cancel()
}
return &delay, nil
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/ratelimiter/lua.go | pkg/middlewares/ratelimiter/lua.go | package ratelimiter
import (
"context"
"github.com/redis/go-redis/v9"
)
type Rediser interface {
Eval(ctx context.Context, script string, keys []string, args ...interface{}) *redis.Cmd
EvalSha(ctx context.Context, sha1 string, keys []string, args ...interface{}) *redis.Cmd
ScriptExists(ctx context.Context, hashes ...string) *redis.BoolSliceCmd
ScriptLoad(ctx context.Context, script string) *redis.StringCmd
Del(ctx context.Context, keys ...string) *redis.IntCmd
EvalRO(ctx context.Context, script string, keys []string, args ...interface{}) *redis.Cmd
EvalShaRO(ctx context.Context, sha1 string, keys []string, args ...interface{}) *redis.Cmd
}
//nolint:dupword
var AllowTokenBucketRaw = `
local key = KEYS[1]
local limit, burst, ttl, t, max_delay = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3]), tonumber(ARGV[4]),
tonumber(ARGV[5])
local bucket = {
limit = limit,
burst = burst,
tokens = 0,
last = 0
}
local rl_source = redis.call('hgetall', key)
if table.maxn(rl_source) == 4 then
-- Get bucket state from redis
bucket.last = tonumber(rl_source[2])
bucket.tokens = tonumber(rl_source[4])
end
local last = bucket.last
if t < last then
last = t
end
local elapsed = t - last
local delta = bucket.limit * elapsed
local tokens = bucket.tokens + delta
tokens = math.min(tokens, bucket.burst)
tokens = tokens - 1
local wait_duration = 0
if tokens < 0 then
wait_duration = (tokens * -1) / bucket.limit
if wait_duration > max_delay then
tokens = tokens + 1
tokens = math.min(tokens, burst)
end
end
redis.call('hset', key, 'last', t, 'tokens', tokens)
redis.call('expire', key, ttl)
return {tostring(true), tostring(wait_duration),tostring(tokens)}`
var AllowTokenBucketScript = redis.NewScript(AllowTokenBucketRaw)
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/tcp/inflightconn/inflight_conn_test.go | pkg/middlewares/tcp/inflightconn/inflight_conn_test.go | package inflightconn
import (
"net"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/tcp"
)
func TestInFlightConn_ServeTCP(t *testing.T) {
proceedCh := make(chan struct{})
waitCh := make(chan struct{})
finishCh := make(chan struct{})
next := tcp.HandlerFunc(func(conn tcp.WriteCloser) {
proceedCh <- struct{}{}
if fc, ok := conn.(fakeConn); !ok || !fc.wait {
return
}
<-waitCh
finishCh <- struct{}{}
})
middleware, err := New(t.Context(), next, dynamic.TCPInFlightConn{Amount: 1}, "foo")
require.NoError(t, err)
// The first connection should succeed and wait.
go middleware.ServeTCP(fakeConn{addr: "127.0.0.1:9000", wait: true})
requireMessage(t, proceedCh)
closeCh := make(chan struct{})
// The second connection from the same remote address should be closed as the maximum number of connections is exceeded.
go middleware.ServeTCP(fakeConn{addr: "127.0.0.1:9000", closeCh: closeCh})
requireMessage(t, closeCh)
// The connection from another remote address should succeed.
go middleware.ServeTCP(fakeConn{addr: "127.0.0.2:9000"})
requireMessage(t, proceedCh)
// Once the first connection is closed, next connection with the same remote address should succeed.
close(waitCh)
requireMessage(t, finishCh)
go middleware.ServeTCP(fakeConn{addr: "127.0.0.1:9000"})
requireMessage(t, proceedCh)
}
func requireMessage(t *testing.T, c chan struct{}) {
t.Helper()
select {
case <-c:
case <-time.After(time.Second):
t.Fatal("Timeout waiting for message")
}
}
type fakeConn struct {
net.Conn
addr string
wait bool
closeCh chan struct{}
}
func (c fakeConn) RemoteAddr() net.Addr {
return fakeAddr{addr: c.addr}
}
func (c fakeConn) Close() error {
close(c.closeCh)
return nil
}
func (c fakeConn) CloseWrite() error {
panic("implement me")
}
type fakeAddr struct {
addr string
}
func (a fakeAddr) Network() string {
return "tcp"
}
func (a fakeAddr) String() string {
return a.addr
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/tcp/inflightconn/inflight_conn.go | pkg/middlewares/tcp/inflightconn/inflight_conn.go | package inflightconn
import (
"context"
"fmt"
"net"
"sync"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/tcp"
)
const typeName = "InFlightConnTCP"
type inFlightConn struct {
name string
next tcp.Handler
maxConnections int64
mu sync.Mutex
connections map[string]int64 // current number of connections by remote IP.
}
// New creates a max connections middleware.
// The connections are identified and grouped by remote IP.
func New(ctx context.Context, next tcp.Handler, config dynamic.TCPInFlightConn, name string) (tcp.Handler, error) {
logger := middlewares.GetLogger(ctx, name, typeName)
logger.Debug().Msg("Creating middleware")
return &inFlightConn{
name: name,
next: next,
connections: make(map[string]int64),
maxConnections: config.Amount,
}, nil
}
// ServeTCP serves the given TCP connection.
func (i *inFlightConn) ServeTCP(conn tcp.WriteCloser) {
logger := middlewares.GetLogger(context.Background(), i.name, typeName)
ip, _, err := net.SplitHostPort(conn.RemoteAddr().String())
if err != nil {
logger.Error().Err(err).Msg("Cannot parse IP from remote addr")
conn.Close()
return
}
if err = i.increment(ip); err != nil {
logger.Error().Err(err).Msg("Connection rejected")
conn.Close()
return
}
defer i.decrement(ip)
i.next.ServeTCP(conn)
}
// increment increases the counter for the number of connections tracked for the
// given IP.
// It returns an error if the counter would go above the max allowed number of
// connections.
func (i *inFlightConn) increment(ip string) error {
i.mu.Lock()
defer i.mu.Unlock()
if i.connections[ip] >= i.maxConnections {
return fmt.Errorf("max number of connections reached for %s", ip)
}
i.connections[ip]++
return nil
}
// decrement decreases the counter for the number of connections tracked for the
// given IP.
// It ensures that the counter does not go below zero.
func (i *inFlightConn) decrement(ip string) {
i.mu.Lock()
defer i.mu.Unlock()
if i.connections[ip] <= 0 {
return
}
i.connections[ip]--
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/tcp/ipallowlist/ip_allowlist_test.go | pkg/middlewares/tcp/ipallowlist/ip_allowlist_test.go | package ipallowlist
import (
"context"
"io"
"net"
"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/tcp"
)
func TestNewIPAllowLister(t *testing.T) {
testCases := []struct {
desc string
allowList dynamic.TCPIPAllowList
expectedError bool
}{
{
desc: "Empty config",
allowList: dynamic.TCPIPAllowList{},
expectedError: true,
},
{
desc: "invalid IP",
allowList: dynamic.TCPIPAllowList{
SourceRange: []string{"foo"},
},
expectedError: true,
},
{
desc: "valid IP",
allowList: dynamic.TCPIPAllowList{
SourceRange: []string{"10.10.10.10"},
},
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
next := tcp.HandlerFunc(func(conn tcp.WriteCloser) {})
allowLister, err := New(t.Context(), next, test.allowList, "traefikTest")
if test.expectedError {
assert.Error(t, err)
} else {
require.NoError(t, err)
assert.NotNil(t, allowLister)
}
})
}
}
func TestIPAllowLister_ServeHTTP(t *testing.T) {
testCases := []struct {
desc string
allowList dynamic.TCPIPAllowList
remoteAddr string
expected string
}{
{
desc: "authorized with remote address",
allowList: dynamic.TCPIPAllowList{
SourceRange: []string{"20.20.20.20"},
},
remoteAddr: "20.20.20.20:1234",
expected: "OK",
},
{
desc: "non authorized with remote address",
allowList: dynamic.TCPIPAllowList{
SourceRange: []string{"20.20.20.20"},
},
remoteAddr: "20.20.20.21:1234",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
next := tcp.HandlerFunc(func(conn tcp.WriteCloser) {
write, err := conn.Write([]byte("OK"))
require.NoError(t, err)
assert.Equal(t, 2, write)
err = conn.Close()
require.NoError(t, err)
})
allowLister, err := New(t.Context(), next, test.allowList, "traefikTest")
require.NoError(t, err)
server, client := net.Pipe()
go func() {
allowLister.ServeTCP(&contextWriteCloser{client, addr{test.remoteAddr}})
}()
read, err := io.ReadAll(server)
require.NoError(t, err)
assert.Equal(t, test.expected, string(read))
})
}
}
type contextWriteCloser struct {
net.Conn
addr
}
type addr struct {
remoteAddr string
}
func (a addr) Network() string {
panic("implement me")
}
func (a addr) String() string {
return a.remoteAddr
}
func (c contextWriteCloser) CloseWrite() error {
panic("implement me")
}
func (c contextWriteCloser) RemoteAddr() net.Addr { return c.addr }
func (c contextWriteCloser) Context() context.Context {
return context.Background()
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/tcp/ipallowlist/ip_allowlist.go | pkg/middlewares/tcp/ipallowlist/ip_allowlist.go | package ipallowlist
import (
"context"
"errors"
"fmt"
"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/tcp"
)
const (
typeName = "IPAllowListerTCP"
)
// ipAllowLister is a middleware that provides Checks of the Requesting IP against a set of Allowlists.
type ipAllowLister struct {
next tcp.Handler
allowLister *ip.Checker
name string
}
// New builds a new TCP IPAllowLister given a list of CIDR-Strings to allow.
func New(ctx context.Context, next tcp.Handler, config dynamic.TCPIPAllowList, name string) (tcp.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, IPAllowLister not created")
}
checker, err := ip.NewChecker(config.SourceRange)
if err != nil {
return nil, fmt.Errorf("cannot parse CIDRs %s: %w", config.SourceRange, err)
}
logger.Debug().Msgf("Setting up IPAllowLister with sourceRange: %s", config.SourceRange)
return &ipAllowLister{
allowLister: checker,
next: next,
name: name,
}, nil
}
func (al *ipAllowLister) ServeTCP(conn tcp.WriteCloser) {
logger := middlewares.GetLogger(context.Background(), al.name, typeName)
addr := conn.RemoteAddr().String()
err := al.allowLister.IsAuthorized(addr)
if err != nil {
logger.Error().Err(err).Msgf("Connection from %s rejected", addr)
conn.Close()
return
}
logger.Debug().Msgf("Connection from %s accepted", addr)
al.next.ServeTCP(conn)
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/tcp/ipwhitelist/ip_whitelist_test.go | pkg/middlewares/tcp/ipwhitelist/ip_whitelist_test.go | package ipwhitelist
import (
"context"
"io"
"net"
"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/tcp"
)
func TestNewIPWhiteLister(t *testing.T) {
testCases := []struct {
desc string
whiteList dynamic.TCPIPWhiteList
expectedError bool
}{
{
desc: "Empty config",
whiteList: dynamic.TCPIPWhiteList{},
expectedError: true,
},
{
desc: "invalid IP",
whiteList: dynamic.TCPIPWhiteList{
SourceRange: []string{"foo"},
},
expectedError: true,
},
{
desc: "valid IP",
whiteList: dynamic.TCPIPWhiteList{
SourceRange: []string{"10.10.10.10"},
},
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
next := tcp.HandlerFunc(func(conn tcp.WriteCloser) {})
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.TCPIPWhiteList
remoteAddr string
expected string
}{
{
desc: "authorized with remote address",
whiteList: dynamic.TCPIPWhiteList{
SourceRange: []string{"20.20.20.20"},
},
remoteAddr: "20.20.20.20:1234",
expected: "OK",
},
{
desc: "non authorized with remote address",
whiteList: dynamic.TCPIPWhiteList{
SourceRange: []string{"20.20.20.20"},
},
remoteAddr: "20.20.20.21:1234",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
next := tcp.HandlerFunc(func(conn tcp.WriteCloser) {
write, err := conn.Write([]byte("OK"))
require.NoError(t, err)
assert.Equal(t, 2, write)
err = conn.Close()
require.NoError(t, err)
})
whiteLister, err := New(t.Context(), next, test.whiteList, "traefikTest")
require.NoError(t, err)
server, client := net.Pipe()
go func() {
whiteLister.ServeTCP(&contextWriteCloser{client, addr{test.remoteAddr}})
}()
read, err := io.ReadAll(server)
require.NoError(t, err)
assert.Equal(t, test.expected, string(read))
})
}
}
type contextWriteCloser struct {
net.Conn
addr
}
type addr struct {
remoteAddr string
}
func (a addr) Network() string {
panic("implement me")
}
func (a addr) String() string {
return a.remoteAddr
}
func (c contextWriteCloser) CloseWrite() error {
panic("implement me")
}
func (c contextWriteCloser) RemoteAddr() net.Addr { return c.addr }
func (c contextWriteCloser) Context() context.Context {
return context.Background()
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/tcp/ipwhitelist/ip_whitelist.go | pkg/middlewares/tcp/ipwhitelist/ip_whitelist.go | package ipwhitelist
import (
"context"
"errors"
"fmt"
"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/tcp"
)
const (
typeName = "IPWhiteListerTCP"
)
// ipWhiteLister is a middleware that provides Checks of the Requesting IP against a set of Whitelists.
type ipWhiteLister struct {
next tcp.Handler
whiteLister *ip.Checker
name string
}
// New builds a new TCP IPWhiteLister given a list of CIDR-Strings to whitelist.
func New(ctx context.Context, next tcp.Handler, config dynamic.TCPIPWhiteList, name string) (tcp.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)
}
logger.Debug().Msgf("Setting up IPWhiteLister with sourceRange: %s", config.SourceRange)
return &ipWhiteLister{
whiteLister: checker,
next: next,
name: name,
}, nil
}
func (wl *ipWhiteLister) ServeTCP(conn tcp.WriteCloser) {
logger := middlewares.GetLogger(context.Background(), wl.name, typeName)
addr := conn.RemoteAddr().String()
err := wl.whiteLister.IsAuthorized(addr)
if err != nil {
logger.Error().Err(err).Msgf("Connection from %s rejected", addr)
conn.Close()
return
}
logger.Debug().Msgf("Connection from %s accepted", addr)
wl.next.ServeTCP(conn)
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/stripprefixregex/strip_prefix_regex_test.go | pkg/middlewares/stripprefixregex/strip_prefix_regex_test.go | package stripprefixregex
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"
"github.com/traefik/traefik/v3/pkg/middlewares/stripprefix"
"github.com/traefik/traefik/v3/pkg/testhelpers"
)
func TestStripPrefixRegex(t *testing.T) {
testPrefixRegex := dynamic.StripPrefixRegex{
Regex: []string{"/a/api/", "/b/([a-z0-9]+)/", "/c/[a-z0-9]+/[0-9]+/"},
}
testCases := []struct {
path string
expectedStatusCode int
expectedPath string
expectedRawPath string
expectedHeader string
}{
{
path: "/a/test",
expectedStatusCode: http.StatusOK,
expectedPath: "/a/test",
},
{
path: "/a/test/",
expectedStatusCode: http.StatusOK,
expectedPath: "/a/test/",
},
{
path: "/a/api/",
expectedStatusCode: http.StatusOK,
expectedPath: "",
expectedHeader: "/a/api/",
},
{
path: "/a/api/test",
expectedStatusCode: http.StatusOK,
expectedPath: "/test",
expectedHeader: "/a/api/",
},
{
path: "/a/api/test/",
expectedStatusCode: http.StatusOK,
expectedPath: "/test/",
expectedHeader: "/a/api/",
},
{
path: "/b/api/",
expectedStatusCode: http.StatusOK,
expectedPath: "",
expectedHeader: "/b/api/",
},
{
path: "/b/api",
expectedStatusCode: http.StatusOK,
expectedPath: "/b/api",
},
{
path: "/b/api/test1",
expectedStatusCode: http.StatusOK,
expectedPath: "/test1",
expectedHeader: "/b/api/",
},
{
path: "/b/api2/test2",
expectedStatusCode: http.StatusOK,
expectedPath: "/test2",
expectedHeader: "/b/api2/",
},
{
path: "/c/api/123/",
expectedStatusCode: http.StatusOK,
expectedPath: "",
expectedHeader: "/c/api/123/",
},
{
path: "/c/api/123",
expectedStatusCode: http.StatusOK,
expectedPath: "/c/api/123",
},
{
path: "/c/api/123/test3",
expectedStatusCode: http.StatusOK,
expectedPath: "/test3",
expectedHeader: "/c/api/123/",
},
{
path: "/c/api/abc/test4",
expectedStatusCode: http.StatusOK,
expectedPath: "/c/api/abc/test4",
},
{
path: "/a/api/a%2Fb",
expectedStatusCode: http.StatusOK,
expectedPath: "/a/b",
expectedRawPath: "/a%2Fb",
expectedHeader: "/a/api/",
},
}
for _, test := range testCases {
t.Run(test.path, func(t *testing.T) {
t.Parallel()
var actualPath, actualRawPath, actualHeader, requestURI string
handlerPath := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
actualPath = r.URL.Path
actualRawPath = r.URL.RawPath
actualHeader = r.Header.Get(stripprefix.ForwardedPrefixHeader)
requestURI = r.RequestURI
})
handler, err := New(t.Context(), handlerPath, testPrefixRegex, "foo-strip-prefix-regex")
require.NoError(t, err)
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost"+test.path, nil)
resp := &httptest.ResponseRecorder{Code: http.StatusOK}
handler.ServeHTTP(resp, req)
assert.Equal(t, test.expectedStatusCode, resp.Code, "Unexpected status code.")
assert.Equal(t, test.expectedPath, actualPath, "Unexpected path.")
assert.Equal(t, test.expectedRawPath, actualRawPath, "Unexpected raw path.")
assert.Equal(t, test.expectedHeader, actualHeader, "Unexpected '%s' header.", stripprefix.ForwardedPrefixHeader)
if test.expectedPath != test.path {
expectedRequestURI := test.expectedPath
if test.expectedRawPath != "" {
// go HTTP uses the raw path when existent in the RequestURI
expectedRequestURI = test.expectedRawPath
}
if test.expectedPath == "" {
expectedRequestURI = "/"
}
assert.Equal(t, expectedRequestURI, requestURI, "Unexpected request URI.")
}
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/stripprefixregex/strip_prefix_regex.go | pkg/middlewares/stripprefixregex/strip_prefix_regex.go | package stripprefixregex
import (
"context"
"net/http"
"regexp"
"strings"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/middlewares/stripprefix"
)
const (
typeName = "StripPrefixRegex"
)
// StripPrefixRegex is a middleware used to strip prefix from an URL request.
type stripPrefixRegex struct {
next http.Handler
expressions []*regexp.Regexp
name string
}
// New builds a new StripPrefixRegex middleware.
func New(ctx context.Context, next http.Handler, config dynamic.StripPrefixRegex, name string) (http.Handler, error) {
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
stripPrefix := stripPrefixRegex{
next: next,
name: name,
}
for _, exp := range config.Regex {
reg, err := regexp.Compile(strings.TrimSpace(exp))
if err != nil {
return nil, err
}
stripPrefix.expressions = append(stripPrefix.expressions, reg)
}
return &stripPrefix, nil
}
func (s *stripPrefixRegex) GetTracingInformation() (string, string) {
return s.name, typeName
}
func (s *stripPrefixRegex) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
for _, exp := range s.expressions {
parts := exp.FindStringSubmatch(req.URL.Path)
if len(parts) > 0 && len(parts[0]) > 0 {
prefix := parts[0]
if !strings.HasPrefix(req.URL.Path, prefix) {
continue
}
req.Header.Add(stripprefix.ForwardedPrefixHeader, prefix)
req.URL.Path = ensureLeadingSlash(strings.Replace(req.URL.Path, prefix, "", 1))
if req.URL.RawPath != "" {
req.URL.RawPath = ensureLeadingSlash(req.URL.RawPath[len(prefix):])
}
req.RequestURI = req.URL.RequestURI()
s.next.ServeHTTP(rw, req)
return
}
}
s.next.ServeHTTP(rw, req)
}
func ensureLeadingSlash(str string) string {
if str == "" {
return str
}
if str[0] == '/' {
return str
}
return "/" + str
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/grpcweb/grpcweb.go | pkg/middlewares/grpcweb/grpcweb.go | package grpcweb
import (
"context"
"net/http"
"github.com/traefik/grpc-web/go/grpcweb"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
)
const typeName = "GRPCWeb"
// New builds a new gRPC web request converter.
func New(ctx context.Context, next http.Handler, config dynamic.GrpcWeb, name string) http.Handler {
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
return grpcweb.WrapHandler(next, grpcweb.WithCorsForRegisteredEndpointsOnly(false), grpcweb.WithOriginFunc(func(origin string) bool {
for _, originCfg := range config.AllowOrigins {
if originCfg == "*" || originCfg == origin {
return true
}
}
return false
}))
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/denyrouterrecursion/deny_router_recursion_test.go | pkg/middlewares/denyrouterrecursion/deny_router_recursion_test.go | package denyrouterrecursion
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestServeHTTP(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, "", nil)
require.NoError(t, err)
_, err = New("", http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {}))
require.Error(t, err)
next := 0
m, err := New("myRouter", http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
next++
}))
require.NoError(t, err)
recorder := httptest.NewRecorder()
m.ServeHTTP(recorder, req)
assert.Equal(t, http.StatusOK, recorder.Code)
assert.Equal(t, "995d26092d19a224", m.routerNameHash)
assert.Equal(t, m.routerNameHash, req.Header.Get(xTraefikRouter))
assert.Equal(t, 1, next)
recorder = httptest.NewRecorder()
m.ServeHTTP(recorder, req)
assert.Equal(t, 1, next)
assert.Equal(t, http.StatusBadRequest, recorder.Code)
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/denyrouterrecursion/deny_router_recursion.go | pkg/middlewares/denyrouterrecursion/deny_router_recursion.go | package denyrouterrecursion
import (
"errors"
"hash/fnv"
"net/http"
"strconv"
"github.com/containous/alice"
"github.com/rs/zerolog/log"
"github.com/traefik/traefik/v3/pkg/observability/logs"
)
const xTraefikRouter = "X-Traefik-Router"
type DenyRouterRecursion struct {
routerName string
routerNameHash string
next http.Handler
}
// WrapHandler Wraps router to alice.Constructor.
func WrapHandler(routerName string) alice.Constructor {
return func(next http.Handler) (http.Handler, error) {
return New(routerName, next)
}
}
// New creates a new DenyRouterRecursion.
// DenyRouterRecursion middleware is an internal middleware used to avoid infinite requests loop on the same router.
func New(routerName string, next http.Handler) (*DenyRouterRecursion, error) {
if routerName == "" {
return nil, errors.New("routerName cannot be empty")
}
return &DenyRouterRecursion{
routerName: routerName,
routerNameHash: makeHash(routerName),
next: next,
}, nil
}
// ServeHTTP implements http.Handler.
func (l *DenyRouterRecursion) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if req.Header.Get(xTraefikRouter) == l.routerNameHash {
logger := log.With().Str(logs.MiddlewareType, "DenyRouterRecursion").Logger()
logger.Debug().Msgf("Rejecting request in provenance of the same router (%q) to stop potential infinite loop.", l.routerName)
rw.WriteHeader(http.StatusBadRequest)
return
}
req.Header.Set(xTraefikRouter, l.routerNameHash)
l.next.ServeHTTP(rw, req)
}
func makeHash(routerName string) string {
hasher := fnv.New64()
// purposely ignoring the error, as no error can be returned from the implementation.
_, _ = hasher.Write([]byte(routerName))
return strconv.FormatUint(hasher.Sum64(), 16)
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/requestdecorator/hostresolver.go | pkg/middlewares/requestdecorator/hostresolver.go | package requestdecorator
import (
"context"
"errors"
"fmt"
"net"
"sort"
"strings"
"time"
"github.com/miekg/dns"
"github.com/patrickmn/go-cache"
"github.com/rs/zerolog/log"
)
type cnameResolv struct {
TTL time.Duration
Record string
}
type byTTL []*cnameResolv
func (a byTTL) Len() int { return len(a) }
func (a byTTL) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byTTL) Less(i, j int) bool { return a[i].TTL > a[j].TTL }
// Resolver used for host resolver.
type Resolver struct {
CnameFlattening bool
ResolvConfig string
ResolvDepth int
cache *cache.Cache
}
// CNAMEFlatten check if CNAME record exists, flatten if possible.
func (hr *Resolver) CNAMEFlatten(ctx context.Context, host string) string {
if hr.cache == nil {
hr.cache = cache.New(30*time.Minute, 5*time.Minute)
}
result := host
request := host
value, found := hr.cache.Get(host)
if found {
return value.(string)
}
logger := log.Ctx(ctx)
cacheDuration := 0 * time.Second
for depth := range hr.ResolvDepth {
resolv, err := cnameResolve(ctx, request, hr.ResolvConfig)
if err != nil {
logger.Error().Err(err).Send()
break
}
if resolv == nil {
break
}
result = resolv.Record
if depth == 0 {
cacheDuration = resolv.TTL
}
request = resolv.Record
}
hr.cache.Set(host, result, cacheDuration)
return result
}
// cnameResolve resolves CNAME if exists, and return with the highest TTL.
func cnameResolve(ctx context.Context, host, resolvPath string) (*cnameResolv, error) {
config, err := dns.ClientConfigFromFile(resolvPath)
if err != nil {
return nil, fmt.Errorf("invalid resolver configuration file: %s", resolvPath)
}
if net.ParseIP(host) != nil {
return nil, nil
}
client := &dns.Client{Timeout: 30 * time.Second}
m := &dns.Msg{}
m.SetQuestion(dns.Fqdn(host), dns.TypeCNAME)
var result []*cnameResolv
for _, server := range config.Servers {
tempRecord, err := getRecord(client, m, server, config.Port)
if err != nil {
if errors.Is(err, errNoCNAMERecord) {
log.Ctx(ctx).Debug().Err(err).Msgf("CNAME lookup for hostname %q", host)
continue
}
log.Ctx(ctx).Error().Err(err).Msgf("CNAME lookup for hostname %q", host)
continue
}
result = append(result, tempRecord)
}
if len(result) == 0 {
return nil, nil
}
sort.Sort(byTTL(result))
return result[0], nil
}
var errNoCNAMERecord = errors.New("no CNAME record for host")
func getRecord(client *dns.Client, msg *dns.Msg, server, port string) (*cnameResolv, error) {
resp, _, err := client.Exchange(msg, net.JoinHostPort(server, port))
if err != nil {
return nil, fmt.Errorf("exchange error for server %s: %w", server, err)
}
if resp == nil || len(resp.Answer) == 0 {
return nil, fmt.Errorf("%w: %s", errNoCNAMERecord, server)
}
rr, ok := resp.Answer[0].(*dns.CNAME)
if !ok {
return nil, fmt.Errorf("invalid response type for server %s", server)
}
return &cnameResolv{
TTL: time.Duration(rr.Hdr.Ttl) * time.Second,
Record: strings.TrimSuffix(rr.Target, "."),
}, nil
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/requestdecorator/request_decorator_test.go | pkg/middlewares/requestdecorator/request_decorator_test.go | package requestdecorator
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/traefik/traefik/v3/pkg/testhelpers"
"github.com/traefik/traefik/v3/pkg/types"
)
func TestRequestHost(t *testing.T) {
testCases := []struct {
desc string
url string
expected string
}{
{
desc: "host without :",
url: "http://host",
expected: "host",
},
{
desc: "host with : and without port",
url: "http://host:",
expected: "host",
},
{
desc: "IP host with : and with port",
url: "http://127.0.0.1:123",
expected: "127.0.0.1",
},
{
desc: "IP host with : and without port",
url: "http://127.0.0.1:",
expected: "127.0.0.1",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
next := http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
host := GetCanonizedHost(r.Context())
assert.Equal(t, test.expected, host)
})
rh := New(nil)
req := testhelpers.MustNewRequest(http.MethodGet, test.url, nil)
rh.ServeHTTP(nil, req, next)
})
}
}
func TestRequestFlattening(t *testing.T) {
testCases := []struct {
desc string
url string
expected string
}{
{
desc: "host with flattening",
url: "http://www.github.com",
expected: "github.com",
},
{
desc: "host without flattening",
url: "http://github.com",
expected: "github.com",
},
{
desc: "ip without flattening",
url: "http://127.0.0.1",
expected: "127.0.0.1",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
next := http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
host := GetCNAMEFlatten(r.Context())
assert.Equal(t, test.expected, host)
})
rh := New(
&types.HostResolverConfig{
CnameFlattening: true,
ResolvConfig: "/etc/resolv.conf",
ResolvDepth: 5,
},
)
req := testhelpers.MustNewRequest(http.MethodGet, test.url, nil)
rh.ServeHTTP(nil, req, next)
})
}
}
func Test_parseHost(t *testing.T) {
testCases := []struct {
desc string
host string
expected string
}{
{
desc: "host without :",
host: "host",
expected: "host",
},
{
desc: "host with : and without port",
host: "host:",
expected: "host",
},
{
desc: "IP host with : and with port",
host: "127.0.0.1:123",
expected: "127.0.0.1",
},
{
desc: "IP host with : and without port",
host: "127.0.0.1:",
expected: "127.0.0.1",
},
{
desc: "host with : and without port",
host: "fe80::215:5dff:fe20:cd6a",
expected: "fe80::215:5dff:fe20:cd6a",
},
{
desc: "IPv6 host with : and with port",
host: "[fe80::215:5dff:fe20:cd6a]:123",
expected: "fe80::215:5dff:fe20:cd6a",
},
{
desc: "IPv6 host with : and without port",
host: "[fe80::215:5dff:fe20:cd6a]:",
expected: "fe80::215:5dff:fe20:cd6a",
},
{
desc: "IPv6 host without : and without port",
host: "[fe80::215:5dff:fe20:cd6a]",
expected: "fe80::215:5dff:fe20:cd6a",
},
{
desc: "invalid IPv6: missing [",
host: "fe80::215:5dff:fe20:cd6a]",
expected: "fe80::215:5dff:fe20:cd6a]",
},
{
desc: "invalid IPv6: missing ]",
host: "[fe80::215:5dff:fe20:cd6a",
expected: "[fe80::215:5dff:fe20:cd6a",
},
{
desc: "empty address",
host: "",
expected: "",
},
{
desc: "only :",
host: ":",
expected: "",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
actual := parseHost(test.host)
assert.Equal(t, test.expected, actual)
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/requestdecorator/request_decorator.go | pkg/middlewares/requestdecorator/request_decorator.go | package requestdecorator
import (
"context"
"net"
"net/http"
"strings"
"github.com/containous/alice"
"github.com/traefik/traefik/v3/pkg/types"
)
const (
canonicalKey key = "canonical"
flattenKey key = "flatten"
)
type key string
// RequestDecorator is the struct for the middleware that adds the CanonicalDomain of the request Host into a context for later use.
type RequestDecorator struct {
hostResolver *Resolver
}
// New creates a new request host middleware.
func New(hostResolverConfig *types.HostResolverConfig) *RequestDecorator {
requestDecorator := &RequestDecorator{}
if hostResolverConfig != nil {
requestDecorator.hostResolver = &Resolver{
CnameFlattening: hostResolverConfig.CnameFlattening,
ResolvConfig: hostResolverConfig.ResolvConfig,
ResolvDepth: hostResolverConfig.ResolvDepth,
}
}
return requestDecorator
}
func (r *RequestDecorator) ServeHTTP(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
host := types.CanonicalDomain(parseHost(req.Host))
reqt := req.WithContext(context.WithValue(req.Context(), canonicalKey, host))
if r.hostResolver != nil && r.hostResolver.CnameFlattening {
flatHost := r.hostResolver.CNAMEFlatten(reqt.Context(), host)
reqt = reqt.WithContext(context.WithValue(reqt.Context(), flattenKey, flatHost))
}
next(rw, reqt)
}
func parseHost(addr string) string {
if !strings.Contains(addr, ":") {
// IPv4 without port or empty address
return addr
}
// IPv4 with port or IPv6
host, _, err := net.SplitHostPort(addr)
if err != nil {
if addr[0] == '[' && addr[len(addr)-1] == ']' {
return addr[1 : len(addr)-1]
}
return addr
}
return host
}
// GetCanonizedHost retrieves the canonized host from the given context (previously stored in the request context by the middleware).
func GetCanonizedHost(ctx context.Context) string {
if val, ok := ctx.Value(canonicalKey).(string); ok {
return val
}
return ""
}
// GetCNAMEFlatten return the flat name if it is present in the context.
func GetCNAMEFlatten(ctx context.Context) string {
if val, ok := ctx.Value(flattenKey).(string); ok {
return val
}
return ""
}
// WrapHandler Wraps a ServeHTTP with next to an alice.Constructor.
func WrapHandler(handler *RequestDecorator) alice.Constructor {
return func(next http.Handler) (http.Handler, error) {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
handler.ServeHTTP(rw, req, next.ServeHTTP)
}), nil
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/requestdecorator/hostresolver_test.go | pkg/middlewares/requestdecorator/hostresolver_test.go | package requestdecorator
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestCNAMEFlatten(t *testing.T) {
testCases := []struct {
desc string
resolvFile string
domain string
expectedDomain string
}{
{
desc: "host request is CNAME record",
resolvFile: "/etc/resolv.conf",
domain: "www.github.com",
expectedDomain: "github.com",
},
{
desc: "resolve file not found",
resolvFile: "/etc/resolv.oops",
domain: "www.github.com",
expectedDomain: "www.github.com",
},
{
desc: "host request is not CNAME record",
resolvFile: "/etc/resolv.conf",
domain: "github.com",
expectedDomain: "github.com",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
hostResolver := &Resolver{
ResolvConfig: test.resolvFile,
ResolvDepth: 5,
}
flatH := hostResolver.CNAMEFlatten(t.Context(), test.domain)
assert.Equal(t, test.expectedDomain, flatH)
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/stripprefix/strip_prefix_test.go | pkg/middlewares/stripprefix/strip_prefix_test.go | package stripprefix
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"
"github.com/traefik/traefik/v3/pkg/testhelpers"
)
func TestStripPrefix(t *testing.T) {
testCases := []struct {
desc string
config dynamic.StripPrefix
path string
expectedStatusCode int
expectedPath string
expectedRawPath string
expectedHeader string
}{
{
desc: "no prefixes configured",
config: dynamic.StripPrefix{
Prefixes: []string{},
},
path: "/noprefixes",
expectedStatusCode: http.StatusOK,
expectedPath: "/noprefixes",
},
{
desc: "wildcard (.*) requests",
config: dynamic.StripPrefix{
Prefixes: []string{"/"},
},
path: "/",
expectedStatusCode: http.StatusOK,
expectedPath: "",
expectedHeader: "/",
},
{
desc: "prefix and path matching",
config: dynamic.StripPrefix{
Prefixes: []string{"/stat"},
},
path: "/stat",
expectedStatusCode: http.StatusOK,
expectedPath: "",
expectedHeader: "/stat",
},
{
desc: "path prefix on exactly matching path",
config: dynamic.StripPrefix{
Prefixes: []string{"/stat/"},
},
path: "/stat/",
expectedStatusCode: http.StatusOK,
expectedPath: "",
expectedHeader: "/stat/",
},
{
desc: "path prefix on matching longer path",
config: dynamic.StripPrefix{
Prefixes: []string{"/stat/"},
},
path: "/stat/us",
expectedStatusCode: http.StatusOK,
expectedPath: "/us",
expectedHeader: "/stat/",
},
{
desc: "path prefix on mismatching path",
config: dynamic.StripPrefix{
Prefixes: []string{"/stat/"},
},
path: "/status",
expectedStatusCode: http.StatusOK,
expectedPath: "/status",
},
{
desc: "general prefix on matching path",
config: dynamic.StripPrefix{
Prefixes: []string{"/stat"},
},
path: "/stat/",
expectedStatusCode: http.StatusOK,
expectedPath: "/",
expectedHeader: "/stat",
},
{
desc: "earlier prefix matching",
config: dynamic.StripPrefix{
Prefixes: []string{"/stat", "/stat/us"},
},
path: "/stat/us",
expectedStatusCode: http.StatusOK,
expectedPath: "/us",
expectedHeader: "/stat",
},
{
desc: "later prefix matching",
config: dynamic.StripPrefix{
Prefixes: []string{"/mismatch", "/stat"},
},
path: "/stat",
expectedStatusCode: http.StatusOK,
expectedPath: "",
expectedHeader: "/stat",
},
{
desc: "prefix matching within slash boundaries",
config: dynamic.StripPrefix{
Prefixes: []string{"/stat"},
},
path: "/status",
expectedStatusCode: http.StatusOK,
expectedPath: "/us",
expectedHeader: "/stat",
},
{
desc: "raw path is also stripped",
config: dynamic.StripPrefix{
Prefixes: []string{"/stat"},
},
path: "/stat/a%2Fb",
expectedStatusCode: http.StatusOK,
expectedPath: "/a/b",
expectedRawPath: "/a%2Fb",
expectedHeader: "/stat",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
var actualPath, actualRawPath, actualHeader, requestURI string
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
actualPath = r.URL.Path
actualRawPath = r.URL.RawPath
actualHeader = r.Header.Get(ForwardedPrefixHeader)
requestURI = r.RequestURI
})
pointer := func(v bool) *bool { return &v }
test.config.ForceSlash = pointer(false)
handler, err := New(t.Context(), next, test.config, "foo-strip-prefix")
require.NoError(t, err)
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost"+test.path, nil)
req.RequestURI = req.URL.RequestURI()
resp := &httptest.ResponseRecorder{Code: http.StatusOK}
handler.ServeHTTP(resp, req)
assert.Equal(t, test.expectedStatusCode, resp.Code, "Unexpected status code.")
assert.Equal(t, test.expectedPath, actualPath, "Unexpected path.")
assert.Equal(t, test.expectedRawPath, actualRawPath, "Unexpected raw path.")
assert.Equal(t, test.expectedHeader, actualHeader, "Unexpected '%s' header.", ForwardedPrefixHeader)
expectedRequestURI := test.expectedPath
if test.expectedRawPath != "" {
// go HTTP uses the raw path when existent in the RequestURI
expectedRequestURI = test.expectedRawPath
}
if test.expectedPath == "" {
expectedRequestURI = "/"
}
assert.Equal(t, expectedRequestURI, requestURI, "Unexpected request URI.")
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/stripprefix/strip_prefix.go | pkg/middlewares/stripprefix/strip_prefix.go | package stripprefix
import (
"context"
"net/http"
"strings"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
)
const (
// ForwardedPrefixHeader is the default header to set prefix.
ForwardedPrefixHeader = "X-Forwarded-Prefix"
typeName = "StripPrefix"
)
// stripPrefix is a middleware used to strip prefix from an URL request.
type stripPrefix struct {
next http.Handler
prefixes []string
name string
// Deprecated: Must be removed (breaking), the default behavior must be forceSlash=false
forceSlash bool
}
// New creates a new strip prefix middleware.
func New(ctx context.Context, next http.Handler, config dynamic.StripPrefix, name string) (http.Handler, error) {
logger := middlewares.GetLogger(ctx, name, typeName)
logger.Debug().Msg("Creating middleware")
if config.ForceSlash != nil {
logger.Warn().Msgf("`ForceSlash` option is deprecated, please remove any usage of this option.")
}
// Handle default value (here because of deprecation and the removal of setDefault).
forceSlash := config.ForceSlash != nil && *config.ForceSlash
return &stripPrefix{
prefixes: config.Prefixes,
next: next,
name: name,
forceSlash: forceSlash,
}, nil
}
func (s *stripPrefix) GetTracingInformation() (string, string) {
return s.name, typeName
}
func (s *stripPrefix) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
for _, prefix := range s.prefixes {
if strings.HasPrefix(req.URL.Path, prefix) {
req.URL.Path = s.getPrefixStripped(req.URL.Path, prefix)
if req.URL.RawPath != "" {
req.URL.RawPath = s.getPrefixStripped(req.URL.RawPath, prefix)
}
s.serveRequest(rw, req, strings.TrimSpace(prefix))
return
}
}
s.next.ServeHTTP(rw, req)
}
func (s *stripPrefix) serveRequest(rw http.ResponseWriter, req *http.Request, prefix string) {
req.Header.Add(ForwardedPrefixHeader, prefix)
req.RequestURI = req.URL.RequestURI()
s.next.ServeHTTP(rw, req)
}
func (s *stripPrefix) getPrefixStripped(urlPath, prefix string) string {
if s.forceSlash {
// Only for compatibility reason with the previous behavior,
// but the previous behavior is wrong.
// This needs to be removed in the next breaking version.
return "/" + strings.TrimPrefix(strings.TrimPrefix(urlPath, prefix), "/")
}
return ensureLeadingSlash(strings.TrimPrefix(urlPath, prefix))
}
func ensureLeadingSlash(str string) string {
if str == "" {
return str
}
if str[0] == '/' {
return str
}
return "/" + str
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/forwardedheaders/forwarded_header.go | pkg/middlewares/forwardedheaders/forwarded_header.go | package forwardedheaders
import (
"net"
"net/http"
"net/textproto"
"os"
"slices"
"strings"
"github.com/traefik/traefik/v3/pkg/ip"
"github.com/traefik/traefik/v3/pkg/proxy/httputil"
"golang.org/x/net/http/httpguts"
)
const (
xForwardedProto = "X-Forwarded-Proto"
xForwardedFor = "X-Forwarded-For"
xForwardedHost = "X-Forwarded-Host"
xForwardedPort = "X-Forwarded-Port"
xForwardedServer = "X-Forwarded-Server"
xForwardedURI = "X-Forwarded-Uri"
xForwardedMethod = "X-Forwarded-Method"
xForwardedPrefix = "X-Forwarded-Prefix"
xForwardedTLSClientCert = "X-Forwarded-Tls-Client-Cert"
xForwardedTLSClientCertInfo = "X-Forwarded-Tls-Client-Cert-Info"
xRealIP = "X-Real-Ip"
connection = "Connection"
upgrade = "Upgrade"
)
var xHeaders = []string{
xForwardedProto,
xForwardedFor,
xForwardedHost,
xForwardedPort,
xForwardedServer,
xForwardedURI,
xForwardedMethod,
xForwardedPrefix,
xForwardedTLSClientCert,
xForwardedTLSClientCertInfo,
xRealIP,
}
// XForwarded is an HTTP handler wrapper that sets the X-Forwarded headers,
// and other relevant headers for a reverse-proxy.
// Unless insecure is set,
// it first removes all the existing values for those headers if the remote address is not one of the trusted ones.
type XForwarded struct {
insecure bool
trustedIPs []string
connectionHeaders []string
notAppendXForwardedFor bool
ipChecker *ip.Checker
next http.Handler
hostname string
}
// NewXForwarded creates a new XForwarded.
func NewXForwarded(insecure bool, trustedIPs []string, connectionHeaders []string, notAppendXForwardedFor bool, next http.Handler) (*XForwarded, error) {
var ipChecker *ip.Checker
if len(trustedIPs) > 0 {
var err error
ipChecker, err = ip.NewChecker(trustedIPs)
if err != nil {
return nil, err
}
}
hostname, err := os.Hostname()
if err != nil {
hostname = "localhost"
}
return &XForwarded{
insecure: insecure,
trustedIPs: trustedIPs,
connectionHeaders: connectionHeaders,
notAppendXForwardedFor: notAppendXForwardedFor,
ipChecker: ipChecker,
next: next,
hostname: hostname,
}, nil
}
func (x *XForwarded) isTrustedIP(ip string) bool {
if x.ipChecker == nil {
return false
}
return x.ipChecker.IsAuthorized(ip) == nil
}
// removeIPv6Zone removes the zone if the given IP is an ipv6 address and it has {zone} information in it,
// like "[fe80::d806:a55d:eb1b:49cc%vEthernet (vmxnet3 Ethernet Adapter - Virtual Switch)]:64692".
func removeIPv6Zone(clientIP string) string {
if idx := strings.Index(clientIP, "%"); idx != -1 {
return clientIP[:idx]
}
return clientIP
}
// isWebsocketRequest returns whether the specified HTTP request is a websocket handshake request.
func isWebsocketRequest(req *http.Request) bool {
containsHeader := func(name, value string) bool {
h := unsafeHeader(req.Header).Get(name)
for {
pos := strings.Index(h, ",")
if pos == -1 {
return strings.EqualFold(value, strings.TrimSpace(h))
}
if strings.EqualFold(value, strings.TrimSpace(h[:pos])) {
return true
}
h = h[pos+1:]
}
}
return containsHeader(connection, "upgrade") && containsHeader(upgrade, "websocket")
}
func forwardedPort(req *http.Request) string {
if req == nil {
return ""
}
if _, port, err := net.SplitHostPort(req.Host); err == nil && port != "" {
return port
}
if unsafeHeader(req.Header).Get(xForwardedProto) == "https" || unsafeHeader(req.Header).Get(xForwardedProto) == "wss" {
return "443"
}
if req.TLS != nil {
return "443"
}
return "80"
}
func (x *XForwarded) rewrite(outreq *http.Request) {
if clientIP, _, err := net.SplitHostPort(outreq.RemoteAddr); err == nil {
clientIP = removeIPv6Zone(clientIP)
if unsafeHeader(outreq.Header).Get(xRealIP) == "" {
unsafeHeader(outreq.Header).Set(xRealIP, clientIP)
}
}
xfProto := unsafeHeader(outreq.Header).Get(xForwardedProto)
if xfProto == "" {
// TODO: is this expected to set the X-Forwarded-Proto header value to
// ws(s) as the underlying request used to upgrade the connection is
// made over HTTP(S)?
if isWebsocketRequest(outreq) {
if outreq.TLS != nil {
unsafeHeader(outreq.Header).Set(xForwardedProto, "wss")
} else {
unsafeHeader(outreq.Header).Set(xForwardedProto, "ws")
}
} else {
if outreq.TLS != nil {
unsafeHeader(outreq.Header).Set(xForwardedProto, "https")
} else {
unsafeHeader(outreq.Header).Set(xForwardedProto, "http")
}
}
}
if xfPort := unsafeHeader(outreq.Header).Get(xForwardedPort); xfPort == "" {
unsafeHeader(outreq.Header).Set(xForwardedPort, forwardedPort(outreq))
}
if xfHost := unsafeHeader(outreq.Header).Get(xForwardedHost); xfHost == "" && outreq.Host != "" {
unsafeHeader(outreq.Header).Set(xForwardedHost, outreq.Host)
}
// Per https://www.rfc-editor.org/rfc/rfc2616#section-4.2, the Forwarded IPs list is in
// the same order as the values in the X-Forwarded-For header(s).
if xffs := unsafeHeader(outreq.Header).Values(xForwardedFor); len(xffs) > 0 {
unsafeHeader(outreq.Header).Set(xForwardedFor, strings.Join(xffs, ", "))
}
if x.hostname != "" {
unsafeHeader(outreq.Header).Set(xForwardedServer, x.hostname)
}
}
// ServeHTTP implements http.Handler.
func (x *XForwarded) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !x.insecure && !x.isTrustedIP(r.RemoteAddr) {
for _, h := range xHeaders {
unsafeHeader(r.Header).Del(h)
}
}
x.rewrite(r)
x.removeConnectionHeaders(r)
if x.notAppendXForwardedFor {
r = r.WithContext(httputil.SetNotAppendXFF(r.Context()))
}
x.next.ServeHTTP(w, r)
}
func (x *XForwarded) removeConnectionHeaders(req *http.Request) {
var reqUpType string
if httpguts.HeaderValuesContainsToken(req.Header[connection], upgrade) {
reqUpType = unsafeHeader(req.Header).Get(upgrade)
}
var connectionHopByHopHeaders []string
for _, f := range req.Header[connection] {
for _, sf := range strings.Split(f, ",") {
if sf = textproto.TrimString(sf); sf != "" {
// Connection header cannot dictate to remove X- headers managed by Traefik,
// as per rfc7230 https://datatracker.ietf.org/doc/html/rfc7230#section-6.1,
// A proxy or gateway MUST ... and then remove the Connection header field itself
// (or replace it with the intermediary's own connection options for the forwarded message).
if slices.Contains(xHeaders, sf) {
continue
}
// Keep headers allowed through the middleware chain.
if slices.Contains(x.connectionHeaders, sf) {
connectionHopByHopHeaders = append(connectionHopByHopHeaders, sf)
continue
}
// Apply Connection header option.
req.Header.Del(sf)
}
}
}
if reqUpType != "" {
connectionHopByHopHeaders = append(connectionHopByHopHeaders, upgrade)
unsafeHeader(req.Header).Set(upgrade, reqUpType)
}
if len(connectionHopByHopHeaders) > 0 {
unsafeHeader(req.Header).Set(connection, strings.Join(connectionHopByHopHeaders, ","))
return
}
unsafeHeader(req.Header).Del(connection)
}
// unsafeHeader allows to manage Header values.
// Must be used only when the header name is already a canonical key.
type unsafeHeader map[string][]string
func (h unsafeHeader) Set(key, value string) {
h[key] = []string{value}
}
func (h unsafeHeader) Get(key string) string {
if len(h[key]) == 0 {
return ""
}
return h[key][0]
}
func (h unsafeHeader) Values(key string) []string {
return h[key]
}
func (h unsafeHeader) Del(key string) {
delete(h, key)
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/forwardedheaders/forwarded_header_test.go | pkg/middlewares/forwardedheaders/forwarded_header_test.go | package forwardedheaders
import (
"crypto/tls"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestServeHTTP(t *testing.T) {
testCases := []struct {
desc string
insecure bool
trustedIps []string
connectionHeaders []string
incomingHeaders map[string][]string
remoteAddr string
expectedHeaders map[string]string
tls bool
websocket bool
host string
}{
{
desc: "all Empty",
insecure: true,
trustedIps: nil,
remoteAddr: "",
incomingHeaders: map[string][]string{},
expectedHeaders: map[string]string{
xForwardedFor: "",
xForwardedURI: "",
xForwardedMethod: "",
xForwardedTLSClientCert: "",
xForwardedTLSClientCertInfo: "",
},
},
{
desc: "insecure true with incoming X-Forwarded headers",
insecure: true,
trustedIps: nil,
remoteAddr: "",
incomingHeaders: map[string][]string{
xForwardedFor: {"10.0.1.0, 10.0.1.12"},
xForwardedURI: {"/bar"},
xForwardedMethod: {"GET"},
xForwardedTLSClientCert: {"Cert"},
xForwardedTLSClientCertInfo: {"CertInfo"},
xForwardedPrefix: {"/prefix"},
},
expectedHeaders: map[string]string{
xForwardedFor: "10.0.1.0, 10.0.1.12",
xForwardedURI: "/bar",
xForwardedMethod: "GET",
xForwardedTLSClientCert: "Cert",
xForwardedTLSClientCertInfo: "CertInfo",
xForwardedPrefix: "/prefix",
},
},
{
desc: "insecure false with incoming X-Forwarded headers",
insecure: false,
trustedIps: nil,
remoteAddr: "",
incomingHeaders: map[string][]string{
xForwardedFor: {"10.0.1.0, 10.0.1.12"},
xForwardedURI: {"/bar"},
xForwardedMethod: {"GET"},
xForwardedTLSClientCert: {"Cert"},
xForwardedTLSClientCertInfo: {"CertInfo"},
xForwardedPrefix: {"/prefix"},
},
expectedHeaders: map[string]string{
xForwardedFor: "",
xForwardedURI: "",
xForwardedMethod: "",
xForwardedTLSClientCert: "",
xForwardedTLSClientCertInfo: "",
xForwardedPrefix: "",
},
},
{
desc: "insecure false with incoming X-Forwarded headers and valid Trusted Ips",
insecure: false,
trustedIps: []string{"10.0.1.100"},
remoteAddr: "10.0.1.100:80",
incomingHeaders: map[string][]string{
xForwardedFor: {"10.0.1.0, 10.0.1.12"},
xForwardedURI: {"/bar"},
xForwardedMethod: {"GET"},
xForwardedTLSClientCert: {"Cert"},
xForwardedTLSClientCertInfo: {"CertInfo"},
xForwardedPrefix: {"/prefix"},
},
expectedHeaders: map[string]string{
xForwardedFor: "10.0.1.0, 10.0.1.12",
xForwardedURI: "/bar",
xForwardedMethod: "GET",
xForwardedTLSClientCert: "Cert",
xForwardedTLSClientCertInfo: "CertInfo",
xForwardedPrefix: "/prefix",
},
},
{
desc: "insecure false with incoming X-Forwarded headers and invalid Trusted Ips",
insecure: false,
trustedIps: []string{"10.0.1.100"},
remoteAddr: "10.0.1.101:80",
incomingHeaders: map[string][]string{
xForwardedFor: {"10.0.1.0, 10.0.1.12"},
xForwardedURI: {"/bar"},
xForwardedMethod: {"GET"},
xForwardedTLSClientCert: {"Cert"},
xForwardedTLSClientCertInfo: {"CertInfo"},
xForwardedPrefix: {"/prefix"},
},
expectedHeaders: map[string]string{
xForwardedFor: "",
xForwardedURI: "",
xForwardedMethod: "",
xForwardedTLSClientCert: "",
xForwardedTLSClientCertInfo: "",
xForwardedPrefix: "",
},
},
{
desc: "insecure false with incoming X-Forwarded headers and valid Trusted Ips CIDR",
insecure: false,
trustedIps: []string{"1.2.3.4/24"},
remoteAddr: "1.2.3.156:80",
incomingHeaders: map[string][]string{
xForwardedFor: {"10.0.1.0, 10.0.1.12"},
xForwardedURI: {"/bar"},
xForwardedMethod: {"GET"},
xForwardedTLSClientCert: {"Cert"},
xForwardedTLSClientCertInfo: {"CertInfo"},
xForwardedPrefix: {"/prefix"},
},
expectedHeaders: map[string]string{
xForwardedFor: "10.0.1.0, 10.0.1.12",
xForwardedURI: "/bar",
xForwardedMethod: "GET",
xForwardedTLSClientCert: "Cert",
xForwardedTLSClientCertInfo: "CertInfo",
xForwardedPrefix: "/prefix",
},
},
{
desc: "insecure false with incoming X-Forwarded headers and invalid Trusted Ips CIDR",
insecure: false,
trustedIps: []string{"1.2.3.4/24"},
remoteAddr: "10.0.1.101:80",
incomingHeaders: map[string][]string{
xForwardedFor: {"10.0.1.0, 10.0.1.12"},
xForwardedURI: {"/bar"},
xForwardedMethod: {"GET"},
xForwardedTLSClientCert: {"Cert"},
xForwardedTLSClientCertInfo: {"CertInfo"},
xForwardedPrefix: {"/prefix"},
},
expectedHeaders: map[string]string{
xForwardedFor: "",
xForwardedURI: "",
xForwardedMethod: "",
xForwardedTLSClientCert: "",
xForwardedTLSClientCertInfo: "",
xForwardedPrefix: "",
},
},
{
desc: "xForwardedFor with multiple header(s) values",
insecure: true,
incomingHeaders: map[string][]string{
xForwardedFor: {
"10.0.0.4, 10.0.0.3",
"10.0.0.2, 10.0.0.1",
"10.0.0.0",
},
},
expectedHeaders: map[string]string{
xForwardedFor: "10.0.0.4, 10.0.0.3, 10.0.0.2, 10.0.0.1, 10.0.0.0",
},
},
{
desc: "xRealIP populated from remote address",
remoteAddr: "10.0.1.101:80",
expectedHeaders: map[string]string{
xRealIP: "10.0.1.101",
},
},
{
desc: "xRealIP was already populated from previous headers",
insecure: true,
remoteAddr: "10.0.1.101:80",
incomingHeaders: map[string][]string{
xRealIP: {"10.0.1.12"},
},
expectedHeaders: map[string]string{
xRealIP: "10.0.1.12",
},
},
{
desc: "xForwardedProto with no tls",
tls: false,
expectedHeaders: map[string]string{
xForwardedProto: "http",
},
},
{
desc: "xForwardedProto with tls",
tls: true,
expectedHeaders: map[string]string{
xForwardedProto: "https",
},
},
{
desc: "xForwardedProto with websocket",
tls: false,
websocket: true,
expectedHeaders: map[string]string{
xForwardedProto: "ws",
},
},
{
desc: "xForwardedProto with websocket and tls",
tls: true,
websocket: true,
expectedHeaders: map[string]string{
xForwardedProto: "wss",
},
},
{
desc: "xForwardedProto with websocket and tls and already x-forwarded-proto with wss",
tls: true,
websocket: true,
incomingHeaders: map[string][]string{
xForwardedProto: {"wss"},
},
expectedHeaders: map[string]string{
xForwardedProto: "wss",
},
},
{
desc: "xForwardedPort with explicit port",
host: "foo.com:8080",
expectedHeaders: map[string]string{
xForwardedPort: "8080",
},
},
{
desc: "xForwardedPort with implicit tls port from proto header",
// setting insecure just so our initial xForwardedProto does not get cleaned
insecure: true,
incomingHeaders: map[string][]string{
xForwardedProto: {"https"},
},
expectedHeaders: map[string]string{
xForwardedProto: "https",
xForwardedPort: "443",
},
},
{
desc: "xForwardedPort with implicit tls port from TLS in req",
tls: true,
expectedHeaders: map[string]string{
xForwardedPort: "443",
},
},
{
desc: "xForwardedHost from req host",
host: "foo.com:8080",
expectedHeaders: map[string]string{
xForwardedHost: "foo.com:8080",
},
},
{
desc: "xForwardedServer from req XForwarded",
host: "foo.com:8080",
expectedHeaders: map[string]string{
xForwardedServer: "foo.com:8080",
},
},
{
desc: "Untrusted: Connection header has no effect on X- forwarded headers",
insecure: false,
incomingHeaders: map[string][]string{
connection: {
xForwardedProto,
xForwardedFor,
xForwardedURI,
xForwardedMethod,
xForwardedHost,
xForwardedPort,
xForwardedTLSClientCert,
xForwardedTLSClientCertInfo,
xForwardedPrefix,
xRealIP,
},
xForwardedProto: {"foo"},
xForwardedFor: {"foo"},
xForwardedURI: {"foo"},
xForwardedMethod: {"foo"},
xForwardedHost: {"foo"},
xForwardedPort: {"foo"},
xForwardedTLSClientCert: {"foo"},
xForwardedTLSClientCertInfo: {"foo"},
xForwardedPrefix: {"foo"},
xRealIP: {"foo"},
},
expectedHeaders: map[string]string{
xForwardedProto: "http",
xForwardedFor: "",
xForwardedURI: "",
xForwardedMethod: "",
xForwardedHost: "",
xForwardedPort: "80",
xForwardedTLSClientCert: "",
xForwardedTLSClientCertInfo: "",
xForwardedPrefix: "",
xRealIP: "",
connection: "",
},
},
{
desc: "Trusted (insecure): Connection header has no effect on X- forwarded headers",
insecure: true,
incomingHeaders: map[string][]string{
connection: {
xForwardedProto,
xForwardedFor,
xForwardedURI,
xForwardedMethod,
xForwardedHost,
xForwardedPort,
xForwardedTLSClientCert,
xForwardedTLSClientCertInfo,
xForwardedPrefix,
xRealIP,
},
xForwardedProto: {"foo"},
xForwardedFor: {"foo"},
xForwardedURI: {"foo"},
xForwardedMethod: {"foo"},
xForwardedHost: {"foo"},
xForwardedPort: {"foo"},
xForwardedTLSClientCert: {"foo"},
xForwardedTLSClientCertInfo: {"foo"},
xForwardedPrefix: {"foo"},
xRealIP: {"foo"},
},
expectedHeaders: map[string]string{
xForwardedProto: "foo",
xForwardedFor: "foo",
xForwardedURI: "foo",
xForwardedMethod: "foo",
xForwardedHost: "foo",
xForwardedPort: "foo",
xForwardedTLSClientCert: "foo",
xForwardedTLSClientCertInfo: "foo",
xForwardedPrefix: "foo",
xRealIP: "foo",
connection: "",
},
},
{
desc: "Untrusted and Connection: Connection header has no effect on X- forwarded headers",
insecure: false,
connectionHeaders: []string{
xForwardedProto,
xForwardedFor,
xForwardedURI,
xForwardedMethod,
xForwardedHost,
xForwardedPort,
xForwardedTLSClientCert,
xForwardedTLSClientCertInfo,
xForwardedPrefix,
xRealIP,
},
incomingHeaders: map[string][]string{
connection: {
xForwardedProto,
xForwardedFor,
xForwardedURI,
xForwardedMethod,
xForwardedHost,
xForwardedPort,
xForwardedTLSClientCert,
xForwardedTLSClientCertInfo,
xForwardedPrefix,
xRealIP,
},
xForwardedProto: {"foo"},
xForwardedFor: {"foo"},
xForwardedURI: {"foo"},
xForwardedMethod: {"foo"},
xForwardedHost: {"foo"},
xForwardedPort: {"foo"},
xForwardedTLSClientCert: {"foo"},
xForwardedTLSClientCertInfo: {"foo"},
xForwardedPrefix: {"foo"},
xRealIP: {"foo"},
},
expectedHeaders: map[string]string{
xForwardedProto: "http",
xForwardedFor: "",
xForwardedURI: "",
xForwardedMethod: "",
xForwardedHost: "",
xForwardedPort: "80",
xForwardedTLSClientCert: "",
xForwardedTLSClientCertInfo: "",
xForwardedPrefix: "",
xRealIP: "",
connection: "",
},
},
{
desc: "Trusted (insecure) and Connection: Connection header has no effect on X- forwarded headers",
insecure: true,
connectionHeaders: []string{
xForwardedProto,
xForwardedFor,
xForwardedURI,
xForwardedMethod,
xForwardedHost,
xForwardedPort,
xForwardedTLSClientCert,
xForwardedTLSClientCertInfo,
xForwardedPrefix,
xRealIP,
},
incomingHeaders: map[string][]string{
connection: {
xForwardedProto,
xForwardedFor,
xForwardedURI,
xForwardedMethod,
xForwardedHost,
xForwardedPort,
xForwardedTLSClientCert,
xForwardedTLSClientCertInfo,
xForwardedPrefix,
xRealIP,
},
xForwardedProto: {"foo"},
xForwardedFor: {"foo"},
xForwardedURI: {"foo"},
xForwardedMethod: {"foo"},
xForwardedHost: {"foo"},
xForwardedPort: {"foo"},
xForwardedTLSClientCert: {"foo"},
xForwardedTLSClientCertInfo: {"foo"},
xForwardedPrefix: {"foo"},
xRealIP: {"foo"},
},
expectedHeaders: map[string]string{
xForwardedProto: "foo",
xForwardedFor: "foo",
xForwardedURI: "foo",
xForwardedMethod: "foo",
xForwardedHost: "foo",
xForwardedPort: "foo",
xForwardedTLSClientCert: "foo",
xForwardedTLSClientCertInfo: "foo",
xForwardedPrefix: "foo",
xRealIP: "foo",
connection: "",
},
},
{
desc: "Connection: one remove, and one passthrough header",
connectionHeaders: []string{
"foo",
},
incomingHeaders: map[string][]string{
connection: {
"foo",
},
"Foo": {"bar"},
"Bar": {"foo"},
},
expectedHeaders: map[string]string{
"Bar": "foo",
},
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
req, err := http.NewRequest(http.MethodGet, "", nil)
require.NoError(t, err)
req.RemoteAddr = test.remoteAddr
if test.tls {
req.TLS = &tls.ConnectionState{}
}
if test.websocket {
req.Header.Set(connection, "upgrade")
req.Header.Set(upgrade, "websocket")
}
if test.host != "" {
req.Host = test.host
}
for k, values := range test.incomingHeaders {
for _, value := range values {
req.Header.Add(k, value)
}
}
m, err := NewXForwarded(test.insecure, test.trustedIps, test.connectionHeaders, false,
http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {}))
require.NoError(t, err)
if test.host != "" {
m.hostname = test.host
}
m.ServeHTTP(nil, req)
for k, v := range test.expectedHeaders {
assert.Equal(t, v, req.Header.Get(k))
}
})
}
}
func Test_isWebsocketRequest(t *testing.T) {
testCases := []struct {
desc string
connectionHeader string
upgradeHeader string
assert assert.BoolAssertionFunc
}{
{
desc: "connection Header multiple values middle",
connectionHeader: "foo,upgrade,bar",
upgradeHeader: "websocket",
assert: assert.True,
},
{
desc: "connection Header multiple values end",
connectionHeader: "foo,bar,upgrade",
upgradeHeader: "websocket",
assert: assert.True,
},
{
desc: "connection Header multiple values begin",
connectionHeader: "upgrade,foo,bar",
upgradeHeader: "websocket",
assert: assert.True,
},
{
desc: "connection Header no upgrade",
connectionHeader: "foo,bar",
upgradeHeader: "websocket",
assert: assert.False,
},
{
desc: "connection Header empty",
connectionHeader: "",
upgradeHeader: "websocket",
assert: assert.False,
},
{
desc: "no header values",
connectionHeader: "foo,bar",
upgradeHeader: "foo,bar",
assert: assert.False,
},
{
desc: "upgrade header multiple values",
connectionHeader: "upgrade",
upgradeHeader: "foo,bar,websocket",
assert: assert.True,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
req.Header.Set(connection, test.connectionHeader)
req.Header.Set(upgrade, test.upgradeHeader)
ok := isWebsocketRequest(req)
test.assert(t, ok)
})
}
}
func TestConnection(t *testing.T) {
testCases := []struct {
desc string
reqHeaders map[string]string
connectionHeaders []string
expected http.Header
}{
{
desc: "simple remove",
reqHeaders: map[string]string{
"Foo": "bar",
connection: "foo",
},
expected: http.Header{},
},
{
desc: "remove and upgrade",
reqHeaders: map[string]string{
upgrade: "test",
"Foo": "bar",
connection: "upgrade,foo",
},
expected: http.Header{
upgrade: []string{"test"},
connection: []string{"Upgrade"},
},
},
{
desc: "no remove",
reqHeaders: map[string]string{
"Foo": "bar",
connection: "fii",
},
expected: http.Header{
"Foo": []string{"bar"},
},
},
{
desc: "no remove because connection header pass through",
reqHeaders: map[string]string{
"Foo": "bar",
connection: "Foo",
},
connectionHeaders: []string{"Foo"},
expected: http.Header{
"Foo": []string{"bar"},
connection: []string{"Foo"},
},
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
forwarded, err := NewXForwarded(true, nil, test.connectionHeaders, false, nil)
require.NoError(t, err)
req := httptest.NewRequest(http.MethodGet, "https://localhost", nil)
for k, v := range test.reqHeaders {
req.Header.Set(k, v)
}
forwarded.removeConnectionHeaders(req)
assert.Equal(t, test.expected, req.Header)
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/metrics/metrics.go | pkg/middlewares/metrics/metrics.go | package metrics
import (
"context"
"net/http"
"slices"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/containous/alice"
gokitmetrics "github.com/go-kit/kit/metrics"
"github.com/rs/zerolog/log"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/middlewares/capture"
"github.com/traefik/traefik/v3/pkg/middlewares/observability"
"github.com/traefik/traefik/v3/pkg/middlewares/retry"
"github.com/traefik/traefik/v3/pkg/observability/metrics"
traefiktls "github.com/traefik/traefik/v3/pkg/tls"
"google.golang.org/grpc/codes"
)
const (
protoHTTP = "http"
protoGRPC = "grpc"
protoGRPCWeb = "grpc-web"
protoSSE = "sse"
protoWebsocket = "websocket"
typeName = "Metrics"
nameEntrypoint = "metrics-entrypoint"
nameRouter = "metrics-router"
nameService = "metrics-service"
)
type metricsMiddleware struct {
next http.Handler
reqsCounter metrics.CounterWithHeaders
reqsTLSCounter gokitmetrics.Counter
reqDurationHistogram metrics.ScalableHistogram
reqsBytesCounter gokitmetrics.Counter
respsBytesCounter gokitmetrics.Counter
baseLabels []string
name string
}
// NewEntryPointMiddleware creates a new metrics middleware for an Entrypoint.
func NewEntryPointMiddleware(ctx context.Context, next http.Handler, registry metrics.Registry, entryPointName string) http.Handler {
middlewares.GetLogger(ctx, nameEntrypoint, typeName).Debug().Msg("Creating middleware")
return &metricsMiddleware{
next: next,
reqsCounter: registry.EntryPointReqsCounter(),
reqsTLSCounter: registry.EntryPointReqsTLSCounter(),
reqDurationHistogram: registry.EntryPointReqDurationHistogram(),
reqsBytesCounter: registry.EntryPointReqsBytesCounter(),
respsBytesCounter: registry.EntryPointRespsBytesCounter(),
baseLabels: []string{"entrypoint", entryPointName},
name: nameEntrypoint,
}
}
// NewRouterMiddleware creates a new metrics middleware for a Router.
func NewRouterMiddleware(ctx context.Context, next http.Handler, registry metrics.Registry, routerName string, serviceName string) http.Handler {
middlewares.GetLogger(ctx, nameRouter, typeName).Debug().Msg("Creating middleware")
return &metricsMiddleware{
next: next,
reqsCounter: registry.RouterReqsCounter(),
reqsTLSCounter: registry.RouterReqsTLSCounter(),
reqDurationHistogram: registry.RouterReqDurationHistogram(),
reqsBytesCounter: registry.RouterReqsBytesCounter(),
respsBytesCounter: registry.RouterRespsBytesCounter(),
baseLabels: []string{"router", routerName, "service", serviceName},
name: nameRouter,
}
}
// NewServiceMiddleware creates a new metrics middleware for a Service.
func NewServiceMiddleware(ctx context.Context, next http.Handler, registry metrics.Registry, serviceName string) http.Handler {
middlewares.GetLogger(ctx, nameService, typeName).Debug().Msg("Creating middleware")
return &metricsMiddleware{
next: next,
reqsCounter: registry.ServiceReqsCounter(),
reqsTLSCounter: registry.ServiceReqsTLSCounter(),
reqDurationHistogram: registry.ServiceReqDurationHistogram(),
reqsBytesCounter: registry.ServiceReqsBytesCounter(),
respsBytesCounter: registry.ServiceRespsBytesCounter(),
baseLabels: []string{"service", serviceName},
name: nameService,
}
}
// EntryPointMetricsHandler returns the metrics entrypoint handler.
func EntryPointMetricsHandler(ctx context.Context, registry metrics.Registry, entryPointName string) alice.Constructor {
return func(next http.Handler) (http.Handler, error) {
if registry == nil || !registry.IsEpEnabled() {
return next, nil
}
return NewEntryPointMiddleware(ctx, next, registry, entryPointName), nil
}
}
// RouterMetricsHandler returns the metrics router handler.
func RouterMetricsHandler(ctx context.Context, registry metrics.Registry, routerName string, serviceName string) alice.Constructor {
return func(next http.Handler) (http.Handler, error) {
if registry == nil || !registry.IsRouterEnabled() {
return next, nil
}
return NewRouterMiddleware(ctx, next, registry, routerName, serviceName), nil
}
}
// ServiceMetricsHandler returns the metrics service handler.
func ServiceMetricsHandler(ctx context.Context, registry metrics.Registry, serviceName string) alice.Constructor {
return func(next http.Handler) (http.Handler, error) {
if registry == nil || !registry.IsSvcEnabled() {
return next, nil
}
return NewServiceMiddleware(ctx, next, registry, serviceName), nil
}
}
func (m *metricsMiddleware) GetTracingInformation() (string, string) {
return m.name, typeName
}
func (m *metricsMiddleware) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if !observability.MetricsEnabled(req.Context()) {
m.next.ServeHTTP(rw, req)
return
}
proto := getRequestProtocol(req)
var labels []string
labels = append(labels, m.baseLabels...)
labels = append(labels, "method", getMethod(req))
labels = append(labels, "protocol", proto)
// TLS metrics
if req.TLS != nil {
var tlsLabels []string
tlsLabels = append(tlsLabels, m.baseLabels...)
tlsLabels = append(tlsLabels, "tls_version", traefiktls.GetVersion(req.TLS), "tls_cipher", traefiktls.GetCipherName(req.TLS))
m.reqsTLSCounter.With(tlsLabels...).Add(1)
}
ctx := req.Context()
capt, err := capture.FromContext(ctx)
if err != nil {
with := log.Ctx(ctx).With()
for i := 0; i < len(m.baseLabels); i += 2 {
with = with.Str(m.baseLabels[i], m.baseLabels[i+1])
}
logger := with.Logger()
logger.Error().Err(err).Msg("Could not get Capture")
observability.SetStatusErrorf(req.Context(), "Could not get Capture")
return
}
next := m.next
if capt.NeedsReset(rw) {
next = capt.Reset(m.next)
}
start := time.Now()
next.ServeHTTP(rw, req)
code := capt.StatusCode()
if proto == protoGRPC || proto == protoGRPCWeb {
code = grpcStatusCode(rw)
}
labels = append(labels, "code", strconv.Itoa(code))
m.reqDurationHistogram.With(labels...).ObserveFromStart(start)
m.reqsCounter.With(req.Header, labels...).Add(1)
m.respsBytesCounter.With(labels...).Add(float64(capt.ResponseSize()))
m.reqsBytesCounter.With(labels...).Add(float64(capt.RequestSize()))
}
func getRequestProtocol(req *http.Request) string {
switch {
case isWebsocketRequest(req):
return protoWebsocket
case isSSERequest(req):
return protoSSE
case isGRPCWebRequest(req):
return protoGRPCWeb
case isGRPCRequest(req):
return protoGRPC
default:
return protoHTTP
}
}
// isWebsocketRequest determines if the specified HTTP request is a websocket handshake request.
func isWebsocketRequest(req *http.Request) bool {
return containsHeader(req, "Connection", "upgrade") && containsHeader(req, "Upgrade", "websocket")
}
// isSSERequest determines if the specified HTTP request is a request for an event subscription.
func isSSERequest(req *http.Request) bool {
return containsHeader(req, "Accept", "text/event-stream")
}
// isGRPCWebRequest determines if the specified HTTP request is a gRPC-Web request.
func isGRPCWebRequest(req *http.Request) bool {
return strings.HasPrefix(req.Header.Get("Content-Type"), "application/grpc-web")
}
// isGRPCRequest determines if the specified HTTP request is a gRPC request.
func isGRPCRequest(req *http.Request) bool {
return strings.HasPrefix(req.Header.Get("Content-Type"), "application/grpc")
}
// grpcStatusCode parses and returns the gRPC status code from the Grpc-Status header.
func grpcStatusCode(rw http.ResponseWriter) int {
code := codes.Unknown
if status := rw.Header().Get("Grpc-Status"); status != "" {
if err := code.UnmarshalJSON([]byte(status)); err != nil {
return int(code)
}
}
return int(code)
}
func containsHeader(req *http.Request, name, value string) bool {
items := strings.Split(req.Header.Get(name), ",")
return slices.ContainsFunc(items, func(item string) bool {
return value == strings.ToLower(strings.TrimSpace(item))
})
}
// getMethod returns the request's method.
// It checks whether the method is a valid UTF-8 string.
// To restrict the (potentially infinite) number of accepted values for the method,
// and avoid unbounded memory issues,
// values that are not part of the set of HTTP verbs are replaced with EXTENSION_METHOD.
// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
// https://datatracker.ietf.org/doc/html/rfc2616/#section-5.1.1.
//
//nolint:usestdlibvars
func getMethod(r *http.Request) string {
if !utf8.ValidString(r.Method) {
log.Warn().Msgf("Invalid HTTP method encoding: %s", r.Method)
return "NON_UTF8_HTTP_METHOD"
}
switch r.Method {
case "HEAD", "GET", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", // https://datatracker.ietf.org/doc/html/rfc7231#section-4
"PATCH", // https://datatracker.ietf.org/doc/html/rfc5789#section-2
"PRI": // https://datatracker.ietf.org/doc/html/rfc7540#section-11.6
return r.Method
default:
return "EXTENSION_METHOD"
}
}
type retryMetrics interface {
ServiceRetriesCounter() gokitmetrics.Counter
}
// NewRetryListener instantiates a MetricsRetryListener with the given retryMetrics.
func NewRetryListener(retryMetrics retryMetrics, serviceName string) retry.Listener {
return &RetryListener{retryMetrics: retryMetrics, serviceName: serviceName}
}
// RetryListener is an implementation of the RetryListener interface to
// record RequestMetrics about retry attempts.
type RetryListener struct {
retryMetrics retryMetrics
serviceName string
}
// Retried tracks the retry in the RequestMetrics implementation.
func (m *RetryListener) Retried(_ *http.Request, _ int) {
m.retryMetrics.ServiceRetriesCounter().With("service", m.serviceName).Add(1)
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/metrics/metrics_test.go | pkg/middlewares/metrics/metrics_test.go | package metrics
import (
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"github.com/go-kit/kit/metrics"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc/codes"
)
// CollectingCounter is a metrics.Counter implementation that enables access to the CounterValue and LastLabelValues.
type CollectingCounter struct {
CounterValue float64
LastLabelValues []string
}
// With is there to satisfy the metrics.Counter interface.
func (c *CollectingCounter) With(labelValues ...string) metrics.Counter {
c.LastLabelValues = labelValues
return c
}
// Add is there to satisfy the metrics.Counter interface.
func (c *CollectingCounter) Add(delta float64) {
c.CounterValue += delta
}
func TestMetricsRetryListener(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
retryMetrics := newCollectingRetryMetrics()
retryListener := NewRetryListener(retryMetrics, "serviceName")
retryListener.Retried(req, 1)
retryListener.Retried(req, 2)
wantCounterValue := float64(2)
if retryMetrics.retriesCounter.CounterValue != wantCounterValue {
t.Errorf("got counter value of %f, want %f", retryMetrics.retriesCounter.CounterValue, wantCounterValue)
}
wantLabelValues := []string{"service", "serviceName"}
if !reflect.DeepEqual(retryMetrics.retriesCounter.LastLabelValues, wantLabelValues) {
t.Errorf("wrong label values %v used, want %v", retryMetrics.retriesCounter.LastLabelValues, wantLabelValues)
}
}
// collectingRetryMetrics is an implementation of the retryMetrics interface that can be used inside tests to collect the times Add() was called.
type collectingRetryMetrics struct {
retriesCounter *CollectingCounter
}
func newCollectingRetryMetrics() *collectingRetryMetrics {
return &collectingRetryMetrics{retriesCounter: &CollectingCounter{}}
}
func (m *collectingRetryMetrics) ServiceRetriesCounter() metrics.Counter {
return m.retriesCounter
}
func Test_getMethod(t *testing.T) {
testCases := []struct {
method string
expected string
}{
{
method: http.MethodGet,
expected: http.MethodGet,
},
{
method: strings.ToLower(http.MethodGet),
expected: "EXTENSION_METHOD",
},
{
method: "THIS_IS_NOT_A_VALID_METHOD",
expected: "EXTENSION_METHOD",
},
}
for _, test := range testCases {
t.Run(test.method, func(t *testing.T) {
t.Parallel()
request := httptest.NewRequest(test.method, "http://example.com", nil)
assert.Equal(t, test.expected, getMethod(request))
})
}
}
func Test_getRequestProtocol(t *testing.T) {
testCases := []struct {
desc string
headers http.Header
expected string
}{
{
desc: "default",
expected: protoHTTP,
},
{
desc: "websocket",
headers: http.Header{
"Connection": []string{"upgrade"},
"Upgrade": []string{"websocket"},
},
expected: protoWebsocket,
},
{
desc: "SSE",
headers: http.Header{
"Accept": []string{"text/event-stream"},
},
expected: protoSSE,
},
{
desc: "grpc web",
headers: http.Header{
"Content-Type": []string{"application/grpc-web-text"},
},
expected: protoGRPCWeb,
},
{
desc: "grpc",
headers: http.Header{
"Content-Type": []string{"application/grpc-text"},
},
expected: protoGRPC,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
req := httptest.NewRequest(http.MethodGet, "https://localhost", http.NoBody)
req.Header = test.headers
protocol := getRequestProtocol(req)
assert.Equal(t, test.expected, protocol)
})
}
}
func Test_grpcStatusCode(t *testing.T) {
testCases := []struct {
desc string
status string
expected codes.Code
}{
{
desc: "invalid number",
status: "foo",
expected: codes.Unknown,
},
{
desc: "number",
status: "1",
expected: codes.Canceled,
},
{
desc: "invalid string",
status: `"foo"`,
expected: codes.Unknown,
},
{
desc: "string",
status: `"OK"`,
expected: codes.OK,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
rw := httptest.NewRecorder()
rw.Header().Set("Grpc-Status", test.status)
code := grpcStatusCode(rw)
assert.EqualValues(t, test.expected, code)
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/retry/retry_test.go | pkg/middlewares/retry/retry_test.go | package retry
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/http/httptrace"
"net/textproto"
"strings"
"testing"
"time"
"github.com/gorilla/websocket"
"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/testhelpers"
)
func TestRetry(t *testing.T) {
testCases := []struct {
desc string
config dynamic.Retry
wantRetryAttempts int
wantResponseStatus int
amountFaultyEndpoints int
}{
{
desc: "no retry on success",
config: dynamic.Retry{Attempts: 5},
wantRetryAttempts: 0,
wantResponseStatus: http.StatusOK,
amountFaultyEndpoints: 0,
},
{
desc: "no retry on success with backoff",
config: dynamic.Retry{Attempts: 5, InitialInterval: ptypes.Duration(time.Microsecond * 50)},
wantRetryAttempts: 0,
wantResponseStatus: http.StatusOK,
amountFaultyEndpoints: 0,
},
{
desc: "no retry when max request attempts is one",
config: dynamic.Retry{Attempts: 1},
wantRetryAttempts: 0,
wantResponseStatus: http.StatusBadGateway,
amountFaultyEndpoints: 1,
},
{
desc: "no retry when max request attempts is one with backoff",
config: dynamic.Retry{Attempts: 1, InitialInterval: ptypes.Duration(time.Microsecond * 50)},
wantRetryAttempts: 0,
wantResponseStatus: http.StatusBadGateway,
amountFaultyEndpoints: 1,
},
{
desc: "one retry when one server is faulty",
config: dynamic.Retry{Attempts: 2},
wantRetryAttempts: 1,
wantResponseStatus: http.StatusOK,
amountFaultyEndpoints: 1,
},
{
desc: "one retry when one server is faulty with backoff",
config: dynamic.Retry{Attempts: 2, InitialInterval: ptypes.Duration(time.Microsecond * 50)},
wantRetryAttempts: 1,
wantResponseStatus: http.StatusOK,
amountFaultyEndpoints: 1,
},
{
desc: "two retries when two servers are faulty",
config: dynamic.Retry{Attempts: 3},
wantRetryAttempts: 2,
wantResponseStatus: http.StatusOK,
amountFaultyEndpoints: 2,
},
{
desc: "two retries when two servers are faulty with backoff",
config: dynamic.Retry{Attempts: 3, InitialInterval: ptypes.Duration(time.Microsecond * 50)},
wantRetryAttempts: 2,
wantResponseStatus: http.StatusOK,
amountFaultyEndpoints: 2,
},
{
desc: "max attempts exhausted delivers the 5xx response",
config: dynamic.Retry{Attempts: 3},
wantRetryAttempts: 2,
wantResponseStatus: http.StatusBadGateway,
amountFaultyEndpoints: 3,
},
{
desc: "max attempts exhausted delivers the 5xx response with backoff",
config: dynamic.Retry{Attempts: 3, InitialInterval: ptypes.Duration(time.Microsecond * 50)},
wantRetryAttempts: 2,
wantResponseStatus: http.StatusBadGateway,
amountFaultyEndpoints: 3,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
retryAttempts := 0
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
// This signals that a connection will be established with the backend
// to enable the Retry middleware mechanism.
shouldRetry := ContextShouldRetry(req.Context())
if shouldRetry != nil {
shouldRetry(true)
}
retryAttempts++
if retryAttempts > test.amountFaultyEndpoints {
// This signals that request headers have been sent to the backend.
if shouldRetry != nil {
shouldRetry(false)
}
rw.WriteHeader(http.StatusOK)
return
}
rw.WriteHeader(http.StatusBadGateway)
})
retryListener := &countingRetryListener{}
retry, err := New(t.Context(), next, test.config, retryListener, "traefikTest")
require.NoError(t, err)
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "http://localhost:3000/ok", nil)
retry.ServeHTTP(recorder, req)
assert.Equal(t, test.wantResponseStatus, recorder.Code)
assert.Equal(t, test.wantRetryAttempts, retryListener.timesCalled)
})
}
}
func TestRetryEmptyServerList(t *testing.T) {
next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.WriteHeader(http.StatusServiceUnavailable)
})
retryListener := &countingRetryListener{}
retry, err := New(t.Context(), next, dynamic.Retry{Attempts: 3}, retryListener, "traefikTest")
require.NoError(t, err)
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "http://localhost:3000/ok", nil)
retry.ServeHTTP(recorder, req)
assert.Equal(t, http.StatusServiceUnavailable, recorder.Code)
assert.Equal(t, 0, retryListener.timesCalled)
}
func TestMultipleRetriesShouldNotLooseHeaders(t *testing.T) {
attempt := 0
expectedHeaderValue := "bar"
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
shouldRetry := ContextShouldRetry(req.Context())
if shouldRetry != nil {
shouldRetry(true)
}
headerName := fmt.Sprintf("X-Foo-Test-%d", attempt)
rw.Header().Add(headerName, expectedHeaderValue)
if attempt < 2 {
attempt++
return
}
// Request has been successfully written to backend
shouldRetry(false)
// And we decide to answer to client.
rw.WriteHeader(http.StatusNoContent)
})
retry, err := New(t.Context(), next, dynamic.Retry{Attempts: 3}, &countingRetryListener{}, "traefikTest")
require.NoError(t, err)
res := httptest.NewRecorder()
retry.ServeHTTP(res, testhelpers.MustNewRequest(http.MethodGet, "http://test", http.NoBody))
// The third header attempt is kept.
headerValue := res.Header().Get("X-Foo-Test-2")
assert.Equal(t, expectedHeaderValue, headerValue)
// Validate that we don't have headers from previous attempts
for i := range attempt {
headerName := fmt.Sprintf("X-Foo-Test-%d", i)
headerValue = res.Header().Get(headerName)
if headerValue != "" {
t.Errorf("Expected no value for header %s, got %s", headerName, headerValue)
}
}
}
func TestRetryShouldNotLooseHeadersOnWrite(t *testing.T) {
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Add("X-Foo-Test", "bar")
// Request has been successfully written to backend.
shouldRetry := ContextShouldRetry(req.Context())
if shouldRetry != nil {
shouldRetry(false)
}
// And we decide to answer to client without calling WriteHeader.
_, err := rw.Write([]byte("bar"))
require.NoError(t, err)
})
retry, err := New(t.Context(), next, dynamic.Retry{Attempts: 3}, &countingRetryListener{}, "traefikTest")
require.NoError(t, err)
res := httptest.NewRecorder()
retry.ServeHTTP(res, testhelpers.MustNewRequest(http.MethodGet, "http://test", http.NoBody))
headerValue := res.Header().Get("X-Foo-Test")
assert.Equal(t, "bar", headerValue)
}
func TestRetryWithFlush(t *testing.T) {
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusOK)
_, err := rw.Write([]byte("FULL "))
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
rw.(http.Flusher).Flush()
_, err = rw.Write([]byte("DATA"))
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
})
retry, err := New(t.Context(), next, dynamic.Retry{Attempts: 1}, &countingRetryListener{}, "traefikTest")
require.NoError(t, err)
responseRecorder := httptest.NewRecorder()
retry.ServeHTTP(responseRecorder, &http.Request{})
assert.Equal(t, "FULL DATA", responseRecorder.Body.String())
}
func TestRetryWebsocket(t *testing.T) {
testCases := []struct {
desc string
maxRequestAttempts int
expectedRetryAttempts int
expectedResponseStatus int
expectedError bool
amountFaultyEndpoints int
}{
{
desc: "Switching ok after 2 retries",
maxRequestAttempts: 3,
expectedRetryAttempts: 2,
amountFaultyEndpoints: 2,
expectedResponseStatus: http.StatusSwitchingProtocols,
},
{
desc: "Switching failed",
maxRequestAttempts: 2,
expectedRetryAttempts: 1,
amountFaultyEndpoints: 2,
expectedResponseStatus: http.StatusBadGateway,
expectedError: true,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
retryAttempts := 0
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
// This signals that a connection will be established with the backend
// to enable the Retry middleware mechanism.
shouldRetry := ContextShouldRetry(req.Context())
if shouldRetry != nil {
shouldRetry(true)
}
retryAttempts++
if retryAttempts > test.amountFaultyEndpoints {
// This signals that request headers have been sent to the backend.
if shouldRetry != nil {
shouldRetry(false)
}
upgrader := websocket.Upgrader{}
_, err := upgrader.Upgrade(rw, req, nil)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
return
}
rw.WriteHeader(http.StatusBadGateway)
})
retryListener := &countingRetryListener{}
retryH, err := New(t.Context(), next, dynamic.Retry{Attempts: test.maxRequestAttempts}, retryListener, "traefikTest")
require.NoError(t, err)
retryServer := httptest.NewServer(retryH)
url := strings.Replace(retryServer.URL, "http", "ws", 1)
_, response, err := websocket.DefaultDialer.Dial(url, nil)
if !test.expectedError {
require.NoError(t, err)
}
assert.Equal(t, test.expectedResponseStatus, response.StatusCode)
assert.Equal(t, test.expectedRetryAttempts, retryListener.timesCalled)
})
}
}
// This test is an adapted version of net/http/httputil.Test1xxResponses test.
func Test1xxResponses(t *testing.T) {
next := 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"))
})
retryListener := &countingRetryListener{}
retry, err := New(t.Context(), next, dynamic.Retry{Attempts: 1}, retryListener, "traefikTest")
require.NoError(t, err)
server := httptest.NewServer(retry)
t.Cleanup(server.Close)
frontendClient := server.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, server.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)
}
assert.Equal(t, 0, retryListener.timesCalled)
}
// countingRetryListener is a Listener implementation to count the times the Retried fn is called.
type countingRetryListener struct {
timesCalled int
}
func (l *countingRetryListener) Retried(req *http.Request, attempt int) {
l.timesCalled++
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/retry/retry.go | pkg/middlewares/retry/retry.go | package retry
import (
"bufio"
"context"
"fmt"
"io"
"math"
"net"
"net/http"
"net/http/httptrace"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/middlewares/observability"
"github.com/traefik/traefik/v3/pkg/observability/tracing"
"go.opentelemetry.io/otel/attribute"
semconv "go.opentelemetry.io/otel/semconv/v1.37.0"
"go.opentelemetry.io/otel/trace"
)
// Compile time validation that the response writer implements http interfaces correctly.
var _ middlewares.Stateful = &responseWriter{}
const typeName = "Retry"
// Listener is used to inform about retry attempts.
type Listener interface {
// Retried will be called when a retry happens, with the request attempt passed to it.
// For the first retry this will be attempt 2.
Retried(req *http.Request, attempt int)
}
// Listeners is a convenience type to construct a list of Listener and notify
// each of them about a retry attempt.
type Listeners []Listener
// Retried exists to implement the Listener interface. It calls Retried on each of its slice entries.
func (l Listeners) Retried(req *http.Request, attempt int) {
for _, listener := range l {
listener.Retried(req, attempt)
}
}
type shouldRetryContextKey struct{}
// ShouldRetry is a function allowing to enable/disable the retry middleware mechanism.
type ShouldRetry func(shouldRetry bool)
// ContextShouldRetry returns the ShouldRetry function if it has been set by the Retry middleware in the chain.
func ContextShouldRetry(ctx context.Context) ShouldRetry {
f, _ := ctx.Value(shouldRetryContextKey{}).(ShouldRetry)
return f
}
// WrapHandler wraps a given http.Handler to inject the httptrace.ClientTrace in the request context when it is needed
// by the retry middleware.
func WrapHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if shouldRetry := ContextShouldRetry(req.Context()); shouldRetry != nil {
shouldRetry(true)
trace := &httptrace.ClientTrace{
WroteHeaders: func() {
shouldRetry(false)
},
WroteRequest: func(httptrace.WroteRequestInfo) {
shouldRetry(false)
},
}
newCtx := httptrace.WithClientTrace(req.Context(), trace)
next.ServeHTTP(rw, req.WithContext(newCtx))
return
}
next.ServeHTTP(rw, req)
})
}
// retry is a middleware that retries requests.
type retry struct {
attempts int
initialInterval time.Duration
next http.Handler
listener Listener
name string
}
// New returns a new retry middleware.
func New(ctx context.Context, next http.Handler, config dynamic.Retry, listener Listener, name string) (http.Handler, error) {
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
if config.Attempts <= 0 {
return nil, fmt.Errorf("incorrect (or empty) value for attempt (%d)", config.Attempts)
}
return &retry{
attempts: config.Attempts,
initialInterval: time.Duration(config.InitialInterval),
next: next,
listener: listener,
name: name,
}, nil
}
func (r *retry) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if r.attempts == 1 {
r.next.ServeHTTP(rw, req)
return
}
closableBody := req.Body
defer closableBody.Close()
// if we might make multiple attempts, swap the body for an io.NopCloser
// cf https://github.com/traefik/traefik/issues/1008
req.Body = io.NopCloser(closableBody)
attempts := 1
initialCtx := req.Context()
tracer := tracing.TracerFromContext(initialCtx)
var currentSpan trace.Span
operation := func() error {
if tracer != nil && observability.DetailedTracingEnabled(req.Context()) {
if currentSpan != nil {
currentSpan.End()
}
// Because multiple tracing spans may need to be created,
// the Retry middleware does not implement trace.Traceable,
// and creates directly a new span for each retry operation.
var tracingCtx context.Context
tracingCtx, currentSpan = tracer.Start(initialCtx, typeName, trace.WithSpanKind(trace.SpanKindInternal))
currentSpan.SetAttributes(attribute.String("traefik.middleware.name", r.name))
// Only add the attribute "http.resend_count" defined by semantic conventions starting from second attempt.
if attempts > 1 {
currentSpan.SetAttributes(semconv.HTTPRequestResendCount(attempts - 1))
}
req = req.WithContext(tracingCtx)
}
remainAttempts := attempts < r.attempts
retryResponseWriter := newResponseWriter(rw)
var shouldRetry ShouldRetry = func(shouldRetry bool) {
retryResponseWriter.SetShouldRetry(remainAttempts && shouldRetry)
}
newCtx := context.WithValue(req.Context(), shouldRetryContextKey{}, shouldRetry)
r.next.ServeHTTP(retryResponseWriter, req.Clone(newCtx))
if !retryResponseWriter.ShouldRetry() {
return nil
}
attempts++
return fmt.Errorf("attempt %d failed", attempts-1)
}
logger := middlewares.GetLogger(req.Context(), r.name, typeName)
backOff := backoff.WithContext(r.newBackOff(), req.Context())
notify := func(err error, d time.Duration) {
logger.Debug().Msgf("New attempt %d for request: %v", attempts, req.URL)
r.listener.Retried(req, attempts)
}
err := backoff.RetryNotify(operation, backOff, notify)
if err != nil {
logger.Debug().Err(err).Msg("Final retry attempt failed")
}
if currentSpan != nil {
currentSpan.End()
}
}
func (r *retry) newBackOff() backoff.BackOff {
if r.attempts < 2 || r.initialInterval <= 0 {
return &backoff.ZeroBackOff{}
}
b := backoff.NewExponentialBackOff()
b.InitialInterval = r.initialInterval
// calculate the multiplier for the given number of attempts
// so that applying the multiplier for the given number of attempts will not exceed 2 times the initial interval
// it allows to control the progression along the attempts
b.Multiplier = math.Pow(2, 1/float64(r.attempts-1))
// according to docs, b.Reset() must be called before using
b.Reset()
return b
}
func newResponseWriter(rw http.ResponseWriter) *responseWriter {
return &responseWriter{
responseWriter: rw,
headers: make(http.Header),
}
}
type responseWriter struct {
responseWriter http.ResponseWriter
headers http.Header
shouldRetry bool
written bool
}
func (r *responseWriter) ShouldRetry() bool {
return r.shouldRetry
}
func (r *responseWriter) SetShouldRetry(shouldRetry bool) {
r.shouldRetry = shouldRetry
}
func (r *responseWriter) Header() http.Header {
if r.written {
return r.responseWriter.Header()
}
return r.headers
}
func (r *responseWriter) Write(buf []byte) (int, error) {
if r.ShouldRetry() {
return len(buf), nil
}
if !r.written {
r.WriteHeader(http.StatusOK)
}
return r.responseWriter.Write(buf)
}
func (r *responseWriter) WriteHeader(code int) {
if r.shouldRetry || r.written {
return
}
// In that case retry case is set to false which means we at least managed
// to write headers to the backend : we are not going to perform any further retry.
// So it is now safe to alter current response headers with headers collected during
// the latest try before writing headers to client.
headers := r.responseWriter.Header()
for header, value := range r.headers {
headers[header] = value
}
r.responseWriter.WriteHeader(code)
// Handling informational headers.
// This allows to keep writing to r.headers map until a final status code is written.
if code >= 100 && code <= 199 {
return
}
r.written = true
}
func (r *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker, ok := r.responseWriter.(http.Hijacker)
if !ok {
return nil, nil, fmt.Errorf("%T is not a http.Hijacker", r.responseWriter)
}
return hijacker.Hijack()
}
func (r *responseWriter) Flush() {
if flusher, ok := r.responseWriter.(http.Flusher); ok {
flusher.Flush()
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/observability/mock_tracing_test.go | pkg/middlewares/observability/mock_tracing_test.go | package observability
import (
"context"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/trace/embedded"
)
type mockTracerProvider struct {
embedded.TracerProvider
}
var _ trace.TracerProvider = mockTracerProvider{}
func (p mockTracerProvider) Tracer(string, ...trace.TracerOption) trace.Tracer {
return &mockTracer{}
}
type mockTracer struct {
embedded.Tracer
spans []*mockSpan
}
var _ trace.Tracer = &mockTracer{}
func (t *mockTracer) Start(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) {
config := trace.NewSpanStartConfig(opts...)
span := &mockSpan{}
span.SetName(name)
span.SetAttributes(attribute.String("span.kind", config.SpanKind().String()))
span.SetAttributes(config.Attributes()...)
t.spans = append(t.spans, span)
return trace.ContextWithSpan(ctx, span), span
}
// mockSpan is an implementation of Span that performs no operations.
type mockSpan struct {
embedded.Span
name string
attributes []attribute.KeyValue
}
var _ trace.Span = &mockSpan{}
func (*mockSpan) SpanContext() trace.SpanContext {
return trace.NewSpanContext(trace.SpanContextConfig{TraceID: trace.TraceID{1}, SpanID: trace.SpanID{1}})
}
func (*mockSpan) IsRecording() bool { return false }
func (s *mockSpan) SetStatus(_ codes.Code, _ string) {}
func (s *mockSpan) SetAttributes(kv ...attribute.KeyValue) {
s.attributes = append(s.attributes, kv...)
}
func (s *mockSpan) End(...trace.SpanEndOption) {}
func (s *mockSpan) RecordError(_ error, _ ...trace.EventOption) {}
func (s *mockSpan) AddEvent(_ string, _ ...trace.EventOption) {}
func (s *mockSpan) AddLink(_ trace.Link) {}
func (s *mockSpan) SetName(name string) { s.name = name }
func (s *mockSpan) TracerProvider() trace.TracerProvider {
return nil
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/observability/middleware.go | pkg/middlewares/observability/middleware.go | package observability
import (
"context"
"net/http"
"github.com/containous/alice"
"github.com/rs/zerolog/log"
"github.com/traefik/traefik/v3/pkg/observability/logs"
"github.com/traefik/traefik/v3/pkg/observability/tracing"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
// Traceable embeds tracing information.
type Traceable interface {
GetTracingInformation() (name string, typeName string)
}
// WrapMiddleware adds traceability to an alice.Constructor.
func WrapMiddleware(ctx context.Context, constructor alice.Constructor) alice.Constructor {
return func(next http.Handler) (http.Handler, error) {
if constructor == nil {
return nil, nil
}
handler, err := constructor(next)
if err != nil {
return nil, err
}
if traceableHandler, ok := handler.(Traceable); ok {
name, typeName := traceableHandler.GetTracingInformation()
log.Ctx(ctx).Debug().Str(logs.MiddlewareName, name).Msg("Adding tracing to middleware")
return NewMiddleware(handler, name, typeName), nil
}
return handler, nil
}
}
// NewMiddleware returns a http.Handler struct.
func NewMiddleware(next http.Handler, name string, typeName string) http.Handler {
return &middlewareTracing{
next: next,
name: name,
typeName: typeName,
}
}
// middlewareTracing is used to wrap http handler middleware.
type middlewareTracing struct {
next http.Handler
name string
typeName string
}
func (w *middlewareTracing) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if tracer := tracing.TracerFromContext(req.Context()); tracer != nil && DetailedTracingEnabled(req.Context()) {
tracingCtx, span := tracer.Start(req.Context(), w.typeName, trace.WithSpanKind(trace.SpanKindInternal))
defer span.End()
req = req.WithContext(tracingCtx)
span.SetAttributes(attribute.String("traefik.middleware.name", w.name))
}
if w.next != nil {
w.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/observability/entrypoint_test.go | pkg/middlewares/observability/entrypoint_test.go | package observability
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/traefik/traefik/v3/pkg/observability/tracing"
"go.opentelemetry.io/otel/attribute"
)
func TestEntryPointMiddleware_tracing(t *testing.T) {
type expected struct {
name string
attributes []attribute.KeyValue
}
testCases := []struct {
desc string
entryPoint string
method string
expected expected
}{
{
desc: "GET",
entryPoint: "test",
method: http.MethodGet,
expected: expected{
name: "GET",
attributes: []attribute.KeyValue{
attribute.String("span.kind", "server"),
attribute.String("entry_point", "test"),
attribute.String("http.request.method", "GET"),
attribute.String("network.protocol.version", "1.1"),
attribute.Int64("http.request.body.size", int64(0)),
attribute.String("url.path", "/search"),
attribute.String("url.query", "q=Opentelemetry&token=REDACTED"),
attribute.String("url.scheme", "http"),
attribute.String("user_agent.original", "entrypoint-test"),
attribute.String("server.address", "www.test.com"),
attribute.String("network.peer.address", "10.0.0.1"),
attribute.String("client.address", "10.0.0.1"),
attribute.Int64("client.port", int64(1234)),
attribute.Int64("network.peer.port", int64(1234)),
attribute.StringSlice("http.request.header.x-foo", []string{"foo", "bar"}),
attribute.Int64("http.response.status_code", int64(404)),
attribute.StringSlice("http.response.header.x-bar", []string{"foo", "bar"}),
},
},
},
{
desc: "POST",
entryPoint: "test",
method: http.MethodPost,
expected: expected{
name: "POST",
attributes: []attribute.KeyValue{
attribute.String("span.kind", "server"),
attribute.String("entry_point", "test"),
attribute.String("http.request.method", "POST"),
attribute.String("network.protocol.version", "1.1"),
attribute.Int64("http.request.body.size", int64(0)),
attribute.String("url.path", "/search"),
attribute.String("url.query", "q=Opentelemetry&token=REDACTED"),
attribute.String("url.scheme", "http"),
attribute.String("user_agent.original", "entrypoint-test"),
attribute.String("server.address", "www.test.com"),
attribute.String("network.peer.address", "10.0.0.1"),
attribute.String("client.address", "10.0.0.1"),
attribute.Int64("client.port", int64(1234)),
attribute.Int64("network.peer.port", int64(1234)),
attribute.StringSlice("http.request.header.x-foo", []string{"foo", "bar"}),
attribute.Int64("http.response.status_code", int64(404)),
attribute.StringSlice("http.response.header.x-bar", []string{"foo", "bar"}),
},
},
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
req := httptest.NewRequest(test.method, "http://www.test.com/search?q=Opentelemetry&token=123", nil)
rw := httptest.NewRecorder()
req.RemoteAddr = "10.0.0.1:1234"
req.Header.Set("User-Agent", "entrypoint-test")
req.Header.Set("X-Forwarded-Proto", "http")
req.Header.Set("X-Foo", "foo")
req.Header.Add("X-Foo", "bar")
next := http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
rw.Header().Set("X-Bar", "foo")
rw.Header().Add("X-Bar", "bar")
rw.WriteHeader(http.StatusNotFound)
})
tracer := &mockTracer{}
// Injection of the observability variables in the request context.
req = req.WithContext(WithObservability(req.Context(), Observability{
TracingEnabled: true,
}))
handler := newEntryPoint(t.Context(), tracing.NewTracer(tracer, []string{"X-Foo"}, []string{"X-Bar"}, []string{"q"}), test.entryPoint, next)
handler.ServeHTTP(rw, req)
require.Len(t, tracer.spans, 1)
assert.Equal(t, test.expected.name, tracer.spans[0].name)
assert.Equal(t, test.expected.attributes, tracer.spans[0].attributes)
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/observability/service.go | pkg/middlewares/observability/service.go | package observability
import (
"context"
"net/http"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/observability/logs"
"github.com/traefik/traefik/v3/pkg/observability/tracing"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
const (
serviceTypeName = "TracingService"
)
type serviceTracing struct {
service string
next http.Handler
}
// NewService creates a new tracing middleware that traces the outgoing requests.
func NewService(ctx context.Context, service string, next http.Handler) http.Handler {
middlewares.GetLogger(ctx, "tracing", serviceTypeName).
Debug().Str(logs.ServiceName, service).Msg("Added outgoing tracing middleware")
return &serviceTracing{
service: service,
next: next,
}
}
func (t *serviceTracing) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if tracer := tracing.TracerFromContext(req.Context()); tracer != nil && DetailedTracingEnabled(req.Context()) {
tracingCtx, span := tracer.Start(req.Context(), "Service", trace.WithSpanKind(trace.SpanKindInternal))
defer span.End()
req = req.WithContext(tracingCtx)
span.SetAttributes(attribute.String("traefik.service.name", t.service))
}
t.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/observability/service_test.go | pkg/middlewares/observability/service_test.go | package observability
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
func TestNewService(t *testing.T) {
type expected struct {
attributes []attribute.KeyValue
name string
}
testCases := []struct {
desc string
service string
expected []expected
}{
{
desc: "base",
service: "myService",
expected: []expected{
{
name: "GET",
attributes: []attribute.KeyValue{
attribute.String("span.kind", "server"),
},
},
{
name: "Service",
attributes: []attribute.KeyValue{
attribute.String("span.kind", "internal"),
attribute.String("http.request.method", "GET"),
attribute.Int64("http.response.status_code", int64(404)),
attribute.String("network.protocol.version", "1.1"),
attribute.String("server.address", "www.test.com"),
attribute.Int64("server.port", int64(80)),
attribute.String("url.full", "http://www.test.com/traces?p=OpenTelemetry"),
attribute.String("url.scheme", "http"),
attribute.String("traefik.service.name", "myService"),
attribute.String("user_agent.original", "service-test"),
},
},
},
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "http://www.test.com/traces?p=OpenTelemetry", nil)
req.RemoteAddr = "10.0.0.1:1234"
req.Header.Set("User-Agent", "service-test")
tracer := &mockTracer{}
tracingCtx, entryPointSpan := tracer.Start(req.Context(), http.MethodGet, trace.WithSpanKind(trace.SpanKindServer))
defer entryPointSpan.End()
req = req.WithContext(tracingCtx)
rw := httptest.NewRecorder()
next := http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
rw.WriteHeader(http.StatusNotFound)
})
handler := NewService(t.Context(), test.service, next)
handler.ServeHTTP(rw, req)
for i, span := range tracer.spans {
assert.Equal(t, test.expected[i].name, span.name)
assert.Equal(t, test.expected[i].attributes, span.attributes)
}
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/observability/semconv.go | pkg/middlewares/observability/semconv.go | package observability
import (
"context"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/containous/alice"
"github.com/rs/zerolog/log"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/middlewares/capture"
"github.com/traefik/traefik/v3/pkg/observability/logs"
"github.com/traefik/traefik/v3/pkg/observability/metrics"
"go.opentelemetry.io/otel/attribute"
semconv "go.opentelemetry.io/otel/semconv/v1.37.0"
"go.opentelemetry.io/otel/semconv/v1.37.0/httpconv"
)
const (
semConvServerMetricsTypeName = "SemConvServerMetrics"
)
type semConvServerMetrics struct {
next http.Handler
semConvMetricRegistry *metrics.SemConvMetricsRegistry
}
// SemConvServerMetricsHandler return the alice.Constructor for semantic conventions servers metrics.
func SemConvServerMetricsHandler(ctx context.Context, semConvMetricRegistry *metrics.SemConvMetricsRegistry) alice.Constructor {
return func(next http.Handler) (http.Handler, error) {
return newServerMetricsSemConv(ctx, semConvMetricRegistry, next), nil
}
}
// newServerMetricsSemConv creates a new semConv server metrics middleware for incoming requests.
func newServerMetricsSemConv(ctx context.Context, semConvMetricRegistry *metrics.SemConvMetricsRegistry, next http.Handler) http.Handler {
middlewares.GetLogger(ctx, "tracing", semConvServerMetricsTypeName).Debug().Msg("Creating middleware")
return &semConvServerMetrics{
semConvMetricRegistry: semConvMetricRegistry,
next: next,
}
}
func (e *semConvServerMetrics) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if e.semConvMetricRegistry == nil || !SemConvMetricsEnabled(req.Context()) {
e.next.ServeHTTP(rw, req)
return
}
start := time.Now()
e.next.ServeHTTP(rw, req)
end := time.Now()
ctx := req.Context()
capt, err := capture.FromContext(ctx)
if err != nil {
log.Ctx(ctx).Error().Err(err).Str(logs.MiddlewareType, semConvServerMetricsTypeName).Msg("Could not get Capture")
return
}
var attrs []attribute.KeyValue
if capt.StatusCode() < 100 || capt.StatusCode() >= 600 {
attrs = append(attrs, attribute.Key("error.type").String(fmt.Sprintf("Invalid HTTP status code ; %d", capt.StatusCode())))
} else if capt.StatusCode() >= 400 {
attrs = append(attrs, attribute.Key("error.type").String(strconv.Itoa(capt.StatusCode())))
}
// Additional optional attributes.
attrs = append(attrs, semconv.HTTPResponseStatusCode(capt.StatusCode()))
attrs = append(attrs, semconv.NetworkProtocolName(strings.ToLower(req.Proto)))
attrs = append(attrs, semconv.NetworkProtocolVersion(Proto(req.Proto)))
attrs = append(attrs, semconv.ServerAddress(req.Host))
e.semConvMetricRegistry.HTTPServerRequestDuration().Record(req.Context(), end.Sub(start).Seconds(),
httpconv.RequestMethodAttr(req.Method), req.Header.Get("X-Forwarded-Proto"), attrs...)
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/observability/router.go | pkg/middlewares/observability/router.go | package observability
import (
"context"
"net/http"
"github.com/containous/alice"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/observability/logs"
"github.com/traefik/traefik/v3/pkg/observability/tracing"
"go.opentelemetry.io/otel/attribute"
semconv "go.opentelemetry.io/otel/semconv/v1.37.0"
"go.opentelemetry.io/otel/trace"
)
const (
routerTypeName = "TracingRouter"
)
type routerTracing struct {
router string
routerRule string
service string
next http.Handler
}
// WrapRouterHandler Wraps tracing to alice.Constructor.
func WrapRouterHandler(ctx context.Context, router, routerRule, service string) alice.Constructor {
return func(next http.Handler) (http.Handler, error) {
return newRouter(ctx, router, routerRule, service, next), nil
}
}
// newRouter creates a new tracing middleware that traces the internal requests.
func newRouter(ctx context.Context, router, routerRule, service string, next http.Handler) http.Handler {
middlewares.GetLogger(ctx, "tracing", routerTypeName).
Debug().Str(logs.RouterName, router).Str(logs.ServiceName, service).Msg("Added outgoing tracing middleware")
return &routerTracing{
router: router,
routerRule: routerRule,
service: service,
next: next,
}
}
func (f *routerTracing) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if tracer := tracing.TracerFromContext(req.Context()); tracer != nil && DetailedTracingEnabled(req.Context()) {
tracingCtx, span := tracer.Start(req.Context(), "Router", trace.WithSpanKind(trace.SpanKindInternal))
defer span.End()
req = req.WithContext(tracingCtx)
span.SetAttributes(attribute.String("traefik.service.name", f.service))
span.SetAttributes(attribute.String("traefik.router.name", f.router))
span.SetAttributes(semconv.HTTPRoute(f.routerRule))
}
f.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/observability/status_code.go | pkg/middlewares/observability/status_code.go | package observability
import (
"bufio"
"net"
"net/http"
)
// newStatusCodeRecorder returns an initialized statusCodeRecoder.
func newStatusCodeRecorder(rw http.ResponseWriter, status int) *statusCodeRecorder {
return &statusCodeRecorder{rw, status}
}
type statusCodeRecorder struct {
http.ResponseWriter
status int
}
// WriteHeader captures the status code for later retrieval.
func (s *statusCodeRecorder) WriteHeader(status int) {
s.status = status
s.ResponseWriter.WriteHeader(status)
}
// Status get response status.
func (s *statusCodeRecorder) Status() int {
return s.status
}
// Hijack hijacks the connection.
func (s *statusCodeRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return s.ResponseWriter.(http.Hijacker).Hijack()
}
// Flush sends any buffered data to the client.
func (s *statusCodeRecorder) Flush() {
if flusher, ok := s.ResponseWriter.(http.Flusher); ok {
flusher.Flush()
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/observability/router_test.go | pkg/middlewares/observability/router_test.go | package observability
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
func TestNewRouter(t *testing.T) {
type expected struct {
attributes []attribute.KeyValue
name string
}
testCases := []struct {
desc string
service string
router string
routerRule string
expected []expected
}{
{
desc: "base",
service: "myService",
router: "myRouter",
routerRule: "Path(`/`)",
expected: []expected{
{
name: "GET",
attributes: []attribute.KeyValue{
attribute.String("span.kind", "server"),
},
},
{
name: "Router",
attributes: []attribute.KeyValue{
attribute.String("span.kind", "internal"),
attribute.String("http.request.method", "GET"),
attribute.Int64("http.response.status_code", int64(404)),
attribute.String("network.protocol.version", "1.1"),
attribute.String("server.address", "www.test.com"),
attribute.Int64("server.port", int64(80)),
attribute.String("url.full", "http://www.test.com/traces?p=OpenTelemetry"),
attribute.String("url.scheme", "http"),
attribute.String("traefik.service.name", "myService"),
attribute.String("traefik.router.name", "myRouter"),
attribute.String("http.route", "Path(`/`)"),
attribute.String("user_agent.original", "router-test"),
},
},
},
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "http://www.test.com/traces?p=OpenTelemetry", nil)
req.RemoteAddr = "10.0.0.1:1234"
req.Header.Set("User-Agent", "router-test")
tracer := &mockTracer{}
tracingCtx, entryPointSpan := tracer.Start(req.Context(), http.MethodGet, trace.WithSpanKind(trace.SpanKindServer))
defer entryPointSpan.End()
req = req.WithContext(tracingCtx)
rw := httptest.NewRecorder()
next := http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
rw.WriteHeader(http.StatusNotFound)
})
handler := newRouter(t.Context(), test.router, test.routerRule, test.service, next)
handler.ServeHTTP(rw, req)
for i, span := range tracer.spans {
assert.Equal(t, test.expected[i].name, span.name)
assert.Equal(t, test.expected[i].attributes, span.attributes)
}
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/observability/semconv_test.go | pkg/middlewares/observability/semconv_test.go | package observability
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"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/observability/metrics"
otypes "github.com/traefik/traefik/v3/pkg/observability/types"
"go.opentelemetry.io/otel/attribute"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/metric/metricdata"
"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest"
)
func TestSemConvServerMetrics(t *testing.T) {
tests := []struct {
desc string
statusCode int
wantAttributes attribute.Set
}{
{
desc: "not found status",
statusCode: http.StatusNotFound,
wantAttributes: attribute.NewSet(
attribute.Key("error.type").String("404"),
attribute.Key("http.request.method").String("GET"),
attribute.Key("http.response.status_code").Int(404),
attribute.Key("network.protocol.name").String("http/1.1"),
attribute.Key("network.protocol.version").String("1.1"),
attribute.Key("server.address").String("www.test.com"),
attribute.Key("url.scheme").String("http"),
),
},
{
desc: "created status",
statusCode: http.StatusCreated,
wantAttributes: attribute.NewSet(
attribute.Key("http.request.method").String("GET"),
attribute.Key("http.response.status_code").Int(201),
attribute.Key("network.protocol.name").String("http/1.1"),
attribute.Key("network.protocol.version").String("1.1"),
attribute.Key("server.address").String("www.test.com"),
attribute.Key("url.scheme").String("http"),
),
},
}
for _, test := range tests {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
var cfg otypes.OTLP
(&cfg).SetDefaults()
cfg.AddRoutersLabels = true
cfg.PushInterval = ptypes.Duration(10 * time.Millisecond)
rdr := sdkmetric.NewManualReader()
meterProvider := sdkmetric.NewMeterProvider(sdkmetric.WithReader(rdr))
// force the meter provider with manual reader to collect metrics for the test.
metrics.SetMeterProvider(meterProvider)
semConvMetricRegistry, err := metrics.NewSemConvMetricRegistry(t.Context(), &cfg)
require.NoError(t, err)
require.NotNil(t, semConvMetricRegistry)
req := httptest.NewRequest(http.MethodGet, "http://www.test.com/search?q=Opentelemetry", nil)
rw := httptest.NewRecorder()
req.RemoteAddr = "10.0.0.1:1234"
req.Header.Set("User-Agent", "entrypoint-test")
req.Header.Set("X-Forwarded-Proto", "http")
next := http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
rw.WriteHeader(test.statusCode)
})
handler := newServerMetricsSemConv(t.Context(), semConvMetricRegistry, next)
handler, err = capture.Wrap(handler)
require.NoError(t, err)
// Injection of the observability variables in the request context.
handler = WithObservabilityHandler(handler, Observability{
SemConvMetricsEnabled: true,
})
handler.ServeHTTP(rw, req)
got := metricdata.ResourceMetrics{}
err = rdr.Collect(t.Context(), &got)
require.NoError(t, err)
require.Len(t, got.ScopeMetrics, 1)
expected := metricdata.Metrics{
Name: "http.server.request.duration",
Description: "Duration of HTTP server requests.",
Unit: "s",
Data: metricdata.Histogram[float64]{
DataPoints: []metricdata.HistogramDataPoint[float64]{
{
Attributes: test.wantAttributes,
Count: 1,
Bounds: []float64{0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10},
BucketCounts: []uint64{0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
Min: metricdata.NewExtrema[float64](1),
Max: metricdata.NewExtrema[float64](1),
Sum: 1,
},
},
Temporality: metricdata.CumulativeTemporality,
},
}
metricdatatest.AssertEqual[metricdata.Metrics](t, expected, got.ScopeMetrics[0].Metrics[0], metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/observability/entrypoint.go | pkg/middlewares/observability/entrypoint.go | package observability
import (
"context"
"net/http"
"time"
"github.com/containous/alice"
"github.com/rs/zerolog/log"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/observability/tracing"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/trace/noop"
)
const (
entryPointTypeName = "TracingEntryPoint"
)
type entryPointTracing struct {
tracer *tracing.Tracer
entryPoint string
next http.Handler
}
// EntryPointHandler Wraps tracing to alice.Constructor.
func EntryPointHandler(ctx context.Context, tracer *tracing.Tracer, entryPointName string) alice.Constructor {
return func(next http.Handler) (http.Handler, error) {
return newEntryPoint(ctx, tracer, entryPointName, next), nil
}
}
// newEntryPoint creates a new tracing middleware for incoming requests.
func newEntryPoint(ctx context.Context, tracer *tracing.Tracer, entryPointName string, next http.Handler) http.Handler {
middlewares.GetLogger(ctx, "tracing", entryPointTypeName).Debug().Msg("Creating middleware")
if tracer == nil {
tracer = tracing.NewTracer(noop.Tracer{}, nil, nil, nil)
}
return &entryPointTracing{
entryPoint: entryPointName,
tracer: tracer,
next: next,
}
}
func (e *entryPointTracing) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if e.tracer == nil || !TracingEnabled(req.Context()) {
e.next.ServeHTTP(rw, req)
return
}
tracingCtx := tracing.ExtractCarrierIntoContext(req.Context(), req.Header)
start := time.Now()
// Follow semantic conventions defined by OTEL: https://opentelemetry.io/docs/specs/semconv/http/http-spans/#name
// At the moment this implementation only gets the {method} as there is no guarantee {target} is low cardinality.
tracingCtx, span := e.tracer.Start(tracingCtx, req.Method, trace.WithSpanKind(trace.SpanKindServer), trace.WithTimestamp(start))
// Associate the request context with the logger.
// This allows the logger to be aware of the tracing context and log accordingly (TraceID, SpanID, etc.).
logger := log.Ctx(tracingCtx).With().Ctx(tracingCtx).Logger()
loggerCtx := logger.WithContext(tracingCtx)
req = req.WithContext(loggerCtx)
span.SetAttributes(attribute.String("entry_point", e.entryPoint))
e.tracer.CaptureServerRequest(span, req)
recorder := newStatusCodeRecorder(rw, http.StatusOK)
e.next.ServeHTTP(recorder, req)
e.tracer.CaptureResponse(span, recorder.Header(), recorder.Status(), trace.SpanKindServer)
end := time.Now()
span.End(trace.WithTimestamp(end))
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/observability/observability.go | pkg/middlewares/observability/observability.go | package observability
import (
"context"
"fmt"
"net/http"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
type contextKey int
const observabilityKey contextKey = iota
type Observability struct {
AccessLogsEnabled bool
MetricsEnabled bool
SemConvMetricsEnabled bool
TracingEnabled bool
DetailedTracingEnabled bool
}
// WithObservabilityHandler sets the observability state in the context for the next handler.
// This is also used for testing purposes to control whether access logs are enabled or not.
func WithObservabilityHandler(next http.Handler, obs Observability) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
next.ServeHTTP(rw, req.WithContext(WithObservability(req.Context(), obs)))
})
}
// WithObservability injects the observability state into the context.
func WithObservability(ctx context.Context, obs Observability) context.Context {
return context.WithValue(ctx, observabilityKey, obs)
}
// AccessLogsEnabled returns whether access-logs are enabled.
func AccessLogsEnabled(ctx context.Context) bool {
obs, ok := ctx.Value(observabilityKey).(Observability)
return ok && obs.AccessLogsEnabled
}
// MetricsEnabled returns whether metrics are enabled.
func MetricsEnabled(ctx context.Context) bool {
obs, ok := ctx.Value(observabilityKey).(Observability)
return ok && obs.MetricsEnabled
}
// SemConvMetricsEnabled returns whether metrics are enabled.
func SemConvMetricsEnabled(ctx context.Context) bool {
obs, ok := ctx.Value(observabilityKey).(Observability)
return ok && obs.SemConvMetricsEnabled
}
// TracingEnabled returns whether tracing is enabled.
func TracingEnabled(ctx context.Context) bool {
obs, ok := ctx.Value(observabilityKey).(Observability)
return ok && obs.TracingEnabled
}
// DetailedTracingEnabled returns whether detailed tracing is enabled.
func DetailedTracingEnabled(ctx context.Context) bool {
obs, ok := ctx.Value(observabilityKey).(Observability)
return ok && obs.DetailedTracingEnabled
}
// SetStatusErrorf flags the span as in error and log an event.
func SetStatusErrorf(ctx context.Context, format string, args ...interface{}) {
if span := trace.SpanFromContext(ctx); span != nil {
span.SetStatus(codes.Error, fmt.Sprintf(format, args...))
}
}
func Proto(proto string) string {
switch proto {
case "HTTP/1.0":
return "1.0"
case "HTTP/1.1":
return "1.1"
case "HTTP/2":
return "2"
case "HTTP/3":
return "3"
default:
return proto
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/inflightreq/inflight_req.go | pkg/middlewares/inflightreq/inflight_req.go | package inflightreq
import (
"context"
"fmt"
"net/http"
"github.com/rs/zerolog"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/observability/logs"
"github.com/vulcand/oxy/v2/connlimit"
)
const (
typeName = "InFlightReq"
)
type inFlightReq struct {
handler http.Handler
name string
}
// New creates a max request middleware.
// If no source criterion is provided in the config, it defaults to RequestHost.
func New(ctx context.Context, next http.Handler, config dynamic.InFlightReq, name string) (http.Handler, error) {
logger := middlewares.GetLogger(ctx, name, typeName)
logger.Debug().Msg("Creating middleware")
ctxLog := logger.WithContext(ctx)
if config.SourceCriterion == nil ||
config.SourceCriterion.IPStrategy == nil &&
config.SourceCriterion.RequestHeaderName == "" && !config.SourceCriterion.RequestHost {
config.SourceCriterion = &dynamic.SourceCriterion{
RequestHost: true,
}
}
sourceMatcher, err := middlewares.GetSourceExtractor(ctxLog, config.SourceCriterion)
if err != nil {
return nil, fmt.Errorf("error creating requests limiter: %w", err)
}
handler, err := connlimit.New(next, sourceMatcher, config.Amount,
connlimit.Logger(logs.NewOxyWrapper(*logger)),
connlimit.Verbose(logger.GetLevel() == zerolog.TraceLevel))
if err != nil {
return nil, fmt.Errorf("error creating connection limit: %w", err)
}
return &inFlightReq{handler: handler, name: name}, nil
}
func (i *inFlightReq) GetTracingInformation() (string, string) {
return i.name, typeName
}
func (i *inFlightReq) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
i.handler.ServeHTTP(rw, req)
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/capture/capture.go | pkg/middlewares/capture/capture.go | // Package capture is a middleware that captures requests/responses size, and status.
//
// For another middleware to get those attributes of a request/response, this middleware
// should be added before in the middleware chain.
//
// chain := alice.New().
// Append(capture.Wrap).
// Append(myOtherMiddleware).
// then(...)
//
// As this middleware stores those data in the request's context, the data can
// be retrieved at anytime after the ServerHTTP.
//
// func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request, next http.Handler) {
// capt, err := capture.FromContext(req.Context())
// if err != nil {
// ...
// }
//
// fmt.Println(capt.Status())
// fmt.Println(capt.ResponseSize())
// fmt.Println(capt.RequestSize())
// }
package capture
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"github.com/traefik/traefik/v3/pkg/middlewares"
)
type key string
const capturedData key = "capturedData"
// Wrap returns a new handler that inserts a Capture into the given handler for each incoming request.
// It satisfies the alice.Constructor type.
func Wrap(next http.Handler) (http.Handler, error) {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
capt, err := FromContext(req.Context())
if err != nil {
c := &Capture{}
newRW, newReq := c.renew(rw, req)
next.ServeHTTP(newRW, newReq)
return
}
if capt.NeedsReset(rw) {
newRW, newReq := capt.renew(rw, req)
next.ServeHTTP(newRW, newReq)
return
}
next.ServeHTTP(rw, req)
}), nil
}
// FromContext returns the Capture value found in ctx, or an empty Capture otherwise.
func FromContext(ctx context.Context) (Capture, error) {
c := ctx.Value(capturedData)
if c == nil {
return Capture{}, errors.New("value not found in context")
}
capt, ok := c.(*Capture)
if !ok {
return Capture{}, errors.New("value stored in context is not a *Capture")
}
return *capt, nil
}
// Capture is the object populated by the capture middleware,
// holding probes that allow to gather information about the request and response.
type Capture struct {
rr *readCounter
crw *captureResponseWriter
}
// NeedsReset returns whether the given http.ResponseWriter is the capture's probe.
func (c *Capture) NeedsReset(rw http.ResponseWriter) bool {
// This comparison is naive.
return c.crw != rw
}
// Reset returns a new handler that renews the Capture's probes, and inserts
// them when deferring to next.
func (c *Capture) Reset(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
newRW, newReq := c.renew(rw, req)
next.ServeHTTP(newRW, newReq)
})
}
func (c *Capture) renew(rw http.ResponseWriter, req *http.Request) (http.ResponseWriter, *http.Request) {
ctx := context.WithValue(req.Context(), capturedData, c)
newReq := req.WithContext(ctx)
if newReq.Body != nil {
readCounter := &readCounter{source: newReq.Body}
c.rr = readCounter
newReq.Body = readCounter
}
c.crw = &captureResponseWriter{rw: rw}
return c.crw, newReq
}
func (c *Capture) ResponseSize() int64 {
return c.crw.Size()
}
func (c *Capture) StatusCode() int {
return c.crw.Status()
}
// RequestSize returns the size of the request's body if it applies,
// zero otherwise.
func (c *Capture) RequestSize() int64 {
if c.rr == nil {
return 0
}
return c.rr.size
}
type readCounter struct {
// source ReadCloser from where the request body is read.
source io.ReadCloser
// size is total the number of bytes read.
size int64
}
func (r *readCounter) Read(p []byte) (int, error) {
n, err := r.source.Read(p)
r.size += int64(n)
return n, err
}
func (r *readCounter) Close() error {
return r.source.Close()
}
var _ middlewares.Stateful = &captureResponseWriter{}
// captureResponseWriter is a wrapper of type http.ResponseWriter
// that tracks response status and size.
type captureResponseWriter struct {
rw http.ResponseWriter
status int
size int64
}
func (crw *captureResponseWriter) Header() http.Header {
return crw.rw.Header()
}
func (crw *captureResponseWriter) Size() int64 {
return crw.size
}
func (crw *captureResponseWriter) Status() int {
return crw.status
}
func (crw *captureResponseWriter) Write(b []byte) (int, error) {
if crw.status == 0 {
crw.status = http.StatusOK
}
size, err := crw.rw.Write(b)
crw.size += int64(size)
return size, err
}
func (crw *captureResponseWriter) WriteHeader(s int) {
crw.rw.WriteHeader(s)
crw.status = s
}
func (crw *captureResponseWriter) Flush() {
if f, ok := crw.rw.(http.Flusher); ok {
f.Flush()
}
}
func (crw *captureResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if h, ok := crw.rw.(http.Hijacker); ok {
return h.Hijack()
}
return nil, nil, fmt.Errorf("not a hijacker: %T", crw.rw)
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/capture/capture_test.go | pkg/middlewares/capture/capture_test.go | package capture
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/containous/alice"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCapture(t *testing.T) {
wrapMiddleware := func(next http.Handler) (http.Handler, error) {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
capt, err := FromContext(req.Context())
require.NoError(t, err)
_, err = fmt.Fprintf(rw, "%d,%d,%d,", capt.RequestSize(), capt.ResponseSize(), capt.StatusCode())
require.NoError(t, err)
next.ServeHTTP(rw, req)
_, err = fmt.Fprintf(rw, ",%d,%d,%d", capt.RequestSize(), capt.ResponseSize(), capt.StatusCode())
require.NoError(t, err)
}), nil
}
handler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
_, err := rw.Write([]byte("foo"))
require.NoError(t, err)
all, err := io.ReadAll(req.Body)
require.NoError(t, err)
assert.Equal(t, "bar", string(all))
})
chain := alice.New()
chain = chain.Append(Wrap)
chain = chain.Append(wrapMiddleware)
handlers, err := chain.Then(handler)
require.NoError(t, err)
request, err := http.NewRequest(http.MethodGet, "/", bytes.NewReader([]byte("bar")))
require.NoError(t, err)
recorder := httptest.NewRecorder()
handlers.ServeHTTP(recorder, request)
// 3 = len("bar")
// 9 = len("0,0,0,toto")
assert.Equal(t, "0,0,0,foo,3,9,200", recorder.Body.String())
}
// BenchmarkCapture with response writer and request reader
// $ go test -bench=. ./pkg/middlewares/capture/
// goos: linux
// goarch: amd64
// pkg: github.com/traefik/traefik/v3/pkg/middlewares/capture
// cpu: Intel(R) Core(TM) i7-10750H CPU @ 2.60GHz
// BenchmarkCapture/2k-12 280507 4015 ns/op 510.03 MB/s 5072 B/op 14 allocs/op
// BenchmarkCapture/20k-12 135726 8301 ns/op 2467.26 MB/s 41936 B/op 14 allocs/op
// BenchmarkCapture/100k-12 45494 26059 ns/op 3929.54 MB/s 213968 B/op 14 allocs/op
// BenchmarkCapture/2k_captured-12 263713 4356 ns/op 470.20 MB/s 5552 B/op 18 allocs/op
// BenchmarkCapture/20k_captured-12 132243 8790 ns/op 2329.98 MB/s 42416 B/op 18 allocs/op
// BenchmarkCapture/100k_captured-12 45650 26587 ns/op 3851.57 MB/s 214448 B/op 18 allocs/op
// BenchmarkCapture/2k_body-12 274135 7471 ns/op 274.12 MB/s 5624 B/op 20 allocs/op
// BenchmarkCapture/20k_body-12 130206 21149 ns/op 968.36 MB/s 42488 B/op 20 allocs/op
// BenchmarkCapture/100k_body-12 41600 51716 ns/op 1980.06 MB/s 214520 B/op 20 allocs/op
// PASS
func BenchmarkCapture(b *testing.B) {
testCases := []struct {
name string
size int
capture bool
body bool
}{
{
name: "2k",
size: 2048,
},
{
name: "20k",
size: 20480,
},
{
name: "100k",
size: 102400,
},
{
name: "2k captured",
size: 2048,
capture: true,
},
{
name: "20k captured",
size: 20480,
capture: true,
},
{
name: "100k captured",
size: 102400,
capture: true,
},
{
name: "2k body",
size: 2048,
body: true,
},
{
name: "20k body",
size: 20480,
body: true,
},
{
name: "100k body",
size: 102400,
body: true,
},
}
for _, test := range testCases {
b.Run(test.name, func(b *testing.B) {
baseBody := generateBytes(test.size)
next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
n, err := rw.Write(baseBody)
require.Equal(b, test.size, n)
require.NoError(b, err)
})
var body io.Reader
if test.body {
body = bytes.NewReader(baseBody)
}
req, err := http.NewRequest(http.MethodGet, "http://foo/", body)
require.NoError(b, err)
chain := alice.New()
if test.capture || test.body {
chain = chain.Append(Wrap)
}
handlers, err := chain.Then(next)
require.NoError(b, err)
b.ReportAllocs()
b.SetBytes(int64(test.size))
b.ResetTimer()
for range b.N {
runBenchmark(b, test.size, req, handlers)
}
})
}
}
func runBenchmark(b *testing.B, size int, req *http.Request, handler http.Handler) {
b.Helper()
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
if code := recorder.Code; code != 200 {
b.Fatalf("Expected 200 but got %d", code)
}
assert.Len(b, recorder.Body.String(), size)
}
func generateBytes(length int) []byte {
var value []byte
for i := range length {
value = append(value, 0x61+byte(i%26))
}
return value
}
func TestRequestReader(t *testing.T) {
buff := bytes.NewBufferString("foo")
rr := readCounter{source: io.NopCloser(buff)}
assert.Equal(t, int64(0), rr.size)
n, err := rr.Read([]byte("bar"))
require.NoError(t, err)
assert.Equal(t, 3, n)
err = rr.Close()
require.NoError(t, err)
assert.Equal(t, int64(3), rr.size)
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/addprefix/add_prefix_test.go | pkg/middlewares/addprefix/add_prefix_test.go | package addprefix
import (
"net/http"
"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/testhelpers"
)
func TestNewAddPrefix(t *testing.T) {
testCases := []struct {
desc string
prefix dynamic.AddPrefix
expectsError bool
}{
{
desc: "Works with a non empty prefix",
prefix: dynamic.AddPrefix{Prefix: "/a"},
},
{
desc: "Fails if prefix is empty",
prefix: dynamic.AddPrefix{Prefix: ""},
expectsError: true,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
_, err := New(t.Context(), next, test.prefix, "foo-add-prefix")
if test.expectsError {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
})
}
}
func TestAddPrefix(t *testing.T) {
testCases := []struct {
desc string
prefix dynamic.AddPrefix
path string
expectedPath string
expectedRawPath string
}{
{
desc: "Works with a regular path",
prefix: dynamic.AddPrefix{Prefix: "/a"},
path: "/b",
expectedPath: "/a/b",
},
{
desc: "Works with missing leading slash",
prefix: dynamic.AddPrefix{Prefix: "a"},
path: "/",
expectedPath: "/a/",
},
{
desc: "Works with a raw path",
prefix: dynamic.AddPrefix{Prefix: "/a"},
path: "/b%2Fc",
expectedPath: "/a/b/c",
expectedRawPath: "/a/b%2Fc",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
var actualPath, actualRawPath, requestURI string
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
actualPath = r.URL.Path
actualRawPath = r.URL.RawPath
requestURI = r.RequestURI
})
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost"+test.path, nil)
handler, err := New(t.Context(), next, test.prefix, "foo-add-prefix")
require.NoError(t, err)
handler.ServeHTTP(nil, req)
assert.Equal(t, test.expectedPath, actualPath)
assert.Equal(t, test.expectedRawPath, actualRawPath)
expectedURI := test.expectedPath
if test.expectedRawPath != "" {
// go HTTP uses the raw path when existent in the RequestURI
expectedURI = test.expectedRawPath
}
assert.Equal(t, expectedURI, requestURI)
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/addprefix/add_prefix.go | pkg/middlewares/addprefix/add_prefix.go | package addprefix
import (
"context"
"errors"
"net/http"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
)
const (
typeName = "AddPrefix"
)
// AddPrefix is a middleware used to add prefix to an URL request.
type addPrefix struct {
next http.Handler
prefix string
name string
}
// New creates a new handler.
func New(ctx context.Context, next http.Handler, config dynamic.AddPrefix, name string) (http.Handler, error) {
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
var result *addPrefix
if len(config.Prefix) > 0 {
result = &addPrefix{
prefix: config.Prefix,
next: next,
name: name,
}
} else {
return nil, errors.New("prefix cannot be empty")
}
return result, nil
}
func (a *addPrefix) GetTracingInformation() (string, string) {
return a.name, typeName
}
func (a *addPrefix) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
logger := middlewares.GetLogger(req.Context(), a.name, typeName)
oldURLPath := req.URL.Path
req.URL.Path = ensureLeadingSlash(a.prefix + req.URL.Path)
logger.Debug().Msgf("URL.Path is now %s (was %s).", req.URL.Path, oldURLPath)
if req.URL.RawPath != "" {
oldURLRawPath := req.URL.RawPath
req.URL.RawPath = ensureLeadingSlash(a.prefix + req.URL.RawPath)
logger.Debug().Msgf("URL.RawPath is now %s (was %s).", req.URL.RawPath, oldURLRawPath)
}
req.RequestURI = req.URL.RequestURI()
a.next.ServeHTTP(rw, req)
}
func ensureLeadingSlash(str string) string {
if str == "" {
return str
}
if str[0] == '/' {
return str
}
return "/" + str
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/circuitbreaker/circuit_breaker.go | pkg/middlewares/circuitbreaker/circuit_breaker.go | package circuitbreaker
import (
"context"
"net/http"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/middlewares/observability"
"github.com/traefik/traefik/v3/pkg/observability/logs"
"github.com/vulcand/oxy/v2/cbreaker"
)
const typeName = "CircuitBreaker"
type circuitBreaker struct {
circuitBreaker *cbreaker.CircuitBreaker
name string
}
// New creates a new circuit breaker middleware.
func New(ctx context.Context, next http.Handler, confCircuitBreaker dynamic.CircuitBreaker, name string) (http.Handler, error) {
expression := confCircuitBreaker.Expression
logger := middlewares.GetLogger(ctx, name, typeName)
logger.Debug().Msg("Creating middleware")
logger.Debug().Msgf("Setting up with expression: %s", expression)
responseCode := confCircuitBreaker.ResponseCode
cbOpts := []cbreaker.Option{
cbreaker.Fallback(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
observability.SetStatusErrorf(req.Context(), "blocked by circuit-breaker (%q)", expression)
rw.WriteHeader(responseCode)
if _, err := rw.Write([]byte(http.StatusText(responseCode))); err != nil {
log.Ctx(req.Context()).Error().Err(err).Send()
}
})),
cbreaker.Logger(logs.NewOxyWrapper(*logger)),
cbreaker.Verbose(logger.GetLevel() == zerolog.TraceLevel),
}
if confCircuitBreaker.CheckPeriod > 0 {
cbOpts = append(cbOpts, cbreaker.CheckPeriod(time.Duration(confCircuitBreaker.CheckPeriod)))
}
if confCircuitBreaker.FallbackDuration > 0 {
cbOpts = append(cbOpts, cbreaker.FallbackDuration(time.Duration(confCircuitBreaker.FallbackDuration)))
}
if confCircuitBreaker.RecoveryDuration > 0 {
cbOpts = append(cbOpts, cbreaker.RecoveryDuration(time.Duration(confCircuitBreaker.RecoveryDuration)))
}
oxyCircuitBreaker, err := cbreaker.New(next, expression, cbOpts...)
if err != nil {
return nil, err
}
return &circuitBreaker{
circuitBreaker: oxyCircuitBreaker,
name: name,
}, nil
}
func (c *circuitBreaker) GetTracingInformation() (string, string) {
return c.name, typeName
}
func (c *circuitBreaker) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
c.circuitBreaker.ServeHTTP(rw, req)
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/gatewayapi/urlrewrite/url_rewrite_test.go | pkg/middlewares/gatewayapi/urlrewrite/url_rewrite_test.go | package urlrewrite
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"k8s.io/utils/ptr"
)
func TestURLRewriteHandler(t *testing.T) {
testCases := []struct {
desc string
config dynamic.URLRewrite
url string
wantURL string
wantHost string
}{
{
desc: "replace path",
config: dynamic.URLRewrite{
Path: ptr.To("/baz"),
},
url: "http://foo.com/foo/bar",
wantURL: "http://foo.com/baz",
wantHost: "foo.com",
},
{
desc: "replace path without trailing slash",
config: dynamic.URLRewrite{
Path: ptr.To("/baz"),
},
url: "http://foo.com/foo/bar/",
wantURL: "http://foo.com/baz",
wantHost: "foo.com",
},
{
desc: "replace path with trailing slash",
config: dynamic.URLRewrite{
Path: ptr.To("/baz/"),
},
url: "http://foo.com/foo/bar",
wantURL: "http://foo.com/baz/",
wantHost: "foo.com",
},
{
desc: "only host",
config: dynamic.URLRewrite{
Hostname: ptr.To("bar.com"),
},
url: "http://foo.com/foo/",
wantURL: "http://foo.com/foo/",
wantHost: "bar.com",
},
{
desc: "host and path",
config: dynamic.URLRewrite{
Hostname: ptr.To("bar.com"),
Path: ptr.To("/baz/"),
},
url: "http://foo.com/foo/",
wantURL: "http://foo.com/baz/",
wantHost: "bar.com",
},
{
desc: "replace prefix path",
config: dynamic.URLRewrite{
Path: ptr.To("/baz"),
PathPrefix: ptr.To("/foo"),
},
url: "http://foo.com/foo/bar",
wantURL: "http://foo.com/baz/bar",
wantHost: "foo.com",
},
{
desc: "replace prefix path with trailing slash",
config: dynamic.URLRewrite{
Path: ptr.To("/baz"),
PathPrefix: ptr.To("/foo"),
},
url: "http://foo.com/foo/bar/",
wantURL: "http://foo.com/baz/bar/",
wantHost: "foo.com",
},
{
desc: "replace prefix path without slash prefix",
config: dynamic.URLRewrite{
Path: ptr.To("baz"),
PathPrefix: ptr.To("/foo"),
},
url: "http://foo.com/foo/bar",
wantURL: "http://foo.com/baz/bar",
wantHost: "foo.com",
},
{
desc: "replace prefix path without slash prefix",
config: dynamic.URLRewrite{
Path: ptr.To("/baz"),
PathPrefix: ptr.To("/foo/"),
},
url: "http://foo.com/foo/bar",
wantURL: "http://foo.com/baz/bar",
wantHost: "foo.com",
},
}
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 := NewURLRewrite(t.Context(), next, test.config, "traefikTest")
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, test.url, nil)
handler.ServeHTTP(recorder, req)
assert.Equal(t, test.wantURL, req.URL.String())
assert.Equal(t, test.wantHost, req.Host)
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/gatewayapi/urlrewrite/url_rewrite.go | pkg/middlewares/gatewayapi/urlrewrite/url_rewrite.go | package urlrewrite
import (
"context"
"net/http"
"path"
"strings"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
)
const (
typeName = "URLRewrite"
)
type urlRewrite struct {
name string
next http.Handler
hostname *string
path *string
pathPrefix *string
}
// NewURLRewrite creates a URL rewrite middleware.
func NewURLRewrite(ctx context.Context, next http.Handler, conf dynamic.URLRewrite, name string) http.Handler {
logger := middlewares.GetLogger(ctx, name, typeName)
logger.Debug().Msg("Creating middleware")
return urlRewrite{
name: name,
next: next,
hostname: conf.Hostname,
path: conf.Path,
pathPrefix: conf.PathPrefix,
}
}
func (u urlRewrite) GetTracingInformation() (string, string) {
return u.name, typeName
}
func (u urlRewrite) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
newPath := req.URL.Path
if u.path != nil && u.pathPrefix == nil {
newPath = *u.path
}
if u.path != nil && u.pathPrefix != nil {
newPath = path.Join(*u.path, strings.TrimPrefix(req.URL.Path, *u.pathPrefix))
// add the trailing slash if needed, as path.Join removes trailing slashes.
if strings.HasSuffix(req.URL.Path, "/") && !strings.HasSuffix(newPath, "/") {
newPath += "/"
}
}
req.URL.Path = newPath
req.URL.RawPath = req.URL.EscapedPath()
req.RequestURI = req.URL.RequestURI()
if u.hostname != nil {
req.Host = *u.hostname
}
u.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/gatewayapi/headermodifier/response_header_modifier_test.go | pkg/middlewares/gatewayapi/headermodifier/response_header_modifier_test.go | package headermodifier
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/testhelpers"
)
func TestResponseHeaderModifier(t *testing.T) {
testCases := []struct {
desc string
config dynamic.HeaderModifier
responseHeaders http.Header
expectedHeaders http.Header
}{
{
desc: "no config",
config: dynamic.HeaderModifier{},
expectedHeaders: map[string][]string{},
},
{
desc: "set header",
config: dynamic.HeaderModifier{
Set: map[string]string{"Foo": "Bar"},
},
expectedHeaders: map[string][]string{"Foo": {"Bar"}},
},
{
desc: "set header with existing headers",
config: dynamic.HeaderModifier{
Set: map[string]string{"Foo": "Bar"},
},
responseHeaders: map[string][]string{"Foo": {"Baz"}, "Bar": {"Foo"}},
expectedHeaders: map[string][]string{"Foo": {"Bar"}, "Bar": {"Foo"}},
},
{
desc: "set multiple headers with existing headers",
config: dynamic.HeaderModifier{
Set: map[string]string{"Foo": "Bar", "Bar": "Foo"},
},
responseHeaders: map[string][]string{"Foo": {"Baz"}, "Bar": {"Foobar"}},
expectedHeaders: map[string][]string{"Foo": {"Bar"}, "Bar": {"Foo"}},
},
{
desc: "add header",
config: dynamic.HeaderModifier{
Add: map[string]string{"Foo": "Bar"},
},
expectedHeaders: map[string][]string{"Foo": {"Bar"}},
},
{
desc: "add header with existing headers",
config: dynamic.HeaderModifier{
Add: map[string]string{"Foo": "Bar"},
},
responseHeaders: map[string][]string{"Foo": {"Baz"}, "Bar": {"Foo"}},
expectedHeaders: map[string][]string{"Foo": {"Baz", "Bar"}, "Bar": {"Foo"}},
},
{
desc: "add multiple headers with existing headers",
config: dynamic.HeaderModifier{
Add: map[string]string{"Foo": "Bar", "Bar": "Foo"},
},
responseHeaders: map[string][]string{"Foo": {"Baz"}, "Bar": {"Foobar"}},
expectedHeaders: map[string][]string{"Foo": {"Baz", "Bar"}, "Bar": {"Foobar", "Foo"}},
},
{
desc: "remove header",
config: dynamic.HeaderModifier{
Remove: []string{"Foo"},
},
expectedHeaders: map[string][]string{},
},
{
desc: "remove header with existing headers",
config: dynamic.HeaderModifier{
Remove: []string{"Foo"},
},
responseHeaders: map[string][]string{"Foo": {"Baz"}, "Bar": {"Foo"}},
expectedHeaders: map[string][]string{"Bar": {"Foo"}},
},
{
desc: "remove multiple headers with existing headers",
config: dynamic.HeaderModifier{
Remove: []string{"Foo", "Bar"},
},
responseHeaders: map[string][]string{"Foo": {"Bar"}, "Bar": {"Foo"}, "Baz": {"Bar"}},
expectedHeaders: map[string][]string{"Baz": {"Bar"}},
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
var nextCallCount int
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
nextCallCount++
rw.WriteHeader(http.StatusOK)
})
handler := NewResponseHeaderModifier(t.Context(), next, test.config, "foo-response-header-modifier")
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost", nil)
resp := httptest.NewRecorder()
for k, v := range test.responseHeaders {
resp.Header()[k] = v
}
handler.ServeHTTP(resp, req)
assert.Equal(t, 1, nextCallCount)
assert.Equal(t, test.expectedHeaders, resp.Header())
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/gatewayapi/headermodifier/request_header_modifier.go | pkg/middlewares/gatewayapi/headermodifier/request_header_modifier.go | package headermodifier
import (
"context"
"net/http"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
)
const requestHeaderModifierTypeName = "RequestHeaderModifier"
// requestHeaderModifier is a middleware used to modify the headers of an HTTP request.
type requestHeaderModifier struct {
next http.Handler
name string
set map[string]string
add map[string]string
remove []string
}
// NewRequestHeaderModifier creates a new request header modifier middleware.
func NewRequestHeaderModifier(ctx context.Context, next http.Handler, config dynamic.HeaderModifier, name string) http.Handler {
logger := middlewares.GetLogger(ctx, name, requestHeaderModifierTypeName)
logger.Debug().Msg("Creating middleware")
return &requestHeaderModifier{
next: next,
name: name,
set: config.Set,
add: config.Add,
remove: config.Remove,
}
}
func (r *requestHeaderModifier) GetTracingInformation() (string, string) {
return r.name, requestHeaderModifierTypeName
}
func (r *requestHeaderModifier) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
for headerName, headerValue := range r.set {
req.Header.Set(headerName, headerValue)
}
for headerName, headerValue := range r.add {
req.Header.Add(headerName, headerValue)
}
for _, headerName := range r.remove {
req.Header.Del(headerName)
}
r.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/gatewayapi/headermodifier/response_header_modifier.go | pkg/middlewares/gatewayapi/headermodifier/response_header_modifier.go | package headermodifier
import (
"context"
"net/http"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
)
const responseHeaderModifierTypeName = "ResponseHeaderModifier"
// requestHeaderModifier is a middleware used to modify the headers of an HTTP response.
type responseHeaderModifier struct {
next http.Handler
name string
set map[string]string
add map[string]string
remove []string
}
// NewResponseHeaderModifier creates a new response header modifier middleware.
func NewResponseHeaderModifier(ctx context.Context, next http.Handler, config dynamic.HeaderModifier, name string) http.Handler {
logger := middlewares.GetLogger(ctx, name, responseHeaderModifierTypeName)
logger.Debug().Msg("Creating middleware")
return &responseHeaderModifier{
next: next,
name: name,
set: config.Set,
add: config.Add,
remove: config.Remove,
}
}
func (r *responseHeaderModifier) GetTracingInformation() (string, string) {
return r.name, responseHeaderModifierTypeName
}
func (r *responseHeaderModifier) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
r.next.ServeHTTP(middlewares.NewResponseModifier(rw, req, r.modifyResponseHeaders), req)
}
func (r *responseHeaderModifier) modifyResponseHeaders(res *http.Response) error {
for headerName, headerValue := range r.set {
res.Header.Set(headerName, headerValue)
}
for headerName, headerValue := range r.add {
res.Header.Add(headerName, headerValue)
}
for _, headerName := range r.remove {
res.Header.Del(headerName)
}
return nil
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/gatewayapi/headermodifier/request_header_modifier_test.go | pkg/middlewares/gatewayapi/headermodifier/request_header_modifier_test.go | package headermodifier
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/testhelpers"
)
func TestRequestHeaderModifier(t *testing.T) {
testCases := []struct {
desc string
config dynamic.HeaderModifier
requestHeaders http.Header
expectedHeaders http.Header
}{
{
desc: "no config",
config: dynamic.HeaderModifier{},
expectedHeaders: map[string][]string{},
},
{
desc: "set header",
config: dynamic.HeaderModifier{
Set: map[string]string{"Foo": "Bar"},
},
expectedHeaders: map[string][]string{"Foo": {"Bar"}},
},
{
desc: "set header with existing headers",
config: dynamic.HeaderModifier{
Set: map[string]string{"Foo": "Bar"},
},
requestHeaders: map[string][]string{"Foo": {"Baz"}, "Bar": {"Foo"}},
expectedHeaders: map[string][]string{"Foo": {"Bar"}, "Bar": {"Foo"}},
},
{
desc: "set multiple headers with existing headers",
config: dynamic.HeaderModifier{
Set: map[string]string{"Foo": "Bar", "Bar": "Foo"},
},
requestHeaders: map[string][]string{"Foo": {"Baz"}, "Bar": {"Foobar"}},
expectedHeaders: map[string][]string{"Foo": {"Bar"}, "Bar": {"Foo"}},
},
{
desc: "add header",
config: dynamic.HeaderModifier{
Add: map[string]string{"Foo": "Bar"},
},
expectedHeaders: map[string][]string{"Foo": {"Bar"}},
},
{
desc: "add header with existing headers",
config: dynamic.HeaderModifier{
Add: map[string]string{"Foo": "Bar"},
},
requestHeaders: map[string][]string{"Foo": {"Baz"}, "Bar": {"Foo"}},
expectedHeaders: map[string][]string{"Foo": {"Baz", "Bar"}, "Bar": {"Foo"}},
},
{
desc: "add multiple headers with existing headers",
config: dynamic.HeaderModifier{
Add: map[string]string{"Foo": "Bar", "Bar": "Foo"},
},
requestHeaders: map[string][]string{"Foo": {"Baz"}, "Bar": {"Foobar"}},
expectedHeaders: map[string][]string{"Foo": {"Baz", "Bar"}, "Bar": {"Foobar", "Foo"}},
},
{
desc: "remove header",
config: dynamic.HeaderModifier{
Remove: []string{"Foo"},
},
expectedHeaders: map[string][]string{},
},
{
desc: "remove header with existing headers",
config: dynamic.HeaderModifier{
Remove: []string{"Foo"},
},
requestHeaders: map[string][]string{"Foo": {"Baz"}, "Bar": {"Foo"}},
expectedHeaders: map[string][]string{"Bar": {"Foo"}},
},
{
desc: "remove multiple headers with existing headers",
config: dynamic.HeaderModifier{
Remove: []string{"Foo", "Bar"},
},
requestHeaders: map[string][]string{"Foo": {"Bar"}, "Bar": {"Foo"}, "Baz": {"Bar"}},
expectedHeaders: map[string][]string{"Baz": {"Bar"}},
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
var gotHeaders http.Header
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotHeaders = r.Header
})
handler := NewRequestHeaderModifier(t.Context(), next, test.config, "foo-request-header-modifier")
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost", nil)
for h, v := range test.requestHeaders {
req.Header[h] = v
}
resp := httptest.NewRecorder()
handler.ServeHTTP(resp, req)
assert.Equal(t, test.expectedHeaders, gotHeaders)
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/gatewayapi/redirect/request_redirect_test.go | pkg/middlewares/gatewayapi/redirect/request_redirect_test.go | package redirect
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"
"k8s.io/utils/ptr"
)
func TestRequestRedirectHandler(t *testing.T) {
testCases := []struct {
desc string
config dynamic.RequestRedirect
url string
wantURL string
wantStatus int
wantErr bool
}{
{
desc: "wrong status code",
config: dynamic.RequestRedirect{
Path: ptr.To("/baz"),
StatusCode: http.StatusOK,
},
url: "http://foo.com:80/foo/bar",
wantErr: true,
},
{
desc: "replace path",
config: dynamic.RequestRedirect{
Path: ptr.To("/baz"),
},
url: "http://foo.com:80/foo/bar",
wantURL: "http://foo.com:80/baz",
wantStatus: http.StatusFound,
},
{
desc: "replace path without trailing slash",
config: dynamic.RequestRedirect{
Path: ptr.To("/baz"),
},
url: "http://foo.com:80/foo/bar/",
wantURL: "http://foo.com:80/baz",
wantStatus: http.StatusFound,
},
{
desc: "replace path with trailing slash",
config: dynamic.RequestRedirect{
Path: ptr.To("/baz/"),
},
url: "http://foo.com:80/foo/bar",
wantURL: "http://foo.com:80/baz/",
wantStatus: http.StatusFound,
},
{
desc: "only hostname",
config: dynamic.RequestRedirect{
Hostname: ptr.To("bar.com"),
},
url: "http://foo.com:8080/foo/",
wantURL: "http://bar.com:8080/foo/",
wantStatus: http.StatusFound,
},
{
desc: "replace prefix path",
config: dynamic.RequestRedirect{
Path: ptr.To("/baz"),
PathPrefix: ptr.To("/foo"),
},
url: "http://foo.com:80/foo/bar",
wantURL: "http://foo.com:80/baz/bar",
wantStatus: http.StatusFound,
},
{
desc: "replace prefix path with trailing slash",
config: dynamic.RequestRedirect{
Path: ptr.To("/baz"),
PathPrefix: ptr.To("/foo"),
},
url: "http://foo.com:80/foo/bar/",
wantURL: "http://foo.com:80/baz/bar/",
wantStatus: http.StatusFound,
},
{
desc: "replace prefix path without slash prefix",
config: dynamic.RequestRedirect{
Path: ptr.To("baz"),
PathPrefix: ptr.To("/foo"),
},
url: "http://foo.com:80/foo/bar",
wantURL: "http://foo.com:80/baz/bar",
wantStatus: http.StatusFound,
},
{
desc: "replace prefix path without slash prefix",
config: dynamic.RequestRedirect{
Path: ptr.To("/baz"),
PathPrefix: ptr.To("/foo/"),
},
url: "http://foo.com:80/foo/bar",
wantURL: "http://foo.com:80/baz/bar",
wantStatus: http.StatusFound,
},
{
desc: "simple redirection",
config: dynamic.RequestRedirect{
Scheme: ptr.To("https"),
Hostname: ptr.To("foobar.com"),
Port: ptr.To("443"),
},
url: "http://foo.com:80",
wantURL: "https://foobar.com:443",
wantStatus: http.StatusFound,
},
{
desc: "HTTP to HTTPS permanent",
config: dynamic.RequestRedirect{
Scheme: ptr.To("https"),
StatusCode: http.StatusMovedPermanently,
},
url: "http://foo",
wantURL: "https://foo",
wantStatus: http.StatusMovedPermanently,
},
{
desc: "HTTPS to HTTP permanent",
config: dynamic.RequestRedirect{
Scheme: ptr.To("http"),
StatusCode: http.StatusMovedPermanently,
},
url: "https://foo",
wantURL: "http://foo",
wantStatus: http.StatusMovedPermanently,
},
{
desc: "HTTP to HTTPS",
config: dynamic.RequestRedirect{
Scheme: ptr.To("https"),
Port: ptr.To("443"),
},
url: "http://foo:80",
wantURL: "https://foo:443",
wantStatus: http.StatusFound,
},
{
desc: "HTTP to HTTPS, with X-Forwarded-Proto",
config: dynamic.RequestRedirect{
Scheme: ptr.To("https"),
Port: ptr.To("443"),
},
url: "http://foo:80",
wantURL: "https://foo:443",
wantStatus: http.StatusFound,
},
{
desc: "HTTPS to HTTP",
config: dynamic.RequestRedirect{
Scheme: ptr.To("http"),
Port: ptr.To("80"),
},
url: "https://foo:443",
wantURL: "http://foo:80",
wantStatus: http.StatusFound,
},
{
desc: "HTTP to HTTP",
config: dynamic.RequestRedirect{
Scheme: ptr.To("http"),
Port: ptr.To("88"),
},
url: "http://foo:80",
wantURL: "http://foo:88",
wantStatus: 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 := NewRequestRedirect(t.Context(), next, test.config, "traefikTest")
if test.wantErr {
require.Error(t, err)
require.Nil(t, handler)
return
}
require.NoError(t, err)
require.NotNil(t, handler)
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, test.url, nil)
handler.ServeHTTP(recorder, req)
assert.Equal(t, test.wantStatus, recorder.Code)
switch test.wantStatus {
case http.StatusMovedPermanently, http.StatusFound:
location, err := recorder.Result().Location()
require.NoError(t, err)
assert.Equal(t, test.wantURL, 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/gatewayapi/redirect/request_redirect.go | pkg/middlewares/gatewayapi/redirect/request_redirect.go | package redirect
import (
"context"
"fmt"
"net"
"net/http"
"path"
"strings"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
)
const typeName = "RequestRedirect"
type redirect struct {
name string
next http.Handler
scheme *string
hostname *string
port *string
path *string
pathPrefix *string
statusCode int
}
// NewRequestRedirect creates a redirect middleware.
func NewRequestRedirect(ctx context.Context, next http.Handler, conf dynamic.RequestRedirect, name string) (http.Handler, error) {
logger := middlewares.GetLogger(ctx, name, typeName)
logger.Debug().Msg("Creating middleware")
statusCode := conf.StatusCode
if statusCode == 0 {
statusCode = http.StatusFound
}
if statusCode != http.StatusMovedPermanently && statusCode != http.StatusFound {
return nil, fmt.Errorf("unsupported status code: %d", statusCode)
}
return redirect{
name: name,
next: next,
scheme: conf.Scheme,
hostname: conf.Hostname,
port: conf.Port,
path: conf.Path,
pathPrefix: conf.PathPrefix,
statusCode: statusCode,
}, nil
}
func (r redirect) GetTracingInformation() (string, string) {
return r.name, typeName
}
func (r redirect) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
redirectURL := *req.URL
redirectURL.Host = req.Host
if r.scheme != nil {
redirectURL.Scheme = *r.scheme
}
host := redirectURL.Hostname()
if r.hostname != nil {
host = *r.hostname
}
port := redirectURL.Port()
if r.port != nil {
port = *r.port
}
if port != "" {
host = net.JoinHostPort(host, port)
}
redirectURL.Host = host
if r.path != nil && r.pathPrefix == nil {
redirectURL.Path = *r.path
}
if r.path != nil && r.pathPrefix != nil {
redirectURL.Path = path.Join(*r.path, strings.TrimPrefix(req.URL.Path, *r.pathPrefix))
// add the trailing slash if needed, as path.Join removes trailing slashes.
if strings.HasSuffix(req.URL.Path, "/") && !strings.HasSuffix(redirectURL.Path, "/") {
redirectURL.Path += "/"
}
}
rw.Header().Set("Location", redirectURL.String())
rw.WriteHeader(r.statusCode)
if _, err := rw.Write([]byte(http.StatusText(r.statusCode))); 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/middlewares/headers/secure_test.go | pkg/middlewares/headers/secure_test.go | package headers
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
)
// Middleware tests based on https://github.com/unrolled/secure
func Test_newSecure_modifyResponse(t *testing.T) {
testCases := []struct {
desc string
cfg dynamic.Headers
expected http.Header
}{
{
desc: "PermissionsPolicy",
cfg: dynamic.Headers{
PermissionsPolicy: "microphone=(),",
},
expected: http.Header{"Permissions-Policy": []string{"microphone=(),"}},
},
{
desc: "STSSeconds",
cfg: dynamic.Headers{
STSSeconds: 1,
ForceSTSHeader: true,
},
expected: http.Header{"Strict-Transport-Security": []string{"max-age=1"}},
},
{
desc: "STSSeconds and STSPreload",
cfg: dynamic.Headers{
STSSeconds: 1,
ForceSTSHeader: true,
STSPreload: true,
},
expected: http.Header{"Strict-Transport-Security": []string{"max-age=1; preload"}},
},
{
desc: "CustomFrameOptionsValue",
cfg: dynamic.Headers{
CustomFrameOptionsValue: "foo",
},
expected: http.Header{"X-Frame-Options": []string{"foo"}},
},
{
desc: "FrameDeny",
cfg: dynamic.Headers{
FrameDeny: true,
},
expected: http.Header{"X-Frame-Options": []string{"DENY"}},
},
{
desc: "ContentTypeNosniff",
cfg: dynamic.Headers{
ContentTypeNosniff: true,
},
expected: http.Header{"X-Content-Type-Options": []string{"nosniff"}},
},
}
emptyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
secure := newSecure(emptyHandler, test.cfg, "mymiddleware")
req := httptest.NewRequest(http.MethodGet, "/foo", nil)
rw := httptest.NewRecorder()
secure.ServeHTTP(rw, req)
assert.Equal(t, test.expected, rw.Result().Header)
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/headers/header.go | pkg/middlewares/headers/header.go | package headers
import (
"fmt"
"net/http"
"regexp"
"strconv"
"strings"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/vulcand/oxy/v2/forward"
)
// Header is a middleware that helps setup a few basic security features.
// A single headerOptions struct can be provided to configure which features should be enabled,
// and the ability to override a few of the default values.
type Header struct {
next http.Handler
hasCustomHeaders bool
hasCorsHeaders bool
headers *dynamic.Headers
allowOriginRegexes []*regexp.Regexp
}
// NewHeader constructs a new header instance from supplied frontend header struct.
func NewHeader(next http.Handler, cfg dynamic.Headers) (*Header, error) {
hasCustomHeaders := cfg.HasCustomHeadersDefined()
hasCorsHeaders := cfg.HasCorsHeadersDefined()
regexes := make([]*regexp.Regexp, len(cfg.AccessControlAllowOriginListRegex))
for i, str := range cfg.AccessControlAllowOriginListRegex {
reg, err := regexp.Compile(str)
if err != nil {
return nil, fmt.Errorf("error occurred during origin parsing: %w", err)
}
regexes[i] = reg
}
return &Header{
next: next,
headers: &cfg,
hasCustomHeaders: hasCustomHeaders,
hasCorsHeaders: hasCorsHeaders,
allowOriginRegexes: regexes,
}, nil
}
func (s *Header) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// Handle Cors headers and preflight if configured.
if isPreflight := s.processCorsHeaders(rw, req); isPreflight {
rw.Header().Set("Content-Length", "0")
rw.WriteHeader(http.StatusOK)
return
}
if s.hasCustomHeaders {
s.modifyCustomRequestHeaders(req)
}
// If there is a next, call it.
if s.next != nil {
s.next.ServeHTTP(middlewares.NewResponseModifier(rw, req, s.PostRequestModifyResponseHeaders), req)
}
}
// modifyCustomRequestHeaders sets or deletes custom request headers.
func (s *Header) modifyCustomRequestHeaders(req *http.Request) {
// Loop through Custom request headers
for header, value := range s.headers.CustomRequestHeaders {
switch {
// Handling https://github.com/golang/go/commit/ecdbffd4ec68b509998792f120868fec319de59b.
case value == "" && header == forward.XForwardedFor:
req.Header[header] = nil
case value == "":
req.Header.Del(header)
case strings.EqualFold(header, "Host"):
req.Host = value
default:
req.Header.Set(header, value)
}
}
}
// PostRequestModifyResponseHeaders set or delete response headers.
// This method is called AFTER the response is generated from the backend
// and can merge/override headers from the backend response.
func (s *Header) PostRequestModifyResponseHeaders(res *http.Response) error {
// Loop through Custom response headers
for header, value := range s.headers.CustomResponseHeaders {
if value == "" {
res.Header.Del(header)
} else {
res.Header.Set(header, value)
}
}
if res != nil && res.Request != nil {
originHeader := res.Request.Header.Get("Origin")
allowed, match := s.isOriginAllowed(originHeader)
if allowed {
res.Header.Set("Access-Control-Allow-Origin", match)
}
}
if s.headers.AccessControlAllowCredentials {
res.Header.Set("Access-Control-Allow-Credentials", "true")
}
if len(s.headers.AccessControlExposeHeaders) > 0 {
exposeHeaders := strings.Join(s.headers.AccessControlExposeHeaders, ",")
res.Header.Set("Access-Control-Expose-Headers", exposeHeaders)
}
if !s.headers.AddVaryHeader {
return nil
}
varyHeader := res.Header.Get("Vary")
if varyHeader == "Origin" {
return nil
}
if varyHeader != "" {
varyHeader += ","
}
varyHeader += "Origin"
res.Header.Set("Vary", varyHeader)
return nil
}
// processCorsHeaders processes the incoming request,
// and returns if it is a preflight request.
// If not a preflight, it handles the preRequestModifyCorsResponseHeaders.
func (s *Header) processCorsHeaders(rw http.ResponseWriter, req *http.Request) bool {
if !s.hasCorsHeaders {
return false
}
reqAcMethod := req.Header.Get("Access-Control-Request-Method")
originHeader := req.Header.Get("Origin")
if reqAcMethod != "" && originHeader != "" && req.Method == http.MethodOptions {
// If the request is an OPTIONS request with an Access-Control-Request-Method header,
// and Origin headers, then it is a CORS preflight request,
// and we need to build a custom response: https://www.w3.org/TR/cors/#preflight-request
if s.headers.AccessControlAllowCredentials {
rw.Header().Set("Access-Control-Allow-Credentials", "true")
}
allowHeaders := strings.Join(s.headers.AccessControlAllowHeaders, ",")
if allowHeaders != "" {
rw.Header().Set("Access-Control-Allow-Headers", allowHeaders)
}
allowMethods := strings.Join(s.headers.AccessControlAllowMethods, ",")
if allowMethods != "" {
rw.Header().Set("Access-Control-Allow-Methods", allowMethods)
}
allowed, match := s.isOriginAllowed(originHeader)
if allowed {
rw.Header().Set("Access-Control-Allow-Origin", match)
}
rw.Header().Set("Access-Control-Max-Age", strconv.Itoa(int(s.headers.AccessControlMaxAge)))
return true
}
return false
}
func (s *Header) isOriginAllowed(origin string) (bool, string) {
for _, item := range s.headers.AccessControlAllowOriginList {
if item == "*" || item == origin {
return true, item
}
}
for _, regex := range s.allowOriginRegexes {
if regex.MatchString(origin) {
return true, origin
}
}
return false, ""
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/headers/header_test.go | pkg/middlewares/headers/header_test.go | package headers
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 TestNewHeader_customRequestHeader(t *testing.T) {
testCases := []struct {
desc string
cfg dynamic.Headers
expected http.Header
}{
{
desc: "adds a header",
cfg: dynamic.Headers{
CustomRequestHeaders: map[string]string{
"X-Custom-Request-Header": "test_request",
},
},
expected: http.Header{"Foo": []string{"bar"}, "X-Custom-Request-Header": []string{"test_request"}},
},
{
desc: "delete a header",
cfg: dynamic.Headers{
CustomRequestHeaders: map[string]string{
"X-Forwarded-For": "",
"X-Custom-Request-Header": "",
"Foo": "",
},
},
expected: http.Header{
"X-Forwarded-For": nil,
},
},
{
desc: "override a header",
cfg: dynamic.Headers{
CustomRequestHeaders: map[string]string{
"Foo": "test",
},
},
expected: http.Header{"Foo": []string{"test"}},
},
}
emptyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
mid, err := NewHeader(emptyHandler, test.cfg)
require.NoError(t, err)
req := httptest.NewRequest(http.MethodGet, "/foo", nil)
req.Header.Set("Foo", "bar")
rw := httptest.NewRecorder()
mid.ServeHTTP(rw, req)
assert.Equal(t, http.StatusOK, rw.Code)
assert.Equal(t, test.expected, req.Header)
})
}
}
func TestNewHeader_customRequestHeader_Host(t *testing.T) {
testCases := []struct {
desc string
customHeaders map[string]string
expectedHost string
expectedURLHost string
}{
{
desc: "standard Host header",
customHeaders: map[string]string{},
expectedHost: "example.org",
expectedURLHost: "example.org",
},
{
desc: "custom Host header",
customHeaders: map[string]string{
"Host": "example.com",
},
expectedHost: "example.com",
expectedURLHost: "example.org",
},
}
emptyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
mid, err := NewHeader(emptyHandler, dynamic.Headers{CustomRequestHeaders: test.customHeaders})
require.NoError(t, err)
req := httptest.NewRequest(http.MethodGet, "http://example.org/foo", nil)
rw := httptest.NewRecorder()
mid.ServeHTTP(rw, req)
assert.Equal(t, http.StatusOK, rw.Code)
assert.Equal(t, test.expectedHost, req.Host)
assert.Equal(t, test.expectedURLHost, req.URL.Host)
})
}
}
func TestNewHeader_CORSPreflights(t *testing.T) {
testCases := []struct {
desc string
cfg dynamic.Headers
requestHeaders http.Header
expected http.Header
}{
{
desc: "Test Simple Preflight",
cfg: dynamic.Headers{
AccessControlAllowMethods: []string{"GET", "OPTIONS", "PUT"},
AccessControlAllowOriginList: []string{"https://foo.bar.org"},
AccessControlMaxAge: 600,
},
requestHeaders: map[string][]string{
"Access-Control-Request-Headers": {"origin"},
"Access-Control-Request-Method": {"GET", "OPTIONS"},
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{
"Content-Length": {"0"},
"Access-Control-Allow-Origin": {"https://foo.bar.org"},
"Access-Control-Max-Age": {"600"},
"Access-Control-Allow-Methods": {"GET,OPTIONS,PUT"},
},
},
{
desc: "Wildcard origin Preflight",
cfg: dynamic.Headers{
AccessControlAllowMethods: []string{"GET", "OPTIONS", "PUT"},
AccessControlAllowOriginList: []string{"*"},
AccessControlMaxAge: 600,
},
requestHeaders: map[string][]string{
"Access-Control-Request-Headers": {"origin"},
"Access-Control-Request-Method": {"GET", "OPTIONS"},
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{
"Content-Length": {"0"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Max-Age": {"600"},
"Access-Control-Allow-Methods": {"GET,OPTIONS,PUT"},
},
},
{
desc: "Allow Credentials Preflight",
cfg: dynamic.Headers{
AccessControlAllowMethods: []string{"GET", "OPTIONS", "PUT"},
AccessControlAllowOriginList: []string{"*"},
AccessControlAllowCredentials: true,
AccessControlMaxAge: 600,
},
requestHeaders: map[string][]string{
"Access-Control-Request-Headers": {"origin"},
"Access-Control-Request-Method": {"GET", "OPTIONS"},
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{
"Content-Length": {"0"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Max-Age": {"600"},
"Access-Control-Allow-Methods": {"GET,OPTIONS,PUT"},
"Access-Control-Allow-Credentials": {"true"},
},
},
{
desc: "Allow Headers Preflight",
cfg: dynamic.Headers{
AccessControlAllowMethods: []string{"GET", "OPTIONS", "PUT"},
AccessControlAllowOriginList: []string{"*"},
AccessControlAllowHeaders: []string{"origin", "X-Forwarded-For"},
AccessControlMaxAge: 600,
},
requestHeaders: map[string][]string{
"Access-Control-Request-Headers": {"origin"},
"Access-Control-Request-Method": {"GET", "OPTIONS"},
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{
"Content-Length": {"0"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Max-Age": {"600"},
"Access-Control-Allow-Methods": {"GET,OPTIONS,PUT"},
"Access-Control-Allow-Headers": {"origin,X-Forwarded-For"},
},
},
{
desc: "No Request Headers Preflight",
cfg: dynamic.Headers{
AccessControlAllowMethods: []string{"GET", "OPTIONS", "PUT"},
AccessControlAllowOriginList: []string{"*"},
AccessControlAllowHeaders: []string{"origin", "X-Forwarded-For"},
AccessControlMaxAge: 600,
},
requestHeaders: map[string][]string{
"Access-Control-Request-Method": {"GET", "OPTIONS"},
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{
"Content-Length": {"0"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Max-Age": {"600"},
"Access-Control-Allow-Methods": {"GET,OPTIONS,PUT"},
"Access-Control-Allow-Headers": {"origin,X-Forwarded-For"},
},
},
}
emptyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
mid, err := NewHeader(emptyHandler, test.cfg)
require.NoError(t, err)
req := httptest.NewRequest(http.MethodOptions, "/foo", nil)
req.Header = test.requestHeaders
rw := httptest.NewRecorder()
mid.ServeHTTP(rw, req)
assert.Equal(t, test.expected, rw.Result().Header)
})
}
}
func TestNewHeader_CORSResponses(t *testing.T) {
emptyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
testCases := []struct {
desc string
next http.Handler
cfg dynamic.Headers
requestHeaders http.Header
expected http.Header
expectedError bool
}{
{
desc: "Test Simple Request",
next: emptyHandler,
cfg: dynamic.Headers{
AccessControlAllowOriginList: []string{"https://foo.bar.org"},
},
requestHeaders: map[string][]string{
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{
"Access-Control-Allow-Origin": {"https://foo.bar.org"},
},
},
{
desc: "Wildcard origin Request",
next: emptyHandler,
cfg: dynamic.Headers{
AccessControlAllowOriginList: []string{"*"},
},
requestHeaders: map[string][]string{
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{
"Access-Control-Allow-Origin": {"*"},
},
},
{
desc: "Regexp Origin Request",
next: emptyHandler,
cfg: dynamic.Headers{
AccessControlAllowOriginListRegex: []string{"^https?://([a-z]+)\\.bar\\.org$"},
},
requestHeaders: map[string][]string{
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{
"Access-Control-Allow-Origin": {"https://foo.bar.org"},
},
},
{
desc: "Partial Regexp Origin Request",
next: emptyHandler,
cfg: dynamic.Headers{
AccessControlAllowOriginListRegex: []string{"([a-z]+)\\.bar"},
},
requestHeaders: map[string][]string{
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{
"Access-Control-Allow-Origin": {"https://foo.bar.org"},
},
},
{
desc: "Regexp Malformed Origin Request",
next: emptyHandler,
cfg: dynamic.Headers{
AccessControlAllowOriginListRegex: []string{"a(b"},
},
requestHeaders: map[string][]string{
"Origin": {"https://foo.bar.org"},
},
expectedError: true,
},
{
desc: "Regexp Origin Request without matching",
next: emptyHandler,
cfg: dynamic.Headers{
AccessControlAllowOriginListRegex: []string{"([a-z]+)\\.bar\\.org"},
},
requestHeaders: map[string][]string{
"Origin": {"https://bar.org"},
},
expected: map[string][]string{},
},
{
desc: "Empty origin Request",
next: emptyHandler,
cfg: dynamic.Headers{
AccessControlAllowOriginList: []string{"https://foo.bar.org"},
},
requestHeaders: map[string][]string{},
expected: map[string][]string{},
},
{
desc: "Not Defined origin Request",
next: emptyHandler,
requestHeaders: map[string][]string{},
expected: map[string][]string{},
},
{
desc: "Allow Credentials Request",
next: emptyHandler,
cfg: dynamic.Headers{
AccessControlAllowOriginList: []string{"*"},
AccessControlAllowCredentials: true,
},
requestHeaders: map[string][]string{
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Allow-Credentials": {"true"},
},
},
{
desc: "Expose Headers Request",
next: emptyHandler,
cfg: dynamic.Headers{
AccessControlAllowOriginList: []string{"*"},
AccessControlExposeHeaders: []string{"origin", "X-Forwarded-For"},
},
requestHeaders: map[string][]string{
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Expose-Headers": {"origin,X-Forwarded-For"},
},
},
{
desc: "Test Simple Request with Vary Headers",
next: emptyHandler,
cfg: dynamic.Headers{
AccessControlAllowOriginList: []string{"https://foo.bar.org"},
AddVaryHeader: true,
},
requestHeaders: map[string][]string{
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{
"Access-Control-Allow-Origin": {"https://foo.bar.org"},
"Vary": {"Origin"},
},
},
{
desc: "Test Simple Request with Vary Headers and non-empty response",
next: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// nonEmptyHandler
w.Header().Set("Vary", "Testing")
w.WriteHeader(http.StatusOK)
}),
cfg: dynamic.Headers{
AccessControlAllowOriginList: []string{"https://foo.bar.org"},
AddVaryHeader: true,
},
requestHeaders: map[string][]string{
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{
"Access-Control-Allow-Origin": {"https://foo.bar.org"},
"Vary": {"Testing,Origin"},
},
},
{
desc: "Test Simple Request with Vary Headers and existing vary:origin response",
next: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// existingOriginHandler
w.Header().Set("Vary", "Origin")
w.WriteHeader(http.StatusOK)
}),
cfg: dynamic.Headers{
AccessControlAllowOriginList: []string{"https://foo.bar.org"},
AddVaryHeader: true,
},
requestHeaders: map[string][]string{
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{
"Access-Control-Allow-Origin": {"https://foo.bar.org"},
"Vary": {"Origin"},
},
},
{
desc: "Test Simple Request with non-empty response: set ACAO",
next: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// existingAccessControlAllowOriginHandlerSet
w.Header().Set("Access-Control-Allow-Origin", "http://foo.bar.org")
w.WriteHeader(http.StatusOK)
}),
cfg: dynamic.Headers{
AccessControlAllowOriginList: []string{"*"},
},
requestHeaders: map[string][]string{
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{
"Access-Control-Allow-Origin": {"*"},
},
},
{
desc: "Test Simple Request with non-empty response: add ACAO",
next: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// existingAccessControlAllowOriginHandlerAdd
w.Header().Add("Access-Control-Allow-Origin", "http://foo.bar.org")
w.WriteHeader(http.StatusOK)
}),
cfg: dynamic.Headers{
AccessControlAllowOriginList: []string{"*"},
},
requestHeaders: map[string][]string{
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{
"Access-Control-Allow-Origin": {"*"},
},
},
{
desc: "Test Simple CustomRequestHeaders Not Hijacked by CORS",
next: emptyHandler,
cfg: dynamic.Headers{
CustomRequestHeaders: map[string]string{"foo": "bar"},
},
requestHeaders: map[string][]string{
"Access-Control-Request-Headers": {"origin"},
"Access-Control-Request-Method": {"GET", "OPTIONS"},
"Origin": {"https://foo.bar.org"},
},
expected: map[string][]string{},
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
mid, err := NewHeader(test.next, test.cfg)
if test.expectedError {
require.Error(t, err)
return
}
require.NoError(t, err)
req := httptest.NewRequest(http.MethodGet, "/foo", nil)
req.Header = test.requestHeaders
rw := httptest.NewRecorder()
mid.ServeHTTP(rw, req)
assert.Equal(t, test.expected, rw.Result().Header)
})
}
}
func TestNewHeader_customResponseHeaders(t *testing.T) {
testCases := []struct {
desc string
config map[string]string
expected http.Header
}{
{
desc: "Test Simple Response",
config: map[string]string{
"Testing": "foo",
"Testing2": "bar",
},
expected: map[string][]string{
"Foo": {"bar"},
"Testing": {"foo"},
"Testing2": {"bar"},
},
},
{
desc: "empty Custom Header",
config: map[string]string{
"Testing": "foo",
"Testing2": "",
},
expected: map[string][]string{
"Foo": {"bar"},
"Testing": {"foo"},
},
},
{
desc: "Deleting Custom Header",
config: map[string]string{
"Testing": "foo",
"Foo": "",
},
expected: map[string][]string{
"Testing": {"foo"},
},
},
}
emptyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Foo", "bar")
w.WriteHeader(http.StatusOK)
})
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
mid, err := NewHeader(emptyHandler, dynamic.Headers{CustomResponseHeaders: test.config})
require.NoError(t, err)
req := httptest.NewRequest(http.MethodGet, "/foo", nil)
rw := httptest.NewRecorder()
mid.ServeHTTP(rw, req)
assert.Equal(t, test.expected, rw.Result().Header)
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/headers/headers_test.go | pkg/middlewares/headers/headers_test.go | package headers
// Middleware tests based on https://github.com/unrolled/secure
import (
"io"
"net/http"
"net/http/httptest"
"net/http/httptrace"
"net/textproto"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
)
func TestNew_withoutOptions(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
mid, err := New(t.Context(), next, dynamic.Headers{}, "testing")
require.Errorf(t, err, "headers configuration not valid")
assert.Nil(t, mid)
}
func TestNew_allowedHosts(t *testing.T) {
testCases := []struct {
desc string
fromHost string
expected int
}{
{
desc: "Should accept the request when given a host that is in the list",
fromHost: "foo.com",
expected: http.StatusOK,
},
{
desc: "Should refuse the request when no host is given",
fromHost: "",
expected: http.StatusInternalServerError,
},
{
desc: "Should refuse the request when no matching host is given",
fromHost: "boo.com",
expected: http.StatusInternalServerError,
},
}
emptyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
cfg := dynamic.Headers{
AllowedHosts: []string{"foo.com", "bar.com"},
}
mid, err := New(t.Context(), emptyHandler, cfg, "foo")
require.NoError(t, err)
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
req := httptest.NewRequest(http.MethodGet, "/foo", nil)
req.Host = test.fromHost
rw := httptest.NewRecorder()
mid.ServeHTTP(rw, req)
assert.Equal(t, test.expected, rw.Code)
})
}
}
func TestNew_customHeaders(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
cfg := dynamic.Headers{
CustomRequestHeaders: map[string]string{
"X-Custom-Request-Header": "test_request",
},
CustomResponseHeaders: map[string]string{
"X-Custom-Response-Header": "test_response",
},
}
mid, err := New(t.Context(), next, cfg, "testing")
require.NoError(t, err)
req := httptest.NewRequest(http.MethodGet, "/foo", nil)
rw := httptest.NewRecorder()
mid.ServeHTTP(rw, req)
assert.Equal(t, http.StatusOK, rw.Code)
assert.Equal(t, "test_request", req.Header.Get("X-Custom-Request-Header"))
assert.Equal(t, "test_response", rw.Header().Get("X-Custom-Response-Header"))
}
func Test_headers_getTracingInformation(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
mid := &headers{
handler: next,
name: "testing",
}
name, typeName := mid.GetTracingInformation()
assert.Equal(t, "testing", name)
assert.Equal(t, "Headers", typeName)
}
// This test is an adapted version of net/http/httputil.Test1xxResponses test.
func Test1xxResponses(t *testing.T) {
next := 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"))
})
cfg := dynamic.Headers{
CustomResponseHeaders: map[string]string{
"X-Custom-Response-Header": "test_response",
},
}
mid, err := New(t.Context(), next, cfg, "testing")
require.NoError(t, err)
server := httptest.NewServer(mid)
t.Cleanup(server.Close)
frontendClient := server.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, server.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)
}
assert.Equal(t, "test_response", res.Header.Get("X-Custom-Response-Header"))
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/headers/secure.go | pkg/middlewares/headers/secure.go | package headers
import (
"net/http"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/unrolled/secure"
)
type secureHeader struct {
next http.Handler
secure *secure.Secure
cfg dynamic.Headers
}
// newSecure constructs a new secure instance with supplied options.
func newSecure(next http.Handler, cfg dynamic.Headers, contextKey string) *secureHeader {
opt := secure.Options{
BrowserXssFilter: cfg.BrowserXSSFilter,
ContentTypeNosniff: cfg.ContentTypeNosniff,
ForceSTSHeader: cfg.ForceSTSHeader,
FrameDeny: cfg.FrameDeny,
IsDevelopment: cfg.IsDevelopment,
STSIncludeSubdomains: cfg.STSIncludeSubdomains,
STSPreload: cfg.STSPreload,
ContentSecurityPolicy: cfg.ContentSecurityPolicy,
ContentSecurityPolicyReportOnly: cfg.ContentSecurityPolicyReportOnly,
CustomBrowserXssValue: cfg.CustomBrowserXSSValue,
CustomFrameOptionsValue: cfg.CustomFrameOptionsValue,
PublicKey: cfg.PublicKey,
ReferrerPolicy: cfg.ReferrerPolicy,
AllowedHosts: cfg.AllowedHosts,
HostsProxyHeaders: cfg.HostsProxyHeaders,
SSLProxyHeaders: cfg.SSLProxyHeaders,
STSSeconds: cfg.STSSeconds,
PermissionsPolicy: cfg.PermissionsPolicy,
SecureContextKey: contextKey,
}
return &secureHeader{
next: next,
secure: secure.New(opt),
cfg: cfg,
}
}
func (s secureHeader) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
s.secure.HandlerFuncWithNextForRequestOnly(rw, req, func(writer http.ResponseWriter, request *http.Request) {
s.next.ServeHTTP(middlewares.NewResponseModifier(writer, request, s.secure.ModifyResponseHeaders), request)
})
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/headers/headers.go | pkg/middlewares/headers/headers.go | // Package headers Middleware based on https://github.com/unrolled/secure.
package headers
import (
"context"
"errors"
"net/http"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
)
const (
typeName = "Headers"
)
type headers struct {
name string
handler http.Handler
}
// New creates a Headers middleware.
func New(ctx context.Context, next http.Handler, cfg dynamic.Headers, name string) (http.Handler, error) {
// HeaderMiddleware -> SecureMiddleWare -> next
logger := middlewares.GetLogger(ctx, name, typeName)
logger.Debug().Msg("Creating middleware")
hasSecureHeaders := cfg.HasSecureHeadersDefined()
hasCustomHeaders := cfg.HasCustomHeadersDefined()
hasCorsHeaders := cfg.HasCorsHeadersDefined()
if !hasSecureHeaders && !hasCustomHeaders && !hasCorsHeaders {
return nil, errors.New("headers configuration not valid")
}
var handler http.Handler
nextHandler := next
if hasSecureHeaders {
logger.Debug().Msgf("Setting up secureHeaders from %v", cfg)
handler = newSecure(next, cfg, name)
nextHandler = handler
}
if hasCustomHeaders || hasCorsHeaders {
logger.Debug().Msgf("Setting up customHeaders/Cors from %v", cfg)
var err error
handler, err = NewHeader(nextHandler, cfg)
if err != nil {
return nil, err
}
}
return &headers{
handler: handler,
name: name,
}, nil
}
func (h *headers) GetTracingInformation() (string, string) {
return h.name, typeName
}
func (h *headers) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
h.handler.ServeHTTP(rw, req)
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/recovery/recovery.go | pkg/middlewares/recovery/recovery.go | package recovery
import (
"bufio"
"context"
"fmt"
"net"
"net/http"
"runtime"
"github.com/traefik/traefik/v3/pkg/middlewares"
)
const (
typeName = "Recovery"
middlewareName = "traefik-internal-recovery"
)
type recovery struct {
next http.Handler
}
// New creates recovery middleware.
func New(ctx context.Context, next http.Handler) (http.Handler, error) {
middlewares.GetLogger(ctx, middlewareName, typeName).Debug().Msg("Creating middleware")
return &recovery{
next: next,
}, nil
}
func (re *recovery) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
recoveryRW := newRecoveryResponseWriter(rw)
defer recoverFunc(recoveryRW, req)
re.next.ServeHTTP(recoveryRW, req)
}
func recoverFunc(rw recoveryResponseWriter, req *http.Request) {
if err := recover(); err != nil {
defer rw.finalizeResponse()
logger := middlewares.GetLogger(req.Context(), middlewareName, typeName)
if !shouldLogPanic(err) {
logger.Debug().Msgf("Request has been aborted [%s - %s]: %v", req.RemoteAddr, req.URL, err)
return
}
logger.Error().Msgf("Recovered from panic in HTTP handler [%s - %s]: %+v", req.RemoteAddr, req.URL, err)
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
logger.Error().Msgf("Stack: %s", buf)
}
}
// https://github.com/golang/go/blob/a0d6420d8be2ae7164797051ec74fa2a2df466a1/src/net/http/server.go#L1761-L1775
// https://github.com/golang/go/blob/c33153f7b416c03983324b3e8f869ce1116d84bc/src/net/http/httputil/reverseproxy.go#L284
func shouldLogPanic(panicValue interface{}) bool {
//nolint:errorlint // false-positive because panicValue is an interface.
return panicValue != nil && panicValue != http.ErrAbortHandler
}
type recoveryResponseWriter interface {
http.ResponseWriter
finalizeResponse()
}
func newRecoveryResponseWriter(rw http.ResponseWriter) recoveryResponseWriter {
wrapper := &responseWriterWrapper{rw: rw}
if _, ok := rw.(http.CloseNotifier); !ok {
return wrapper
}
return &responseWriterWrapperWithCloseNotify{wrapper}
}
type responseWriterWrapper struct {
rw http.ResponseWriter
headersSent bool
}
func (r *responseWriterWrapper) Header() http.Header {
return r.rw.Header()
}
func (r *responseWriterWrapper) Write(bytes []byte) (int, error) {
r.headersSent = true
return r.rw.Write(bytes)
}
func (r *responseWriterWrapper) WriteHeader(code int) {
if r.headersSent {
return
}
// Handling informational headers.
if code >= 100 && code <= 199 {
r.rw.WriteHeader(code)
return
}
r.headersSent = true
r.rw.WriteHeader(code)
}
func (r *responseWriterWrapper) Flush() {
if f, ok := r.rw.(http.Flusher); ok {
f.Flush()
}
}
func (r *responseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if h, ok := r.rw.(http.Hijacker); ok {
return h.Hijack()
}
return nil, nil, fmt.Errorf("not a hijacker: %T", r.rw)
}
func (r *responseWriterWrapper) finalizeResponse() {
// If headers have been sent this is not possible to respond with an HTTP error,
// and we let the server abort the response silently thanks to the http.ErrAbortHandler sentinel panic value.
if r.headersSent {
panic(http.ErrAbortHandler)
}
// The response has not yet started to be written,
// we can safely return a fresh new error response.
http.Error(r.rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
type responseWriterWrapperWithCloseNotify struct {
*responseWriterWrapper
}
func (r *responseWriterWrapperWithCloseNotify) CloseNotify() <-chan bool {
return r.rw.(http.CloseNotifier).CloseNotify()
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/recovery/recovery_test.go | pkg/middlewares/recovery/recovery_test.go | package recovery
import (
"errors"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRecoverHandler(t *testing.T) {
tests := []struct {
desc string
panicErr error
headersSent bool
}{
{
desc: "headers sent and custom panic error",
panicErr: errors.New("foo"),
headersSent: true,
},
{
desc: "headers sent and error abort handler",
panicErr: http.ErrAbortHandler,
headersSent: true,
},
{
desc: "custom panic error",
panicErr: errors.New("foo"),
},
{
desc: "error abort handler",
panicErr: http.ErrAbortHandler,
},
}
for _, test := range tests {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
fn := func(rw http.ResponseWriter, req *http.Request) {
if test.headersSent {
rw.WriteHeader(http.StatusTeapot)
}
panic(test.panicErr)
}
recovery, err := New(t.Context(), http.HandlerFunc(fn))
require.NoError(t, err)
server := httptest.NewServer(recovery)
t.Cleanup(server.Close)
res, err := http.Get(server.URL)
if test.headersSent {
require.Nil(t, res)
assert.ErrorIs(t, err, io.EOF)
} else {
require.NoError(t, err)
assert.Equal(t, http.StatusInternalServerError, res.StatusCode)
}
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/snicheck/snicheck_test.go | pkg/middlewares/snicheck/snicheck_test.go | package snicheck
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestSNICheck_ServeHTTP(t *testing.T) {
testCases := []struct {
desc string
tlsOptionsForHost map[string]string
host string
expected int
}{
{
desc: "no TLS options",
expected: http.StatusOK,
},
{
desc: "with TLS options",
tlsOptionsForHost: map[string]string{
"example.com": "foo",
},
expected: http.StatusOK,
},
{
desc: "server name and host doesn't have the same TLS configuration",
tlsOptionsForHost: map[string]string{
"example.com": "foo",
},
host: "example.com",
expected: http.StatusMisdirectedRequest,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {})
sniCheck := New(test.tlsOptionsForHost, next)
req := httptest.NewRequest(http.MethodGet, "https://localhost", nil)
if test.host != "" {
req.Host = test.host
}
recorder := httptest.NewRecorder()
sniCheck.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/snicheck/snicheck.go | pkg/middlewares/snicheck/snicheck.go | package snicheck
import (
"net"
"net/http"
"strings"
"github.com/rs/zerolog/log"
"github.com/traefik/traefik/v3/pkg/middlewares/requestdecorator"
traefiktls "github.com/traefik/traefik/v3/pkg/tls"
)
// SNICheck is an HTTP handler that checks whether the TLS configuration for the server name is the same as for the host header.
type SNICheck struct {
next http.Handler
tlsOptionsForHost map[string]string
}
// New creates a new SNICheck.
func New(tlsOptionsForHost map[string]string, next http.Handler) *SNICheck {
return &SNICheck{next: next, tlsOptionsForHost: tlsOptionsForHost}
}
func (s SNICheck) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if req.TLS == nil {
s.next.ServeHTTP(rw, req)
return
}
host := getHost(req)
serverName := strings.TrimSpace(req.TLS.ServerName)
// Domain Fronting
if !strings.EqualFold(host, serverName) {
tlsOptionHeader := findTLSOptionName(s.tlsOptionsForHost, host, true)
tlsOptionSNI := findTLSOptionName(s.tlsOptionsForHost, serverName, false)
if tlsOptionHeader != tlsOptionSNI {
log.Debug().
Str("host", host).
Str("req.Host", req.Host).
Str("req.TLS.ServerName", req.TLS.ServerName).
Msgf("TLS options difference: SNI:%s, Header:%s", tlsOptionSNI, tlsOptionHeader)
http.Error(rw, http.StatusText(http.StatusMisdirectedRequest), http.StatusMisdirectedRequest)
return
}
}
s.next.ServeHTTP(rw, req)
}
func getHost(req *http.Request) string {
h := requestdecorator.GetCNAMEFlatten(req.Context())
if h != "" {
return h
}
h = requestdecorator.GetCanonizedHost(req.Context())
if h != "" {
return h
}
host, _, err := net.SplitHostPort(req.Host)
if err != nil {
host = req.Host
}
return strings.TrimSpace(host)
}
func findTLSOptionName(tlsOptionsForHost map[string]string, host string, fqdn bool) string {
name := findTLSOptName(tlsOptionsForHost, host, fqdn)
if name != "" {
return name
}
name = findTLSOptName(tlsOptionsForHost, strings.ToLower(host), fqdn)
if name != "" {
return name
}
return traefiktls.DefaultTLSConfigName
}
func findTLSOptName(tlsOptionsForHost map[string]string, host string, fqdn bool) string {
if tlsOptions, ok := tlsOptionsForHost[host]; ok {
return tlsOptions
}
if !fqdn {
return ""
}
if last := len(host) - 1; last >= 0 && host[last] == '.' {
if tlsOptions, ok := tlsOptionsForHost[host[:last]]; ok {
return tlsOptions
}
return ""
}
if tlsOptions, ok := tlsOptionsForHost[host+"."]; ok {
return tlsOptions
}
return ""
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/buffering/buffering_test.go | pkg/middlewares/buffering/buffering_test.go | package buffering
import (
"bytes"
"crypto/rand"
"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"
)
func TestBuffering(t *testing.T) {
payload := make([]byte, math.MaxInt8)
_, _ = rand.Read(payload)
testCases := []struct {
desc string
config dynamic.Buffering
body []byte
expectedCode int
}{
{
desc: "Unlimited response and request body size",
body: payload,
expectedCode: http.StatusOK,
},
{
desc: "Limited request body size",
config: dynamic.Buffering{
MaxRequestBodyBytes: 1,
},
body: payload,
expectedCode: http.StatusRequestEntityTooLarge,
},
{
desc: "Limited response body size",
config: dynamic.Buffering{
MaxResponseBodyBytes: 1,
},
body: payload,
expectedCode: http.StatusInternalServerError,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusOK)
_, err := rw.Write(test.body)
require.NoError(t, err)
})
buffMiddleware, err := New(t.Context(), next, test.config, "foo")
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPost, "http://localhost", bytes.NewBuffer(test.body))
recorder := httptest.NewRecorder()
buffMiddleware.ServeHTTP(recorder, req)
assert.Equal(t, test.expectedCode, recorder.Code)
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/buffering/buffering.go | pkg/middlewares/buffering/buffering.go | package buffering
import (
"context"
"net/http"
"github.com/rs/zerolog"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/observability/logs"
oxybuffer "github.com/vulcand/oxy/v2/buffer"
)
const (
typeName = "Buffer"
)
type buffer struct {
name string
buffer *oxybuffer.Buffer
}
// New creates a buffering middleware.
func New(ctx context.Context, next http.Handler, config dynamic.Buffering, name string) (http.Handler, error) {
logger := middlewares.GetLogger(ctx, name, typeName)
logger.Debug().Msg("Creating middleware")
logger.Debug().Msgf("Setting up buffering: request limits: %d (mem), %d (max), response limits: %d (mem), %d (max) with retry: '%s'",
config.MemRequestBodyBytes, config.MaxRequestBodyBytes, config.MemResponseBodyBytes, config.MaxResponseBodyBytes, config.RetryExpression)
oxyBuffer, err := oxybuffer.New(
next,
oxybuffer.MemRequestBodyBytes(config.MemRequestBodyBytes),
oxybuffer.MaxRequestBodyBytes(config.MaxRequestBodyBytes),
oxybuffer.MemResponseBodyBytes(config.MemResponseBodyBytes),
oxybuffer.MaxResponseBodyBytes(config.MaxResponseBodyBytes),
oxybuffer.Logger(logs.NewOxyWrapper(*logger)),
oxybuffer.Verbose(logger.GetLevel() == zerolog.TraceLevel),
oxybuffer.Cond(len(config.RetryExpression) > 0, oxybuffer.Retry(config.RetryExpression)),
)
if err != nil {
return nil, err
}
return &buffer{
name: name,
buffer: oxyBuffer,
}, nil
}
func (b *buffer) GetTracingInformation() (string, string) {
return b.name, typeName
}
func (b *buffer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
b.buffer.ServeHTTP(rw, req)
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/customerrors/custom_errors_test.go | pkg/middlewares/customerrors/custom_errors_test.go | package customerrors
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/http/httptrace"
"net/textproto"
"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/testhelpers"
)
func TestHandler(t *testing.T) {
testCases := []struct {
desc string
errorPage *dynamic.ErrorPage
backendCode int
backendErrorHandler http.HandlerFunc
validate func(t *testing.T, recorder *httptest.ResponseRecorder)
}{
{
desc: "no error",
errorPage: &dynamic.ErrorPage{Service: "error", Query: "/test", Status: []string{"500-501", "503-599"}},
backendCode: http.StatusOK,
backendErrorHandler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintln(w, "My error page.")
}),
validate: func(t *testing.T, recorder *httptest.ResponseRecorder) {
t.Helper()
assert.Equal(t, http.StatusOK, recorder.Code, "HTTP status")
assert.Contains(t, recorder.Body.String(), http.StatusText(http.StatusOK))
},
},
{
desc: "no error, but not a 200",
errorPage: &dynamic.ErrorPage{Service: "error", Query: "/test", Status: []string{"500-501", "503-599"}},
backendCode: http.StatusPartialContent,
backendErrorHandler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintln(w, "My error page.")
}),
validate: func(t *testing.T, recorder *httptest.ResponseRecorder) {
t.Helper()
assert.Equal(t, http.StatusPartialContent, recorder.Code, "HTTP status")
assert.Contains(t, recorder.Body.String(), http.StatusText(http.StatusPartialContent))
},
},
{
desc: "a 304, so no Write called",
errorPage: &dynamic.ErrorPage{Service: "error", Query: "/test", Status: []string{"500-501", "503-599"}},
backendCode: http.StatusNotModified,
backendErrorHandler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintln(w, "whatever, should not be called")
}),
validate: func(t *testing.T, recorder *httptest.ResponseRecorder) {
t.Helper()
assert.Equal(t, http.StatusNotModified, recorder.Code, "HTTP status")
assert.Contains(t, recorder.Body.String(), "")
},
},
{
desc: "in the range",
errorPage: &dynamic.ErrorPage{Service: "error", Query: "/test", Status: []string{"500-501", "503-599"}},
backendCode: http.StatusInternalServerError,
backendErrorHandler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintln(w, "My error page.")
}),
validate: func(t *testing.T, recorder *httptest.ResponseRecorder) {
t.Helper()
assert.Equal(t, http.StatusInternalServerError, recorder.Code, "HTTP status")
assert.Contains(t, recorder.Body.String(), "My error page.")
},
},
{
desc: "not in the range",
errorPage: &dynamic.ErrorPage{Service: "error", Query: "/test", Status: []string{"500-501", "503-599"}},
backendCode: http.StatusBadGateway,
backendErrorHandler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintln(w, "My error page.")
}),
validate: func(t *testing.T, recorder *httptest.ResponseRecorder) {
t.Helper()
assert.Equal(t, http.StatusBadGateway, recorder.Code, "HTTP status")
assert.Contains(t, recorder.Body.String(), http.StatusText(http.StatusBadGateway))
},
},
{
desc: "query replacement",
errorPage: &dynamic.ErrorPage{Service: "error", Query: "/{status}", Status: []string{"503-503"}},
backendCode: http.StatusServiceUnavailable,
backendErrorHandler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.RequestURI != "/503" {
return
}
_, _ = fmt.Fprintln(w, "My 503 page.")
}),
validate: func(t *testing.T, recorder *httptest.ResponseRecorder) {
t.Helper()
assert.Equal(t, http.StatusServiceUnavailable, recorder.Code, "HTTP status")
assert.Contains(t, recorder.Body.String(), "My 503 page.")
},
},
{
desc: "single code and query replacement",
errorPage: &dynamic.ErrorPage{Service: "error", Query: "/{status}", Status: []string{"503"}},
backendCode: http.StatusServiceUnavailable,
backendErrorHandler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.RequestURI != "/503" {
return
}
_, _ = fmt.Fprintln(w, "My 503 page.")
}),
validate: func(t *testing.T, recorder *httptest.ResponseRecorder) {
t.Helper()
assert.Equal(t, http.StatusServiceUnavailable, recorder.Code, "HTTP status")
assert.Contains(t, recorder.Body.String(), "My 503 page.")
},
},
{
desc: "forward request host header",
errorPage: &dynamic.ErrorPage{Service: "error", Query: "/test", Status: []string{"503"}},
backendCode: http.StatusServiceUnavailable,
backendErrorHandler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintln(w, r.Host)
}),
validate: func(t *testing.T, recorder *httptest.ResponseRecorder) {
t.Helper()
assert.Equal(t, http.StatusServiceUnavailable, recorder.Code, "HTTP status")
assert.Contains(t, recorder.Body.String(), "localhost")
},
},
{
desc: "full query replacement",
errorPage: &dynamic.ErrorPage{Service: "error", Query: "/?status={status}&url={url}", Status: []string{"503"}},
backendCode: http.StatusServiceUnavailable,
backendErrorHandler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.RequestURI != "/?status=503&url=http%3A%2F%2Flocalhost%2Ftest%3Ffoo%3Dbar%26baz%3Dbuz" {
t.Log(r.RequestURI)
return
}
_, _ = fmt.Fprintln(w, "My 503 page.")
}),
validate: func(t *testing.T, recorder *httptest.ResponseRecorder) {
t.Helper()
assert.Equal(t, http.StatusServiceUnavailable, recorder.Code, "HTTP status")
assert.Contains(t, recorder.Body.String(), "My 503 page.")
},
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
serviceBuilderMock := &mockServiceBuilder{handler: test.backendErrorHandler}
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(test.backendCode)
if test.backendCode == http.StatusNotModified {
return
}
_, _ = fmt.Fprintln(w, http.StatusText(test.backendCode))
})
errorPageHandler, err := New(t.Context(), handler, *test.errorPage, serviceBuilderMock, "test")
require.NoError(t, err)
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost/test?foo=bar&baz=buz", nil)
// Client like browser and curl will issue a relative HTTP request, which not have a host and scheme in the URL. But the http.NewRequest will set them automatically.
req.URL.Host = ""
req.URL.Scheme = ""
recorder := httptest.NewRecorder()
errorPageHandler.ServeHTTP(recorder, req)
test.validate(t, recorder)
})
}
}
// This test is an adapted version of net/http/httputil.Test1xxResponses test.
func Test1xxResponses(t *testing.T) {
next := 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)
h.Add("User-Agent", "foobar")
_, _ = w.Write([]byte("Hello"))
w.WriteHeader(http.StatusBadGateway)
})
serviceBuilderMock := &mockServiceBuilder{handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintln(w, "My error page.")
})}
config := dynamic.ErrorPage{Service: "error", Query: "/", Status: []string{"200"}}
errorPageHandler, err := New(t.Context(), next, config, serviceBuilderMock, "test")
require.NoError(t, err)
server := httptest.NewServer(errorPageHandler)
t.Cleanup(server.Close)
frontendClient := server.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, server.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)
assert.Equal(t, "My error page.\n", string(body))
}
type mockServiceBuilder struct {
handler http.Handler
}
func (m *mockServiceBuilder) BuildHTTP(_ context.Context, _ string) (http.Handler, error) {
return m.handler, nil
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/customerrors/custom_errors.go | pkg/middlewares/customerrors/custom_errors.go | package customerrors
import (
"bufio"
"context"
"fmt"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/middlewares/observability"
"github.com/traefik/traefik/v3/pkg/types"
"github.com/vulcand/oxy/v2/utils"
)
// Compile time validation that the response recorder implements http interfaces correctly.
var (
_ middlewares.Stateful = &codeModifier{}
_ middlewares.Stateful = &codeCatcher{}
)
const typeName = "CustomError"
type serviceBuilder interface {
BuildHTTP(ctx context.Context, serviceName string) (http.Handler, error)
}
// customErrors is a middleware that provides the custom error pages.
type customErrors struct {
name string
next http.Handler
backendHandler http.Handler
httpCodeRanges types.HTTPCodeRanges
backendQuery string
statusRewrites []statusRewrite
}
type statusRewrite struct {
fromCodes types.HTTPCodeRanges
toCode int
}
// New creates a new custom error pages middleware.
func New(ctx context.Context, next http.Handler, config dynamic.ErrorPage, serviceBuilder serviceBuilder, name string) (http.Handler, error) {
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
httpCodeRanges, err := types.NewHTTPCodeRanges(config.Status)
if err != nil {
return nil, err
}
backend, err := serviceBuilder.BuildHTTP(ctx, config.Service)
if err != nil {
return nil, err
}
// Parse StatusRewrites
statusRewrites := make([]statusRewrite, 0, len(config.StatusRewrites))
for k, v := range config.StatusRewrites {
ranges, err := types.NewHTTPCodeRanges([]string{k})
if err != nil {
return nil, err
}
statusRewrites = append(statusRewrites, statusRewrite{
fromCodes: ranges,
toCode: v,
})
}
return &customErrors{
name: name,
next: next,
backendHandler: backend,
httpCodeRanges: httpCodeRanges,
backendQuery: config.Query,
statusRewrites: statusRewrites,
}, nil
}
func (c *customErrors) GetTracingInformation() (string, string) {
return c.name, typeName
}
func (c *customErrors) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
logger := middlewares.GetLogger(req.Context(), c.name, typeName)
if c.backendHandler == nil {
logger.Error().Msg("No backend handler.")
observability.SetStatusErrorf(req.Context(), "No backend handler.")
c.next.ServeHTTP(rw, req)
return
}
catcher := newCodeCatcher(rw, c.httpCodeRanges)
c.next.ServeHTTP(catcher, req)
if !catcher.isFilteredCode() {
return
}
// check the recorder code against the configured http status code ranges
code := catcher.getCode()
originalCode := code
// Check if we need to rewrite the status code
for _, rsc := range c.statusRewrites {
if rsc.fromCodes.Contains(code) {
code = rsc.toCode
break
}
}
if code != originalCode {
logger.Debug().Msgf("Caught HTTP Status Code %d (rewritten to %d), returning error page", originalCode, code)
} else {
logger.Debug().Msgf("Caught HTTP Status Code %d, returning error page", code)
}
var query string
scheme := "http"
if req.TLS != nil {
scheme = "https"
}
orig := &url.URL{Scheme: scheme, Host: req.Host, Path: req.URL.Path, RawPath: req.URL.RawPath, RawQuery: req.URL.RawQuery, Fragment: req.URL.Fragment}
if len(c.backendQuery) > 0 {
query = "/" + strings.TrimPrefix(c.backendQuery, "/")
query = strings.ReplaceAll(query, "{status}", strconv.Itoa(code))
query = strings.ReplaceAll(query, "{originalStatus}", strconv.Itoa(originalCode))
query = strings.ReplaceAll(query, "{url}", url.QueryEscape(orig.String()))
}
pageReq, err := newRequest("http://" + req.Host + query)
if err != nil {
logger.Error().Msgf("Unable to create error page request: %v", err)
observability.SetStatusErrorf(req.Context(), "Unable to create error page request: %v", err)
http.Error(rw, http.StatusText(code), code)
return
}
utils.CopyHeaders(pageReq.Header, req.Header)
c.backendHandler.ServeHTTP(newCodeModifier(rw, code),
pageReq.WithContext(req.Context()))
}
func newRequest(baseURL string) (*http.Request, error) {
u, err := url.Parse(baseURL)
if err != nil {
return nil, fmt.Errorf("error pages: error when parse URL: %w", err)
}
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
return nil, fmt.Errorf("error pages: error when create query: %w", err)
}
req.RequestURI = u.RequestURI()
return req, nil
}
// codeCatcher is a response writer that detects as soon as possible
// whether the response is a code within the ranges of codes it watches for.
// If it is, it simply drops the data from the response.
// Otherwise, it forwards it directly to the original client (its responseWriter) without any buffering.
type codeCatcher struct {
headerMap http.Header
code int
httpCodeRanges types.HTTPCodeRanges
caughtFilteredCode bool
responseWriter http.ResponseWriter
headersSent bool
}
func newCodeCatcher(rw http.ResponseWriter, httpCodeRanges types.HTTPCodeRanges) *codeCatcher {
return &codeCatcher{
headerMap: make(http.Header),
code: http.StatusOK, // If backend does not call WriteHeader on us, we consider it's a 200.
responseWriter: rw,
httpCodeRanges: httpCodeRanges,
}
}
func (cc *codeCatcher) Header() http.Header {
if cc.headersSent {
return cc.responseWriter.Header()
}
if cc.headerMap == nil {
cc.headerMap = make(http.Header)
}
return cc.headerMap
}
func (cc *codeCatcher) getCode() int {
return cc.code
}
// isFilteredCode returns whether the codeCatcher received a response code among the ones it is watching,
// and for which the response should be deferred to the error handler.
func (cc *codeCatcher) isFilteredCode() bool {
return cc.caughtFilteredCode
}
func (cc *codeCatcher) Write(buf []byte) (int, error) {
// If WriteHeader was already called from the caller, this is a NOOP.
// Otherwise, cc.code is actually a 200 here.
cc.WriteHeader(cc.code)
if cc.caughtFilteredCode {
// We don't care about the contents of the response,
// since we want to serve the ones from the error page,
// so we just drop them.
return len(buf), nil
}
return cc.responseWriter.Write(buf)
}
// WriteHeader is, in the specific case of 1xx status codes, a direct call to the wrapped ResponseWriter, without marking headers as sent,
// allowing so further calls.
func (cc *codeCatcher) WriteHeader(code int) {
if cc.headersSent || cc.caughtFilteredCode {
return
}
// Handling informational headers.
if code >= 100 && code <= 199 {
// Multiple informational status codes can be used,
// so here the copy is not appending the values to not repeat them.
for k, v := range cc.Header() {
cc.responseWriter.Header()[k] = v
}
cc.responseWriter.WriteHeader(code)
return
}
cc.code = code
for _, block := range cc.httpCodeRanges {
if cc.code >= block[0] && cc.code <= block[1] {
cc.caughtFilteredCode = true
// it will be up to the caller to send the headers,
// so it is out of our hands now.
return
}
}
// The copy is not appending the values,
// to not repeat them in case any informational status code has been written.
for k, v := range cc.Header() {
cc.responseWriter.Header()[k] = v
}
cc.responseWriter.WriteHeader(cc.code)
cc.headersSent = true
}
// Hijack hijacks the connection.
func (cc *codeCatcher) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if hj, ok := cc.responseWriter.(http.Hijacker); ok {
return hj.Hijack()
}
return nil, nil, fmt.Errorf("%T is not a http.Hijacker", cc.responseWriter)
}
// Flush sends any buffered data to the client.
func (cc *codeCatcher) Flush() {
// If WriteHeader was already called from the caller, this is a NOOP.
// Otherwise, cc.code is actually a 200 here.
cc.WriteHeader(cc.code)
// We don't care about the contents of the response,
// since we want to serve the ones from the error page,
// so we just don't flush.
// (e.g., To prevent superfluous WriteHeader on request with a
// `Transfer-Encoding: chunked` header).
if cc.caughtFilteredCode {
return
}
if flusher, ok := cc.responseWriter.(http.Flusher); ok {
flusher.Flush()
}
}
// codeModifier forwards a response back to the client,
// while enforcing a given response code.
type codeModifier struct {
code int // the code enforced in the response.
// headerSent is whether the headers have already been sent,
// either through Write or WriteHeader.
headerSent bool
headerMap http.Header // the HTTP response headers from the backend.
responseWriter http.ResponseWriter
}
// newCodeModifier returns a codeModifier that enforces the given code.
func newCodeModifier(rw http.ResponseWriter, code int) *codeModifier {
return &codeModifier{
headerMap: make(http.Header),
code: code,
responseWriter: rw,
}
}
// Header returns the response headers.
func (r *codeModifier) Header() http.Header {
if r.headerSent {
return r.responseWriter.Header()
}
if r.headerMap == nil {
r.headerMap = make(http.Header)
}
return r.headerMap
}
// Write calls WriteHeader to send the enforced code,
// then writes the data directly to r.responseWriter.
func (r *codeModifier) Write(buf []byte) (int, error) {
r.WriteHeader(r.code)
return r.responseWriter.Write(buf)
}
// WriteHeader sends the headers, with the enforced code (the code in argument is always ignored),
// if it hasn't already been done.
// WriteHeader is, in the specific case of 1xx status codes, a direct call to the wrapped ResponseWriter, without marking headers as sent,
// allowing so further calls.
func (r *codeModifier) WriteHeader(code int) {
if r.headerSent {
return
}
// Handling informational headers.
if code >= 100 && code <= 199 {
// Multiple informational status codes can be used,
// so here the copy is not appending the values to not repeat them.
for k, v := range r.headerMap {
r.responseWriter.Header()[k] = v
}
r.responseWriter.WriteHeader(code)
return
}
for k, v := range r.headerMap {
r.responseWriter.Header()[k] = v
}
r.responseWriter.WriteHeader(r.code)
r.headerSent = true
}
// Hijack hijacks the connection.
func (r *codeModifier) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker, ok := r.responseWriter.(http.Hijacker)
if !ok {
return nil, nil, fmt.Errorf("%T is not a http.Hijacker", r.responseWriter)
}
return hijacker.Hijack()
}
// Flush sends any buffered data to the client.
func (r *codeModifier) Flush() {
r.WriteHeader(r.code)
if flusher, ok := r.responseWriter.(http.Flusher); ok {
flusher.Flush()
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/compress/compress.go | pkg/middlewares/compress/compress.go | package compress
import (
"context"
"errors"
"fmt"
"mime"
"net/http"
"slices"
"github.com/andybalholm/brotli"
"github.com/klauspost/compress/gzhttp"
"github.com/klauspost/compress/zstd"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
)
const typeName = "Compress"
// defaultMinSize is the default minimum size (in bytes) required to enable compression.
// See https://github.com/klauspost/compress/blob/9559b037e79ad673c71f6ef7c732c00949014cd2/gzhttp/compress.go#L47.
const defaultMinSize = 1024
var defaultSupportedEncodings = []string{gzipName, brotliName, zstdName}
// Compress is a middleware that allows to compress the response.
type compress struct {
next http.Handler
name string
excludes []string
includes []string
minSize int
encodings []string
defaultEncoding string
// supportedEncodings is a map of supported encodings and their priority.
supportedEncodings map[string]int
brotliHandler http.Handler
gzipHandler http.Handler
zstdHandler http.Handler
}
// New creates a new compress middleware.
func New(ctx context.Context, next http.Handler, conf dynamic.Compress, name string) (http.Handler, error) {
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
if len(conf.ExcludedContentTypes) > 0 && len(conf.IncludedContentTypes) > 0 {
return nil, errors.New("excludedContentTypes and includedContentTypes options are mutually exclusive")
}
excludes := []string{"application/grpc"}
for _, v := range conf.ExcludedContentTypes {
mediaType, _, err := mime.ParseMediaType(v)
if err != nil {
return nil, fmt.Errorf("parsing excluded media type: %w", err)
}
excludes = append(excludes, mediaType)
}
var includes []string
for _, v := range conf.IncludedContentTypes {
mediaType, _, err := mime.ParseMediaType(v)
if err != nil {
return nil, fmt.Errorf("parsing included media type: %w", err)
}
includes = append(includes, mediaType)
}
minSize := defaultMinSize
if conf.MinResponseBodyBytes > 0 {
minSize = conf.MinResponseBodyBytes
}
if len(conf.Encodings) == 0 {
return nil, errors.New("at least one encoding must be specified")
}
for _, encoding := range conf.Encodings {
if !slices.Contains(defaultSupportedEncodings, encoding) {
return nil, fmt.Errorf("unsupported encoding: %s", encoding)
}
}
if conf.DefaultEncoding != "" && !slices.Contains(conf.Encodings, conf.DefaultEncoding) {
return nil, fmt.Errorf("unsupported default encoding: %s", conf.DefaultEncoding)
}
c := &compress{
next: next,
name: name,
excludes: excludes,
includes: includes,
minSize: minSize,
encodings: conf.Encodings,
defaultEncoding: conf.DefaultEncoding,
supportedEncodings: buildSupportedEncodings(conf.Encodings),
}
var err error
c.zstdHandler, err = c.newZstdHandler(name)
if err != nil {
return nil, err
}
c.brotliHandler, err = c.newBrotliHandler(name)
if err != nil {
return nil, err
}
c.gzipHandler, err = c.newGzipHandler()
if err != nil {
return nil, err
}
return c, nil
}
func buildSupportedEncodings(encodings []string) map[string]int {
supportedEncodings := map[string]int{
// the most permissive first.
wildcardName: -1,
// the less permissive last.
identityName: len(encodings),
}
for i, encoding := range encodings {
supportedEncodings[encoding] = i
}
return supportedEncodings
}
func (c *compress) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
logger := middlewares.GetLogger(req.Context(), c.name, typeName)
if req.Method == http.MethodHead {
c.next.ServeHTTP(rw, req)
return
}
mediaType, _, err := mime.ParseMediaType(req.Header.Get("Content-Type"))
if err != nil {
logger.Debug().Err(err).Msg("Unable to parse MIME type")
}
// Notably for text/event-stream requests the response should not be compressed.
// See https://github.com/traefik/traefik/issues/2576
if slices.Contains(c.excludes, mediaType) {
c.next.ServeHTTP(rw, req)
return
}
acceptEncoding, ok := req.Header[acceptEncodingHeader]
if !ok {
if c.defaultEncoding != "" {
// RFC says: "If no Accept-Encoding header field is in the request, any content coding is considered acceptable by the user agent."
// https://www.rfc-editor.org/rfc/rfc9110#field.accept-encoding
c.chooseHandler(c.defaultEncoding, rw, req)
return
}
// Client doesn't specify a preferred encoding, for compatibility don't encode the request
// See https://github.com/traefik/traefik/issues/9734
c.next.ServeHTTP(rw, req)
return
}
c.chooseHandler(c.getCompressionEncoding(acceptEncoding), rw, req)
}
func (c *compress) chooseHandler(typ string, rw http.ResponseWriter, req *http.Request) {
switch typ {
case zstdName:
c.zstdHandler.ServeHTTP(rw, req)
case brotliName:
c.brotliHandler.ServeHTTP(rw, req)
case gzipName:
c.gzipHandler.ServeHTTP(rw, req)
default:
c.next.ServeHTTP(rw, req)
}
}
func (c *compress) GetTracingInformation() (string, string) {
return c.name, typeName
}
func (c *compress) newGzipHandler() (http.Handler, error) {
var wrapper func(http.Handler) http.HandlerFunc
var err error
if len(c.includes) > 0 {
wrapper, err = gzhttp.NewWrapper(
gzhttp.ContentTypes(c.includes),
gzhttp.MinSize(c.minSize),
)
} else {
wrapper, err = gzhttp.NewWrapper(
gzhttp.ExceptContentTypes(c.excludes),
gzhttp.MinSize(c.minSize),
)
}
if err != nil {
return nil, fmt.Errorf("new gzip wrapper: %w", err)
}
return wrapper(c.next), nil
}
func (c *compress) newBrotliHandler(middlewareName string) (http.Handler, error) {
cfg := Config{MinSize: c.minSize, MiddlewareName: middlewareName}
if len(c.includes) > 0 {
cfg.IncludedContentTypes = c.includes
} else {
cfg.ExcludedContentTypes = c.excludes
}
newBrotliWriter := func(rw http.ResponseWriter) (CompressionWriter, string, error) {
return brotli.NewWriter(rw), brotliName, nil
}
return NewCompressionHandler(cfg, newBrotliWriter, c.next)
}
func (c *compress) newZstdHandler(middlewareName string) (http.Handler, error) {
cfg := Config{MinSize: c.minSize, MiddlewareName: middlewareName}
if len(c.includes) > 0 {
cfg.IncludedContentTypes = c.includes
} else {
cfg.ExcludedContentTypes = c.excludes
}
newZstdWriter := func(rw http.ResponseWriter) (CompressionWriter, string, error) {
writer, err := zstd.NewWriter(rw)
if err != nil {
return nil, "", fmt.Errorf("creating zstd writer: %w", err)
}
return writer, zstdName, nil
}
return NewCompressionHandler(cfg, newZstdWriter, c.next)
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/compress/acceptencoding.go | pkg/middlewares/compress/acceptencoding.go | package compress
import (
"cmp"
"slices"
"strconv"
"strings"
)
const acceptEncodingHeader = "Accept-Encoding"
const (
brotliName = "br"
gzipName = "gzip"
zstdName = "zstd"
identityName = "identity"
wildcardName = "*"
notAcceptable = "not_acceptable"
)
type Encoding struct {
Type string
Weight float64
}
func (c *compress) getCompressionEncoding(acceptEncoding []string) string {
// RFC says: An Accept-Encoding header field with a field value that is empty implies that the user agent does not want any content coding in response.
// https://datatracker.ietf.org/doc/html/rfc9110#name-accept-encoding
if len(acceptEncoding) == 1 && acceptEncoding[0] == "" {
return identityName
}
acceptableEncodings := parseAcceptableEncodings(acceptEncoding, c.supportedEncodings)
// An empty Accept-Encoding header field would have been handled earlier.
// If empty, it means no encoding is supported, we do not encode.
if len(acceptableEncodings) == 0 {
// TODO: return 415 status code instead of deactivating the compression, if the backend was not to compress as well.
return notAcceptable
}
slices.SortFunc(acceptableEncodings, func(a, b Encoding) int {
if a.Weight == b.Weight {
// At same weight, we want to prioritize based on the encoding priority.
// the lower the index, the higher the priority.
return cmp.Compare(c.supportedEncodings[a.Type], c.supportedEncodings[b.Type])
}
return cmp.Compare(b.Weight, a.Weight)
})
if acceptableEncodings[0].Type == wildcardName {
if c.defaultEncoding == "" {
return c.encodings[0]
}
return c.defaultEncoding
}
return acceptableEncodings[0].Type
}
func parseAcceptableEncodings(acceptEncoding []string, supportedEncodings map[string]int) []Encoding {
var encodings []Encoding
for _, line := range acceptEncoding {
for _, item := range strings.Split(strings.ReplaceAll(line, " ", ""), ",") {
parsed := strings.SplitN(item, ";", 2)
if len(parsed) == 0 {
continue
}
if _, ok := supportedEncodings[parsed[0]]; !ok {
continue
}
// If no "q" parameter is present, the default weight is 1.
// https://www.rfc-editor.org/rfc/rfc9110.html#name-quality-values
weight := 1.0
if len(parsed) > 1 && strings.HasPrefix(parsed[1], "q=") {
w, _ := strconv.ParseFloat(strings.TrimPrefix(parsed[1], "q="), 64)
// If the weight is 0, the encoding is not acceptable.
// We can skip the encoding.
if w == 0 {
continue
}
weight = w
}
encodings = append(encodings, Encoding{
Type: parsed[0],
Weight: weight,
})
}
}
return encodings
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/compress/acceptencoding_test.go | pkg/middlewares/compress/acceptencoding_test.go | package compress
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
)
func Test_getCompressionEncoding(t *testing.T) {
testCases := []struct {
desc string
acceptEncoding []string
defaultEncoding string
supportedEncodings []string
expected string
}{
{
desc: "Empty Accept-Encoding",
acceptEncoding: []string{""},
expected: identityName,
},
{
desc: "gzip > br (no weight)",
acceptEncoding: []string{"gzip, br"},
expected: gzipName,
},
{
desc: "gzip > br > zstd (no weight)",
acceptEncoding: []string{"gzip, br, zstd"},
expected: gzipName,
},
{
desc: "known compression encoding (no weight)",
acceptEncoding: []string{"compress, gzip"},
expected: gzipName,
},
{
desc: "unknown compression encoding (no weight), no encoding",
acceptEncoding: []string{"compress, rar"},
expected: notAcceptable,
},
{
desc: "wildcard returns the default compression encoding",
acceptEncoding: []string{"*"},
expected: gzipName,
},
{
desc: "wildcard returns the custom default compression encoding",
acceptEncoding: []string{"*"},
defaultEncoding: brotliName,
expected: brotliName,
},
{
desc: "follows weight",
acceptEncoding: []string{"br;q=0.8, gzip;q=1.0, *;q=0.1"},
expected: gzipName,
},
{
desc: "identity with higher weight is preferred",
acceptEncoding: []string{"br;q=0.8, identity;q=1.0"},
expected: identityName,
},
{
desc: "identity with equal weight is not preferred",
acceptEncoding: []string{"br;q=0.8, identity;q=0.8"},
expected: brotliName,
},
{
desc: "ignore unknown compression encoding",
acceptEncoding: []string{"compress;q=1.0, gzip;q=0.5"},
expected: gzipName,
},
{
desc: "fallback on non-zero compression encoding",
acceptEncoding: []string{"compress;q=1.0, gzip, identity;q=0"},
expected: gzipName,
},
{
desc: "not acceptable (identity)",
acceptEncoding: []string{"compress;q=1.0, identity;q=0"},
expected: notAcceptable,
},
{
desc: "not acceptable (wildcard)",
acceptEncoding: []string{"compress;q=1.0, *;q=0"},
expected: notAcceptable,
},
{
desc: "non-zero is higher than 0",
acceptEncoding: []string{"gzip, *;q=0"},
expected: gzipName,
},
{
desc: "zstd forbidden, brotli first",
acceptEncoding: []string{"zstd, gzip, br"},
supportedEncodings: []string{brotliName, gzipName},
expected: brotliName,
},
{
desc: "follows weight, ignores forbidden encoding",
acceptEncoding: []string{"br;q=0.8, gzip;q=1.0, *;q=0.1"},
supportedEncodings: []string{zstdName, brotliName},
expected: brotliName,
},
{
desc: "mixed weight",
acceptEncoding: []string{"gzip, br;q=0.9"},
supportedEncodings: []string{gzipName, brotliName},
expected: gzipName,
},
{
desc: "Zero weights, no compression",
acceptEncoding: []string{"br;q=0, gzip;q=0, zstd;q=0"},
expected: notAcceptable,
},
{
desc: "Zero weights, default encoding, no compression",
acceptEncoding: []string{"br;q=0, gzip;q=0, zstd;q=0"},
defaultEncoding: "br",
expected: notAcceptable,
},
{
desc: "Same weight, first supported encoding",
acceptEncoding: []string{"br;q=1.0, gzip;q=1.0, zstd;q=1.0"},
expected: gzipName,
},
{
desc: "Same weight, first supported encoding, order has no effect",
acceptEncoding: []string{"br;q=1.0, zstd;q=1.0, gzip;q=1.0"},
expected: gzipName,
},
{
desc: "Same weight, first supported encoding, defaultEncoding has no effect",
acceptEncoding: []string{"br;q=1.0, zstd;q=1.0, gzip;q=1.0"},
defaultEncoding: "br",
expected: gzipName,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
if test.supportedEncodings == nil {
test.supportedEncodings = defaultSupportedEncodings
}
conf := dynamic.Compress{
Encodings: test.supportedEncodings,
DefaultEncoding: test.defaultEncoding,
}
h, err := New(t.Context(), nil, conf, "test")
require.NoError(t, err)
c, ok := h.(*compress)
require.True(t, ok)
encoding := c.getCompressionEncoding(test.acceptEncoding)
assert.Equal(t, test.expected, encoding)
})
}
}
func Test_parseAcceptEncoding(t *testing.T) {
testCases := []struct {
desc string
values []string
supportedEncodings []string
expected []Encoding
assertWeight assert.BoolAssertionFunc
}{
{
desc: "weight",
values: []string{"br;q=1.0, zstd;q=0.9, gzip;q=0.8, *;q=0.1"},
expected: []Encoding{
{Type: brotliName, Weight: 1},
{Type: zstdName, Weight: 0.9},
{Type: gzipName, Weight: 0.8},
{Type: wildcardName, Weight: 0.1},
},
assertWeight: assert.True,
},
{
desc: "weight with supported encodings",
values: []string{"br;q=1.0, zstd;q=0.9, gzip;q=0.8, *;q=0.1"},
supportedEncodings: []string{brotliName, gzipName},
expected: []Encoding{
{Type: brotliName, Weight: 1},
{Type: gzipName, Weight: 0.8},
{Type: wildcardName, Weight: 0.1},
},
assertWeight: assert.True,
},
{
desc: "mixed",
values: []string{"zstd,gzip, br;q=1.0, *;q=0"},
expected: []Encoding{
{Type: zstdName, Weight: 1},
{Type: gzipName, Weight: 1},
{Type: brotliName, Weight: 1},
},
assertWeight: assert.True,
},
{
desc: "mixed with supported encodings",
values: []string{"zstd,gzip, br;q=1.0, *;q=0"},
supportedEncodings: []string{zstdName},
expected: []Encoding{
{Type: zstdName, Weight: 1},
},
assertWeight: assert.True,
},
{
desc: "no weight",
values: []string{"zstd, gzip, br, *"},
expected: []Encoding{
{Type: zstdName, Weight: 1},
{Type: gzipName, Weight: 1},
{Type: brotliName, Weight: 1},
{Type: wildcardName, Weight: 1},
},
assertWeight: assert.False,
},
{
desc: "no weight with supported encodings",
values: []string{"zstd, gzip, br, *"},
supportedEncodings: []string{"gzip"},
expected: []Encoding{
{Type: gzipName, Weight: 1},
{Type: wildcardName, Weight: 1},
},
assertWeight: assert.False,
},
{
desc: "weight and identity",
values: []string{"gzip;q=1.0, identity; q=0.5, *;q=0"},
expected: []Encoding{
{Type: gzipName, Weight: 1},
{Type: identityName, Weight: 0.5},
},
assertWeight: assert.True,
},
{
desc: "weight and identity",
values: []string{"gzip;q=1.0, identity; q=0.5, *;q=0"},
supportedEncodings: []string{"br"},
expected: []Encoding{
{Type: identityName, Weight: 0.5},
},
assertWeight: assert.True,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
if test.supportedEncodings == nil {
test.supportedEncodings = defaultSupportedEncodings
}
supportedEncodings := buildSupportedEncodings(test.supportedEncodings)
aes := parseAcceptableEncodings(test.values, supportedEncodings)
assert.Equal(t, test.expected, aes)
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/compress/compression_handler.go | pkg/middlewares/compress/compression_handler.go | package compress
import (
"bufio"
"errors"
"fmt"
"io"
"mime"
"net"
"net/http"
"sync"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/middlewares/observability"
)
const (
vary = "Vary"
acceptEncoding = "Accept-Encoding"
contentEncoding = "Content-Encoding"
contentLength = "Content-Length"
contentType = "Content-Type"
)
// CompressionWriter compresses the written bytes.
type CompressionWriter interface {
// Write data to the encoder.
// Input data will be buffered and as the buffer fills up
// content will be compressed and written to the output.
// When done writing, use Close to flush the remaining output
// and write CRC if requested.
Write(p []byte) (n int, err error)
// Flush will send the currently written data to output
// and block until everything has been written.
// This should only be used on rare occasions where pushing the currently queued data is critical.
Flush() error
// Close closes the underlying writers if/when appropriate.
// Note that the compressed writer should not be closed if we never used it,
// as it would otherwise send some extra "end of compression" bytes.
// Close also makes sure to flush whatever was left to write from the buffer.
Close() error
// Reset reinitializes the state of the encoder, allowing it to be reused.
Reset(w io.Writer)
}
// NewCompressionWriter returns a new CompressionWriter with its corresponding algorithm.
type NewCompressionWriter func(rw http.ResponseWriter) (CompressionWriter, string, error)
// Config is the Brotli handler configuration.
type Config struct {
// ExcludedContentTypes is the list of content types for which we should not compress.
// Mutually exclusive with the IncludedContentTypes option.
ExcludedContentTypes []string
// IncludedContentTypes is the list of content types for which compression should be exclusively enabled.
// Mutually exclusive with the ExcludedContentTypes option.
IncludedContentTypes []string
// MinSize is the minimum size (in bytes) required to enable compression.
MinSize int
// MiddlewareName use for logging purposes
MiddlewareName string
}
// CompressionHandler handles Brolti and Zstd compression.
type CompressionHandler struct {
cfg Config
excludedContentTypes []parsedContentType
includedContentTypes []parsedContentType
next http.Handler
writerPool sync.Pool
newWriter NewCompressionWriter
}
// NewCompressionHandler returns a new compressing handler.
func NewCompressionHandler(cfg Config, newWriter NewCompressionWriter, next http.Handler) (http.Handler, error) {
if cfg.MinSize < 0 {
return nil, errors.New("minimum size must be greater than or equal to zero")
}
if len(cfg.ExcludedContentTypes) > 0 && len(cfg.IncludedContentTypes) > 0 {
return nil, errors.New("excludedContentTypes and includedContentTypes options are mutually exclusive")
}
var excludedContentTypes []parsedContentType
for _, v := range cfg.ExcludedContentTypes {
mediaType, params, err := mime.ParseMediaType(v)
if err != nil {
return nil, fmt.Errorf("parsing excluded media type: %w", err)
}
excludedContentTypes = append(excludedContentTypes, parsedContentType{mediaType, params})
}
var includedContentTypes []parsedContentType
for _, v := range cfg.IncludedContentTypes {
mediaType, params, err := mime.ParseMediaType(v)
if err != nil {
return nil, fmt.Errorf("parsing included media type: %w", err)
}
includedContentTypes = append(includedContentTypes, parsedContentType{mediaType, params})
}
return &CompressionHandler{
cfg: cfg,
excludedContentTypes: excludedContentTypes,
includedContentTypes: includedContentTypes,
next: next,
newWriter: newWriter,
}, nil
}
func (c *CompressionHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
rw.Header().Add(vary, acceptEncoding)
compressionWriter, err := c.getCompressionWriter(rw)
if err != nil {
logger := middlewares.GetLogger(r.Context(), c.cfg.MiddlewareName, typeName)
logger.Debug().Msgf("Create compression handler: %v", err)
observability.SetStatusErrorf(r.Context(), "Create compression handler: %v", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
defer c.putCompressionWriter(compressionWriter)
responseWriter := &responseWriter{
rw: rw,
compressionWriter: compressionWriter,
minSize: c.cfg.MinSize,
statusCode: http.StatusOK,
excludedContentTypes: c.excludedContentTypes,
includedContentTypes: c.includedContentTypes,
}
defer responseWriter.close()
c.next.ServeHTTP(responseWriter, r)
}
func (c *CompressionHandler) getCompressionWriter(rw http.ResponseWriter) (*compressionWriterWrapper, error) {
if writer, ok := c.writerPool.Get().(*compressionWriterWrapper); ok {
writer.Reset(rw)
return writer, nil
}
writer, algo, err := c.newWriter(rw)
if err != nil {
return nil, fmt.Errorf("creating compression writer: %w", err)
}
return &compressionWriterWrapper{CompressionWriter: writer, algo: algo}, nil
}
func (c *CompressionHandler) putCompressionWriter(writer *compressionWriterWrapper) {
writer.Reset(nil)
c.writerPool.Put(writer)
}
type compressionWriterWrapper struct {
CompressionWriter
algo string
}
func (c *compressionWriterWrapper) ContentEncoding() string {
return c.algo
}
// TODO: check whether we want to implement content-type sniffing (as gzip does)
// TODO: check whether we should support Accept-Ranges (as gzip does, see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Ranges)
type responseWriter struct {
rw http.ResponseWriter
compressionWriter *compressionWriterWrapper
minSize int
excludedContentTypes []parsedContentType
includedContentTypes []parsedContentType
buf []byte
hijacked bool
compressionStarted bool
compressionDisabled bool
headersSent bool
// Mostly needed to avoid calling bw.Flush/bw.Close when no data was
// written in bw.
seenData bool
statusCodeSet bool
statusCode int
}
func (r *responseWriter) Header() http.Header {
return r.rw.Header()
}
func (r *responseWriter) WriteHeader(statusCode int) {
// Handle informational headers
// This is gated to not forward 1xx responses on builds prior to go1.20.
if statusCode >= 100 && statusCode <= 199 {
r.rw.WriteHeader(statusCode)
return
}
if !r.statusCodeSet {
r.statusCode = statusCode
r.statusCodeSet = true
}
}
func (r *responseWriter) Write(p []byte) (int, error) {
// i.e. has write ever been called at least once with non nil data.
if !r.seenData && len(p) > 0 {
r.seenData = true
}
// We do not compress, either for contentEncoding or contentType reasons.
if r.compressionDisabled {
return r.rw.Write(p)
}
// We have already buffered more than minSize,
// We are now in compression cruise mode until the end of times.
if r.compressionStarted {
// If compressionStarted we assume we have sent headers already
return r.compressionWriter.Write(p)
}
// If we detect a contentEncoding, we know we are never going to compress.
if r.rw.Header().Get(contentEncoding) != "" {
r.compressionDisabled = true
r.rw.WriteHeader(r.statusCode)
return r.rw.Write(p)
}
// Disable compression according to user wishes in excludedContentTypes or includedContentTypes.
if ct := r.rw.Header().Get(contentType); ct != "" {
mediaType, params, err := mime.ParseMediaType(ct)
// To align the behavior with the klauspost handler for Gzip,
// if the MIME type is not parsable the compression is disabled.
if err != nil {
r.compressionDisabled = true
r.rw.WriteHeader(r.statusCode)
return r.rw.Write(p)
}
if len(r.includedContentTypes) > 0 {
var found bool
for _, includedContentType := range r.includedContentTypes {
if includedContentType.equals(mediaType, params) {
found = true
break
}
}
if !found {
r.compressionDisabled = true
r.rw.WriteHeader(r.statusCode)
return r.rw.Write(p)
}
}
for _, excludedContentType := range r.excludedContentTypes {
if excludedContentType.equals(mediaType, params) {
r.compressionDisabled = true
r.rw.WriteHeader(r.statusCode)
return r.rw.Write(p)
}
}
}
// We buffer until we know whether to compress (i.e. when we reach minSize received).
if len(r.buf)+len(p) < r.minSize {
r.buf = append(r.buf, p...)
return len(p), nil
}
// If we ever make it here, we have received at least minSize, which means we want to compress,
// and we are going to send headers right away.
r.compressionStarted = true
// Since we know we are going to compress we will never be able to know the actual length.
r.rw.Header().Del(contentLength)
r.rw.Header().Set(contentEncoding, r.compressionWriter.ContentEncoding())
r.rw.WriteHeader(r.statusCode)
r.headersSent = true
// Start with sending what we have previously buffered, before actually writing
// the bytes in argument.
n, err := r.compressionWriter.Write(r.buf)
if err != nil {
r.buf = r.buf[n:]
// Return zero because we haven't taken care of the bytes in argument yet.
return 0, err
}
// If we wrote less than what we wanted, we need to reclaim the leftovers + the bytes in argument,
// and keep them for a subsequent Write.
if n < len(r.buf) {
r.buf = r.buf[n:]
r.buf = append(r.buf, p...)
return len(p), nil
}
// Otherwise just reset the buffer.
r.buf = r.buf[:0]
// Now that we emptied the buffer, we can actually write the given bytes.
return r.compressionWriter.Write(p)
}
// Flush flushes data to the appropriate underlying writer(s), although it does
// not guarantee that all buffered data will be sent.
// If not enough bytes have been written to determine whether to enable compression,
// no flushing will take place.
func (r *responseWriter) Flush() {
if !r.seenData {
// we should not flush if there never was any data, because flushing the bw
// (just like closing) would send some extra end of compressionStarted stream bytes.
return
}
// It was already established by Write that compression is disabled, we only
// have to flush the uncompressed writer.
if r.compressionDisabled {
if rw, ok := r.rw.(http.Flusher); ok {
rw.Flush()
}
return
}
// Here, nothing was ever written either to rw or to bw (since we're still
// waiting to decide whether to compress), so to be aligned with klauspost's
// gzip behavior we force the compression and flush whatever was in the buffer in this case.
if !r.compressionStarted {
r.rw.Header().Del(contentLength)
r.rw.Header().Set(contentEncoding, r.compressionWriter.ContentEncoding())
r.rw.WriteHeader(r.statusCode)
r.headersSent = true
r.compressionStarted = true
}
// Conversely, we here know that something was already written to bw (or is
// going to be written right after anyway), so bw will have to be flushed.
// Also, since we know that bw writes to rw, but (apparently) never flushes it,
// we have to do it ourselves.
defer func() {
// because we also ignore the error returned by Write anyway
_ = r.compressionWriter.Flush()
if rw, ok := r.rw.(http.Flusher); ok {
rw.Flush()
}
}()
// We empty whatever is left of the buffer that Write never took care of.
n, err := r.compressionWriter.Write(r.buf)
if err != nil {
return
}
// And just like in Write we also handle "short writes".
if n < len(r.buf) {
r.buf = r.buf[n:]
return
}
r.buf = r.buf[:0]
}
func (r *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if hijacker, ok := r.rw.(http.Hijacker); ok {
// We only make use of r.hijacked in close (and not in Write/WriteHeader)
// because we want to let the stdlib catch the error on writes, as
// they already do a good job of logging it.
r.hijacked = true
return hijacker.Hijack()
}
return nil, nil, fmt.Errorf("%T is not a http.Hijacker", r.rw)
}
// close closes the underlying writers if/when appropriate.
// Note that the compressed writer should not be closed if we never used it,
// as it would otherwise send some extra "end of compression" bytes.
// Close also makes sure to flush whatever was left to write from the buffer.
func (r *responseWriter) close() error {
if r.hijacked {
return nil
}
// We have to take care of statusCode ourselves (in case there was never any
// call to Write or WriteHeader before us) as it's the only header we buffer.
if !r.headersSent {
r.rw.WriteHeader(r.statusCode)
r.headersSent = true
}
// Nothing was ever written anywhere, nothing to flush.
if !r.seenData {
return nil
}
// If compression was disabled, there never was anything in the buffer to flush,
// and nothing was ever written to bw.
if r.compressionDisabled {
return nil
}
if len(r.buf) == 0 {
// If we got here we know compression has started, so we can safely flush on bw.
return r.compressionWriter.Close()
}
// There is still data in the buffer, because we never reached minSize (to
// determine whether to compress). We therefore flush it uncompressed.
if !r.compressionStarted {
n, err := r.rw.Write(r.buf)
if err != nil {
return err
}
if n < len(r.buf) {
return io.ErrShortWrite
}
return nil
}
// There is still data in the buffer, simply because Write did not take care of it all.
// We flush it to the compressed writer.
n, err := r.compressionWriter.Write(r.buf)
if err != nil {
r.compressionWriter.Close()
return err
}
if n < len(r.buf) {
r.compressionWriter.Close()
return io.ErrShortWrite
}
return r.compressionWriter.Close()
}
// parsedContentType is the parsed representation of one of the inputs to ContentTypes.
// From https://github.com/klauspost/compress/blob/master/gzhttp/compress.go#L401.
type parsedContentType struct {
mediaType string
params map[string]string
}
// equals returns whether this content type matches another content type.
func (p parsedContentType) equals(mediaType string, params map[string]string) bool {
if p.mediaType != mediaType {
return false
}
// if p has no params, don't care about other's params
if len(p.params) == 0 {
return true
}
// if p has any params, they must be identical to other's.
if len(p.params) != len(params) {
return false
}
for k, v := range p.params {
if w, ok := params[k]; !ok || v != w {
return false
}
}
return true
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/compress/compression_handler_test.go | pkg/middlewares/compress/compression_handler_test.go | package compress
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/andybalholm/brotli"
"github.com/klauspost/compress/zstd"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var (
smallTestBody = []byte("aaabbc" + strings.Repeat("aaabbbccc", 9) + "aaabbbc")
bigTestBody = []byte(strings.Repeat(strings.Repeat("aaabbbccc", 66)+" ", 6) + strings.Repeat("aaabbbccc", 66))
)
func Test_Vary(t *testing.T) {
testCases := []struct {
desc string
h http.Handler
acceptEncoding string
}{
{
desc: "brotli",
h: newTestBrotliHandler(t, smallTestBody),
acceptEncoding: "br",
},
{
desc: "zstd",
h: newTestZstandardHandler(t, smallTestBody),
acceptEncoding: "zstd",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
req, _ := http.NewRequest(http.MethodGet, "/whatever", nil)
req.Header.Set(acceptEncoding, test.acceptEncoding)
rw := httptest.NewRecorder()
test.h.ServeHTTP(rw, req)
assert.Equal(t, http.StatusAccepted, rw.Code)
assert.Equal(t, acceptEncoding, rw.Header().Get(vary))
})
}
}
func Test_SmallBodyNoCompression(t *testing.T) {
testCases := []struct {
desc string
h http.Handler
acceptEncoding string
}{
{
desc: "brotli",
h: newTestBrotliHandler(t, smallTestBody),
acceptEncoding: "br",
},
{
desc: "zstd",
h: newTestZstandardHandler(t, smallTestBody),
acceptEncoding: "zstd",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
req, _ := http.NewRequest(http.MethodGet, "/whatever", nil)
req.Header.Set(acceptEncoding, test.acceptEncoding)
rw := httptest.NewRecorder()
test.h.ServeHTTP(rw, req)
// With less than 1024 bytes the response should not be compressed.
assert.Equal(t, http.StatusAccepted, rw.Code)
assert.Empty(t, rw.Header().Get(contentEncoding))
assert.Equal(t, smallTestBody, rw.Body.Bytes())
})
}
}
func Test_AlreadyCompressed(t *testing.T) {
testCases := []struct {
desc string
h http.Handler
acceptEncoding string
}{
{
desc: "brotli",
h: newTestBrotliHandler(t, bigTestBody),
acceptEncoding: "br",
},
{
desc: "zstd",
h: newTestZstandardHandler(t, bigTestBody),
acceptEncoding: "zstd",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
req, _ := http.NewRequest(http.MethodGet, "/compressed", nil)
req.Header.Set(acceptEncoding, test.acceptEncoding)
rw := httptest.NewRecorder()
test.h.ServeHTTP(rw, req)
assert.Equal(t, http.StatusAccepted, rw.Code)
assert.Equal(t, bigTestBody, rw.Body.Bytes())
})
}
}
func Test_NoBody(t *testing.T) {
testCases := []struct {
desc string
statusCode int
body []byte
}{
{
desc: "status no content",
statusCode: http.StatusNoContent,
body: nil,
},
{
desc: "status not modified",
statusCode: http.StatusNotModified,
body: nil,
},
{
desc: "status OK with empty body",
statusCode: http.StatusOK,
body: []byte{},
},
{
desc: "status OK with nil body",
statusCode: http.StatusOK,
body: nil,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(test.statusCode)
_, err := rw.Write(test.body)
require.NoError(t, err)
})
h := mustNewCompressionHandler(t, Config{MinSize: 1024}, zstdName, next)
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(acceptEncoding, "zstd")
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
body, err := io.ReadAll(rw.Body)
require.NoError(t, err)
assert.Empty(t, rw.Header().Get(contentEncoding))
assert.Empty(t, body)
})
}
}
func Test_MinSize(t *testing.T) {
cfg := Config{
MinSize: 128,
}
var bodySize int
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
for range bodySize {
// We make sure to Write at least once less than minSize so that both
// cases below go through the same algo: i.e. they start buffering
// because they haven't reached minSize.
_, err := rw.Write([]byte{'x'})
require.NoError(t, err)
}
})
h := mustNewCompressionHandler(t, cfg, zstdName, next)
req, _ := http.NewRequest(http.MethodGet, "/whatever", &bytes.Buffer{})
req.Header.Add(acceptEncoding, "zstd")
// Short response is not compressed
bodySize = cfg.MinSize - 1
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
assert.Empty(t, rw.Result().Header.Get(contentEncoding))
// Long response is compressed
bodySize = cfg.MinSize
rw = httptest.NewRecorder()
h.ServeHTTP(rw, req)
assert.Equal(t, "zstd", rw.Result().Header.Get(contentEncoding))
}
func Test_MultipleWriteHeader(t *testing.T) {
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
// We ensure that the subsequent call to WriteHeader is a noop.
rw.WriteHeader(http.StatusInternalServerError)
rw.WriteHeader(http.StatusNotFound)
})
h := mustNewCompressionHandler(t, Config{MinSize: 1024}, zstdName, next)
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(acceptEncoding, "zstd")
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
assert.Equal(t, http.StatusInternalServerError, rw.Code)
}
func Test_FlushBeforeWrite(t *testing.T) {
testCases := []struct {
desc string
cfg Config
algo string
readerBuilder func(io.Reader) (io.Reader, error)
acceptEncoding string
}{
{
desc: "brotli",
cfg: Config{MinSize: 1024, MiddlewareName: "Test"},
algo: brotliName,
readerBuilder: func(reader io.Reader) (io.Reader, error) {
return brotli.NewReader(reader), nil
},
acceptEncoding: "br",
},
{
desc: "zstd",
cfg: Config{MinSize: 1024, MiddlewareName: "Test"},
algo: zstdName,
readerBuilder: func(reader io.Reader) (io.Reader, error) {
return zstd.NewReader(reader)
},
acceptEncoding: "zstd",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusOK)
rw.(http.Flusher).Flush()
_, err := rw.Write(bigTestBody)
require.NoError(t, err)
})
srv := httptest.NewServer(mustNewCompressionHandler(t, test.cfg, test.algo, next))
defer srv.Close()
req, err := http.NewRequest(http.MethodGet, srv.URL, http.NoBody)
require.NoError(t, err)
req.Header.Set(acceptEncoding, test.acceptEncoding)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer res.Body.Close()
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, test.acceptEncoding, res.Header.Get(contentEncoding))
reader, err := test.readerBuilder(res.Body)
require.NoError(t, err)
got, err := io.ReadAll(reader)
require.NoError(t, err)
assert.Equal(t, bigTestBody, got)
})
}
}
func Test_FlushAfterWrite(t *testing.T) {
testCases := []struct {
desc string
cfg Config
algo string
readerBuilder func(io.Reader) (io.Reader, error)
acceptEncoding string
}{
{
desc: "brotli",
cfg: Config{MinSize: 1024, MiddlewareName: "Test"},
algo: brotliName,
readerBuilder: func(reader io.Reader) (io.Reader, error) {
return brotli.NewReader(reader), nil
},
acceptEncoding: "br",
},
{
desc: "zstd",
cfg: Config{MinSize: 1024, MiddlewareName: "Test"},
algo: zstdName,
readerBuilder: func(reader io.Reader) (io.Reader, error) {
return zstd.NewReader(reader)
},
acceptEncoding: "zstd",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusOK)
_, err := rw.Write(bigTestBody[0:1])
require.NoError(t, err)
rw.(http.Flusher).Flush()
for _, b := range bigTestBody[1:] {
_, err := rw.Write([]byte{b})
require.NoError(t, err)
}
})
srv := httptest.NewServer(mustNewCompressionHandler(t, test.cfg, test.algo, next))
defer srv.Close()
req, err := http.NewRequest(http.MethodGet, srv.URL, http.NoBody)
require.NoError(t, err)
req.Header.Set(acceptEncoding, test.acceptEncoding)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer res.Body.Close()
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, test.acceptEncoding, res.Header.Get(contentEncoding))
reader, err := test.readerBuilder(res.Body)
require.NoError(t, err)
got, err := io.ReadAll(reader)
require.NoError(t, err)
assert.Equal(t, bigTestBody, got)
})
}
}
func Test_FlushAfterWriteNil(t *testing.T) {
testCases := []struct {
desc string
cfg Config
algo string
readerBuilder func(io.Reader) (io.Reader, error)
acceptEncoding string
}{
{
desc: "brotli",
cfg: Config{MinSize: 1024, MiddlewareName: "Test"},
algo: brotliName,
readerBuilder: func(reader io.Reader) (io.Reader, error) {
return brotli.NewReader(reader), nil
},
acceptEncoding: "br",
},
{
desc: "zstd",
cfg: Config{MinSize: 1024, MiddlewareName: "Test"},
algo: zstdName,
readerBuilder: func(reader io.Reader) (io.Reader, error) {
return zstd.NewReader(reader)
},
acceptEncoding: "zstd",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusOK)
_, err := rw.Write(nil)
require.NoError(t, err)
rw.(http.Flusher).Flush()
})
srv := httptest.NewServer(mustNewCompressionHandler(t, test.cfg, test.algo, next))
defer srv.Close()
req, err := http.NewRequest(http.MethodGet, srv.URL, http.NoBody)
require.NoError(t, err)
req.Header.Set(acceptEncoding, test.acceptEncoding)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer res.Body.Close()
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Empty(t, res.Header.Get(contentEncoding))
reader, err := test.readerBuilder(res.Body)
require.NoError(t, err)
got, err := io.ReadAll(reader)
require.NoError(t, err)
assert.Empty(t, got)
})
}
}
func Test_FlushAfterAllWrites(t *testing.T) {
testCases := []struct {
desc string
cfg Config
algo string
readerBuilder func(io.Reader) (io.Reader, error)
acceptEncoding string
}{
{
desc: "brotli",
cfg: Config{MinSize: 1024, MiddlewareName: "Test"},
algo: brotliName,
readerBuilder: func(reader io.Reader) (io.Reader, error) {
return brotli.NewReader(reader), nil
},
acceptEncoding: "br",
},
{
desc: "zstd",
cfg: Config{MinSize: 1024, MiddlewareName: "Test"},
algo: zstdName,
readerBuilder: func(reader io.Reader) (io.Reader, error) {
return zstd.NewReader(reader)
},
acceptEncoding: "zstd",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
for i := range bigTestBody {
_, err := rw.Write(bigTestBody[i : i+1])
require.NoError(t, err)
}
rw.(http.Flusher).Flush()
})
srv := httptest.NewServer(mustNewCompressionHandler(t, test.cfg, test.algo, next))
defer srv.Close()
req, err := http.NewRequest(http.MethodGet, srv.URL, http.NoBody)
require.NoError(t, err)
req.Header.Set(acceptEncoding, test.acceptEncoding)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer res.Body.Close()
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, test.acceptEncoding, res.Header.Get(contentEncoding))
reader, err := test.readerBuilder(res.Body)
require.NoError(t, err)
got, err := io.ReadAll(reader)
require.NoError(t, err)
assert.Equal(t, bigTestBody, got)
})
}
}
func Test_FlushForceCompress(t *testing.T) {
testCases := []struct {
desc string
cfg Config
algo string
readerBuilder func(io.Reader) (io.Reader, error)
acceptEncoding string
}{
{
desc: "brotli",
cfg: Config{MinSize: 1024, MiddlewareName: "Test"},
algo: brotliName,
readerBuilder: func(reader io.Reader) (io.Reader, error) {
return brotli.NewReader(reader), nil
},
acceptEncoding: "br",
},
{
desc: "zstd",
cfg: Config{MinSize: 1024, MiddlewareName: "Test"},
algo: zstdName,
readerBuilder: func(reader io.Reader) (io.Reader, error) {
return zstd.NewReader(reader)
},
acceptEncoding: "zstd",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusOK)
_, err := rw.Write(smallTestBody)
require.NoError(t, err)
rw.(http.Flusher).Flush()
})
srv := httptest.NewServer(mustNewCompressionHandler(t, test.cfg, test.algo, next))
defer srv.Close()
req, err := http.NewRequest(http.MethodGet, srv.URL, http.NoBody)
require.NoError(t, err)
req.Header.Set(acceptEncoding, test.acceptEncoding)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer res.Body.Close()
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, test.acceptEncoding, res.Header.Get(contentEncoding))
reader, err := test.readerBuilder(res.Body)
require.NoError(t, err)
got, err := io.ReadAll(reader)
require.NoError(t, err)
assert.Equal(t, smallTestBody, got)
})
}
}
func Test_ExcludedContentTypes(t *testing.T) {
testCases := []struct {
desc string
contentType string
excludedContentTypes []string
expCompression bool
}{
{
desc: "Always compress when content types are empty",
contentType: "",
expCompression: true,
},
{
desc: "MIME malformed",
contentType: "application/json;charset=UTF-8;charset=utf-8",
expCompression: false,
},
{
desc: "MIME match",
contentType: "application/json",
excludedContentTypes: []string{"application/json"},
expCompression: false,
},
{
desc: "MIME no match",
contentType: "text/xml",
excludedContentTypes: []string{"application/json"},
expCompression: true,
},
{
desc: "MIME match with no other directive ignores non-MIME directives",
contentType: "application/json; charset=utf-8",
excludedContentTypes: []string{"application/json"},
expCompression: false,
},
{
desc: "MIME match with other directives requires all directives be equal, different charset",
contentType: "application/json; charset=ascii",
excludedContentTypes: []string{"application/json; charset=utf-8"},
expCompression: true,
},
{
desc: "MIME match with other directives requires all directives be equal, same charset",
contentType: "application/json; charset=utf-8",
excludedContentTypes: []string{"application/json; charset=utf-8"},
expCompression: false,
},
{
desc: "MIME match with other directives requires all directives be equal, missing charset",
contentType: "application/json",
excludedContentTypes: []string{"application/json; charset=ascii"},
expCompression: true,
},
{
desc: "MIME match case insensitive",
contentType: "Application/Json",
excludedContentTypes: []string{"application/json"},
expCompression: false,
},
{
desc: "MIME match ignore whitespace",
contentType: "application/json;charset=utf-8",
excludedContentTypes: []string{"application/json; charset=utf-8"},
expCompression: false,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
cfg := Config{
MinSize: 1024,
ExcludedContentTypes: test.excludedContentTypes,
}
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set(contentType, test.contentType)
rw.WriteHeader(http.StatusAccepted)
_, err := rw.Write(bigTestBody)
require.NoError(t, err)
})
h := mustNewCompressionHandler(t, cfg, zstdName, next)
req, _ := http.NewRequest(http.MethodGet, "/whatever", nil)
req.Header.Set(acceptEncoding, zstdName)
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
assert.Equal(t, http.StatusAccepted, rw.Code)
if test.expCompression {
assert.Equal(t, zstdName, rw.Header().Get(contentEncoding))
reader, err := zstd.NewReader(rw.Body)
require.NoError(t, err)
got, err := io.ReadAll(reader)
assert.NoError(t, err)
assert.Equal(t, bigTestBody, got)
} else {
assert.NotEqual(t, zstdName, rw.Header().Get("Content-Encoding"))
got, err := io.ReadAll(rw.Body)
assert.NoError(t, err)
assert.Equal(t, bigTestBody, got)
}
})
}
}
func Test_IncludedContentTypes(t *testing.T) {
testCases := []struct {
desc string
contentType string
includedContentTypes []string
expCompression bool
}{
{
desc: "Always compress when content types are empty",
contentType: "",
expCompression: true,
},
{
desc: "MIME malformed",
contentType: "application/json;charset=UTF-8;charset=utf-8",
expCompression: false,
},
{
desc: "MIME match",
contentType: "application/json",
includedContentTypes: []string{"application/json"},
expCompression: true,
},
{
desc: "MIME no match",
contentType: "text/xml",
includedContentTypes: []string{"application/json"},
expCompression: false,
},
{
desc: "MIME match with no other directive ignores non-MIME directives",
contentType: "application/json; charset=utf-8",
includedContentTypes: []string{"application/json"},
expCompression: true,
},
{
desc: "MIME match with other directives requires all directives be equal, different charset",
contentType: "application/json; charset=ascii",
includedContentTypes: []string{"application/json; charset=utf-8"},
expCompression: false,
},
{
desc: "MIME match with other directives requires all directives be equal, same charset",
contentType: "application/json; charset=utf-8",
includedContentTypes: []string{"application/json; charset=utf-8"},
expCompression: true,
},
{
desc: "MIME match with other directives requires all directives be equal, missing charset",
contentType: "application/json",
includedContentTypes: []string{"application/json; charset=ascii"},
expCompression: false,
},
{
desc: "MIME match case insensitive",
contentType: "Application/Json",
includedContentTypes: []string{"application/json"},
expCompression: true,
},
{
desc: "MIME match ignore whitespace",
contentType: "application/json;charset=utf-8",
includedContentTypes: []string{"application/json; charset=utf-8"},
expCompression: true,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
cfg := Config{
MinSize: 1024,
IncludedContentTypes: test.includedContentTypes,
}
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set(contentType, test.contentType)
rw.WriteHeader(http.StatusAccepted)
_, err := rw.Write(bigTestBody)
require.NoError(t, err)
})
h := mustNewCompressionHandler(t, cfg, zstdName, next)
req, _ := http.NewRequest(http.MethodGet, "/whatever", nil)
req.Header.Set(acceptEncoding, zstdName)
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
assert.Equal(t, http.StatusAccepted, rw.Code)
if test.expCompression {
assert.Equal(t, zstdName, rw.Header().Get(contentEncoding))
reader, err := zstd.NewReader(rw.Body)
require.NoError(t, err)
got, err := io.ReadAll(reader)
assert.NoError(t, err)
assert.Equal(t, bigTestBody, got)
} else {
assert.NotEqual(t, zstdName, rw.Header().Get("Content-Encoding"))
got, err := io.ReadAll(rw.Body)
assert.NoError(t, err)
assert.Equal(t, bigTestBody, got)
}
})
}
}
func Test_FlushExcludedContentTypes(t *testing.T) {
testCases := []struct {
desc string
contentType string
excludedContentTypes []string
expCompression bool
}{
{
desc: "Always compress when content types are empty",
contentType: "",
expCompression: true,
},
{
desc: "MIME match",
contentType: "application/json",
excludedContentTypes: []string{"application/json"},
expCompression: false,
},
{
desc: "MIME no match",
contentType: "text/xml",
excludedContentTypes: []string{"application/json"},
expCompression: true,
},
{
desc: "MIME match with no other directive ignores non-MIME directives",
contentType: "application/json; charset=utf-8",
excludedContentTypes: []string{"application/json"},
expCompression: false,
},
{
desc: "MIME match with other directives requires all directives be equal, different charset",
contentType: "application/json; charset=ascii",
excludedContentTypes: []string{"application/json; charset=utf-8"},
expCompression: true,
},
{
desc: "MIME match with other directives requires all directives be equal, same charset",
contentType: "application/json; charset=utf-8",
excludedContentTypes: []string{"application/json; charset=utf-8"},
expCompression: false,
},
{
desc: "MIME match with other directives requires all directives be equal, missing charset",
contentType: "application/json",
excludedContentTypes: []string{"application/json; charset=ascii"},
expCompression: true,
},
{
desc: "MIME match case insensitive",
contentType: "Application/Json",
excludedContentTypes: []string{"application/json"},
expCompression: false,
},
{
desc: "MIME match ignore whitespace",
contentType: "application/json;charset=utf-8",
excludedContentTypes: []string{"application/json; charset=utf-8"},
expCompression: false,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
cfg := Config{
MinSize: 1024,
ExcludedContentTypes: test.excludedContentTypes,
}
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set(contentType, test.contentType)
rw.WriteHeader(http.StatusOK)
tb := bigTestBody
for len(tb) > 0 {
// Write 100 bytes per run
// Detection should not be affected (we send 100 bytes)
toWrite := 100
if toWrite > len(tb) {
toWrite = len(tb)
}
_, err := rw.Write(tb[:toWrite])
require.NoError(t, err)
// Flush between each write
rw.(http.Flusher).Flush()
tb = tb[toWrite:]
}
})
h := mustNewCompressionHandler(t, cfg, zstdName, next)
req, _ := http.NewRequest(http.MethodGet, "/whatever", nil)
req.Header.Set(acceptEncoding, zstdName)
// This doesn't allow checking flushes, but we validate if content is correct.
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
assert.Equal(t, http.StatusOK, rw.Code)
if test.expCompression {
assert.Equal(t, zstdName, rw.Header().Get(contentEncoding))
reader, err := zstd.NewReader(rw.Body)
require.NoError(t, err)
got, err := io.ReadAll(reader)
assert.NoError(t, err)
assert.Equal(t, bigTestBody, got)
} else {
assert.NotEqual(t, zstdName, rw.Header().Get(contentEncoding))
got, err := io.ReadAll(rw.Body)
assert.NoError(t, err)
assert.Equal(t, bigTestBody, got)
}
})
}
}
func Test_FlushIncludedContentTypes(t *testing.T) {
testCases := []struct {
desc string
contentType string
includedContentTypes []string
expCompression bool
}{
{
desc: "Always compress when content types are empty",
contentType: "",
expCompression: true,
},
{
desc: "MIME match",
contentType: "application/json",
includedContentTypes: []string{"application/json"},
expCompression: true,
},
{
desc: "MIME no match",
contentType: "text/xml",
includedContentTypes: []string{"application/json"},
expCompression: false,
},
{
desc: "MIME match with no other directive ignores non-MIME directives",
contentType: "application/json; charset=utf-8",
includedContentTypes: []string{"application/json"},
expCompression: true,
},
{
desc: "MIME match with other directives requires all directives be equal, different charset",
contentType: "application/json; charset=ascii",
includedContentTypes: []string{"application/json; charset=utf-8"},
expCompression: false,
},
{
desc: "MIME match with other directives requires all directives be equal, same charset",
contentType: "application/json; charset=utf-8",
includedContentTypes: []string{"application/json; charset=utf-8"},
expCompression: true,
},
{
desc: "MIME match with other directives requires all directives be equal, missing charset",
contentType: "application/json",
includedContentTypes: []string{"application/json; charset=ascii"},
expCompression: false,
},
{
desc: "MIME match case insensitive",
contentType: "Application/Json",
includedContentTypes: []string{"application/json"},
expCompression: true,
},
{
desc: "MIME match ignore whitespace",
contentType: "application/json;charset=utf-8",
includedContentTypes: []string{"application/json; charset=utf-8"},
expCompression: true,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
cfg := Config{
MinSize: 1024,
IncludedContentTypes: test.includedContentTypes,
}
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set(contentType, test.contentType)
rw.WriteHeader(http.StatusOK)
tb := bigTestBody
for len(tb) > 0 {
// Write 100 bytes per run
// Detection should not be affected (we send 100 bytes)
toWrite := 100
if toWrite > len(tb) {
toWrite = len(tb)
}
_, err := rw.Write(tb[:toWrite])
require.NoError(t, err)
// Flush between each write
rw.(http.Flusher).Flush()
tb = tb[toWrite:]
}
})
h := mustNewCompressionHandler(t, cfg, zstdName, next)
req, _ := http.NewRequest(http.MethodGet, "/whatever", nil)
req.Header.Set(acceptEncoding, zstdName)
// This doesn't allow checking flushes, but we validate if content is correct.
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
assert.Equal(t, http.StatusOK, rw.Code)
if test.expCompression {
assert.Equal(t, zstdName, rw.Header().Get(contentEncoding))
reader, err := zstd.NewReader(rw.Body)
require.NoError(t, err)
got, err := io.ReadAll(reader)
assert.NoError(t, err)
assert.Equal(t, bigTestBody, got)
} else {
assert.NotEqual(t, zstdName, rw.Header().Get(contentEncoding))
got, err := io.ReadAll(rw.Body)
assert.NoError(t, err)
assert.Equal(t, bigTestBody, got)
}
})
}
}
func mustNewCompressionHandler(t *testing.T, cfg Config, algo string, next http.Handler) http.Handler {
t.Helper()
var writer NewCompressionWriter
switch algo {
case zstdName:
writer = func(rw http.ResponseWriter) (CompressionWriter, string, error) {
writer, err := zstd.NewWriter(rw)
require.NoError(t, err)
return writer, zstdName, nil
}
case brotliName:
writer = func(rw http.ResponseWriter) (CompressionWriter, string, error) {
return brotli.NewWriter(rw), brotliName, nil
}
default:
assert.Failf(t, "unknown compression algorithm: %s", algo)
}
w, err := NewCompressionHandler(cfg, writer, next)
require.NoError(t, err)
return w
}
func newTestBrotliHandler(t *testing.T, body []byte) http.Handler {
t.Helper()
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/compressed" {
rw.Header().Set("Content-Encoding", brotliName)
}
rw.WriteHeader(http.StatusAccepted)
_, err := rw.Write(body)
require.NoError(t, err)
})
return mustNewCompressionHandler(t, Config{MinSize: 1024, MiddlewareName: "Compress"}, brotliName, next)
}
func newTestZstandardHandler(t *testing.T, body []byte) http.Handler {
t.Helper()
next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/compressed" {
rw.Header().Set("Content-Encoding", zstdName)
}
rw.WriteHeader(http.StatusAccepted)
_, err := rw.Write(body)
require.NoError(t, err)
})
return mustNewCompressionHandler(t, Config{MinSize: 1024, MiddlewareName: "Compress"}, zstdName, next)
}
func Test_ParseContentType_equals(t *testing.T) {
testCases := []struct {
desc string
pct parsedContentType
mediaType string
params map[string]string
expect assert.BoolAssertionFunc
}{
{
desc: "empty parsed content type",
expect: assert.True,
},
{
desc: "simple content type",
pct: parsedContentType{
mediaType: "plain/text",
},
mediaType: "plain/text",
expect: assert.True,
},
{
desc: "content type with params",
pct: parsedContentType{
mediaType: "plain/text",
params: map[string]string{
"charset": "utf8",
},
},
mediaType: "plain/text",
params: map[string]string{
"charset": "utf8",
},
expect: assert.True,
},
{
desc: "different content type",
pct: parsedContentType{
mediaType: "plain/text",
},
mediaType: "application/json",
expect: assert.False,
},
{
desc: "content type with params",
pct: parsedContentType{
mediaType: "plain/text",
params: map[string]string{
"charset": "utf8",
},
},
mediaType: "plain/text",
params: map[string]string{
"charset": "latin-1",
},
expect: assert.False,
},
{
desc: "different number of parameters",
pct: parsedContentType{
mediaType: "plain/text",
params: map[string]string{
"charset": "utf8",
},
},
mediaType: "plain/text",
params: map[string]string{
"charset": "utf8",
"q": "0.8",
},
expect: assert.False,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
test.expect(t, test.pct.equals(test.mediaType, test.params))
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/compress/compress_test.go | pkg/middlewares/compress/compress_test.go | package compress
import (
"compress/gzip"
"io"
"net/http"
"net/http/httptest"
"net/http/httptrace"
"net/textproto"
"testing"
"github.com/klauspost/compress/gzhttp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/testhelpers"
)
const (
contentEncodingHeader = "Content-Encoding"
contentTypeHeader = "Content-Type"
varyHeader = "Vary"
)
func TestNegotiation(t *testing.T) {
testCases := []struct {
desc string
acceptEncHeader string
expEncoding string
}{
{
desc: "no accept header",
expEncoding: "",
},
{
desc: "unsupported accept header",
acceptEncHeader: "notreal",
expEncoding: "",
},
{
// In this test, the default encodings are defaulted to gzip, brotli, and zstd,
// which make gzip the default encoding, and will be selected.
// However, the klauspost/compress gzhttp handler does not compress when Accept-Encoding: * is set.
// Until klauspost/compress gzhttp package supports the asterisk,
// we will not support it when selecting the gzip encoding.
desc: "accept any header",
acceptEncHeader: "*",
expEncoding: "",
},
{
desc: "gzip accept header",
acceptEncHeader: "gzip",
expEncoding: gzipName,
},
{
desc: "br accept header",
acceptEncHeader: "br",
expEncoding: brotliName,
},
{
desc: "multi accept header, prefer br",
acceptEncHeader: "br;q=0.8, gzip;q=0.6",
expEncoding: brotliName,
},
{
desc: "multi accept header, prefer gzip",
acceptEncHeader: "gzip;q=1.0, br;q=0.8",
expEncoding: gzipName,
},
{
desc: "multi accept header list, prefer br",
acceptEncHeader: "gzip, br",
expEncoding: gzipName,
},
{
desc: "zstd accept header",
acceptEncHeader: "zstd",
expEncoding: zstdName,
},
{
desc: "multi accept header, prefer zstd",
acceptEncHeader: "zstd;q=0.9, br;q=0.8, gzip;q=0.6",
expEncoding: zstdName,
},
{
desc: "multi accept header, prefer brotli",
acceptEncHeader: "gzip;q=0.8, br;q=1.0, zstd;q=0.7",
expEncoding: brotliName,
},
{
desc: "multi accept header, prefer gzip",
acceptEncHeader: "gzip;q=1.0, br;q=0.8, zstd;q=0.7",
expEncoding: gzipName,
},
{
desc: "multi accept header list, prefer gzip",
acceptEncHeader: "gzip, br, zstd",
expEncoding: gzipName,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost", nil)
if test.acceptEncHeader != "" {
req.Header.Add(acceptEncodingHeader, test.acceptEncHeader)
}
next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
_, _ = rw.Write(generateBytes(10))
})
cfg := dynamic.Compress{
MinResponseBodyBytes: 1,
Encodings: defaultSupportedEncodings,
}
handler, err := New(t.Context(), next, cfg, "testing")
require.NoError(t, err)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, req)
assert.Equal(t, test.expEncoding, rw.Header().Get(contentEncodingHeader))
})
}
}
func TestShouldCompressWhenNoContentEncodingHeader(t *testing.T) {
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost", nil)
req.Header.Add(acceptEncodingHeader, gzipName)
baseBody := generateBytes(gzhttp.DefaultMinSize)
next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
_, err := rw.Write(baseBody)
assert.NoError(t, err)
})
handler, err := New(t.Context(), next, dynamic.Compress{Encodings: defaultSupportedEncodings}, "testing")
require.NoError(t, err)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, req)
assert.Equal(t, gzipName, rw.Header().Get(contentEncodingHeader))
assert.Equal(t, acceptEncodingHeader, rw.Header().Get(varyHeader))
gr, err := gzip.NewReader(rw.Body)
require.NoError(t, err)
got, err := io.ReadAll(gr)
require.NoError(t, err)
assert.Equal(t, got, baseBody)
}
func TestShouldNotCompressWhenContentEncodingHeader(t *testing.T) {
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost", nil)
req.Header.Add(acceptEncodingHeader, gzipName)
fakeCompressedBody := generateBytes(gzhttp.DefaultMinSize)
next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Add(contentEncodingHeader, gzipName)
rw.Header().Add(varyHeader, acceptEncodingHeader)
_, err := rw.Write(fakeCompressedBody)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
})
handler, err := New(t.Context(), next, dynamic.Compress{Encodings: defaultSupportedEncodings}, "testing")
require.NoError(t, err)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, req)
assert.Equal(t, gzipName, rw.Header().Get(contentEncodingHeader))
assert.Equal(t, acceptEncodingHeader, rw.Header().Get(varyHeader))
assert.Equal(t, rw.Body.Bytes(), fakeCompressedBody)
}
func TestShouldNotCompressWhenNoAcceptEncodingHeader(t *testing.T) {
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost", nil)
fakeBody := generateBytes(gzhttp.DefaultMinSize)
next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
_, err := rw.Write(fakeBody)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
})
handler, err := New(t.Context(), next, dynamic.Compress{Encodings: defaultSupportedEncodings}, "testing")
require.NoError(t, err)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, req)
assert.Empty(t, rw.Header().Get(contentEncodingHeader))
assert.Empty(t, rw.Header().Get(varyHeader))
assert.Equal(t, rw.Body.Bytes(), fakeBody)
}
func TestEmptyAcceptEncoding(t *testing.T) {
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost", nil)
req.Header.Add(acceptEncodingHeader, "")
fakeBody := generateBytes(gzhttp.DefaultMinSize)
next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
_, err := rw.Write(fakeBody)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
})
handler, err := New(t.Context(), next, dynamic.Compress{Encodings: defaultSupportedEncodings}, "testing")
require.NoError(t, err)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, req)
assert.Empty(t, rw.Header().Get(contentEncodingHeader))
assert.Empty(t, rw.Header().Get(varyHeader))
assert.Equal(t, rw.Body.Bytes(), fakeBody)
}
func TestShouldNotCompressWhenIdentityAcceptEncodingHeader(t *testing.T) {
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost", nil)
req.Header.Set(acceptEncodingHeader, "identity")
fakeBody := generateBytes(gzhttp.DefaultMinSize)
next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if r.Header.Get(acceptEncodingHeader) != "identity" {
http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
_, err := rw.Write(fakeBody)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
})
handler, err := New(t.Context(), next, dynamic.Compress{Encodings: defaultSupportedEncodings}, "testing")
require.NoError(t, err)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, req)
assert.Empty(t, rw.Header().Get(contentEncodingHeader))
assert.Empty(t, rw.Header().Get(varyHeader))
assert.Equal(t, rw.Body.Bytes(), fakeBody)
}
func TestShouldNotCompressWhenEmptyAcceptEncodingHeader(t *testing.T) {
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost", nil)
req.Header.Set(acceptEncodingHeader, "")
fakeBody := generateBytes(gzhttp.DefaultMinSize)
next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if r.Header.Get(acceptEncodingHeader) != "" {
http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
_, err := rw.Write(fakeBody)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
})
handler, err := New(t.Context(), next, dynamic.Compress{Encodings: defaultSupportedEncodings}, "testing")
require.NoError(t, err)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, req)
assert.Empty(t, rw.Header().Get(contentEncodingHeader))
assert.Empty(t, rw.Header().Get(varyHeader))
assert.Equal(t, rw.Body.Bytes(), fakeBody)
}
func TestShouldNotCompressHeadRequest(t *testing.T) {
req := testhelpers.MustNewRequest(http.MethodHead, "http://localhost", nil)
req.Header.Add(acceptEncodingHeader, gzipName)
fakeBody := generateBytes(gzhttp.DefaultMinSize)
next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
_, err := rw.Write(fakeBody)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
})
handler, err := New(t.Context(), next, dynamic.Compress{Encodings: defaultSupportedEncodings}, "testing")
require.NoError(t, err)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, req)
assert.Empty(t, rw.Header().Get(contentEncodingHeader))
assert.Empty(t, rw.Header().Get(varyHeader))
assert.Equal(t, rw.Body.Bytes(), fakeBody)
}
func TestShouldNotCompressWhenSpecificContentType(t *testing.T) {
baseBody := generateBytes(gzhttp.DefaultMinSize)
testCases := []struct {
desc string
conf dynamic.Compress
reqContentType string
respContentType string
}{
{
desc: "Exclude Request Content-Type",
conf: dynamic.Compress{
Encodings: defaultSupportedEncodings,
ExcludedContentTypes: []string{"text/event-stream"},
},
reqContentType: "text/event-stream",
},
{
desc: "Exclude Response Content-Type",
conf: dynamic.Compress{
Encodings: defaultSupportedEncodings,
ExcludedContentTypes: []string{"text/event-stream"},
},
respContentType: "text/event-stream",
},
{
desc: "Include Response Content-Type",
conf: dynamic.Compress{
Encodings: defaultSupportedEncodings,
IncludedContentTypes: []string{"text/plain"},
},
respContentType: "text/html",
},
{
desc: "Ignoring application/grpc with exclude option",
conf: dynamic.Compress{
Encodings: defaultSupportedEncodings,
ExcludedContentTypes: []string{"application/json"},
},
reqContentType: "application/grpc",
},
{
desc: "Ignoring application/grpc with include option",
conf: dynamic.Compress{
Encodings: defaultSupportedEncodings,
IncludedContentTypes: []string{"application/json"},
},
reqContentType: "application/grpc",
},
{
desc: "Ignoring application/grpc with no option",
conf: dynamic.Compress{
Encodings: defaultSupportedEncodings,
},
reqContentType: "application/grpc",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost", nil)
req.Header.Add(acceptEncodingHeader, gzipName)
if test.reqContentType != "" {
req.Header.Add(contentTypeHeader, test.reqContentType)
}
next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if len(test.respContentType) > 0 {
rw.Header().Set(contentTypeHeader, test.respContentType)
}
_, err := rw.Write(baseBody)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
})
handler, err := New(t.Context(), next, test.conf, "test")
require.NoError(t, err)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, req)
assert.Empty(t, rw.Header().Get(acceptEncodingHeader))
assert.Empty(t, rw.Header().Get(contentEncodingHeader))
assert.Equal(t, rw.Body.Bytes(), baseBody)
})
}
}
func TestShouldCompressWhenSpecificContentType(t *testing.T) {
baseBody := generateBytes(gzhttp.DefaultMinSize)
testCases := []struct {
desc string
conf dynamic.Compress
respContentType string
}{
{
desc: "Include Response Content-Type",
conf: dynamic.Compress{
Encodings: defaultSupportedEncodings,
IncludedContentTypes: []string{"text/html"},
},
respContentType: "text/html",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost", nil)
req.Header.Add(acceptEncodingHeader, gzipName)
next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set(contentTypeHeader, test.respContentType)
if _, err := rw.Write(baseBody); err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
})
handler, err := New(t.Context(), next, test.conf, "test")
require.NoError(t, err)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, req)
assert.Equal(t, gzipName, rw.Header().Get(contentEncodingHeader))
assert.Equal(t, acceptEncodingHeader, rw.Header().Get(varyHeader))
assert.NotEqual(t, rw.Body.Bytes(), baseBody)
})
}
}
func TestIntegrationShouldNotCompress(t *testing.T) {
fakeCompressedBody := generateBytes(100000)
testCases := []struct {
name string
handler http.Handler
expectedStatusCode int
}{
{
name: "when content already compressed",
handler: http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Add(contentEncodingHeader, gzipName)
rw.Header().Add(varyHeader, acceptEncodingHeader)
_, err := rw.Write(fakeCompressedBody)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
}),
expectedStatusCode: http.StatusOK,
},
{
name: "when content already compressed and status code Created",
handler: http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Add(contentEncodingHeader, gzipName)
rw.Header().Add(varyHeader, acceptEncodingHeader)
rw.WriteHeader(http.StatusCreated)
_, err := rw.Write(fakeCompressedBody)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
}),
expectedStatusCode: http.StatusCreated,
},
}
for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
compress, err := New(t.Context(), test.handler, dynamic.Compress{Encodings: defaultSupportedEncodings}, "testing")
require.NoError(t, err)
ts := httptest.NewServer(compress)
defer ts.Close()
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
req.Header.Add(acceptEncodingHeader, gzipName)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, test.expectedStatusCode, resp.StatusCode)
assert.Equal(t, gzipName, resp.Header.Get(contentEncodingHeader))
assert.Equal(t, acceptEncodingHeader, resp.Header.Get(varyHeader))
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, fakeCompressedBody, body)
})
}
}
func TestShouldWriteHeaderWhenFlush(t *testing.T) {
next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Add(contentEncodingHeader, gzipName)
rw.Header().Add(varyHeader, acceptEncodingHeader)
rw.WriteHeader(http.StatusUnauthorized)
rw.(http.Flusher).Flush()
_, err := rw.Write([]byte("short"))
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
})
handler, err := New(t.Context(), next, dynamic.Compress{Encodings: defaultSupportedEncodings}, "testing")
require.NoError(t, err)
ts := httptest.NewServer(handler)
defer ts.Close()
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
req.Header.Add(acceptEncodingHeader, gzipName)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusUnauthorized, resp.StatusCode)
assert.Equal(t, gzipName, resp.Header.Get(contentEncodingHeader))
assert.Equal(t, acceptEncodingHeader, resp.Header.Get(varyHeader))
}
func TestIntegrationShouldCompress(t *testing.T) {
fakeBody := generateBytes(100000)
testCases := []struct {
name string
handler http.Handler
expectedStatusCode int
}{
{
name: "when AcceptEncoding header is present",
handler: http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
_, err := rw.Write(fakeBody)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
}),
expectedStatusCode: http.StatusOK,
},
{
name: "when AcceptEncoding header is present and status code Created",
handler: http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.WriteHeader(http.StatusCreated)
_, err := rw.Write(fakeBody)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
}),
expectedStatusCode: http.StatusCreated,
},
}
for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
compress, err := New(t.Context(), test.handler, dynamic.Compress{Encodings: defaultSupportedEncodings}, "testing")
require.NoError(t, err)
ts := httptest.NewServer(compress)
defer ts.Close()
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
req.Header.Add(acceptEncodingHeader, gzipName)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, test.expectedStatusCode, resp.StatusCode)
assert.Equal(t, gzipName, resp.Header.Get(contentEncodingHeader))
assert.Equal(t, acceptEncodingHeader, resp.Header.Get(varyHeader))
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
if assert.ObjectsAreEqualValues(body, fakeBody) {
assert.Fail(t, "expected a compressed body", "got %v", body)
}
})
}
}
func TestMinResponseBodyBytes(t *testing.T) {
fakeBody := generateBytes(100000)
testCases := []struct {
name string
minResponseBodyBytes int
expectedCompression bool
}{
{
name: "should compress",
expectedCompression: true,
},
{
name: "should not compress",
minResponseBodyBytes: 100001,
},
}
for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost", nil)
req.Header.Add(acceptEncodingHeader, gzipName)
next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if _, err := rw.Write(fakeBody); err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
})
cfg := dynamic.Compress{
MinResponseBodyBytes: test.minResponseBodyBytes,
Encodings: defaultSupportedEncodings,
}
handler, err := New(t.Context(), next, cfg, "testing")
require.NoError(t, err)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, req)
if test.expectedCompression {
assert.Equal(t, gzipName, rw.Header().Get(contentEncodingHeader))
assert.NotEqual(t, rw.Body.Bytes(), fakeBody)
return
}
assert.Empty(t, rw.Header().Get(contentEncodingHeader))
assert.Equal(t, rw.Body.Bytes(), fakeBody)
})
}
}
// This test is an adapted version of net/http/httputil.Test1xxResponses test.
func Test1xxResponses(t *testing.T) {
fakeBody := generateBytes(100000)
testCases := []struct {
desc string
encoding string
}{
{
desc: "gzip",
encoding: gzipName,
},
{
desc: "brotli",
encoding: brotliName,
},
{
desc: "zstd",
encoding: zstdName,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
next := 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)
if _, err := w.Write(fakeBody); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
cfg := dynamic.Compress{
MinResponseBodyBytes: 1024,
Encodings: defaultSupportedEncodings,
}
compress, err := New(t.Context(), next, cfg, "testing")
require.NoError(t, err)
server := httptest.NewServer(compress)
t.Cleanup(server.Close)
frontendClient := server.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, server.URL, nil)
req.Header.Add(acceptEncodingHeader, test.encoding)
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"])
assert.Equal(t, test.encoding, res.Header.Get(contentEncodingHeader))
body, _ := io.ReadAll(res.Body)
assert.NotEqual(t, body, fakeBody)
})
}
}
func BenchmarkCompressGzip(b *testing.B) {
runCompressionBenchmark(b, gzipName)
}
func BenchmarkCompressBrotli(b *testing.B) {
runCompressionBenchmark(b, brotliName)
}
func BenchmarkCompressZstandard(b *testing.B) {
runCompressionBenchmark(b, zstdName)
}
func runCompressionBenchmark(b *testing.B, algorithm string) {
b.Helper()
testCases := []struct {
name string
parallel bool
size int
}{
{"2k", false, 2048},
{"20k", false, 20480},
{"100k", false, 102400},
{"2k parallel", true, 2048},
{"20k parallel", true, 20480},
{"100k parallel", true, 102400},
}
for _, test := range testCases {
b.Run(test.name, func(b *testing.B) {
baseBody := generateBytes(test.size)
next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
_, err := rw.Write(baseBody)
assert.NoError(b, err)
})
handler, _ := New(b.Context(), next, dynamic.Compress{}, "testing")
req, _ := http.NewRequest(http.MethodGet, "/whatever", nil)
req.Header.Set("Accept-Encoding", algorithm)
b.ReportAllocs()
b.SetBytes(int64(test.size))
if test.parallel {
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
runBenchmark(b, req, handler, algorithm)
}
})
return
}
b.ResetTimer()
for range b.N {
runBenchmark(b, req, handler, algorithm)
}
})
}
}
func runBenchmark(b *testing.B, req *http.Request, handler http.Handler, algorithm string) {
b.Helper()
res := httptest.NewRecorder()
handler.ServeHTTP(res, req)
if code := res.Code; code != 200 {
b.Fatalf("Expected 200 but got %d", code)
}
assert.Equal(b, algorithm, res.Header().Get(contentEncodingHeader))
}
func generateBytes(length int) []byte {
var value []byte
for i := range length {
value = append(value, 0x61+byte(i))
}
return value
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/ipallowlist/ip_allowlist_test.go | pkg/middlewares/ipallowlist/ip_allowlist_test.go | package ipallowlist
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 TestNewIPAllowLister(t *testing.T) {
testCases := []struct {
desc string
allowList dynamic.IPAllowList
expectedError bool
}{
{
desc: "invalid IP",
allowList: dynamic.IPAllowList{
SourceRange: []string{"foo"},
},
expectedError: true,
},
{
desc: "valid IP",
allowList: dynamic.IPAllowList{
SourceRange: []string{"10.10.10.10"},
},
},
{
desc: "invalid HTTP status code",
allowList: dynamic.IPAllowList{
SourceRange: []string{"10.10.10.10"},
RejectStatusCode: 600,
},
expectedError: true,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
allowLister, err := New(t.Context(), next, test.allowList, "traefikTest")
if test.expectedError {
assert.Error(t, err)
} else {
require.NoError(t, err)
assert.NotNil(t, allowLister)
}
})
}
}
func TestIPAllowLister_ServeHTTP(t *testing.T) {
testCases := []struct {
desc string
allowList dynamic.IPAllowList
remoteAddr string
expected int
}{
{
desc: "authorized with remote address",
allowList: dynamic.IPAllowList{
SourceRange: []string{"20.20.20.20"},
},
remoteAddr: "20.20.20.20:1234",
expected: 200,
},
{
desc: "non authorized with remote address",
allowList: dynamic.IPAllowList{
SourceRange: []string{"20.20.20.20"},
},
remoteAddr: "20.20.20.21:1234",
expected: 403,
},
{
desc: "authorized with remote address, reject 404",
allowList: dynamic.IPAllowList{
SourceRange: []string{"20.20.20.20"},
RejectStatusCode: 404,
},
remoteAddr: "20.20.20.20:1234",
expected: 200,
},
{
desc: "non authorized with remote address, reject 404",
allowList: dynamic.IPAllowList{
SourceRange: []string{"20.20.20.20"},
RejectStatusCode: 404,
},
remoteAddr: "20.20.20.21:1234",
expected: 404,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
allowLister, err := New(t.Context(), next, test.allowList, "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
}
allowLister.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/ipallowlist/ip_allowlist.go | pkg/middlewares/ipallowlist/ip_allowlist.go | package ipallowlist
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 = "IPAllowLister"
)
// ipAllowLister is a middleware that provides Checks of the Requesting IP against a set of Allowlists.
type ipAllowLister struct {
next http.Handler
allowLister *ip.Checker
strategy ip.Strategy
name string
rejectStatusCode int
}
// New builds a new IPAllowLister given a list of CIDR-Strings to allow.
func New(ctx context.Context, next http.Handler, config dynamic.IPAllowList, 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, IPAllowLister not created")
}
rejectStatusCode := config.RejectStatusCode
// If RejectStatusCode is not given, default to Forbidden (403).
if rejectStatusCode == 0 {
rejectStatusCode = http.StatusForbidden
} else if http.StatusText(rejectStatusCode) == "" {
return nil, fmt.Errorf("invalid HTTP status code %d", rejectStatusCode)
}
checker, err := ip.NewChecker(config.SourceRange)
if err != nil {
return nil, fmt.Errorf("cannot parse CIDRs %s: %w", config.SourceRange, err)
}
strategy, err := config.IPStrategy.Get()
if err != nil {
return nil, err
}
logger.Debug().Msgf("Setting up IPAllowLister with sourceRange: %s", config.SourceRange)
return &ipAllowLister{
strategy: strategy,
allowLister: checker,
next: next,
name: name,
rejectStatusCode: rejectStatusCode,
}, nil
}
func (al *ipAllowLister) GetTracingInformation() (string, string) {
return al.name, typeName
}
func (al *ipAllowLister) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
logger := middlewares.GetLogger(req.Context(), al.name, typeName)
ctx := logger.WithContext(req.Context())
clientIP := al.strategy.GetIP(req)
err := al.allowLister.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, al.rejectStatusCode, rw)
return
}
logger.Debug().Msgf("Accepting IP %s", clientIP)
al.next.ServeHTTP(rw, req)
}
func reject(ctx context.Context, statusCode int, rw http.ResponseWriter) {
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/passtlsclientcert/pass_tls_client_cert.go | pkg/middlewares/passtlsclientcert/pass_tls_client_cert.go | package passtlsclientcert
import (
"context"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/rs/zerolog/log"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
)
const typeName = "PassClientTLSCert"
const (
xForwardedTLSClientCert = "X-Forwarded-Tls-Client-Cert"
xForwardedTLSClientCertInfo = "X-Forwarded-Tls-Client-Cert-Info"
)
const (
certSeparator = ","
fieldSeparator = ";"
subFieldSeparator = ","
)
var attributeTypeNames = map[string]string{
"0.9.2342.19200300.100.1.25": "DC", // Domain component OID - RFC 2247
}
// IssuerDistinguishedNameOptions is a struct for specifying the configuration
// for the distinguished name info of the issuer. This information is defined in
// RFC3739, section 3.1.1.
type IssuerDistinguishedNameOptions struct {
CommonName bool
CountryName bool
DomainComponent bool
LocalityName bool
OrganizationName bool
SerialNumber bool
StateOrProvinceName bool
}
func newIssuerDistinguishedNameOptions(info *dynamic.TLSClientCertificateIssuerDNInfo) *IssuerDistinguishedNameOptions {
if info == nil {
return nil
}
return &IssuerDistinguishedNameOptions{
CommonName: info.CommonName,
CountryName: info.Country,
DomainComponent: info.DomainComponent,
LocalityName: info.Locality,
OrganizationName: info.Organization,
SerialNumber: info.SerialNumber,
StateOrProvinceName: info.Province,
}
}
// SubjectDistinguishedNameOptions is a struct for specifying the configuration
// for the distinguished name info of the subject. This information is defined
// in RFC3739, section 3.1.2.
type SubjectDistinguishedNameOptions struct {
CommonName bool
CountryName bool
DomainComponent bool
LocalityName bool
OrganizationName bool
OrganizationalUnitName bool
SerialNumber bool
StateOrProvinceName bool
}
func newSubjectDistinguishedNameOptions(info *dynamic.TLSClientCertificateSubjectDNInfo) *SubjectDistinguishedNameOptions {
if info == nil {
return nil
}
return &SubjectDistinguishedNameOptions{
CommonName: info.CommonName,
CountryName: info.Country,
DomainComponent: info.DomainComponent,
LocalityName: info.Locality,
OrganizationName: info.Organization,
OrganizationalUnitName: info.OrganizationalUnit,
SerialNumber: info.SerialNumber,
StateOrProvinceName: info.Province,
}
}
// tlsClientCertificateInfo is a struct for specifying the configuration for the passTLSClientCert middleware.
type tlsClientCertificateInfo struct {
notAfter bool
notBefore bool
sans bool
subject *SubjectDistinguishedNameOptions
issuer *IssuerDistinguishedNameOptions
serialNumber bool
}
func newTLSClientCertificateInfo(info *dynamic.TLSClientCertificateInfo) *tlsClientCertificateInfo {
if info == nil {
return nil
}
return &tlsClientCertificateInfo{
issuer: newIssuerDistinguishedNameOptions(info.Issuer),
notAfter: info.NotAfter,
notBefore: info.NotBefore,
subject: newSubjectDistinguishedNameOptions(info.Subject),
serialNumber: info.SerialNumber,
sans: info.Sans,
}
}
// passTLSClientCert is a middleware that helps setup a few tls info features.
type passTLSClientCert struct {
next http.Handler
name string
pem bool // pass the sanitized pem to the backend in a specific header
info *tlsClientCertificateInfo // pass selected information from the client certificate
}
// New constructs a new PassTLSClientCert instance from supplied frontend header struct.
func New(ctx context.Context, next http.Handler, config dynamic.PassTLSClientCert, name string) (http.Handler, error) {
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
return &passTLSClientCert{
next: next,
name: name,
pem: config.PEM,
info: newTLSClientCertificateInfo(config.Info),
}, nil
}
func (p *passTLSClientCert) GetTracingInformation() (string, string) {
return p.name, typeName
}
func (p *passTLSClientCert) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
logger := middlewares.GetLogger(req.Context(), p.name, typeName)
ctx := logger.WithContext(req.Context())
if p.pem {
if req.TLS != nil && len(req.TLS.PeerCertificates) > 0 {
req.Header.Set(xForwardedTLSClientCert, getCertificates(ctx, req.TLS.PeerCertificates))
} else {
logger.Debug().Msg("Tried to extract a certificate on a request without mutual TLS")
}
}
if p.info != nil {
if req.TLS != nil && len(req.TLS.PeerCertificates) > 0 {
headerContent := p.getCertInfo(ctx, req.TLS.PeerCertificates)
req.Header.Set(xForwardedTLSClientCertInfo, url.QueryEscape(headerContent))
} else {
logger.Debug().Msg("Tried to extract a certificate on a request without mutual TLS")
}
}
p.next.ServeHTTP(rw, req)
}
// getCertInfo Build a string with the wanted client certificates information
// - the `,` is used to separate certificates
// - the `;` is used to separate root fields
// - the value of root fields is always wrapped by double quote
// - if a field is empty, the field is ignored.
func (p *passTLSClientCert) getCertInfo(ctx context.Context, certs []*x509.Certificate) string {
var headerValues []string
for _, peerCert := range certs {
var values []string
if p.info != nil {
subject := getSubjectDNInfo(ctx, p.info.subject, &peerCert.Subject)
if subject != "" {
values = append(values, fmt.Sprintf(`Subject="%s"`, strings.TrimSuffix(subject, subFieldSeparator)))
}
issuer := getIssuerDNInfo(ctx, p.info.issuer, &peerCert.Issuer)
if issuer != "" {
values = append(values, fmt.Sprintf(`Issuer="%s"`, strings.TrimSuffix(issuer, subFieldSeparator)))
}
if p.info.serialNumber && peerCert.SerialNumber != nil {
sn := peerCert.SerialNumber.String()
if sn != "" {
values = append(values, fmt.Sprintf(`SerialNumber="%s"`, strings.TrimSuffix(sn, subFieldSeparator)))
}
}
if p.info.notBefore {
values = append(values, fmt.Sprintf(`NB="%d"`, uint64(peerCert.NotBefore.Unix())))
}
if p.info.notAfter {
values = append(values, fmt.Sprintf(`NA="%d"`, uint64(peerCert.NotAfter.Unix())))
}
if p.info.sans {
sans := getSANs(peerCert)
if len(sans) > 0 {
values = append(values, fmt.Sprintf(`SAN="%s"`, strings.Join(sans, subFieldSeparator)))
}
}
}
value := strings.Join(values, fieldSeparator)
headerValues = append(headerValues, value)
}
return strings.Join(headerValues, certSeparator)
}
func getIssuerDNInfo(ctx context.Context, options *IssuerDistinguishedNameOptions, cs *pkix.Name) string {
if options == nil {
return ""
}
content := &strings.Builder{}
// Manage non-standard attributes
for _, name := range cs.Names {
// Domain Component - RFC 2247
if options.DomainComponent && attributeTypeNames[name.Type.String()] == "DC" {
_, _ = fmt.Fprintf(content, "DC=%s%s", name.Value, subFieldSeparator)
}
}
if options.CountryName {
writeParts(ctx, content, cs.Country, "C")
}
if options.StateOrProvinceName {
writeParts(ctx, content, cs.Province, "ST")
}
if options.LocalityName {
writeParts(ctx, content, cs.Locality, "L")
}
if options.OrganizationName {
writeParts(ctx, content, cs.Organization, "O")
}
if options.SerialNumber {
writePart(ctx, content, cs.SerialNumber, "SN")
}
if options.CommonName {
writePart(ctx, content, cs.CommonName, "CN")
}
return content.String()
}
func getSubjectDNInfo(ctx context.Context, options *SubjectDistinguishedNameOptions, cs *pkix.Name) string {
if options == nil {
return ""
}
content := &strings.Builder{}
// Manage non standard attributes
for _, name := range cs.Names {
// Domain Component - RFC 2247
if options.DomainComponent && attributeTypeNames[name.Type.String()] == "DC" {
_, _ = fmt.Fprintf(content, "DC=%s%s", name.Value, subFieldSeparator)
}
}
if options.CountryName {
writeParts(ctx, content, cs.Country, "C")
}
if options.StateOrProvinceName {
writeParts(ctx, content, cs.Province, "ST")
}
if options.LocalityName {
writeParts(ctx, content, cs.Locality, "L")
}
if options.OrganizationName {
writeParts(ctx, content, cs.Organization, "O")
}
if options.OrganizationalUnitName {
writeParts(ctx, content, cs.OrganizationalUnit, "OU")
}
if options.SerialNumber {
writePart(ctx, content, cs.SerialNumber, "SN")
}
if options.CommonName {
writePart(ctx, content, cs.CommonName, "CN")
}
return content.String()
}
func writeParts(ctx context.Context, content io.StringWriter, entries []string, prefix string) {
for _, entry := range entries {
writePart(ctx, content, entry, prefix)
}
}
func writePart(ctx context.Context, content io.StringWriter, entry, prefix string) {
if len(entry) > 0 {
_, err := content.WriteString(fmt.Sprintf("%s=%s%s", prefix, entry, subFieldSeparator))
if err != nil {
log.Ctx(ctx).Error().Err(err).Send()
}
}
}
// sanitize As we pass the raw certificates, remove the useless data and make it http request compliant.
func sanitize(cert []byte) string {
return strings.NewReplacer(
"-----BEGIN CERTIFICATE-----", "",
"-----END CERTIFICATE-----", "",
"\n", "",
).Replace(string(cert))
}
// getCertificates Build a string with the client certificates.
func getCertificates(ctx context.Context, certs []*x509.Certificate) string {
var headerValues []string
for _, peerCert := range certs {
headerValues = append(headerValues, extractCertificate(ctx, peerCert))
}
return strings.Join(headerValues, certSeparator)
}
// extractCertificate extract the certificate from the request.
func extractCertificate(ctx context.Context, cert *x509.Certificate) string {
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
if certPEM == nil {
log.Ctx(ctx).Error().Msg("Cannot extract the certificate content")
return ""
}
return sanitize(certPEM)
}
// getSANs get the Subject Alternate Name values.
func getSANs(cert *x509.Certificate) []string {
if cert == nil {
return nil
}
var sans []string
sans = append(sans, cert.DNSNames...)
sans = append(sans, cert.EmailAddresses...)
for _, ip := range cert.IPAddresses {
sans = append(sans, ip.String())
}
for _, uri := range cert.URIs {
sans = append(sans, uri.String())
}
return sans
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/passtlsclientcert/pass_tls_client_cert_test.go | pkg/middlewares/passtlsclientcert/pass_tls_client_cert_test.go | package passtlsclientcert
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"net"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"strings"
"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/testhelpers"
)
const (
signingCA = `Certificate:
Data:
Version: 3 (0x2)
Serial Number: 2 (0x2)
Signature Algorithm: sha1WithRSAEncryption
Issuer: DC=org, DC=cheese, O=Cheese, O=Cheese 2, OU=Cheese Section, OU=Cheese Section 2, CN=Simple Root CA, CN=Simple Root CA 2, C=FR, C=US, L=TOULOUSE, L=LYON, ST=Root State, ST=Root State 2/emailAddress=root@signing.com/emailAddress=root2@signing.com
Validity
Not Before: Dec 6 11:10:09 2018 GMT
Not After : Dec 5 11:10:09 2028 GMT
Subject: DC=org, DC=cheese, O=Cheese, O=Cheese 2, OU=Simple Signing Section, OU=Simple Signing Section 2, CN=Simple Signing CA, CN=Simple Signing CA 2, C=FR, C=US, L=TOULOUSE, L=LYON, ST=Signing State, ST=Signing State 2/emailAddress=simple@signing.com/emailAddress=simple2@signing.com
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public-Key: (2048 bit)
Modulus:
00:c3:9d:9f:61:15:57:3f:78:cc:e7:5d:20:e2:3e:
2e:79:4a:c3:3a:0c:26:40:18:db:87:08:85:c2:f7:
af:87:13:1a:ff:67:8a:b7:2b:58:a7:cc:89:dd:77:
ff:5e:27:65:11:80:82:8f:af:a0:af:25:86:ec:a2:
4f:20:0e:14:15:16:12:d7:74:5a:c3:99:bd:3b:81:
c8:63:6f:fc:90:14:86:d2:39:ee:87:b2:ff:6d:a5:
69:da:ab:5a:3a:97:cd:23:37:6a:4b:ba:63:cd:a1:
a9:e6:79:aa:37:b8:d1:90:c9:24:b5:e8:70:fc:15:
ad:39:97:28:73:47:66:f6:22:79:5a:b0:03:83:8a:
f1:ca:ae:8b:50:1e:c8:fa:0d:9f:76:2e:00:c2:0e:
75:bc:47:5a:b6:d8:05:ed:5a:bc:6d:50:50:36:6b:
ab:ab:69:f6:9b:1b:6c:7e:a8:9f:b2:33:3a:3c:8c:
6d:5e:83:ce:17:82:9e:10:51:a6:39:ec:98:4e:50:
b7:b1:aa:8b:ac:bb:a1:60:1b:ea:31:3b:b8:0a:ea:
63:41:79:b5:ec:ee:19:e9:85:8e:f3:6d:93:80:da:
98:58:a2:40:93:a5:53:eb:1d:24:b6:66:07:ec:58:
10:63:e7:fa:6e:18:60:74:76:15:39:3c:f4:95:95:
7e:df
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Key Usage: critical
Certificate Sign, CRL Sign
X509v3 Basic Constraints: critical
CA:TRUE, pathlen:0
X509v3 Subject Key Identifier:
1E:52:A2:E8:54:D5:37:EB:D5:A8:1D:E4:C2:04:1D:37:E2:F7:70:03
X509v3 Authority Key Identifier:
keyid:36:70:35:AA:F0:F6:93:B2:86:5D:32:73:F9:41:5A:3F:3B:C8:BC:8B
Signature Algorithm: sha1WithRSAEncryption
76:f3:16:21:27:6d:a2:2e:e8:18:49:aa:54:1e:f8:3b:07:fa:
65:50:d8:1f:a2:cf:64:6c:15:e0:0f:c8:46:b2:d7:b8:0e:cd:
05:3b:06:fb:dd:c6:2f:01:ae:bd:69:d3:bb:55:47:a9:f6:e5:
ba:be:4b:45:fb:2e:3c:33:e0:57:d4:3e:8e:3e:11:f2:0a:f1:
7d:06:ab:04:2e:a5:76:20:c2:db:a4:68:5a:39:00:62:2a:1d:
c2:12:b1:90:66:8c:36:a8:fd:83:d1:1b:da:23:a7:1d:5b:e6:
9b:40:c4:78:25:c7:b7:6b:75:35:cf:bb:37:4a:4f:fc:7e:32:
1f:8c:cf:12:d2:c9:c8:99:d9:4a:55:0a:1e:ac:de:b4:cb:7c:
bf:c4:fb:60:2c:a8:f7:e7:63:5c:b0:1c:62:af:01:3c:fe:4d:
3c:0b:18:37:4c:25:fc:d0:b2:f6:b2:f1:c3:f4:0f:53:d6:1e:
b5:fa:bc:d8:ad:dd:1c:f5:45:9f:af:fe:0a:01:79:92:9a:d8:
71:db:37:f3:1e:bd:fb:c7:1e:0a:0f:97:2a:61:f3:7b:19:93:
9c:a6:8a:69:cd:b0:f5:91:02:a5:1b:10:f4:80:5d:42:af:4e:
82:12:30:3e:d3:a7:11:14:ce:50:91:04:80:d7:2a:03:ef:71:
10:b8:db:a5
-----BEGIN CERTIFICATE-----
MIIFzTCCBLWgAwIBAgIBAjANBgkqhkiG9w0BAQUFADCCAWQxEzARBgoJkiaJk/Is
ZAEZFgNvcmcxFjAUBgoJkiaJk/IsZAEZFgZjaGVlc2UxDzANBgNVBAoMBkNoZWVz
ZTERMA8GA1UECgwIQ2hlZXNlIDIxFzAVBgNVBAsMDkNoZWVzZSBTZWN0aW9uMRkw
FwYDVQQLDBBDaGVlc2UgU2VjdGlvbiAyMRcwFQYDVQQDDA5TaW1wbGUgUm9vdCBD
QTEZMBcGA1UEAwwQU2ltcGxlIFJvb3QgQ0EgMjELMAkGA1UEBhMCRlIxCzAJBgNV
BAYTAlVTMREwDwYDVQQHDAhUT1VMT1VTRTENMAsGA1UEBwwETFlPTjETMBEGA1UE
CAwKUm9vdCBTdGF0ZTEVMBMGA1UECAwMUm9vdCBTdGF0ZSAyMR8wHQYJKoZIhvcN
AQkBFhByb290QHNpZ25pbmcuY29tMSAwHgYJKoZIhvcNAQkBFhFyb290MkBzaWdu
aW5nLmNvbTAeFw0xODEyMDYxMTEwMDlaFw0yODEyMDUxMTEwMDlaMIIBhDETMBEG
CgmSJomT8ixkARkWA29yZzEWMBQGCgmSJomT8ixkARkWBmNoZWVzZTEPMA0GA1UE
CgwGQ2hlZXNlMREwDwYDVQQKDAhDaGVlc2UgMjEfMB0GA1UECwwWU2ltcGxlIFNp
Z25pbmcgU2VjdGlvbjEhMB8GA1UECwwYU2ltcGxlIFNpZ25pbmcgU2VjdGlvbiAy
MRowGAYDVQQDDBFTaW1wbGUgU2lnbmluZyBDQTEcMBoGA1UEAwwTU2ltcGxlIFNp
Z25pbmcgQ0EgMjELMAkGA1UEBhMCRlIxCzAJBgNVBAYTAlVTMREwDwYDVQQHDAhU
T1VMT1VTRTENMAsGA1UEBwwETFlPTjEWMBQGA1UECAwNU2lnbmluZyBTdGF0ZTEY
MBYGA1UECAwPU2lnbmluZyBTdGF0ZSAyMSEwHwYJKoZIhvcNAQkBFhJzaW1wbGVA
c2lnbmluZy5jb20xIjAgBgkqhkiG9w0BCQEWE3NpbXBsZTJAc2lnbmluZy5jb20w
ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDDnZ9hFVc/eMznXSDiPi55
SsM6DCZAGNuHCIXC96+HExr/Z4q3K1inzIndd/9eJ2URgIKPr6CvJYbsok8gDhQV
FhLXdFrDmb07gchjb/yQFIbSOe6Hsv9tpWnaq1o6l80jN2pLumPNoanmeao3uNGQ
ySS16HD8Fa05lyhzR2b2InlasAODivHKrotQHsj6DZ92LgDCDnW8R1q22AXtWrxt
UFA2a6urafabG2x+qJ+yMzo8jG1eg84Xgp4QUaY57JhOULexqousu6FgG+oxO7gK
6mNBebXs7hnphY7zbZOA2phYokCTpVPrHSS2ZgfsWBBj5/puGGB0dhU5PPSVlX7f
AgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAGAQH/AgEAMB0G
A1UdDgQWBBQeUqLoVNU369WoHeTCBB034vdwAzAfBgNVHSMEGDAWgBQ2cDWq8PaT
soZdMnP5QVo/O8i8izANBgkqhkiG9w0BAQUFAAOCAQEAdvMWISdtoi7oGEmqVB74
Owf6ZVDYH6LPZGwV4A/IRrLXuA7NBTsG+93GLwGuvWnTu1VHqfblur5LRfsuPDPg
V9Q+jj4R8grxfQarBC6ldiDC26RoWjkAYiodwhKxkGaMNqj9g9Eb2iOnHVvmm0DE
eCXHt2t1Nc+7N0pP/H4yH4zPEtLJyJnZSlUKHqzetMt8v8T7YCyo9+djXLAcYq8B
PP5NPAsYN0wl/NCy9rLxw/QPU9Yetfq82K3dHPVFn6/+CgF5kprYcds38x69+8ce
Cg+XKmHzexmTnKaKac2w9ZECpRsQ9IBdQq9OghIwPtOnERTOUJEEgNcqA+9xELjb
pQ==
-----END CERTIFICATE-----
`
minimalCheeseCrt = `-----BEGIN CERTIFICATE-----
MIIEQDCCAygCFFRY0OBk/L5Se0IZRj3CMljawL2UMA0GCSqGSIb3DQEBCwUAMIIB
hDETMBEGCgmSJomT8ixkARkWA29yZzEWMBQGCgmSJomT8ixkARkWBmNoZWVzZTEP
MA0GA1UECgwGQ2hlZXNlMREwDwYDVQQKDAhDaGVlc2UgMjEfMB0GA1UECwwWU2lt
cGxlIFNpZ25pbmcgU2VjdGlvbjEhMB8GA1UECwwYU2ltcGxlIFNpZ25pbmcgU2Vj
dGlvbiAyMRowGAYDVQQDDBFTaW1wbGUgU2lnbmluZyBDQTEcMBoGA1UEAwwTU2lt
cGxlIFNpZ25pbmcgQ0EgMjELMAkGA1UEBhMCRlIxCzAJBgNVBAYTAlVTMREwDwYD
VQQHDAhUT1VMT1VTRTENMAsGA1UEBwwETFlPTjEWMBQGA1UECAwNU2lnbmluZyBT
dGF0ZTEYMBYGA1UECAwPU2lnbmluZyBTdGF0ZSAyMSEwHwYJKoZIhvcNAQkBFhJz
aW1wbGVAc2lnbmluZy5jb20xIjAgBgkqhkiG9w0BCQEWE3NpbXBsZTJAc2lnbmlu
Zy5jb20wHhcNMTgxMjA2MTExMDM2WhcNMjEwOTI1MTExMDM2WjAzMQswCQYDVQQG
EwJGUjETMBEGA1UECAwKU29tZS1TdGF0ZTEPMA0GA1UECgwGQ2hlZXNlMIIBIjAN
BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAskX/bUtwFo1gF2BTPNaNcTUMaRFu
FMZozK8IgLjccZ4kZ0R9oFO6Yp8Zl/IvPaf7tE26PI7XP7eHriUdhnQzX7iioDd0
RZa68waIhAGc+xPzRFrP3b3yj3S2a9Rve3c0K+SCV+EtKAwsxMqQDhoo9PcBfo5B
RHfht07uD5MncUcGirwN+/pxHV5xzAGPcc7On0/5L7bq/G+63nhu78zw9XyuLaHC
PM5VbOUvpyIESJHbMMzTdFGL8ob9VKO+Kr1kVGdEA9i8FLGl3xz/GBKuW/JD0xyW
DrU29mri5vYWHmkuv7ZWHGXnpXjTtPHwveE9/0/ArnmpMyR9JtqFr1oEvQIDAQAB
MA0GCSqGSIb3DQEBCwUAA4IBAQBHta+NWXI08UHeOkGzOTGRiWXsOH2dqdX6gTe9
xF1AIjyoQ0gvpoGVvlnChSzmlUj+vnx/nOYGIt1poE3hZA3ZHZD/awsvGyp3GwWD
IfXrEViSCIyF+8tNNKYyUcEO3xdAsAUGgfUwwF/mZ6MBV5+A/ZEEILlTq8zFt9dV
vdKzIt7fZYxYBBHFSarl1x8pDgWXlf3hAufevGJXip9xGYmznF0T5cq1RbWJ4be3
/9K7yuWhuBYC3sbTbCneHBa91M82za+PIISc1ygCYtWSBoZKSAqLk0rkZpHaekDP
WqeUSNGYV//RunTeuRDAf5OxehERb1srzBXhRZ3cZdzXbgR/
-----END CERTIFICATE-----
`
completeCheeseCrt = `Certificate:
Data:
Version: 3 (0x2)
Serial Number: 1 (0x1)
Signature Algorithm: sha1WithRSAEncryption
Issuer: DC=org, DC=cheese, O=Cheese, O=Cheese 2, OU=Simple Signing Section, OU=Simple Signing Section 2, CN=Simple Signing CA, CN=Simple Signing CA 2, C=FR, C=US, L=TOULOUSE, L=LYON, ST=Signing State, ST=Signing State 2/emailAddress=simple@signing.com/emailAddress=simple2@signing.com
Validity
Not Before: Dec 6 11:10:16 2018 GMT
Not After : Dec 5 11:10:16 2020 GMT
Subject: DC=org, DC=cheese, O=Cheese, O=Cheese 2, OU=Simple Signing Section, OU=Simple Signing Section 2, CN=*.cheese.org, CN=*.cheese.com, C=FR, C=US, L=TOULOUSE, L=LYON, ST=Cheese org state, ST=Cheese com state/emailAddress=cert@cheese.org/emailAddress=cert@scheese.com
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public-Key: (2048 bit)
Modulus:
00:de:77:fa:8d:03:70:30:39:dd:51:1b:cc:60:db:
a9:5a:13:b1:af:fe:2c:c6:38:9b:88:0a:0f:8e:d9:
1b:a1:1d:af:0d:66:e4:13:5b:bc:5d:36:92:d7:5e:
d0:fa:88:29:d3:78:e1:81:de:98:b2:a9:22:3f:bf:
8a:af:12:92:63:d4:a9:c3:f2:e4:7e:d2:dc:a2:c5:
39:1c:7a:eb:d7:12:70:63:2e:41:47:e0:f0:08:e8:
dc:be:09:01:ec:28:09:af:35:d7:79:9c:50:35:d1:
6b:e5:87:7b:34:f6:d2:31:65:1d:18:42:69:6c:04:
11:83:fe:44:ae:90:92:2d:0b:75:39:57:62:e6:17:
2f:47:2b:c7:53:dd:10:2d:c9:e3:06:13:d2:b9:ba:
63:2e:3c:7d:83:6b:d6:89:c9:cc:9d:4d:bf:9f:e8:
a3:7b:da:c8:99:2b:ba:66:d6:8e:f8:41:41:a0:c9:
d0:5e:c8:11:a4:55:4a:93:83:87:63:04:63:41:9c:
fb:68:04:67:c2:71:2f:f2:65:1d:02:5d:15:db:2c:
d9:04:69:85:c2:7d:0d:ea:3b:ac:85:f8:d4:8f:0f:
c5:70:b2:45:e1:ec:b2:54:0b:e9:f7:82:b4:9b:1b:
2d:b9:25:d4:ab:ca:8f:5b:44:3e:15:dd:b8:7f:b7:
ee:f9
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Key Usage: critical
Digital Signature, Key Encipherment
X509v3 Basic Constraints:
CA:FALSE
X509v3 Extended Key Usage:
TLS Web Server Authentication, TLS Web Client Authentication
X509v3 Subject Key Identifier:
94:BA:73:78:A2:87:FB:58:28:28:CF:98:3B:C2:45:70:16:6E:29:2F
X509v3 Authority Key Identifier:
keyid:1E:52:A2:E8:54:D5:37:EB:D5:A8:1D:E4:C2:04:1D:37:E2:F7:70:03
X509v3 Subject Alternative Name:
DNS:*.cheese.org, DNS:*.cheese.net, DNS:*.cheese.com, IP Address:10.0.1.0, IP Address:10.0.1.2, email:test@cheese.org, email:test@cheese.net
Signature Algorithm: sha1WithRSAEncryption
76:6b:05:b0:0e:34:11:b1:83:99:91:dc:ae:1b:e2:08:15:8b:
16:b2:9b:27:1c:02:ac:b5:df:1b:d0:d0:75:a4:2b:2c:5c:65:
ed:99:ab:f7:cd:fe:38:3f:c3:9a:22:31:1b:ac:8c:1c:c2:f9:
5d:d4:75:7a:2e:72:c7:85:a9:04:af:9f:2a:cc:d3:96:75:f0:
8e:c7:c6:76:48:ac:45:a4:b9:02:1e:2f:c0:15:c4:07:08:92:
cb:27:50:67:a1:c8:05:c5:3a:b3:a6:48:be:eb:d5:59:ab:a2:
1b:95:30:71:13:5b:0a:9a:73:3b:60:cc:10:d0:6a:c7:e5:d7:
8b:2f:f9:2e:98:f2:ff:81:14:24:09:e3:4b:55:57:09:1a:22:
74:f1:f6:40:13:31:43:89:71:0a:96:1a:05:82:1f:83:3a:87:
9b:17:25:ef:5a:55:f2:2d:cd:0d:4d:e4:81:58:b6:e3:8d:09:
62:9a:0c:bd:e4:e5:5c:f0:95:da:cb:c7:34:2c:34:5f:6d:fc:
60:7b:12:5b:86:fd:df:21:89:3b:48:08:30:bf:67:ff:8c:e6:
9b:53:cc:87:36:47:70:40:3b:d9:90:2a:d2:d2:82:c6:9c:f5:
d1:d8:e0:e6:fd:aa:2f:95:7e:39:ac:fc:4e:d4:ce:65:b3:ec:
c6:98:8a:31
-----BEGIN CERTIFICATE-----
MIIGWjCCBUKgAwIBAgIBATANBgkqhkiG9w0BAQUFADCCAYQxEzARBgoJkiaJk/Is
ZAEZFgNvcmcxFjAUBgoJkiaJk/IsZAEZFgZjaGVlc2UxDzANBgNVBAoMBkNoZWVz
ZTERMA8GA1UECgwIQ2hlZXNlIDIxHzAdBgNVBAsMFlNpbXBsZSBTaWduaW5nIFNl
Y3Rpb24xITAfBgNVBAsMGFNpbXBsZSBTaWduaW5nIFNlY3Rpb24gMjEaMBgGA1UE
AwwRU2ltcGxlIFNpZ25pbmcgQ0ExHDAaBgNVBAMME1NpbXBsZSBTaWduaW5nIENB
IDIxCzAJBgNVBAYTAkZSMQswCQYDVQQGEwJVUzERMA8GA1UEBwwIVE9VTE9VU0Ux
DTALBgNVBAcMBExZT04xFjAUBgNVBAgMDVNpZ25pbmcgU3RhdGUxGDAWBgNVBAgM
D1NpZ25pbmcgU3RhdGUgMjEhMB8GCSqGSIb3DQEJARYSc2ltcGxlQHNpZ25pbmcu
Y29tMSIwIAYJKoZIhvcNAQkBFhNzaW1wbGUyQHNpZ25pbmcuY29tMB4XDTE4MTIw
NjExMTAxNloXDTIwMTIwNTExMTAxNlowggF2MRMwEQYKCZImiZPyLGQBGRYDb3Jn
MRYwFAYKCZImiZPyLGQBGRYGY2hlZXNlMQ8wDQYDVQQKDAZDaGVlc2UxETAPBgNV
BAoMCENoZWVzZSAyMR8wHQYDVQQLDBZTaW1wbGUgU2lnbmluZyBTZWN0aW9uMSEw
HwYDVQQLDBhTaW1wbGUgU2lnbmluZyBTZWN0aW9uIDIxFTATBgNVBAMMDCouY2hl
ZXNlLm9yZzEVMBMGA1UEAwwMKi5jaGVlc2UuY29tMQswCQYDVQQGEwJGUjELMAkG
A1UEBhMCVVMxETAPBgNVBAcMCFRPVUxPVVNFMQ0wCwYDVQQHDARMWU9OMRkwFwYD
VQQIDBBDaGVlc2Ugb3JnIHN0YXRlMRkwFwYDVQQIDBBDaGVlc2UgY29tIHN0YXRl
MR4wHAYJKoZIhvcNAQkBFg9jZXJ0QGNoZWVzZS5vcmcxHzAdBgkqhkiG9w0BCQEW
EGNlcnRAc2NoZWVzZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB
AQDed/qNA3AwOd1RG8xg26laE7Gv/izGOJuICg+O2RuhHa8NZuQTW7xdNpLXXtD6
iCnTeOGB3piyqSI/v4qvEpJj1KnD8uR+0tyixTkceuvXEnBjLkFH4PAI6Ny+CQHs
KAmvNdd5nFA10Wvlh3s09tIxZR0YQmlsBBGD/kSukJItC3U5V2LmFy9HK8dT3RAt
yeMGE9K5umMuPH2Da9aJycydTb+f6KN72siZK7pm1o74QUGgydBeyBGkVUqTg4dj
BGNBnPtoBGfCcS/yZR0CXRXbLNkEaYXCfQ3qO6yF+NSPD8VwskXh7LJUC+n3grSb
Gy25JdSryo9bRD4V3bh/t+75AgMBAAGjgeAwgd0wDgYDVR0PAQH/BAQDAgWgMAkG
A1UdEwQCMAAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMB0GA1UdDgQW
BBSUunN4oof7WCgoz5g7wkVwFm4pLzAfBgNVHSMEGDAWgBQeUqLoVNU369WoHeTC
BB034vdwAzBhBgNVHREEWjBYggwqLmNoZWVzZS5vcmeCDCouY2hlZXNlLm5ldIIM
Ki5jaGVlc2UuY29thwQKAAEAhwQKAAECgQ90ZXN0QGNoZWVzZS5vcmeBD3Rlc3RA
Y2hlZXNlLm5ldDANBgkqhkiG9w0BAQUFAAOCAQEAdmsFsA40EbGDmZHcrhviCBWL
FrKbJxwCrLXfG9DQdaQrLFxl7Zmr983+OD/DmiIxG6yMHML5XdR1ei5yx4WpBK+f
KszTlnXwjsfGdkisRaS5Ah4vwBXEBwiSyydQZ6HIBcU6s6ZIvuvVWauiG5UwcRNb
CppzO2DMENBqx+XXiy/5Lpjy/4EUJAnjS1VXCRoidPH2QBMxQ4lxCpYaBYIfgzqH
mxcl71pV8i3NDU3kgVi2440JYpoMveTlXPCV2svHNCw0X238YHsSW4b93yGJO0gI
ML9n/4zmm1PMhzZHcEA72ZAq0tKCxpz10djg5v2qL5V+Oaz8TtTOZbPsxpiKMQ==
-----END CERTIFICATE-----
`
minimalCert = `-----BEGIN CERTIFICATE-----
MIIDGTCCAgECCQCqLd75YLi2kDANBgkqhkiG9w0BAQsFADBYMQswCQYDVQQGEwJG
UjETMBEGA1UECAwKU29tZS1TdGF0ZTERMA8GA1UEBwwIVG91bG91c2UxITAfBgNV
BAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0xODA3MTgwODI4MTZaFw0x
ODA4MTcwODI4MTZaMEUxCzAJBgNVBAYTAkZSMRMwEQYDVQQIDApTb21lLVN0YXRl
MSEwHwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3
DQEBAQUAA4IBDwAwggEKAoIBAQC/+frDMMTLQyXG34F68BPhQq0kzK4LIq9Y0/gl
FjySZNn1C0QDWA1ubVCAcA6yY204I9cxcQDPNrhC7JlS5QA8Y5rhIBrqQlzZizAi
Rj3NTrRjtGUtOScnHuJaWjLy03DWD+aMwb7q718xt5SEABmmUvLwQK+EjW2MeDwj
y8/UEIpvrRDmdhGaqv7IFpIDkcIF7FowJ/hwDvx3PMc+z/JWK0ovzpvgbx69AVbw
ZxCimeha65rOqVi+lEetD26le+WnOdYsdJ2IkmpPNTXGdfb15xuAc+gFXfMCh7Iw
3Ynl6dZtZM/Ok2kiA7/OsmVnRKkWrtBfGYkI9HcNGb3zrk6nAgMBAAEwDQYJKoZI
hvcNAQELBQADggEBAC/R+Yvhh1VUhcbK49olWsk/JKqfS3VIDQYZg1Eo+JCPbwgS
I1BSYVfMcGzuJTX6ua3m/AHzGF3Tap4GhF4tX12jeIx4R4utnjj7/YKkTvuEM2f4
xT56YqI7zalGScIB0iMeyNz1QcimRl+M/49au8ow9hNX8C2tcA2cwd/9OIj/6T8q
SBRHc6ojvbqZSJCO0jziGDT1L3D+EDgTjED4nd77v/NRdP+egb0q3P0s4dnQ/5AV
aQlQADUn61j3ScbGJ4NSeZFFvsl38jeRi/MEzp0bGgNBcPj6JHi7qbbauZcZfQ05
jECvgAY7Nfd9mZ1KtyNaW31is+kag7NsvjxU/kM=
-----END CERTIFICATE-----`
)
var next = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte("bar"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
func TestPassTLSClientCert_PEM(t *testing.T) {
testCases := []struct {
desc string
certContents []string // set the request TLS attribute if defined
config dynamic.PassTLSClientCert
expectedHeader string
}{
{
desc: "No TLS, no option",
},
{
desc: "TLS, no option",
certContents: []string{minimalCheeseCrt},
},
{
desc: "No TLS, with pem option true",
config: dynamic.PassTLSClientCert{PEM: true},
},
{
desc: "TLS with simple certificate, with pem option true",
certContents: []string{minimalCheeseCrt},
config: dynamic.PassTLSClientCert{PEM: true},
expectedHeader: getCleanCertContents([]string{minimalCert}),
},
{
desc: "TLS with complete certificate, with pem option true",
certContents: []string{minimalCheeseCrt},
config: dynamic.PassTLSClientCert{PEM: true},
expectedHeader: getCleanCertContents([]string{minimalCheeseCrt}),
},
{
desc: "TLS with two certificate, with pem option true",
certContents: []string{minimalCert, minimalCheeseCrt},
config: dynamic.PassTLSClientCert{PEM: true},
expectedHeader: getCleanCertContents([]string{minimalCert, minimalCheeseCrt}),
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
tlsClientHeaders, err := New(t.Context(), next, test.config, "foo")
require.NoError(t, err)
res := httptest.NewRecorder()
req := testhelpers.MustNewRequest(http.MethodGet, "http://example.com/foo", nil)
if len(test.certContents) > 0 {
req.TLS = buildTLSWith(test.certContents)
}
tlsClientHeaders.ServeHTTP(res, req)
assert.Equal(t, http.StatusOK, res.Code, "Http Status should be OK")
assert.Equal(t, "bar", res.Body.String(), "Should be the expected body")
if test.expectedHeader != "" {
expected := getCleanCertContents(test.certContents)
assert.Equal(t, expected, req.Header.Get(xForwardedTLSClientCert), "The request header should contain the cleaned certificate")
} else {
assert.Empty(t, req.Header.Get(xForwardedTLSClientCert))
}
assert.Empty(t, res.Header().Get(xForwardedTLSClientCert), "The response header should be always empty")
})
}
}
func TestPassTLSClientCert_certInfo(t *testing.T) {
minimalCheeseCertAllInfo := strings.Join([]string{
`Subject="C=FR,ST=Some-State,O=Cheese"`,
`Issuer="DC=org,DC=cheese,C=FR,C=US,ST=Signing State,ST=Signing State 2,L=TOULOUSE,L=LYON,O=Cheese,O=Cheese 2,CN=Simple Signing CA 2"`,
`SerialNumber="481535886039632329873080491016862977516759989652"`,
`NB="1544094636"`,
`NA="1632568236"`,
}, fieldSeparator)
completeCertAllInfo := strings.Join([]string{
`Subject="DC=org,DC=cheese,C=FR,C=US,ST=Cheese org state,ST=Cheese com state,L=TOULOUSE,L=LYON,O=Cheese,O=Cheese 2,OU=Simple Signing Section,OU=Simple Signing Section 2,CN=*.cheese.com"`,
`Issuer="DC=org,DC=cheese,C=FR,C=US,ST=Signing State,ST=Signing State 2,L=TOULOUSE,L=LYON,O=Cheese,O=Cheese 2,CN=Simple Signing CA 2"`,
`SerialNumber="1"`,
`NB="1544094616"`,
`NA="1607166616"`,
`SAN="*.cheese.org,*.cheese.net,*.cheese.com,test@cheese.org,test@cheese.net,10.0.1.0,10.0.1.2"`,
}, fieldSeparator)
testCases := []struct {
desc string
certContents []string // set the request TLS attribute if defined
config dynamic.PassTLSClientCert
expectedHeader string
}{
{
desc: "No TLS, no option",
},
{
desc: "TLS, no option",
certContents: []string{minimalCert},
},
{
desc: "No TLS, with subject info",
config: dynamic.PassTLSClientCert{
Info: &dynamic.TLSClientCertificateInfo{
Subject: &dynamic.TLSClientCertificateSubjectDNInfo{
CommonName: true,
Organization: true,
OrganizationalUnit: true,
Locality: true,
Province: true,
Country: true,
SerialNumber: true,
},
},
},
},
{
desc: "No TLS, with pem option false with empty subject info",
config: dynamic.PassTLSClientCert{
PEM: false,
Info: &dynamic.TLSClientCertificateInfo{
Subject: &dynamic.TLSClientCertificateSubjectDNInfo{},
},
},
},
{
desc: "TLS with simple certificate, with all info",
certContents: []string{minimalCheeseCrt},
config: dynamic.PassTLSClientCert{
Info: &dynamic.TLSClientCertificateInfo{
NotAfter: true,
NotBefore: true,
Sans: true,
SerialNumber: true,
Subject: &dynamic.TLSClientCertificateSubjectDNInfo{
CommonName: true,
Country: true,
DomainComponent: true,
Locality: true,
Organization: true,
OrganizationalUnit: true,
Province: true,
SerialNumber: true,
},
Issuer: &dynamic.TLSClientCertificateIssuerDNInfo{
CommonName: true,
Country: true,
DomainComponent: true,
Locality: true,
Organization: true,
Province: true,
SerialNumber: true,
},
},
},
expectedHeader: minimalCheeseCertAllInfo,
},
{
desc: "TLS with simple certificate, with some info",
certContents: []string{minimalCheeseCrt},
config: dynamic.PassTLSClientCert{
Info: &dynamic.TLSClientCertificateInfo{
NotAfter: true,
Sans: true,
Subject: &dynamic.TLSClientCertificateSubjectDNInfo{
Organization: true,
},
Issuer: &dynamic.TLSClientCertificateIssuerDNInfo{
Country: true,
},
},
},
expectedHeader: `Subject="O=Cheese";Issuer="C=FR,C=US";NA="1632568236"`,
},
{
desc: "TLS with simple certificate, requesting non-existent info",
certContents: []string{minimalCheeseCrt},
config: dynamic.PassTLSClientCert{
Info: &dynamic.TLSClientCertificateInfo{
NotAfter: true,
Sans: true,
Subject: &dynamic.TLSClientCertificateSubjectDNInfo{
Organization: true,
// OrganizationalUnit is not set on this example certificate,
// so even though it's requested, it will be absent.
OrganizationalUnit: true,
},
Issuer: &dynamic.TLSClientCertificateIssuerDNInfo{
Country: true,
},
},
},
expectedHeader: `Subject="O=Cheese";Issuer="C=FR,C=US";NA="1632568236"`,
},
{
desc: "TLS with complete certificate, with all info",
certContents: []string{completeCheeseCrt},
config: dynamic.PassTLSClientCert{
Info: &dynamic.TLSClientCertificateInfo{
NotAfter: true,
NotBefore: true,
Sans: true,
SerialNumber: true,
Subject: &dynamic.TLSClientCertificateSubjectDNInfo{
Country: true,
Province: true,
Locality: true,
Organization: true,
OrganizationalUnit: true,
CommonName: true,
SerialNumber: true,
DomainComponent: true,
},
Issuer: &dynamic.TLSClientCertificateIssuerDNInfo{
Country: true,
Province: true,
Locality: true,
Organization: true,
CommonName: true,
SerialNumber: true,
DomainComponent: true,
},
},
},
expectedHeader: completeCertAllInfo,
},
{
desc: "TLS with 2 certificates, with all info",
certContents: []string{minimalCheeseCrt, completeCheeseCrt},
config: dynamic.PassTLSClientCert{
Info: &dynamic.TLSClientCertificateInfo{
NotAfter: true,
NotBefore: true,
Sans: true,
SerialNumber: true,
Subject: &dynamic.TLSClientCertificateSubjectDNInfo{
Country: true,
Province: true,
Locality: true,
Organization: true,
OrganizationalUnit: true,
CommonName: true,
SerialNumber: true,
DomainComponent: true,
},
Issuer: &dynamic.TLSClientCertificateIssuerDNInfo{
Country: true,
Province: true,
Locality: true,
Organization: true,
CommonName: true,
SerialNumber: true,
DomainComponent: true,
},
},
},
expectedHeader: strings.Join([]string{minimalCheeseCertAllInfo, completeCertAllInfo}, certSeparator),
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
tlsClientHeaders, err := New(t.Context(), next, test.config, "foo")
require.NoError(t, err)
res := httptest.NewRecorder()
req := testhelpers.MustNewRequest(http.MethodGet, "http://example.com/foo", nil)
if len(test.certContents) > 0 {
req.TLS = buildTLSWith(test.certContents)
}
tlsClientHeaders.ServeHTTP(res, req)
assert.Equal(t, http.StatusOK, res.Code, "Http Status should be OK")
assert.Equal(t, "bar", res.Body.String(), "Should be the expected body")
if test.expectedHeader != "" {
unescape, err := url.QueryUnescape(req.Header.Get(xForwardedTLSClientCertInfo))
require.NoError(t, err)
assert.Equal(t, test.expectedHeader, unescape, "The request header should contain the cleaned certificate")
} else {
assert.Empty(t, req.Header.Get(xForwardedTLSClientCertInfo))
}
assert.Empty(t, res.Header().Get(xForwardedTLSClientCertInfo), "The response header should be always empty")
})
}
}
func Test_sanitize(t *testing.T) {
testCases := []struct {
desc string
toSanitize []byte
expected string
}{
{
desc: "Empty",
},
{
desc: "With a minimal cert",
toSanitize: []byte(minimalCheeseCrt),
expected: `MIIEQDCCAygCFFRY0OBk/L5Se0IZRj3CMljawL2UMA0GCSqGSIb3DQEBCwUAMIIB
hDETMBEGCgmSJomT8ixkARkWA29yZzEWMBQGCgmSJomT8ixkARkWBmNoZWVzZTEP
MA0GA1UECgwGQ2hlZXNlMREwDwYDVQQKDAhDaGVlc2UgMjEfMB0GA1UECwwWU2lt
cGxlIFNpZ25pbmcgU2VjdGlvbjEhMB8GA1UECwwYU2ltcGxlIFNpZ25pbmcgU2Vj
dGlvbiAyMRowGAYDVQQDDBFTaW1wbGUgU2lnbmluZyBDQTEcMBoGA1UEAwwTU2lt
cGxlIFNpZ25pbmcgQ0EgMjELMAkGA1UEBhMCRlIxCzAJBgNVBAYTAlVTMREwDwYD
VQQHDAhUT1VMT1VTRTENMAsGA1UEBwwETFlPTjEWMBQGA1UECAwNU2lnbmluZyBT
dGF0ZTEYMBYGA1UECAwPU2lnbmluZyBTdGF0ZSAyMSEwHwYJKoZIhvcNAQkBFhJz
aW1wbGVAc2lnbmluZy5jb20xIjAgBgkqhkiG9w0BCQEWE3NpbXBsZTJAc2lnbmlu
Zy5jb20wHhcNMTgxMjA2MTExMDM2WhcNMjEwOTI1MTExMDM2WjAzMQswCQYDVQQG
EwJGUjETMBEGA1UECAwKU29tZS1TdGF0ZTEPMA0GA1UECgwGQ2hlZXNlMIIBIjAN
BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAskX/bUtwFo1gF2BTPNaNcTUMaRFu
FMZozK8IgLjccZ4kZ0R9oFO6Yp8Zl/IvPaf7tE26PI7XP7eHriUdhnQzX7iioDd0
RZa68waIhAGc+xPzRFrP3b3yj3S2a9Rve3c0K+SCV+EtKAwsxMqQDhoo9PcBfo5B
RHfht07uD5MncUcGirwN+/pxHV5xzAGPcc7On0/5L7bq/G+63nhu78zw9XyuLaHC
PM5VbOUvpyIESJHbMMzTdFGL8ob9VKO+Kr1kVGdEA9i8FLGl3xz/GBKuW/JD0xyW
DrU29mri5vYWHmkuv7ZWHGXnpXjTtPHwveE9/0/ArnmpMyR9JtqFr1oEvQIDAQAB
MA0GCSqGSIb3DQEBCwUAA4IBAQBHta+NWXI08UHeOkGzOTGRiWXsOH2dqdX6gTe9
xF1AIjyoQ0gvpoGVvlnChSzmlUj+vnx/nOYGIt1poE3hZA3ZHZD/awsvGyp3GwWD
IfXrEViSCIyF+8tNNKYyUcEO3xdAsAUGgfUwwF/mZ6MBV5+A/ZEEILlTq8zFt9dV
vdKzIt7fZYxYBBHFSarl1x8pDgWXlf3hAufevGJXip9xGYmznF0T5cq1RbWJ4be3
/9K7yuWhuBYC3sbTbCneHBa91M82za+PIISc1ygCYtWSBoZKSAqLk0rkZpHaekDP
WqeUSNGYV//RunTeuRDAf5OxehERb1srzBXhRZ3cZdzXbgR/`,
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
content := sanitize(test.toSanitize)
expected := strings.ReplaceAll(test.expected, "\n", "")
assert.Equal(t, expected, content, "The sanitized certificates should be equal")
})
}
}
func Test_getSANs(t *testing.T) {
urlFoo := testhelpers.MustParseURL("my.foo.com")
urlBar := testhelpers.MustParseURL("my.bar.com")
testCases := []struct {
desc string
cert *x509.Certificate // set the request TLS attribute if defined
expected []string
}{
{
desc: "With nil",
},
{
desc: "Certificate without Sans",
cert: &x509.Certificate{},
},
{
desc: "Certificate with all Sans",
cert: &x509.Certificate{
DNSNames: []string{"foo", "bar"},
EmailAddresses: []string{"test@test.com", "test2@test.com"},
IPAddresses: []net.IP{net.IPv4(10, 0, 0, 1), net.IPv4(10, 0, 0, 2)},
URIs: []*url.URL{urlFoo, urlBar},
},
expected: []string{"foo", "bar", "test@test.com", "test2@test.com", "10.0.0.1", "10.0.0.2", urlFoo.String(), urlBar.String()},
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
sans := getSANs(test.cert)
if len(test.expected) > 0 {
for i, expected := range test.expected {
assert.Equal(t, expected, sans[i])
}
} else {
assert.Empty(t, sans)
}
})
}
}
func getCleanCertContents(certContents []string) string {
exp := regexp.MustCompile("-----BEGIN CERTIFICATE-----(?s)(.*)")
var cleanedCertContent []string
for _, certContent := range certContents {
cert := sanitize([]byte(exp.FindString(certContent)))
cleanedCertContent = append(cleanedCertContent, cert)
}
return strings.Join(cleanedCertContent, certSeparator)
}
func buildTLSWith(certContents []string) *tls.ConnectionState {
var peerCertificates []*x509.Certificate
for _, certContent := range certContents {
peerCertificates = append(peerCertificates, getCertificate(certContent))
}
return &tls.ConnectionState{PeerCertificates: peerCertificates}
}
func getCertificate(certContent string) *x509.Certificate {
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM([]byte(signingCA))
if !ok {
panic("failed to parse root certificate")
}
block, _ := pem.Decode([]byte(certContent))
if block == nil {
panic("failed to parse certificate PEM")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
panic("failed to parse certificate: " + err.Error())
}
return cert
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/replacepathregex/replace_path_regex_test.go | pkg/middlewares/replacepathregex/replace_path_regex_test.go | package replacepathregex
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"
"github.com/traefik/traefik/v3/pkg/middlewares/replacepath"
)
func TestReplacePathRegex(t *testing.T) {
testCases := []struct {
desc string
path string
config dynamic.ReplacePathRegex
expectedPath string
expectedRawPath string
expectedHeader string
expectsError bool
}{
{
desc: "simple regex",
path: "/whoami/and/whoami",
config: dynamic.ReplacePathRegex{
Replacement: "/who-am-i/$1",
Regex: `^/whoami/(.*)`,
},
expectedPath: "/who-am-i/and/whoami",
expectedRawPath: "/who-am-i/and/whoami",
expectedHeader: "/whoami/and/whoami",
},
{
desc: "simple replace (no regex)",
path: "/whoami/and/whoami",
config: dynamic.ReplacePathRegex{
Replacement: "/who-am-i",
Regex: `/whoami`,
},
expectedPath: "/who-am-i/and/who-am-i",
expectedRawPath: "/who-am-i/and/who-am-i",
expectedHeader: "/whoami/and/whoami",
},
{
desc: "empty replacement",
path: "/whoami/and/whoami",
config: dynamic.ReplacePathRegex{
Replacement: "",
Regex: `/whoami`,
},
expectedPath: "/and",
expectedRawPath: "/and",
expectedHeader: "/whoami/and/whoami",
},
{
desc: "empty trimmed replacement",
path: "/whoami/and/whoami",
config: dynamic.ReplacePathRegex{
Replacement: " ",
Regex: `/whoami`,
},
expectedPath: "/and",
expectedRawPath: "/and",
expectedHeader: "/whoami/and/whoami",
},
{
desc: "no match",
path: "/whoami/and/whoami",
config: dynamic.ReplacePathRegex{
Replacement: "/whoami",
Regex: `/no-match`,
},
expectedPath: "/whoami/and/whoami",
},
{
desc: "multiple replacement",
path: "/downloads/src/source.go",
config: dynamic.ReplacePathRegex{
Replacement: "/downloads/$1-$2",
Regex: `^(?i)/downloads/([^/]+)/([^/]+)$`,
},
expectedPath: "/downloads/src-source.go",
expectedRawPath: "/downloads/src-source.go",
expectedHeader: "/downloads/src/source.go",
},
{
desc: "invalid regular expression",
path: "/invalid/regexp/test",
config: dynamic.ReplacePathRegex{
Replacement: "/valid/regexp/$1",
Regex: `^(?err)/invalid/regexp/([^/]+)$`,
},
expectedPath: "/invalid/regexp/test",
expectsError: true,
},
{
desc: "replacement with escaped char",
path: "/aaa/bbb",
config: dynamic.ReplacePathRegex{
Replacement: "/foo%2Fbar",
Regex: `/aaa/bbb`,
},
expectedPath: "/foo/bar",
expectedRawPath: "/foo%2Fbar",
expectedHeader: "/aaa/bbb",
},
{
desc: "path and regex with escaped char",
path: "/aaa%2Fbbb",
config: dynamic.ReplacePathRegex{
Replacement: "/foo/bar",
Regex: `/aaa%2Fbbb`,
},
expectedPath: "/foo/bar",
expectedRawPath: "/foo/bar",
expectedHeader: "/aaa%2Fbbb",
},
{
desc: "path with escaped char (no match)",
path: "/aaa%2Fbbb",
config: dynamic.ReplacePathRegex{
Replacement: "/foo/bar",
Regex: `/aaa/bbb`,
},
expectedPath: "/aaa/bbb",
expectedRawPath: "/aaa%2Fbbb",
},
{
desc: "path with percent encoded backspace char",
path: "/foo/%08bar",
config: dynamic.ReplacePathRegex{
Replacement: "/$1",
Regex: `^/foo/(.*)`,
},
expectedPath: "/\bbar",
expectedRawPath: "/%08bar",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
var actualPath, actualRawPath, actualHeader, requestURI string
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
actualPath = r.URL.Path
actualRawPath = r.URL.RawPath
actualHeader = r.Header.Get(replacepath.ReplacedPathHeader)
requestURI = r.RequestURI
})
handler, err := New(t.Context(), next, test.config, "foo-replace-path-regexp")
if test.expectsError {
require.Error(t, err)
return
}
require.NoError(t, err)
server := httptest.NewServer(handler)
defer server.Close()
resp, err := http.Get(server.URL + test.path)
require.NoError(t, err, "Unexpected error while making test request")
require.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, test.expectedPath, actualPath, "Unexpected path.")
assert.Equal(t, test.expectedRawPath, actualRawPath, "Unexpected raw path.")
if actualRawPath == "" {
assert.Equal(t, actualPath, requestURI, "Unexpected request URI.")
} else {
assert.Equal(t, actualRawPath, requestURI, "Unexpected request URI.")
}
if test.expectedHeader != "" {
assert.Equal(t, test.expectedHeader, actualHeader, "Unexpected '%s' header.", replacepath.ReplacedPathHeader)
}
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/replacepathregex/replace_path_regex.go | pkg/middlewares/replacepathregex/replace_path_regex.go | package replacepathregex
import (
"context"
"fmt"
"net/http"
"net/url"
"regexp"
"strings"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/middlewares/observability"
"github.com/traefik/traefik/v3/pkg/middlewares/replacepath"
)
const typeName = "ReplacePathRegex"
// ReplacePathRegex is a middleware used to replace the path of a URL request with a regular expression.
type replacePathRegex struct {
next http.Handler
regexp *regexp.Regexp
replacement string
name string
}
// New creates a new replace path regex middleware.
func New(ctx context.Context, next http.Handler, config dynamic.ReplacePathRegex, name string) (http.Handler, error) {
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
exp, err := regexp.Compile(strings.TrimSpace(config.Regex))
if err != nil {
return nil, fmt.Errorf("error compiling regular expression %s: %w", config.Regex, err)
}
return &replacePathRegex{
regexp: exp,
replacement: strings.TrimSpace(config.Replacement),
next: next,
name: name,
}, nil
}
func (rp *replacePathRegex) GetTracingInformation() (string, string) {
return rp.name, typeName
}
func (rp *replacePathRegex) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
currentPath := req.URL.RawPath
if currentPath == "" {
currentPath = req.URL.EscapedPath()
}
if rp.regexp != nil && rp.regexp.MatchString(currentPath) {
req.Header.Add(replacepath.ReplacedPathHeader, currentPath)
req.URL.RawPath = rp.regexp.ReplaceAllString(currentPath, rp.replacement)
// as replacement can introduce escaped characters
// Path must remain an unescaped version of RawPath
// Doesn't handle multiple times encoded replacement (`/` => `%2F` => `%252F` => ...)
var err error
req.URL.Path, err = url.PathUnescape(req.URL.RawPath)
if err != nil {
middlewares.GetLogger(context.Background(), rp.name, typeName).Error().Msgf("Unable to unescape url raw path %q: %v", req.URL.RawPath, err)
observability.SetStatusErrorf(req.Context(), "Unable to unescape url raw path %q: %v", req.URL.RawPath, err)
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
req.RequestURI = req.URL.RequestURI()
}
rp.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/contenttype/content_type.go | pkg/middlewares/contenttype/content_type.go | package contenttype
import (
"context"
"net/http"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
)
const (
typeName = "ContentType"
)
// ContentType is a middleware used to activate Content-Type auto-detection.
type contentType struct {
next http.Handler
name string
}
// New creates a new handler.
func New(ctx context.Context, next http.Handler, config dynamic.ContentType, name string) (http.Handler, error) {
logger := middlewares.GetLogger(ctx, name, typeName)
logger.Debug().Msg("Creating middleware")
if config.AutoDetect != nil {
logger.Warn().Msg("AutoDetect option is deprecated, Content-Type middleware is only meant to be used to enable the content-type detection, please remove any usage of this option.")
// Disable content-type detection (idempotent).
if !*config.AutoDetect {
return next, nil
}
}
return &contentType{next: next, name: name}, nil
}
func (c *contentType) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// Re-enable auto-detection.
if ct, ok := rw.Header()["Content-Type"]; ok && ct == nil {
middlewares.GetLogger(req.Context(), c.name, typeName).
Debug().Msg("Enable Content-Type auto-detection.")
delete(rw.Header(), "Content-Type")
}
c.next.ServeHTTP(rw, req)
}
func DisableAutoDetection(next http.Handler) http.HandlerFunc {
return func(rw http.ResponseWriter, req *http.Request) {
// Prevent Content-Type auto-detection.
if _, ok := rw.Header()["Content-Type"]; !ok {
rw.Header()["Content-Type"] = nil
}
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/contenttype/content_type_test.go | pkg/middlewares/contenttype/content_type_test.go | package contenttype
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"
"github.com/traefik/traefik/v3/pkg/testhelpers"
)
func TestAutoDetection(t *testing.T) {
testCases := []struct {
desc string
autoDetect bool
contentType string
wantContentType string
}{
{
desc: "Keep the Content-Type returned by the server",
autoDetect: false,
contentType: "application/json",
wantContentType: "application/json",
},
{
desc: "Don't auto-detect Content-Type header by default when not set by the server",
autoDetect: false,
contentType: "",
wantContentType: "",
},
{
desc: "Keep the Content-Type returned by the server with auto-detection middleware",
autoDetect: true,
contentType: "application/json",
wantContentType: "application/json",
},
{
desc: "Auto-detect when Content-Type header is not already set by the server with auto-detection middleware",
autoDetect: true,
contentType: "",
wantContentType: "text/plain; charset=utf-8",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
var next http.Handler
next = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if test.contentType != "" {
w.Header().Set("Content-Type", test.contentType)
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("Test"))
})
if test.autoDetect {
var err error
next, err = New(t.Context(), next, dynamic.ContentType{}, "foo-content-type")
require.NoError(t, err)
}
server := httptest.NewServer(
DisableAutoDetection(next),
)
t.Cleanup(server.Close)
req := testhelpers.MustNewRequest(http.MethodGet, server.URL, nil)
res, err := server.Client().Do(req)
require.NoError(t, err)
assert.Equal(t, test.wantContentType, res.Header.Get("Content-Type"))
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/replacepath/replace_path_test.go | pkg/middlewares/replacepath/replace_path_test.go | package replacepath
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 TestReplacePath(t *testing.T) {
testCases := []struct {
desc string
path string
config dynamic.ReplacePath
expectedPath string
expectedRawPath string
expectedHeader string
}{
{
desc: "simple path",
path: "/example",
config: dynamic.ReplacePath{
Path: "/replacement-path",
},
expectedPath: "/replacement-path",
expectedRawPath: "",
expectedHeader: "/example",
},
{
desc: "long path",
path: "/some/really/long/path",
config: dynamic.ReplacePath{
Path: "/replacement-path",
},
expectedPath: "/replacement-path",
expectedRawPath: "",
expectedHeader: "/some/really/long/path",
},
{
desc: "path with escaped value",
path: "/foo%2Fbar",
config: dynamic.ReplacePath{
Path: "/replacement-path",
},
expectedPath: "/replacement-path",
expectedRawPath: "",
expectedHeader: "/foo%2Fbar",
},
{
desc: "replacement with escaped value",
path: "/path",
config: dynamic.ReplacePath{
Path: "/foo%2Fbar",
},
expectedPath: "/foo/bar",
expectedRawPath: "/foo%2Fbar",
expectedHeader: "/path",
},
{
desc: "replacement with percent encoded backspace char",
path: "/path/%08bar",
config: dynamic.ReplacePath{
Path: "/path/%08bar",
},
expectedPath: "/path/\bbar",
expectedRawPath: "/path/%08bar",
expectedHeader: "/path/%08bar",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
var actualPath, actualRawPath, actualHeader, requestURI string
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
actualPath = r.URL.Path
actualRawPath = r.URL.RawPath
actualHeader = r.Header.Get(ReplacedPathHeader)
requestURI = r.RequestURI
})
handler, err := New(t.Context(), next, test.config, "foo-replace-path")
require.NoError(t, err)
server := httptest.NewServer(handler)
defer server.Close()
resp, err := http.Get(server.URL + test.path)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, test.expectedPath, actualPath, "Unexpected path.")
assert.Equal(t, test.expectedHeader, actualHeader, "Unexpected '%s' header.", ReplacedPathHeader)
if actualRawPath == "" {
assert.Equal(t, actualPath, requestURI, "Unexpected request URI.")
} else {
assert.Equal(t, actualRawPath, requestURI, "Unexpected request URI.")
}
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/replacepath/replace_path.go | pkg/middlewares/replacepath/replace_path.go | package replacepath
import (
"context"
"net/http"
"net/url"
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/middlewares/observability"
)
const (
// ReplacedPathHeader is the default header to set the old path to.
ReplacedPathHeader = "X-Replaced-Path"
typeName = "ReplacePath"
)
// ReplacePath is a middleware used to replace the path of a URL request.
type replacePath struct {
next http.Handler
path string
name string
}
// New creates a new replace path middleware.
func New(ctx context.Context, next http.Handler, config dynamic.ReplacePath, name string) (http.Handler, error) {
middlewares.GetLogger(ctx, name, typeName).Debug().Msg("Creating middleware")
return &replacePath{
next: next,
path: config.Path,
name: name,
}, nil
}
func (r *replacePath) GetTracingInformation() (string, string) {
return r.name, typeName
}
func (r *replacePath) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
currentPath := req.URL.RawPath
if currentPath == "" {
currentPath = req.URL.EscapedPath()
}
req.Header.Add(ReplacedPathHeader, currentPath)
req.URL.RawPath = r.path
var err error
req.URL.Path, err = url.PathUnescape(req.URL.RawPath)
if err != nil {
middlewares.GetLogger(context.Background(), r.name, typeName).Error().Msgf("Unable to unescape url raw path %q: %v", req.URL.RawPath, err)
observability.SetStatusErrorf(req.Context(), "Unable to unescape url raw path %q: %v", req.URL.RawPath, err)
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
req.RequestURI = req.URL.RequestURI()
r.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/parser.go | pkg/middlewares/accesslog/parser.go | package accesslog
import (
"bytes"
"regexp"
)
// ParseAccessLog parse line of access log and return a map with each fields.
func ParseAccessLog(data string) (map[string]string, error) {
var buffer bytes.Buffer
buffer.WriteString(`(\S+)`) // 1 - ClientHost
buffer.WriteString(`\s-\s`) // - - Spaces
buffer.WriteString(`(\S+)\s`) // 2 - ClientUsername
buffer.WriteString(`\[([^]]+)\]\s`) // 3 - StartUTC
buffer.WriteString(`"(\S*)\s?`) // 4 - RequestMethod
buffer.WriteString(`((?:[^"]*(?:\\")?)*)\s`) // 5 - RequestPath
buffer.WriteString(`([^"]*)"\s`) // 6 - RequestProtocol
buffer.WriteString(`(\S+)\s`) // 7 - OriginStatus
buffer.WriteString(`(\S+)\s`) // 8 - OriginContentSize
buffer.WriteString(`("?\S+"?)\s`) // 9 - Referrer
buffer.WriteString(`("\S+")\s`) // 10 - User-Agent
buffer.WriteString(`(\S+)\s`) // 11 - RequestCount
buffer.WriteString(`("[^"]*"|-)\s`) // 12 - FrontendName
buffer.WriteString(`("[^"]*"|-)\s`) // 13 - BackendURL
buffer.WriteString(`(\S+)`) // 14 - Duration
regex, err := regexp.Compile(buffer.String())
if err != nil {
return nil, err
}
submatch := regex.FindStringSubmatch(data)
result := make(map[string]string)
// Need to be > 13 to match CLF format
if len(submatch) > 13 {
result[ClientHost] = submatch[1]
result[ClientUsername] = submatch[2]
result[StartUTC] = submatch[3]
result[RequestMethod] = submatch[4]
result[RequestPath] = submatch[5]
result[RequestProtocol] = submatch[6]
result[OriginStatus] = submatch[7]
result[OriginContentSize] = submatch[8]
result[RequestRefererHeader] = submatch[9]
result[RequestUserAgentHeader] = submatch[10]
result[RequestCount] = submatch[11]
result[RouterName] = submatch[12]
result[ServiceURL] = submatch[13]
result[Duration] = submatch[14]
}
return result, nil
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/accesslog/save_retries_test.go | pkg/middlewares/accesslog/save_retries_test.go | package accesslog
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
func TestSaveRetries(t *testing.T) {
tests := []struct {
requestAttempt int
wantRetryAttemptsInLog int
}{
{
requestAttempt: 0,
wantRetryAttemptsInLog: 0,
},
{
requestAttempt: 1,
wantRetryAttemptsInLog: 0,
},
{
requestAttempt: 3,
wantRetryAttemptsInLog: 2,
},
}
for _, test := range tests {
t.Run(fmt.Sprintf("%d retries", test.requestAttempt), func(t *testing.T) {
t.Parallel()
saveRetries := &SaveRetries{}
logDataTable := &LogData{Core: make(CoreLogData)}
req := httptest.NewRequest(http.MethodGet, "/some/path", nil)
reqWithDataTable := req.WithContext(context.WithValue(req.Context(), DataTableKey, logDataTable))
saveRetries.Retried(reqWithDataTable, test.requestAttempt)
if logDataTable.Core[RetryAttempts] != test.wantRetryAttemptsInLog {
t.Errorf("got %v in logDataTable, want %v", logDataTable.Core[RetryAttempts], test.wantRetryAttemptsInLog)
}
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/accesslog/logger_formatters_test.go | pkg/middlewares/accesslog/logger_formatters_test.go | package accesslog
import (
"net/http"
"testing"
"time"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCommonLogFormatter_Format(t *testing.T) {
clf := CommonLogFormatter{}
testCases := []struct {
name string
data map[string]interface{}
expectedLog string
}{
{
name: "DownstreamStatus & DownstreamContentSize are nil",
data: map[string]interface{}{
StartUTC: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
Duration: 123 * time.Second,
ClientHost: "10.0.0.1",
ClientUsername: "Client",
RequestMethod: http.MethodGet,
RequestPath: "/foo",
RequestProtocol: "http",
DownstreamStatus: nil,
DownstreamContentSize: nil,
RequestRefererHeader: "",
RequestUserAgentHeader: "",
RequestCount: 0,
RouterName: "",
ServiceURL: "",
},
expectedLog: `10.0.0.1 - Client [10/Nov/2009:23:00:00 +0000] "GET /foo http" - - "-" "-" 0 "-" "-" 123000ms
`,
},
{
name: "all data",
data: map[string]interface{}{
StartUTC: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
Duration: 123 * time.Second,
ClientHost: "10.0.0.1",
ClientUsername: "Client",
RequestMethod: http.MethodGet,
RequestPath: "/foo",
RequestProtocol: "http",
DownstreamStatus: 123,
DownstreamContentSize: 132,
RequestRefererHeader: "referer",
RequestUserAgentHeader: "agent",
RequestCount: nil,
RouterName: "foo",
ServiceURL: "http://10.0.0.2/toto",
},
expectedLog: `10.0.0.1 - Client [10/Nov/2009:23:00:00 +0000] "GET /foo http" 123 132 "referer" "agent" - "foo" "http://10.0.0.2/toto" 123000ms
`,
},
{
name: "all data with local time",
data: map[string]interface{}{
StartLocal: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
Duration: 123 * time.Second,
ClientHost: "10.0.0.1",
ClientUsername: "Client",
RequestMethod: http.MethodGet,
RequestPath: "/foo",
RequestProtocol: "http",
DownstreamStatus: 123,
DownstreamContentSize: 132,
RequestRefererHeader: "referer",
RequestUserAgentHeader: "agent",
RequestCount: nil,
RouterName: "foo",
ServiceURL: "http://10.0.0.2/toto",
},
expectedLog: `10.0.0.1 - Client [10/Nov/2009:14:00:00 -0900] "GET /foo http" 123 132 "referer" "agent" - "foo" "http://10.0.0.2/toto" 123000ms
`,
},
}
var err error
time.Local, err = time.LoadLocation("Etc/GMT+9")
require.NoError(t, err)
for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
entry := &logrus.Entry{Data: test.data}
raw, err := clf.Format(entry)
assert.NoError(t, err)
assert.Equal(t, test.expectedLog, string(raw))
})
}
}
func TestGenericCLFLogFormatter_Format(t *testing.T) {
clf := GenericCLFLogFormatter{}
testCases := []struct {
name string
data map[string]interface{}
expectedLog string
}{
{
name: "DownstreamStatus & DownstreamContentSize are nil",
data: map[string]interface{}{
StartUTC: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
Duration: 123 * time.Second,
ClientHost: "10.0.0.1",
ClientUsername: "Client",
RequestMethod: http.MethodGet,
RequestPath: "/foo",
RequestProtocol: "http",
DownstreamStatus: nil,
DownstreamContentSize: nil,
RequestRefererHeader: "",
RequestUserAgentHeader: "",
RequestCount: 0,
RouterName: "",
ServiceURL: "",
},
expectedLog: `10.0.0.1 - Client [10/Nov/2009:23:00:00 +0000] "GET /foo http" - - "-" "-"
`,
},
{
name: "all data",
data: map[string]interface{}{
StartUTC: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
Duration: 123 * time.Second,
ClientHost: "10.0.0.1",
ClientUsername: "Client",
RequestMethod: http.MethodGet,
RequestPath: "/foo",
RequestProtocol: "http",
DownstreamStatus: 123,
DownstreamContentSize: 132,
RequestRefererHeader: "referer",
RequestUserAgentHeader: "agent",
RequestCount: nil,
RouterName: "foo",
ServiceURL: "http://10.0.0.2/toto",
},
expectedLog: `10.0.0.1 - Client [10/Nov/2009:23:00:00 +0000] "GET /foo http" 123 132 "referer" "agent"
`,
},
{
name: "all data with local time",
data: map[string]interface{}{
StartLocal: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
Duration: 123 * time.Second,
ClientHost: "10.0.0.1",
ClientUsername: "Client",
RequestMethod: http.MethodGet,
RequestPath: "/foo",
RequestProtocol: "http",
DownstreamStatus: 123,
DownstreamContentSize: 132,
RequestRefererHeader: "referer",
RequestUserAgentHeader: "agent",
RequestCount: nil,
RouterName: "foo",
ServiceURL: "http://10.0.0.2/toto",
},
expectedLog: `10.0.0.1 - Client [10/Nov/2009:14:00:00 -0900] "GET /foo http" 123 132 "referer" "agent"
`,
},
}
var err error
time.Local, err = time.LoadLocation("Etc/GMT+9")
require.NoError(t, err)
for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
entry := &logrus.Entry{Data: test.data}
raw, err := clf.Format(entry)
assert.NoError(t, err)
assert.Equal(t, test.expectedLog, string(raw))
})
}
}
func Test_toLog(t *testing.T) {
testCases := []struct {
desc string
fields logrus.Fields
fieldName string
defaultValue string
quoted bool
expectedLog interface{}
}{
{
desc: "Should return int 1",
fields: logrus.Fields{
"Powpow": 1,
},
fieldName: "Powpow",
defaultValue: defaultValue,
quoted: false,
expectedLog: 1,
},
{
desc: "Should return string foo",
fields: logrus.Fields{
"Powpow": "foo",
},
fieldName: "Powpow",
defaultValue: defaultValue,
quoted: true,
expectedLog: `"foo"`,
},
{
desc: "Should return defaultValue if fieldName does not exist",
fields: logrus.Fields{
"Powpow": "foo",
},
fieldName: "",
defaultValue: defaultValue,
quoted: false,
expectedLog: "-",
},
{
desc: "Should return defaultValue if fields is nil",
fields: nil,
fieldName: "",
defaultValue: defaultValue,
quoted: false,
expectedLog: "-",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
lg := toLog(test.fields, test.fieldName, defaultValue, test.quoted)
assert.Equal(t, test.expectedLog, lg)
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/accesslog/logger_formatters.go | pkg/middlewares/accesslog/logger_formatters.go | package accesslog
import (
"bytes"
"fmt"
"time"
"github.com/sirupsen/logrus"
)
// default format for time presentation.
const (
commonLogTimeFormat = "02/Jan/2006:15:04:05 -0700"
defaultValue = "-"
)
// CommonLogFormatter provides formatting in the Traefik common log format.
type CommonLogFormatter struct{}
// Format formats the log entry in the Traefik common log format.
func (f *CommonLogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
b := &bytes.Buffer{}
timestamp := defaultValue
if v, ok := entry.Data[StartUTC]; ok {
timestamp = v.(time.Time).Format(commonLogTimeFormat)
} else if v, ok := entry.Data[StartLocal]; ok {
timestamp = v.(time.Time).Local().Format(commonLogTimeFormat)
}
var elapsedMillis int64
if v, ok := entry.Data[Duration]; ok {
elapsedMillis = v.(time.Duration).Nanoseconds() / 1000000
}
_, err := fmt.Fprintf(b, "%s - %s [%s] \"%s %s %s\" %v %v %s %s %v %s %s %dms\n",
toLog(entry.Data, ClientHost, defaultValue, false),
toLog(entry.Data, ClientUsername, defaultValue, false),
timestamp,
toLog(entry.Data, RequestMethod, defaultValue, false),
toLog(entry.Data, RequestPath, defaultValue, false),
toLog(entry.Data, RequestProtocol, defaultValue, false),
toLog(entry.Data, DownstreamStatus, defaultValue, true),
toLog(entry.Data, DownstreamContentSize, defaultValue, true),
toLog(entry.Data, "request_Referer", `"-"`, true),
toLog(entry.Data, "request_User-Agent", `"-"`, true),
toLog(entry.Data, RequestCount, defaultValue, true),
toLog(entry.Data, RouterName, `"-"`, true),
toLog(entry.Data, ServiceURL, `"-"`, true),
elapsedMillis)
return b.Bytes(), err
}
// GenericCLFLogFormatter provides formatting in the generic CLF log format.
type GenericCLFLogFormatter struct{}
// Format formats the log entry in the generic CLF log format.
func (f *GenericCLFLogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
b := &bytes.Buffer{}
timestamp := defaultValue
if v, ok := entry.Data[StartUTC]; ok {
timestamp = v.(time.Time).Format(commonLogTimeFormat)
} else if v, ok := entry.Data[StartLocal]; ok {
timestamp = v.(time.Time).Local().Format(commonLogTimeFormat)
}
_, err := fmt.Fprintf(b, "%s - %s [%s] \"%s %s %s\" %v %v %s %s\n",
toLog(entry.Data, ClientHost, defaultValue, false),
toLog(entry.Data, ClientUsername, defaultValue, false),
timestamp,
toLog(entry.Data, RequestMethod, defaultValue, false),
toLog(entry.Data, RequestPath, defaultValue, false),
toLog(entry.Data, RequestProtocol, defaultValue, false),
toLog(entry.Data, DownstreamStatus, defaultValue, true),
toLog(entry.Data, DownstreamContentSize, defaultValue, true),
toLog(entry.Data, "request_Referer", `"-"`, true),
toLog(entry.Data, "request_User-Agent", `"-"`, true))
return b.Bytes(), err
}
func toLog(fields logrus.Fields, key, defaultValue string, quoted bool) interface{} {
if v, ok := fields[key]; ok {
if v == nil {
return defaultValue
}
switch s := v.(type) {
case string:
return toLogEntry(s, defaultValue, quoted)
case fmt.Stringer:
return toLogEntry(s.String(), defaultValue, quoted)
default:
return v
}
}
return defaultValue
}
func toLogEntry(s, defaultValue string, quote bool) string {
if len(s) == 0 {
return defaultValue
}
if quote {
return `"` + s + `"`
}
return s
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
traefik/traefik | https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/middlewares/accesslog/parser_test.go | pkg/middlewares/accesslog/parser_test.go | package accesslog
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestParseAccessLog(t *testing.T) {
testCases := []struct {
desc string
value string
expected map[string]string
}{
{
desc: "full log",
value: `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`,
expected: map[string]string{
ClientHost: "TestHost",
ClientUsername: "TestUser",
StartUTC: "13/Apr/2016:07:14:19 -0700",
RequestMethod: "POST",
RequestPath: "testpath",
RequestProtocol: "HTTP/0.0",
OriginStatus: "123",
OriginContentSize: "12",
RequestRefererHeader: `"testReferer"`,
RequestUserAgentHeader: `"testUserAgent"`,
RequestCount: "1",
RouterName: `"testRouter"`,
ServiceURL: `"http://127.0.0.1/testService"`,
Duration: "1ms",
},
},
{
desc: "log with space",
value: `127.0.0.1 - - [09/Mar/2018:10:51:32 +0000] "GET / HTTP/1.1" 401 17 "-" "Go-http-client/1.1" 1 "testRouter with space" - 0ms`,
expected: map[string]string{
ClientHost: "127.0.0.1",
ClientUsername: "-",
StartUTC: "09/Mar/2018:10:51:32 +0000",
RequestMethod: "GET",
RequestPath: "/",
RequestProtocol: "HTTP/1.1",
OriginStatus: "401",
OriginContentSize: "17",
RequestRefererHeader: `"-"`,
RequestUserAgentHeader: `"Go-http-client/1.1"`,
RequestCount: "1",
RouterName: `"testRouter with space"`,
ServiceURL: `-`,
Duration: "0ms",
},
},
{
desc: "bad log",
value: `bad`,
expected: map[string]string{},
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
result, err := ParseAccessLog(test.value)
assert.NoError(t, err)
assert.Len(t, result, len(test.expected))
for key, value := range test.expected {
assert.Equal(t, value, result[key])
}
})
}
}
| go | MIT | f7280439e6378221a541910f43a01323d52db048 | 2026-01-07T08:35:43.502324Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.