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/config/dynamic/plugins_test.go
pkg/config/dynamic/plugins_test.go
package dynamic import ( "testing" "github.com/stretchr/testify/assert" ) type FakeConfig struct { Name string `json:"name"` } // DeepCopyInto is a deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *FakeConfig) DeepCopyInto(out *FakeConfig) { *out = *in } // DeepCopy is a deepcopy function, copying the receiver, creating a new AddPrefix. func (in *FakeConfig) DeepCopy() *FakeConfig { if in == nil { return nil } out := new(FakeConfig) in.DeepCopyInto(out) return out } type Foo struct { Name string } func TestPluginConf_DeepCopy_mapOfStruct(t *testing.T) { f := &FakeConfig{Name: "bir"} p := PluginConf{ "fii": f, } clone := p.DeepCopy() assert.Equal(t, &p, clone) f.Name = "bur" assert.NotEqual(t, &p, clone) } func TestPluginConf_DeepCopy_map(t *testing.T) { m := map[string]interface{}{ "name": "bar", } p := PluginConf{ "config": map[string]interface{}{ "foo": m, }, } clone := p.DeepCopy() assert.Equal(t, &p, clone) p["one"] = "a" m["two"] = "b" assert.NotEqual(t, &p, clone) } func TestPluginConf_DeepCopy_panic(t *testing.T) { p := &PluginConf{ "config": map[string]interface{}{ "foo": &Foo{Name: "gigi"}, }, } assert.Panics(t, func() { p.DeepCopy() }) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/dynamic/config.go
pkg/config/dynamic/config.go
package dynamic import ( "github.com/traefik/traefik/v3/pkg/tls" ) // +k8s:deepcopy-gen=true // Message holds configuration information exchanged between parts of traefik. type Message struct { ProviderName string Configuration *Configuration } // +k8s:deepcopy-gen=true // Configurations is for currentConfigurations Map. type Configurations map[string]*Configuration // +k8s:deepcopy-gen=true // Configuration is the root of the dynamic configuration. type Configuration struct { HTTP *HTTPConfiguration `json:"http,omitempty" toml:"http,omitempty" yaml:"http,omitempty" export:"true"` TCP *TCPConfiguration `json:"tcp,omitempty" toml:"tcp,omitempty" yaml:"tcp,omitempty" export:"true"` UDP *UDPConfiguration `json:"udp,omitempty" toml:"udp,omitempty" yaml:"udp,omitempty" export:"true"` TLS *TLSConfiguration `json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // TLSConfiguration contains all the configuration parameters of a TLS connection. type TLSConfiguration struct { Certificates []*tls.CertAndStores `json:"certificates,omitempty" toml:"certificates,omitempty" yaml:"certificates,omitempty" label:"-" export:"true"` Options map[string]tls.Options `json:"options,omitempty" toml:"options,omitempty" yaml:"options,omitempty" label:"-" export:"true"` Stores map[string]tls.Store `json:"stores,omitempty" toml:"stores,omitempty" yaml:"stores,omitempty" export:"true"` }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/dynamic/middlewares.go
pkg/config/dynamic/middlewares.go
package dynamic import ( "fmt" "net/http" "time" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/ip" "github.com/traefik/traefik/v3/pkg/types" ) // ForwardAuthDefaultMaxBodySize is the ForwardAuth.MaxBodySize option default value. const ForwardAuthDefaultMaxBodySize int64 = -1 // +k8s:deepcopy-gen=true // Middleware holds the Middleware configuration. type Middleware struct { AddPrefix *AddPrefix `json:"addPrefix,omitempty" toml:"addPrefix,omitempty" yaml:"addPrefix,omitempty" export:"true"` StripPrefix *StripPrefix `json:"stripPrefix,omitempty" toml:"stripPrefix,omitempty" yaml:"stripPrefix,omitempty" export:"true"` StripPrefixRegex *StripPrefixRegex `json:"stripPrefixRegex,omitempty" toml:"stripPrefixRegex,omitempty" yaml:"stripPrefixRegex,omitempty" export:"true"` ReplacePath *ReplacePath `json:"replacePath,omitempty" toml:"replacePath,omitempty" yaml:"replacePath,omitempty" export:"true"` ReplacePathRegex *ReplacePathRegex `json:"replacePathRegex,omitempty" toml:"replacePathRegex,omitempty" yaml:"replacePathRegex,omitempty" export:"true"` Chain *Chain `json:"chain,omitempty" toml:"chain,omitempty" yaml:"chain,omitempty" export:"true"` // Deprecated: please use IPAllowList instead. IPWhiteList *IPWhiteList `json:"ipWhiteList,omitempty" toml:"ipWhiteList,omitempty" yaml:"ipWhiteList,omitempty" export:"true"` IPAllowList *IPAllowList `json:"ipAllowList,omitempty" toml:"ipAllowList,omitempty" yaml:"ipAllowList,omitempty" export:"true"` Headers *Headers `json:"headers,omitempty" toml:"headers,omitempty" yaml:"headers,omitempty" export:"true"` Errors *ErrorPage `json:"errors,omitempty" toml:"errors,omitempty" yaml:"errors,omitempty" export:"true"` RateLimit *RateLimit `json:"rateLimit,omitempty" toml:"rateLimit,omitempty" yaml:"rateLimit,omitempty" export:"true"` RedirectRegex *RedirectRegex `json:"redirectRegex,omitempty" toml:"redirectRegex,omitempty" yaml:"redirectRegex,omitempty" export:"true"` RedirectScheme *RedirectScheme `json:"redirectScheme,omitempty" toml:"redirectScheme,omitempty" yaml:"redirectScheme,omitempty" export:"true"` BasicAuth *BasicAuth `json:"basicAuth,omitempty" toml:"basicAuth,omitempty" yaml:"basicAuth,omitempty" export:"true"` DigestAuth *DigestAuth `json:"digestAuth,omitempty" toml:"digestAuth,omitempty" yaml:"digestAuth,omitempty" export:"true"` ForwardAuth *ForwardAuth `json:"forwardAuth,omitempty" toml:"forwardAuth,omitempty" yaml:"forwardAuth,omitempty" export:"true"` InFlightReq *InFlightReq `json:"inFlightReq,omitempty" toml:"inFlightReq,omitempty" yaml:"inFlightReq,omitempty" export:"true"` Buffering *Buffering `json:"buffering,omitempty" toml:"buffering,omitempty" yaml:"buffering,omitempty" export:"true"` CircuitBreaker *CircuitBreaker `json:"circuitBreaker,omitempty" toml:"circuitBreaker,omitempty" yaml:"circuitBreaker,omitempty" export:"true"` Compress *Compress `json:"compress,omitempty" toml:"compress,omitempty" yaml:"compress,omitempty" label:"allowEmpty" file:"allowEmpty" kv:"allowEmpty" export:"true"` PassTLSClientCert *PassTLSClientCert `json:"passTLSClientCert,omitempty" toml:"passTLSClientCert,omitempty" yaml:"passTLSClientCert,omitempty" export:"true"` Retry *Retry `json:"retry,omitempty" toml:"retry,omitempty" yaml:"retry,omitempty" export:"true"` ContentType *ContentType `json:"contentType,omitempty" toml:"contentType,omitempty" yaml:"contentType,omitempty" label:"allowEmpty" file:"allowEmpty" kv:"allowEmpty" export:"true"` GrpcWeb *GrpcWeb `json:"grpcWeb,omitempty" toml:"grpcWeb,omitempty" yaml:"grpcWeb,omitempty" export:"true"` Plugin map[string]PluginConf `json:"plugin,omitempty" toml:"plugin,omitempty" yaml:"plugin,omitempty" export:"true"` // Gateway API filter middlewares. RequestHeaderModifier *HeaderModifier `json:"requestHeaderModifier,omitempty" toml:"-" yaml:"-" label:"-" file:"-" kv:"-" export:"true"` ResponseHeaderModifier *HeaderModifier `json:"responseHeaderModifier,omitempty" toml:"-" yaml:"-" label:"-" file:"-" kv:"-" export:"true"` RequestRedirect *RequestRedirect `json:"requestRedirect,omitempty" toml:"-" yaml:"-" label:"-" file:"-" kv:"-" export:"true"` URLRewrite *URLRewrite `json:"URLRewrite,omitempty" toml:"-" yaml:"-" label:"-" file:"-" kv:"-" export:"true"` } // +k8s:deepcopy-gen=true // GrpcWeb holds the gRPC web middleware configuration. // This middleware converts a gRPC web request to an HTTP/2 gRPC request. type GrpcWeb struct { // AllowOrigins is a list of allowable origins. // Can also be a wildcard origin "*". AllowOrigins []string `json:"allowOrigins,omitempty" toml:"allowOrigins,omitempty" yaml:"allowOrigins,omitempty"` } // +k8s:deepcopy-gen=true // ContentType holds the content-type middleware configuration. // This middleware exists to enable the correct behavior until at least the default one can be changed in a future version. type ContentType struct { // AutoDetect specifies whether to let the `Content-Type` header, if it has not been set by the backend, // be automatically set to a value derived from the contents of the response. // Deprecated: 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. AutoDetect *bool `json:"autoDetect,omitempty" toml:"autoDetect,omitempty" yaml:"autoDetect,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // AddPrefix holds the add prefix middleware configuration. // This middleware updates the path of a request before forwarding it. // More info: https://doc.traefik.io/traefik/v3.6/middlewares/http/addprefix/ type AddPrefix struct { // Prefix is the string to add before the current path in the requested URL. // It should include a leading slash (/). // +kubebuilder:validation:XValidation:message="must start with a '/'",rule="self.startsWith('/')" Prefix string `json:"prefix,omitempty" toml:"prefix,omitempty" yaml:"prefix,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // BasicAuth holds the basic auth middleware configuration. // This middleware restricts access to your services to known users. // More info: https://doc.traefik.io/traefik/v3.6/middlewares/http/basicauth/ type BasicAuth struct { // Users is an array of authorized users. // Each user must be declared using the name:hashed-password format. // Tip: Use htpasswd to generate the passwords. Users Users `json:"users,omitempty" toml:"users,omitempty" yaml:"users,omitempty" loggable:"false"` // UsersFile is the path to an external file that contains the authorized users. UsersFile string `json:"usersFile,omitempty" toml:"usersFile,omitempty" yaml:"usersFile,omitempty"` // Realm allows the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme. // Default: traefik. Realm string `json:"realm,omitempty" toml:"realm,omitempty" yaml:"realm,omitempty"` // RemoveHeader sets the removeHeader option to true to remove the authorization header before forwarding the request to your service. // Default: false. RemoveHeader bool `json:"removeHeader,omitempty" toml:"removeHeader,omitempty" yaml:"removeHeader,omitempty" export:"true"` // HeaderField defines a header field to store the authenticated user. // More info: https://doc.traefik.io/traefik/v3.6/middlewares/http/basicauth/#headerfield HeaderField string `json:"headerField,omitempty" toml:"headerField,omitempty" yaml:"headerField,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // Buffering holds the buffering middleware configuration. // This middleware retries or limits the size of requests that can be forwarded to backends. // More info: https://doc.traefik.io/traefik/v3.6/middlewares/http/buffering/#maxrequestbodybytes type Buffering struct { // MaxRequestBodyBytes defines the maximum allowed body size for the request (in bytes). // If the request exceeds the allowed size, it is not forwarded to the service, and the client gets a 413 (Request Entity Too Large) response. // Default: 0 (no maximum). MaxRequestBodyBytes int64 `json:"maxRequestBodyBytes,omitempty" toml:"maxRequestBodyBytes,omitempty" yaml:"maxRequestBodyBytes,omitempty" export:"true"` // MemRequestBodyBytes defines the threshold (in bytes) from which the request will be buffered on disk instead of in memory. // Default: 1048576 (1Mi). MemRequestBodyBytes int64 `json:"memRequestBodyBytes,omitempty" toml:"memRequestBodyBytes,omitempty" yaml:"memRequestBodyBytes,omitempty" export:"true"` // MaxResponseBodyBytes defines the maximum allowed response size from the service (in bytes). // If the response exceeds the allowed size, it is not forwarded to the client. The client gets a 500 (Internal Server Error) response instead. // Default: 0 (no maximum). MaxResponseBodyBytes int64 `json:"maxResponseBodyBytes,omitempty" toml:"maxResponseBodyBytes,omitempty" yaml:"maxResponseBodyBytes,omitempty" export:"true"` // MemResponseBodyBytes defines the threshold (in bytes) from which the response will be buffered on disk instead of in memory. // Default: 1048576 (1Mi). MemResponseBodyBytes int64 `json:"memResponseBodyBytes,omitempty" toml:"memResponseBodyBytes,omitempty" yaml:"memResponseBodyBytes,omitempty" export:"true"` // RetryExpression defines the retry conditions. // It is a logical combination of functions with operators AND (&&) and OR (||). // More info: https://doc.traefik.io/traefik/v3.6/middlewares/http/buffering/#retryexpression RetryExpression string `json:"retryExpression,omitempty" toml:"retryExpression,omitempty" yaml:"retryExpression,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // Chain holds the chain middleware configuration. // This middleware enables to define reusable combinations of other pieces of middleware. type Chain struct { // Middlewares is the list of middleware names which composes the chain. Middlewares []string `json:"middlewares,omitempty" toml:"middlewares,omitempty" yaml:"middlewares,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // CircuitBreaker holds the circuit breaker middleware configuration. // This middleware protects the system from stacking requests to unhealthy services, resulting in cascading failures. // More info: https://doc.traefik.io/traefik/v3.6/middlewares/http/circuitbreaker/ type CircuitBreaker struct { // Expression defines the expression that, once matched, opens the circuit breaker and applies the fallback mechanism instead of calling the services. Expression string `json:"expression,omitempty" toml:"expression,omitempty" yaml:"expression,omitempty" export:"true"` // CheckPeriod is the interval between successive checks of the circuit breaker condition (when in standby state). CheckPeriod ptypes.Duration `json:"checkPeriod,omitempty" toml:"checkPeriod,omitempty" yaml:"checkPeriod,omitempty" export:"true"` // FallbackDuration is the duration for which the circuit breaker will wait before trying to recover (from a tripped state). FallbackDuration ptypes.Duration `json:"fallbackDuration,omitempty" toml:"fallbackDuration,omitempty" yaml:"fallbackDuration,omitempty" export:"true"` // RecoveryDuration is the duration for which the circuit breaker will try to recover (as soon as it is in recovering state). RecoveryDuration ptypes.Duration `json:"recoveryDuration,omitempty" toml:"recoveryDuration,omitempty" yaml:"recoveryDuration,omitempty" export:"true"` // ResponseCode is the status code that the circuit breaker will return while it is in the open state. ResponseCode int `json:"responseCode,omitempty" toml:"responseCode,omitempty" yaml:"responseCode,omitempty" export:"true"` } // SetDefaults sets the default values on a RateLimit. func (c *CircuitBreaker) SetDefaults() { c.CheckPeriod = ptypes.Duration(100 * time.Millisecond) c.FallbackDuration = ptypes.Duration(10 * time.Second) c.RecoveryDuration = ptypes.Duration(10 * time.Second) c.ResponseCode = http.StatusServiceUnavailable } // +k8s:deepcopy-gen=true // Compress holds the compress middleware configuration. // This middleware compresses responses before sending them to the client, using gzip, brotli, or zstd compression. type Compress struct { // ExcludedContentTypes defines the list of content types to compare the Content-Type header of the incoming requests and responses before compressing. // `application/grpc` is always excluded. ExcludedContentTypes []string `json:"excludedContentTypes,omitempty" toml:"excludedContentTypes,omitempty" yaml:"excludedContentTypes,omitempty" export:"true"` // IncludedContentTypes defines the list of content types to compare the Content-Type header of the responses before compressing. IncludedContentTypes []string `json:"includedContentTypes,omitempty" toml:"includedContentTypes,omitempty" yaml:"includedContentTypes,omitempty" export:"true"` // MinResponseBodyBytes defines the minimum amount of bytes a response body must have to be compressed. // Default: 1024. // +kubebuilder:validation:Minimum=0 MinResponseBodyBytes int `json:"minResponseBodyBytes,omitempty" toml:"minResponseBodyBytes,omitempty" yaml:"minResponseBodyBytes,omitempty" export:"true"` // Encodings defines the list of supported compression algorithms. Encodings []string `json:"encodings,omitempty" toml:"encodings,omitempty" yaml:"encodings,omitempty" export:"true"` // DefaultEncoding specifies the default encoding if the `Accept-Encoding` header is not in the request or contains a wildcard (`*`). DefaultEncoding string `json:"defaultEncoding,omitempty" toml:"defaultEncoding,omitempty" yaml:"defaultEncoding,omitempty" export:"true"` } func (c *Compress) SetDefaults() { c.Encodings = []string{"gzip", "br", "zstd"} } // +k8s:deepcopy-gen=true // DigestAuth holds the digest auth middleware configuration. // This middleware restricts access to your services to known users. // More info: https://doc.traefik.io/traefik/v3.6/middlewares/http/digestauth/ type DigestAuth struct { // Users defines the authorized users. // Each user should be declared using the name:realm:encoded-password format. Users Users `json:"users,omitempty" toml:"users,omitempty" yaml:"users,omitempty" loggable:"false"` // UsersFile is the path to an external file that contains the authorized users for the middleware. UsersFile string `json:"usersFile,omitempty" toml:"usersFile,omitempty" yaml:"usersFile,omitempty"` // RemoveHeader defines whether to remove the authorization header before forwarding the request to the backend. RemoveHeader bool `json:"removeHeader,omitempty" toml:"removeHeader,omitempty" yaml:"removeHeader,omitempty" export:"true"` // Realm allows the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme. // Default: traefik. Realm string `json:"realm,omitempty" toml:"realm,omitempty" yaml:"realm,omitempty"` // HeaderField defines a header field to store the authenticated user. // More info: https://doc.traefik.io/traefik/v3.6/middlewares/http/basicauth/#headerfield HeaderField string `json:"headerField,omitempty" toml:"headerField,omitempty" yaml:"headerField,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // ErrorPage holds the custom error middleware configuration. // This middleware returns a custom page in lieu of the default, according to configured ranges of HTTP Status codes. type ErrorPage struct { // Status defines which status or range of statuses should result in an error page. // It can be either a status code as a number (500), // as multiple comma-separated numbers (500,502), // as ranges by separating two codes with a dash (500-599), // or a combination of the two (404,418,500-599). Status []string `json:"status,omitempty" toml:"status,omitempty" yaml:"status,omitempty" export:"true"` // StatusRewrites defines a mapping of status codes that should be returned instead of the original error status codes. // For example: "418": 404 or "410-418": 404 StatusRewrites map[string]int `json:"statusRewrites,omitempty" toml:"statusRewrites,omitempty" yaml:"statusRewrites,omitempty" export:"true"` // Service defines the name of the service that will serve the error page. Service string `json:"service,omitempty" toml:"service,omitempty" yaml:"service,omitempty" export:"true"` // Query defines the URL for the error page (hosted by service). // The {status} variable can be used in order to insert the status code in the URL. // The {originalStatus} variable can be used in order to insert the upstream status code in the URL. // The {url} variable can be used in order to insert the escaped request URL. Query string `json:"query,omitempty" toml:"query,omitempty" yaml:"query,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // ForwardAuth holds the forward auth middleware configuration. // This middleware delegates the request authentication to a Service. // More info: https://doc.traefik.io/traefik/v3.6/middlewares/http/forwardauth/ type ForwardAuth struct { // Address defines the authentication server address. Address string `json:"address,omitempty" toml:"address,omitempty" yaml:"address,omitempty"` // TLS defines the configuration used to secure the connection to the authentication server. TLS *ClientTLS `json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" export:"true"` // TrustForwardHeader defines whether to trust (ie: forward) all X-Forwarded-* headers. TrustForwardHeader bool `json:"trustForwardHeader,omitempty" toml:"trustForwardHeader,omitempty" yaml:"trustForwardHeader,omitempty" export:"true"` // AuthResponseHeaders defines the list of headers to copy from the authentication server response and set on forwarded request, replacing any existing conflicting headers. AuthResponseHeaders []string `json:"authResponseHeaders,omitempty" toml:"authResponseHeaders,omitempty" yaml:"authResponseHeaders,omitempty" export:"true"` // AuthResponseHeadersRegex defines the regex to match headers to copy from the authentication server response and set on forwarded request, after stripping all headers that match the regex. // More info: https://doc.traefik.io/traefik/v3.6/middlewares/http/forwardauth/#authresponseheadersregex AuthResponseHeadersRegex string `json:"authResponseHeadersRegex,omitempty" toml:"authResponseHeadersRegex,omitempty" yaml:"authResponseHeadersRegex,omitempty" export:"true"` // AuthRequestHeaders defines the list of the headers to copy from the request to the authentication server. // If not set or empty then all request headers are passed. AuthRequestHeaders []string `json:"authRequestHeaders,omitempty" toml:"authRequestHeaders,omitempty" yaml:"authRequestHeaders,omitempty" export:"true"` // AddAuthCookiesToResponse defines the list of cookies to copy from the authentication server response to the response. AddAuthCookiesToResponse []string `json:"addAuthCookiesToResponse,omitempty" toml:"addAuthCookiesToResponse,omitempty" yaml:"addAuthCookiesToResponse,omitempty" export:"true"` // HeaderField defines a header field to store the authenticated user. // More info: https://doc.traefik.io/traefik/v3.6/middlewares/http/forwardauth/#headerfield HeaderField string `json:"headerField,omitempty" toml:"headerField,omitempty" yaml:"headerField,omitempty" export:"true"` // ForwardBody defines whether to send the request body to the authentication server. ForwardBody bool `json:"forwardBody,omitempty" toml:"forwardBody,omitempty" yaml:"forwardBody,omitempty" export:"true"` // MaxBodySize defines the maximum body size in bytes allowed to be forwarded to the authentication server. MaxBodySize *int64 `json:"maxBodySize,omitempty" toml:"maxBodySize,omitempty" yaml:"maxBodySize,omitempty" export:"true"` // PreserveLocationHeader defines whether to forward the Location header to the client as is or prefix it with the domain name of the authentication server. PreserveLocationHeader bool `json:"preserveLocationHeader,omitempty" toml:"preserveLocationHeader,omitempty" yaml:"preserveLocationHeader,omitempty" export:"true"` // PreserveRequestMethod defines whether to preserve the original request method while forwarding the request to the authentication server. PreserveRequestMethod bool `json:"preserveRequestMethod,omitempty" toml:"preserveRequestMethod,omitempty" yaml:"preserveRequestMethod,omitempty" export:"true"` } func (f *ForwardAuth) SetDefaults() { defaultMaxBodySize := ForwardAuthDefaultMaxBodySize f.MaxBodySize = &defaultMaxBodySize } // +k8s:deepcopy-gen=true // ClientTLS holds TLS specific configurations as client // CA, Cert and Key can be either path or file contents. // TODO: remove this struct when CAOptional option will be removed. type ClientTLS struct { CA string `description:"TLS CA" json:"ca,omitempty" toml:"ca,omitempty" yaml:"ca,omitempty"` Cert string `description:"TLS cert" json:"cert,omitempty" toml:"cert,omitempty" yaml:"cert,omitempty"` Key string `description:"TLS key" json:"key,omitempty" toml:"key,omitempty" yaml:"key,omitempty" loggable:"false"` InsecureSkipVerify bool `description:"TLS insecure skip verify" json:"insecureSkipVerify,omitempty" toml:"insecureSkipVerify,omitempty" yaml:"insecureSkipVerify,omitempty" export:"true"` // Deprecated: TLS client authentication is a server side option (see https://github.com/golang/go/blob/740a490f71d026bb7d2d13cb8fa2d6d6e0572b70/src/crypto/tls/common.go#L634). CAOptional *bool `description:"TLS CA.Optional" json:"caOptional,omitempty" toml:"caOptional,omitempty" yaml:"caOptional,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // Headers holds the headers middleware configuration. // This middleware manages the requests and responses headers. // More info: https://doc.traefik.io/traefik/v3.6/middlewares/http/headers/#customrequestheaders type Headers struct { // CustomRequestHeaders defines the header names and values to apply to the request. CustomRequestHeaders map[string]string `json:"customRequestHeaders,omitempty" toml:"customRequestHeaders,omitempty" yaml:"customRequestHeaders,omitempty" export:"true"` // CustomResponseHeaders defines the header names and values to apply to the response. CustomResponseHeaders map[string]string `json:"customResponseHeaders,omitempty" toml:"customResponseHeaders,omitempty" yaml:"customResponseHeaders,omitempty" export:"true"` // AccessControlAllowCredentials defines whether the request can include user credentials. AccessControlAllowCredentials bool `json:"accessControlAllowCredentials,omitempty" toml:"accessControlAllowCredentials,omitempty" yaml:"accessControlAllowCredentials,omitempty" export:"true"` // AccessControlAllowHeaders defines the Access-Control-Request-Headers values sent in preflight response. AccessControlAllowHeaders []string `json:"accessControlAllowHeaders,omitempty" toml:"accessControlAllowHeaders,omitempty" yaml:"accessControlAllowHeaders,omitempty" export:"true"` // AccessControlAllowMethods defines the Access-Control-Request-Method values sent in preflight response. AccessControlAllowMethods []string `json:"accessControlAllowMethods,omitempty" toml:"accessControlAllowMethods,omitempty" yaml:"accessControlAllowMethods,omitempty" export:"true"` // AccessControlAllowOriginList is a list of allowable origins. Can also be a wildcard origin "*". AccessControlAllowOriginList []string `json:"accessControlAllowOriginList,omitempty" toml:"accessControlAllowOriginList,omitempty" yaml:"accessControlAllowOriginList,omitempty"` // AccessControlAllowOriginListRegex is a list of allowable origins written following the Regular Expression syntax (https://golang.org/pkg/regexp/). AccessControlAllowOriginListRegex []string `json:"accessControlAllowOriginListRegex,omitempty" toml:"accessControlAllowOriginListRegex,omitempty" yaml:"accessControlAllowOriginListRegex,omitempty"` // AccessControlExposeHeaders defines the Access-Control-Expose-Headers values sent in preflight response. AccessControlExposeHeaders []string `json:"accessControlExposeHeaders,omitempty" toml:"accessControlExposeHeaders,omitempty" yaml:"accessControlExposeHeaders,omitempty" export:"true"` // AccessControlMaxAge defines the time that a preflight request may be cached. AccessControlMaxAge int64 `json:"accessControlMaxAge,omitempty" toml:"accessControlMaxAge,omitempty" yaml:"accessControlMaxAge,omitempty" export:"true"` // AddVaryHeader defines whether the Vary header is automatically added/updated when the AccessControlAllowOriginList is set. AddVaryHeader bool `json:"addVaryHeader,omitempty" toml:"addVaryHeader,omitempty" yaml:"addVaryHeader,omitempty" export:"true"` // AllowedHosts defines the fully qualified list of allowed domain names. AllowedHosts []string `json:"allowedHosts,omitempty" toml:"allowedHosts,omitempty" yaml:"allowedHosts,omitempty"` // HostsProxyHeaders defines the header keys that may hold a proxied hostname value for the request. HostsProxyHeaders []string `json:"hostsProxyHeaders,omitempty" toml:"hostsProxyHeaders,omitempty" yaml:"hostsProxyHeaders,omitempty" export:"true"` // SSLProxyHeaders defines the header keys with associated values that would indicate a valid HTTPS request. // It can be useful when using other proxies (example: "X-Forwarded-Proto": "https"). SSLProxyHeaders map[string]string `json:"sslProxyHeaders,omitempty" toml:"sslProxyHeaders,omitempty" yaml:"sslProxyHeaders,omitempty"` // STSSeconds defines the max-age of the Strict-Transport-Security header. // If set to 0, the header is not set. // +kubebuilder:validation:Minimum=0 STSSeconds int64 `json:"stsSeconds,omitempty" toml:"stsSeconds,omitempty" yaml:"stsSeconds,omitempty" export:"true"` // STSIncludeSubdomains defines whether the includeSubDomains directive is appended to the Strict-Transport-Security header. STSIncludeSubdomains bool `json:"stsIncludeSubdomains,omitempty" toml:"stsIncludeSubdomains,omitempty" yaml:"stsIncludeSubdomains,omitempty" export:"true"` // STSPreload defines whether the preload flag is appended to the Strict-Transport-Security header. STSPreload bool `json:"stsPreload,omitempty" toml:"stsPreload,omitempty" yaml:"stsPreload,omitempty" export:"true"` // ForceSTSHeader defines whether to add the STS header even when the connection is HTTP. ForceSTSHeader bool `json:"forceSTSHeader,omitempty" toml:"forceSTSHeader,omitempty" yaml:"forceSTSHeader,omitempty" export:"true"` // FrameDeny defines whether to add the X-Frame-Options header with the DENY value. FrameDeny bool `json:"frameDeny,omitempty" toml:"frameDeny,omitempty" yaml:"frameDeny,omitempty" export:"true"` // CustomFrameOptionsValue defines the X-Frame-Options header value. // This overrides the FrameDeny option. CustomFrameOptionsValue string `json:"customFrameOptionsValue,omitempty" toml:"customFrameOptionsValue,omitempty" yaml:"customFrameOptionsValue,omitempty"` // ContentTypeNosniff defines whether to add the X-Content-Type-Options header with the nosniff value. ContentTypeNosniff bool `json:"contentTypeNosniff,omitempty" toml:"contentTypeNosniff,omitempty" yaml:"contentTypeNosniff,omitempty" export:"true"` // BrowserXSSFilter defines whether to add the X-XSS-Protection header with the value 1; mode=block. BrowserXSSFilter bool `json:"browserXssFilter,omitempty" toml:"browserXssFilter,omitempty" yaml:"browserXssFilter,omitempty" export:"true"` // CustomBrowserXSSValue defines the X-XSS-Protection header value. // This overrides the BrowserXssFilter option. CustomBrowserXSSValue string `json:"customBrowserXSSValue,omitempty" toml:"customBrowserXSSValue,omitempty" yaml:"customBrowserXSSValue,omitempty"` // ContentSecurityPolicy defines the Content-Security-Policy header value. ContentSecurityPolicy string `json:"contentSecurityPolicy,omitempty" toml:"contentSecurityPolicy,omitempty" yaml:"contentSecurityPolicy,omitempty"` // ContentSecurityPolicyReportOnly defines the Content-Security-Policy-Report-Only header value. ContentSecurityPolicyReportOnly string `json:"contentSecurityPolicyReportOnly,omitempty" toml:"contentSecurityPolicyReportOnly,omitempty" yaml:"contentSecurityPolicyReportOnly,omitempty"` // PublicKey is the public key that implements HPKP to prevent MITM attacks with forged certificates. PublicKey string `json:"publicKey,omitempty" toml:"publicKey,omitempty" yaml:"publicKey,omitempty"` // ReferrerPolicy defines the Referrer-Policy header value. // This allows sites to control whether browsers forward the Referer header to other sites. ReferrerPolicy string `json:"referrerPolicy,omitempty" toml:"referrerPolicy,omitempty" yaml:"referrerPolicy,omitempty" export:"true"` // PermissionsPolicy defines the Permissions-Policy header value. // This allows sites to control browser features. PermissionsPolicy string `json:"permissionsPolicy,omitempty" toml:"permissionsPolicy,omitempty" yaml:"permissionsPolicy,omitempty" export:"true"` // IsDevelopment defines whether to mitigate the unwanted effects of the AllowedHosts, SSL, and STS options when developing. // Usually testing takes place using HTTP, not HTTPS, and on localhost, not your production domain. // If you would like your development environment to mimic production with complete Host blocking, SSL redirects, // and STS headers, leave this as false. IsDevelopment bool `json:"isDevelopment,omitempty" toml:"isDevelopment,omitempty" yaml:"isDevelopment,omitempty" export:"true"` // Deprecated: FeaturePolicy option is deprecated, please use PermissionsPolicy instead. FeaturePolicy *string `json:"featurePolicy,omitempty" toml:"featurePolicy,omitempty" yaml:"featurePolicy,omitempty" export:"true"` // Deprecated: SSLRedirect option is deprecated, please use EntryPoint redirection or RedirectScheme instead. SSLRedirect *bool `json:"sslRedirect,omitempty" toml:"sslRedirect,omitempty" yaml:"sslRedirect,omitempty" export:"true"` // Deprecated: SSLTemporaryRedirect option is deprecated, please use EntryPoint redirection or RedirectScheme instead. SSLTemporaryRedirect *bool `json:"sslTemporaryRedirect,omitempty" toml:"sslTemporaryRedirect,omitempty" yaml:"sslTemporaryRedirect,omitempty" export:"true"` // Deprecated: SSLHost option is deprecated, please use RedirectRegex instead. SSLHost *string `json:"sslHost,omitempty" toml:"sslHost,omitempty" yaml:"sslHost,omitempty"` // Deprecated: SSLForceHost option is deprecated, please use RedirectRegex instead. SSLForceHost *bool `json:"sslForceHost,omitempty" toml:"sslForceHost,omitempty" yaml:"sslForceHost,omitempty" export:"true"` } // HasCustomHeadersDefined checks to see if any of the custom header elements have been set. func (h *Headers) HasCustomHeadersDefined() bool { return h != nil && (len(h.CustomResponseHeaders) != 0 || len(h.CustomRequestHeaders) != 0) } // HasCorsHeadersDefined checks to see if any of the cors header elements have been set. func (h *Headers) HasCorsHeadersDefined() bool { return h != nil && (h.AccessControlAllowCredentials || len(h.AccessControlAllowHeaders) != 0 || len(h.AccessControlAllowMethods) != 0 || len(h.AccessControlAllowOriginList) != 0 || len(h.AccessControlAllowOriginListRegex) != 0 || len(h.AccessControlExposeHeaders) != 0 || h.AccessControlMaxAge != 0 || h.AddVaryHeader) } // HasSecureHeadersDefined checks to see if any of the secure header elements have been set. func (h *Headers) HasSecureHeadersDefined() bool { return h != nil && (len(h.AllowedHosts) != 0 || len(h.HostsProxyHeaders) != 0 || (h.SSLRedirect != nil && *h.SSLRedirect) || (h.SSLTemporaryRedirect != nil && *h.SSLTemporaryRedirect) || (h.SSLForceHost != nil && *h.SSLForceHost) || (h.SSLHost != nil && *h.SSLHost != "") || len(h.SSLProxyHeaders) != 0 || h.STSSeconds != 0 || h.STSIncludeSubdomains || h.STSPreload || h.ForceSTSHeader || h.FrameDeny || h.CustomFrameOptionsValue != "" || h.ContentTypeNosniff || h.BrowserXSSFilter || h.CustomBrowserXSSValue != "" || h.ContentSecurityPolicy != "" || h.ContentSecurityPolicyReportOnly != "" || h.PublicKey != "" || h.ReferrerPolicy != "" || (h.FeaturePolicy != nil && *h.FeaturePolicy != "") || h.PermissionsPolicy != "" || h.IsDevelopment) } // +k8s:deepcopy-gen=true // IPStrategy holds the IP strategy configuration used by Traefik to determine the client IP. // More info: https://doc.traefik.io/traefik/v3.6/middlewares/http/ipallowlist/#ipstrategy
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/dynamic/plugins.go
pkg/config/dynamic/plugins.go
package dynamic import ( "encoding/json" "fmt" "reflect" ) // +k8s:deepcopy-gen=false // PluginConf holds the plugin configuration. type PluginConf map[string]any // DeepCopyInto is a deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PluginConf) DeepCopyInto(out *PluginConf) { if in == nil { *out = nil } else { *out = deepCopyJSON(*in) } } // DeepCopy is a deepcopy function, copying the receiver, creating a new PluginConf. func (in *PluginConf) DeepCopy() *PluginConf { if in == nil { return nil } out := new(PluginConf) in.DeepCopyInto(out) return out } // inspired by https://github.com/kubernetes/apimachinery/blob/53ecdf01b997ca93c7db7615dfe7b27ad8391983/pkg/runtime/converter.go#L607 func deepCopyJSON(x map[string]any) map[string]any { return deepCopyJSONValue(x).(map[string]any) } func deepCopyJSONValue(x any) any { switch x := x.(type) { case map[string]any: if x == nil { // Typed nil - an any that contains a type map[string]any with a value of nil return x } clone := make(map[string]any, len(x)) for k, v := range x { clone[k] = deepCopyJSONValue(v) } return clone case []any: if x == nil { // Typed nil - an any that contains a type []any with a value of nil return x } clone := make([]any, len(x)) for i, v := range x { clone[i] = deepCopyJSONValue(v) } return clone case string, int64, bool, float64, nil, json.Number: return x default: v := reflect.ValueOf(x) if v.NumMethod() == 0 { panic(fmt.Errorf("cannot deep copy %T", x)) } method := v.MethodByName("DeepCopy") if method.Kind() == reflect.Invalid { panic(fmt.Errorf("cannot deep copy %T", x)) } call := method.Call(nil) return call[0].Interface() } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/dynamic/tcp_middlewares.go
pkg/config/dynamic/tcp_middlewares.go
package dynamic // +k8s:deepcopy-gen=true // TCPMiddleware holds the TCPMiddleware configuration. type TCPMiddleware struct { InFlightConn *TCPInFlightConn `json:"inFlightConn,omitempty" toml:"inFlightConn,omitempty" yaml:"inFlightConn,omitempty" export:"true"` // Deprecated: please use IPAllowList instead. IPWhiteList *TCPIPWhiteList `json:"ipWhiteList,omitempty" toml:"ipWhiteList,omitempty" yaml:"ipWhiteList,omitempty" export:"true"` IPAllowList *TCPIPAllowList `json:"ipAllowList,omitempty" toml:"ipAllowList,omitempty" yaml:"ipAllowList,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // TCPInFlightConn holds the TCP InFlightConn middleware configuration. // This middleware prevents services from being overwhelmed with high load, // by limiting the number of allowed simultaneous connections for one IP. // More info: https://doc.traefik.io/traefik/v3.6/middlewares/tcp/inflightconn/ type TCPInFlightConn struct { // Amount defines the maximum amount of allowed simultaneous connections. // The middleware closes the connection if there are already amount connections opened. // +kubebuilder:validation:Minimum=0 Amount int64 `json:"amount,omitempty" toml:"amount,omitempty" yaml:"amount,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // TCPIPWhiteList holds the TCP IPWhiteList middleware configuration. // Deprecated: please use IPAllowList instead. type TCPIPWhiteList struct { // SourceRange defines the allowed IPs (or ranges of allowed IPs by using CIDR notation). SourceRange []string `json:"sourceRange,omitempty" toml:"sourceRange,omitempty" yaml:"sourceRange,omitempty"` } // +k8s:deepcopy-gen=true // TCPIPAllowList holds the TCP IPAllowList middleware configuration. // This middleware limits allowed requests based on the client IP. // More info: https://doc.traefik.io/traefik/v3.6/middlewares/tcp/ipallowlist/ type TCPIPAllowList struct { // SourceRange defines the allowed IPs (or ranges of allowed IPs by using CIDR notation). SourceRange []string `json:"sourceRange,omitempty" toml:"sourceRange,omitempty" yaml:"sourceRange,omitempty"` }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/dynamic/config_test.go
pkg/config/dynamic/config_test.go
package dynamic import ( "reflect" "testing" "github.com/BurntSushi/toml" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestDeepCopy(t *testing.T) { cfg := &Configuration{} _, err := toml.DecodeFile("./fixtures/sample.toml", &cfg) require.NoError(t, err) cfgCopy := cfg assert.Equal(t, reflect.ValueOf(cfgCopy), reflect.ValueOf(cfg)) assert.Equal(t, reflect.ValueOf(cfgCopy), reflect.ValueOf(cfg)) assert.Equal(t, cfgCopy, cfg) cfgDeepCopy := cfg.DeepCopy() assert.NotEqual(t, reflect.ValueOf(cfgDeepCopy), reflect.ValueOf(cfg)) assert.Equal(t, reflect.TypeOf(cfgDeepCopy), reflect.TypeOf(cfg)) assert.Equal(t, cfgDeepCopy, cfg) // Update cfg cfg.HTTP.Routers["powpow"] = &Router{} assert.Equal(t, reflect.ValueOf(cfgCopy), reflect.ValueOf(cfg)) assert.Equal(t, reflect.ValueOf(cfgCopy), reflect.ValueOf(cfg)) assert.Equal(t, cfgCopy, cfg) assert.NotEqual(t, reflect.ValueOf(cfgDeepCopy), reflect.ValueOf(cfg)) assert.Equal(t, reflect.TypeOf(cfgDeepCopy), reflect.TypeOf(cfg)) assert.NotEqual(t, cfgDeepCopy, cfg) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/dynamic/tcp_config.go
pkg/config/dynamic/tcp_config.go
package dynamic import ( "reflect" "time" ptypes "github.com/traefik/paerser/types" traefiktls "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" ) // +k8s:deepcopy-gen=true // TCPConfiguration contains all the TCP configuration parameters. type TCPConfiguration struct { Routers map[string]*TCPRouter `json:"routers,omitempty" toml:"routers,omitempty" yaml:"routers,omitempty" export:"true"` Services map[string]*TCPService `json:"services,omitempty" toml:"services,omitempty" yaml:"services,omitempty" export:"true"` Middlewares map[string]*TCPMiddleware `json:"middlewares,omitempty" toml:"middlewares,omitempty" yaml:"middlewares,omitempty" export:"true"` Models map[string]*TCPModel `json:"-" toml:"-" yaml:"-" label:"-" file:"-" kv:"-" export:"true"` ServersTransports map[string]*TCPServersTransport `json:"serversTransports,omitempty" toml:"serversTransports,omitempty" yaml:"serversTransports,omitempty" label:"-" export:"true"` } // +k8s:deepcopy-gen=true // TCPModel is a set of default router's values. type TCPModel struct { DefaultRuleSyntax string `json:"-" toml:"-" yaml:"-" label:"-" file:"-" kv:"-" export:"true"` } // +k8s:deepcopy-gen=true // TCPService holds a tcp service configuration (can only be of one type at the same time). type TCPService struct { LoadBalancer *TCPServersLoadBalancer `json:"loadBalancer,omitempty" toml:"loadBalancer,omitempty" yaml:"loadBalancer,omitempty" export:"true"` Weighted *TCPWeightedRoundRobin `json:"weighted,omitempty" toml:"weighted,omitempty" yaml:"weighted,omitempty" label:"-" export:"true"` } // +k8s:deepcopy-gen=true // TCPWeightedRoundRobin is a weighted round robin tcp load-balancer of services. type TCPWeightedRoundRobin struct { Services []TCPWRRService `json:"services,omitempty" toml:"services,omitempty" yaml:"services,omitempty" export:"true"` HealthCheck *HealthCheck `json:"healthCheck,omitempty" toml:"healthCheck,omitempty" yaml:"healthCheck,omitempty" label:"allowEmpty" file:"allowEmpty" kv:"allowEmpty" export:"true"` } // +k8s:deepcopy-gen=true // TCPWRRService is a reference to a tcp service load-balanced with weighted round robin. type TCPWRRService struct { Name string `json:"name,omitempty" toml:"name,omitempty" yaml:"name,omitempty" export:"true"` Weight *int `json:"weight,omitempty" toml:"weight,omitempty" yaml:"weight,omitempty" export:"true"` } // SetDefaults Default values for a TCPWRRService. func (w *TCPWRRService) SetDefaults() { defaultWeight := 1 w.Weight = &defaultWeight } // +k8s:deepcopy-gen=true // TCPRouter holds the router configuration. type TCPRouter struct { EntryPoints []string `json:"entryPoints,omitempty" toml:"entryPoints,omitempty" yaml:"entryPoints,omitempty" export:"true"` Middlewares []string `json:"middlewares,omitempty" toml:"middlewares,omitempty" yaml:"middlewares,omitempty" export:"true"` Service string `json:"service,omitempty" toml:"service,omitempty" yaml:"service,omitempty" export:"true"` Rule string `json:"rule,omitempty" toml:"rule,omitempty" yaml:"rule,omitempty"` // Deprecated: Please do not use this field and rewrite the router rules to use the v3 syntax. RuleSyntax string `json:"ruleSyntax,omitempty" toml:"ruleSyntax,omitempty" yaml:"ruleSyntax,omitempty" export:"true"` Priority int `json:"priority,omitempty" toml:"priority,omitempty,omitzero" yaml:"priority,omitempty" export:"true"` TLS *RouterTCPTLSConfig `json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" label:"allowEmpty" file:"allowEmpty" kv:"allowEmpty" export:"true"` } // +k8s:deepcopy-gen=true // RouterTCPTLSConfig holds the TLS configuration for a router. type RouterTCPTLSConfig struct { Passthrough bool `json:"passthrough" toml:"passthrough" yaml:"passthrough" export:"true"` Options string `json:"options,omitempty" toml:"options,omitempty" yaml:"options,omitempty" export:"true"` CertResolver string `json:"certResolver,omitempty" toml:"certResolver,omitempty" yaml:"certResolver,omitempty" export:"true"` Domains []types.Domain `json:"domains,omitempty" toml:"domains,omitempty" yaml:"domains,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // TCPServersLoadBalancer holds the LoadBalancerService configuration. type TCPServersLoadBalancer struct { Servers []TCPServer `json:"servers,omitempty" toml:"servers,omitempty" yaml:"servers,omitempty" label-slice-as-struct:"server" export:"true"` ServersTransport string `json:"serversTransport,omitempty" toml:"serversTransport,omitempty" yaml:"serversTransport,omitempty" export:"true"` // ProxyProtocol holds the PROXY Protocol configuration. // Deprecated: use ServersTransport to configure ProxyProtocol instead. ProxyProtocol *ProxyProtocol `json:"proxyProtocol,omitempty" toml:"proxyProtocol,omitempty" yaml:"proxyProtocol,omitempty" label:"allowEmpty" file:"allowEmpty" kv:"allowEmpty" export:"true"` // TerminationDelay, corresponds to the deadline that the proxy sets, after one // of its connected peers indicates it has closed the writing capability of its // connection, to close the reading capability as well, hence fully terminating the // connection. It is a duration in milliseconds, defaulting to 100. A negative value // means an infinite deadline (i.e. the reading capability is never closed). // Deprecated: use ServersTransport to configure the TerminationDelay instead. TerminationDelay *int `json:"terminationDelay,omitempty" toml:"terminationDelay,omitempty" yaml:"terminationDelay,omitempty" export:"true"` HealthCheck *TCPServerHealthCheck `json:"healthCheck,omitempty" toml:"healthCheck,omitempty" yaml:"healthCheck,omitempty" label:"allowEmpty" file:"allowEmpty" kv:"allowEmpty" export:"true"` } // Mergeable tells if the given service is mergeable. func (l *TCPServersLoadBalancer) Mergeable(loadBalancer *TCPServersLoadBalancer) bool { savedServers := l.Servers defer func() { l.Servers = savedServers }() l.Servers = nil savedServersLB := loadBalancer.Servers defer func() { loadBalancer.Servers = savedServersLB }() loadBalancer.Servers = nil return reflect.DeepEqual(l, loadBalancer) } // +k8s:deepcopy-gen=true // TCPServer holds a TCP Server configuration. type TCPServer struct { Address string `json:"address,omitempty" toml:"address,omitempty" yaml:"address,omitempty" label:"-"` Port string `json:"-" toml:"-" yaml:"-"` TLS bool `json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty"` } // +k8s:deepcopy-gen=true // ProxyProtocol holds the PROXY Protocol configuration. // More info: https://doc.traefik.io/traefik/v3.6/routing/services/#proxy-protocol type ProxyProtocol struct { // Version defines the PROXY Protocol version to use. // +kubebuilder:validation:Minimum=1 // +kubebuilder:validation:Maximum=2 Version int `description:"Defines the PROXY Protocol version to use." json:"version,omitempty" toml:"version,omitempty" yaml:"version,omitempty" export:"true"` } // SetDefaults Default values for a ProxyProtocol. func (p *ProxyProtocol) SetDefaults() { p.Version = 2 } // +k8s:deepcopy-gen=true // TCPServersTransport options to configure communication between Traefik and the servers. type TCPServersTransport struct { DialKeepAlive ptypes.Duration `description:"Defines the interval between keep-alive probes for an active network connection. If zero, keep-alive probes are sent with a default value (currently 15 seconds), if supported by the protocol and operating system. Network protocols or operating systems that do not support keep-alives ignore this field. If negative, keep-alive probes are disabled" json:"dialKeepAlive,omitempty" toml:"dialKeepAlive,omitempty" yaml:"dialKeepAlive,omitempty" export:"true"` DialTimeout ptypes.Duration `description:"Defines the amount of time to wait until a connection to a backend server can be established. If zero, no timeout exists." json:"dialTimeout,omitempty" toml:"dialTimeout,omitempty" yaml:"dialTimeout,omitempty" export:"true"` // ProxyProtocol holds the PROXY Protocol configuration. ProxyProtocol *ProxyProtocol `description:"Defines the PROXY Protocol configuration." json:"proxyProtocol,omitempty" toml:"proxyProtocol,omitempty" yaml:"proxyProtocol,omitempty" label:"allowEmpty" file:"allowEmpty" kv:"allowEmpty" export:"true"` // TerminationDelay, corresponds to the deadline that the proxy sets, after one // of its connected peers indicates it has closed the writing capability of its // connection, to close the reading capability as well, hence fully terminating the // connection. It is a duration in milliseconds, defaulting to 100. A negative value // means an infinite deadline (i.e. the reading capability is never closed). TerminationDelay ptypes.Duration `description:"Defines the delay to wait before fully terminating the connection, after one connected peer has closed its writing capability." json:"terminationDelay,omitempty" toml:"terminationDelay,omitempty" yaml:"terminationDelay,omitempty" export:"true"` TLS *TLSClientConfig `description:"Defines the TLS configuration." json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" label:"allowEmpty" file:"allowEmpty" kv:"allowEmpty" export:"true"` } // SetDefaults sets the default values for a TCPServersTransport. func (t *TCPServersTransport) SetDefaults() { t.DialTimeout = ptypes.Duration(30 * time.Second) t.DialKeepAlive = ptypes.Duration(15 * time.Second) t.TerminationDelay = ptypes.Duration(100 * time.Millisecond) } // +k8s:deepcopy-gen=true // TLSClientConfig options to configure TLS communication between Traefik and the servers. type TLSClientConfig struct { ServerName string `description:"Defines the serverName used to contact the server." json:"serverName,omitempty" toml:"serverName,omitempty" yaml:"serverName,omitempty"` InsecureSkipVerify bool `description:"Disables SSL certificate verification." json:"insecureSkipVerify,omitempty" toml:"insecureSkipVerify,omitempty" yaml:"insecureSkipVerify,omitempty" export:"true"` RootCAs []types.FileOrContent `description:"Defines a list of CA certificates used to validate server certificates." json:"rootCAs,omitempty" toml:"rootCAs,omitempty" yaml:"rootCAs,omitempty"` Certificates traefiktls.Certificates `description:"Defines a list of client certificates for mTLS." json:"certificates,omitempty" toml:"certificates,omitempty" yaml:"certificates,omitempty" export:"true"` PeerCertURI string `description:"Defines the URI used to match against SAN URI during the peer certificate verification." json:"peerCertURI,omitempty" toml:"peerCertURI,omitempty" yaml:"peerCertURI,omitempty" export:"true"` Spiffe *Spiffe `description:"Defines the SPIFFE TLS configuration." json:"spiffe,omitempty" toml:"spiffe,omitempty" yaml:"spiffe,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` } // +k8s:deepcopy-gen=true // TCPServerHealthCheck holds the HealthCheck configuration. type TCPServerHealthCheck struct { Port int `json:"port,omitempty" toml:"port,omitempty,omitzero" yaml:"port,omitempty" export:"true"` Send string `json:"send,omitempty" toml:"send,omitempty" yaml:"send,omitempty" export:"true"` Expect string `json:"expect,omitempty" toml:"expect,omitempty" yaml:"expect,omitempty" export:"true"` Interval ptypes.Duration `json:"interval,omitempty" toml:"interval,omitempty" yaml:"interval,omitempty" export:"true"` UnhealthyInterval *ptypes.Duration `json:"unhealthyInterval,omitempty" toml:"unhealthyInterval,omitempty" yaml:"unhealthyInterval,omitempty" export:"true"` Timeout ptypes.Duration `json:"timeout,omitempty" toml:"timeout,omitempty" yaml:"timeout,omitempty" export:"true"` } // SetDefaults sets the default values for a TCPServerHealthCheck. func (t *TCPServerHealthCheck) SetDefaults() { t.Interval = DefaultHealthCheckInterval t.Timeout = DefaultHealthCheckTimeout }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/dynamic/http_config.go
pkg/config/dynamic/http_config.go
package dynamic import ( "reflect" "time" ptypes "github.com/traefik/paerser/types" otypes "github.com/traefik/traefik/v3/pkg/observability/types" traefiktls "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" "google.golang.org/grpc/codes" ) const ( // DefaultHealthCheckInterval is the default value for the ServerHealthCheck interval. DefaultHealthCheckInterval = ptypes.Duration(30 * time.Second) // DefaultHealthCheckTimeout is the default value for the ServerHealthCheck timeout. DefaultHealthCheckTimeout = ptypes.Duration(5 * time.Second) // DefaultPassHostHeader is the default value for the ServersLoadBalancer passHostHeader. DefaultPassHostHeader = true // DefaultFlushInterval is the default value for the ResponseForwarding flush interval. DefaultFlushInterval = ptypes.Duration(100 * time.Millisecond) // MirroringDefaultMirrorBody is the Mirroring.MirrorBody option default value. MirroringDefaultMirrorBody = true // MirroringDefaultMaxBodySize is the Mirroring.MaxBodySize option default value. MirroringDefaultMaxBodySize int64 = -1 ) // +k8s:deepcopy-gen=true // HTTPConfiguration contains all the HTTP configuration parameters. type HTTPConfiguration struct { Routers map[string]*Router `json:"routers,omitempty" toml:"routers,omitempty" yaml:"routers,omitempty" export:"true"` Services map[string]*Service `json:"services,omitempty" toml:"services,omitempty" yaml:"services,omitempty" export:"true"` Middlewares map[string]*Middleware `json:"middlewares,omitempty" toml:"middlewares,omitempty" yaml:"middlewares,omitempty" export:"true"` Models map[string]*Model `json:"models,omitempty" toml:"models,omitempty" yaml:"models,omitempty" export:"true"` ServersTransports map[string]*ServersTransport `json:"serversTransports,omitempty" toml:"serversTransports,omitempty" yaml:"serversTransports,omitempty" label:"-" export:"true"` } // +k8s:deepcopy-gen=true // Model holds model configuration. type Model struct { Middlewares []string `json:"middlewares,omitempty" toml:"middlewares,omitempty" yaml:"middlewares,omitempty" export:"true"` TLS *RouterTLSConfig `json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" label:"allowEmpty" file:"allowEmpty" kv:"allowEmpty" export:"true"` Observability RouterObservabilityConfig `json:"observability,omitempty" toml:"observability,omitempty" yaml:"observability,omitempty" export:"true"` DeniedEncodedPathCharacters *RouterDeniedEncodedPathCharacters `json:"-" toml:"-" yaml:"-" label:"-" file:"-" kv:"-" export:"true"` DefaultRuleSyntax string `json:"-" toml:"-" yaml:"-" label:"-" file:"-" kv:"-" export:"true"` } // +k8s:deepcopy-gen=true // Service holds a service configuration (can only be of one type at the same time). type Service struct { LoadBalancer *ServersLoadBalancer `json:"loadBalancer,omitempty" toml:"loadBalancer,omitempty" yaml:"loadBalancer,omitempty" export:"true"` HighestRandomWeight *HighestRandomWeight `json:"highestRandomWeight,omitempty" toml:"highestRandomWeight,omitempty" yaml:"highestRandomWeight,omitempty" label:"-" export:"true"` Weighted *WeightedRoundRobin `json:"weighted,omitempty" toml:"weighted,omitempty" yaml:"weighted,omitempty" label:"-" export:"true"` Mirroring *Mirroring `json:"mirroring,omitempty" toml:"mirroring,omitempty" yaml:"mirroring,omitempty" label:"-" export:"true"` Failover *Failover `json:"failover,omitempty" toml:"failover,omitempty" yaml:"failover,omitempty" label:"-" export:"true"` } // +k8s:deepcopy-gen=true // Router holds the router configuration. type Router struct { EntryPoints []string `json:"entryPoints,omitempty" toml:"entryPoints,omitempty" yaml:"entryPoints,omitempty" export:"true"` Middlewares []string `json:"middlewares,omitempty" toml:"middlewares,omitempty" yaml:"middlewares,omitempty" export:"true"` Service string `json:"service,omitempty" toml:"service,omitempty" yaml:"service,omitempty" export:"true"` Rule string `json:"rule,omitempty" toml:"rule,omitempty" yaml:"rule,omitempty"` ParentRefs []string `json:"parentRefs,omitempty" toml:"parentRefs,omitempty" yaml:"parentRefs,omitempty" label:"-" export:"true"` // Deprecated: Please do not use this field and rewrite the router rules to use the v3 syntax. RuleSyntax string `json:"ruleSyntax,omitempty" toml:"ruleSyntax,omitempty" yaml:"ruleSyntax,omitempty" export:"true"` Priority int `json:"priority,omitempty" toml:"priority,omitempty,omitzero" yaml:"priority,omitempty" export:"true"` TLS *RouterTLSConfig `json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" label:"allowEmpty" file:"allowEmpty" kv:"allowEmpty" export:"true"` Observability *RouterObservabilityConfig `json:"observability,omitempty" toml:"observability,omitempty" yaml:"observability,omitempty" export:"true"` DefaultRule bool `json:"-" toml:"-" yaml:"-" label:"-" file:"-"` DeniedEncodedPathCharacters RouterDeniedEncodedPathCharacters `json:"-" toml:"-" yaml:"-" label:"-" file:"-"` } // +k8s:deepcopy-gen=true // RouterDeniedEncodedPathCharacters configures which encoded characters are allowed in the request path. type RouterDeniedEncodedPathCharacters struct { AllowEncodedSlash bool `description:"Defines whether requests with encoded slash characters in the path are allowed." json:"allowEncodedSlash,omitempty" toml:"allowEncodedSlash,omitempty" yaml:"allowEncodedSlash,omitempty" export:"true"` AllowEncodedBackSlash bool `description:"Defines whether requests with encoded back slash characters in the path are allowed." json:"allowEncodedBackSlash,omitempty" toml:"allowEncodedBackSlash,omitempty" yaml:"allowEncodedBackSlash,omitempty" export:"true"` AllowEncodedNullCharacter bool `description:"Defines whether requests with encoded null characters in the path are allowed." json:"allowEncodedNullCharacter,omitempty" toml:"allowEncodedNullCharacter,omitempty" yaml:"allowEncodedNullCharacter,omitempty" export:"true"` AllowEncodedSemicolon bool `description:"Defines whether requests with encoded semicolon characters in the path are allowed." json:"allowEncodedSemicolon,omitempty" toml:"allowEncodedSemicolon,omitempty" yaml:"allowEncodedSemicolon,omitempty" export:"true"` AllowEncodedPercent bool `description:"Defines whether requests with encoded percent characters in the path are allowed." json:"allowEncodedPercent,omitempty" toml:"allowEncodedPercent,omitempty" yaml:"allowEncodedPercent,omitempty" export:"true"` AllowEncodedQuestionMark bool `description:"Defines whether requests with encoded question mark characters in the path are allowed." json:"allowEncodedQuestionMark,omitempty" toml:"allowEncodedQuestionMark,omitempty" yaml:"allowEncodedQuestionMark,omitempty" export:"true"` AllowEncodedHash bool `description:"Defines whether requests with encoded hash characters in the path are allowed." json:"allowEncodedHash,omitempty" toml:"allowEncodedHash,omitempty" yaml:"allowEncodedHash,omitempty" export:"true"` } // Map returns a map of unallowed encoded characters. func (r *RouterDeniedEncodedPathCharacters) Map() map[string]struct{} { characters := make(map[string]struct{}) if !r.AllowEncodedSlash { characters["%2F"] = struct{}{} characters["%2f"] = struct{}{} } if !r.AllowEncodedBackSlash { characters["%5C"] = struct{}{} characters["%5c"] = struct{}{} } if !r.AllowEncodedNullCharacter { characters["%00"] = struct{}{} } if !r.AllowEncodedSemicolon { characters["%3B"] = struct{}{} characters["%3b"] = struct{}{} } if !r.AllowEncodedPercent { characters["%25"] = struct{}{} } if !r.AllowEncodedQuestionMark { characters["%3F"] = struct{}{} characters["%3f"] = struct{}{} } if !r.AllowEncodedHash { characters["%23"] = struct{}{} } return characters } // +k8s:deepcopy-gen=true // RouterTLSConfig holds the TLS configuration for a router. type RouterTLSConfig struct { Options string `json:"options,omitempty" toml:"options,omitempty" yaml:"options,omitempty" export:"true"` CertResolver string `json:"certResolver,omitempty" toml:"certResolver,omitempty" yaml:"certResolver,omitempty" export:"true"` Domains []types.Domain `json:"domains,omitempty" toml:"domains,omitempty" yaml:"domains,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // RouterObservabilityConfig holds the observability configuration for a router. type RouterObservabilityConfig struct { // AccessLogs enables access logs for this router. AccessLogs *bool `json:"accessLogs,omitempty" toml:"accessLogs,omitempty" yaml:"accessLogs,omitempty" export:"true"` // Metrics enables metrics for this router. Metrics *bool `json:"metrics,omitempty" toml:"metrics,omitempty" yaml:"metrics,omitempty" export:"true"` // Tracing enables tracing for this router. Tracing *bool `json:"tracing,omitempty" toml:"tracing,omitempty" yaml:"tracing,omitempty" export:"true"` // TraceVerbosity defines the verbosity level of the tracing for this router. // +kubebuilder:validation:Enum=minimal;detailed // +kubebuilder:default=minimal TraceVerbosity otypes.TracingVerbosity `json:"traceVerbosity,omitempty" toml:"traceVerbosity,omitempty" yaml:"traceVerbosity,omitempty" export:"true"` } // SetDefaults Default values for a RouterObservabilityConfig. func (r *RouterObservabilityConfig) SetDefaults() { r.TraceVerbosity = otypes.MinimalVerbosity } // +k8s:deepcopy-gen=true // Mirroring holds the Mirroring configuration. type Mirroring struct { Service string `json:"service,omitempty" toml:"service,omitempty" yaml:"service,omitempty" export:"true"` MirrorBody *bool `json:"mirrorBody,omitempty" toml:"mirrorBody,omitempty" yaml:"mirrorBody,omitempty" export:"true"` MaxBodySize *int64 `json:"maxBodySize,omitempty" toml:"maxBodySize,omitempty" yaml:"maxBodySize,omitempty" export:"true"` Mirrors []MirrorService `json:"mirrors,omitempty" toml:"mirrors,omitempty" yaml:"mirrors,omitempty" export:"true"` HealthCheck *HealthCheck `json:"healthCheck,omitempty" toml:"healthCheck,omitempty" yaml:"healthCheck,omitempty" label:"allowEmpty" file:"allowEmpty" kv:"allowEmpty" export:"true"` } // SetDefaults Default values for a WRRService. func (m *Mirroring) SetDefaults() { defaultMirrorBody := MirroringDefaultMirrorBody m.MirrorBody = &defaultMirrorBody defaultMaxBodySize := MirroringDefaultMaxBodySize m.MaxBodySize = &defaultMaxBodySize } // +k8s:deepcopy-gen=true // Failover holds the Failover configuration. type Failover struct { Service string `json:"service,omitempty" toml:"service,omitempty" yaml:"service,omitempty" export:"true"` Fallback string `json:"fallback,omitempty" toml:"fallback,omitempty" yaml:"fallback,omitempty" export:"true"` HealthCheck *HealthCheck `json:"healthCheck,omitempty" toml:"healthCheck,omitempty" yaml:"healthCheck,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` } // +k8s:deepcopy-gen=true // MirrorService holds the MirrorService configuration. type MirrorService struct { Name string `json:"name,omitempty" toml:"name,omitempty" yaml:"name,omitempty" export:"true"` Percent int `json:"percent,omitempty" toml:"percent,omitempty" yaml:"percent,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // WeightedRoundRobin is a weighted round robin load-balancer of services. type WeightedRoundRobin struct { Services []WRRService `json:"services,omitempty" toml:"services,omitempty" yaml:"services,omitempty" export:"true"` Sticky *Sticky `json:"sticky,omitempty" toml:"sticky,omitempty" yaml:"sticky,omitempty" export:"true"` // HealthCheck enables automatic self-healthcheck for this service, i.e. // whenever one of its children is reported as down, this service becomes aware of it, // and takes it into account (i.e. it ignores the down child) when running the // load-balancing algorithm. In addition, if the parent of this service also has // HealthCheck enabled, this service reports to its parent any status change. HealthCheck *HealthCheck `json:"healthCheck,omitempty" toml:"healthCheck,omitempty" yaml:"healthCheck,omitempty" label:"allowEmpty" file:"allowEmpty" kv:"allowEmpty" export:"true"` } // +k8s:deepcopy-gen=true // HighestRandomWeight is a weighted sticky load-balancer of services. type HighestRandomWeight struct { Services []HRWService `json:"services,omitempty" toml:"services,omitempty" yaml:"services,omitempty" export:"true"` // HealthCheck enables automatic self-healthcheck for this service, i.e. // whenever one of its children is reported as down, this service becomes aware of it, // and takes it into account (i.e. it ignores the down child) when running the // load-balancing algorithm. In addition, if the parent of this service also has // HealthCheck enabled, this service reports to its parent any status change. HealthCheck *HealthCheck `json:"healthCheck,omitempty" toml:"healthCheck,omitempty" yaml:"healthCheck,omitempty" label:"allowEmpty" file:"allowEmpty" kv:"allowEmpty" export:"true"` } // +k8s:deepcopy-gen=true // WRRService is a reference to a service load-balanced with weighted round-robin. type WRRService struct { Name string `json:"name,omitempty" toml:"name,omitempty" yaml:"name,omitempty" export:"true"` Weight *int `json:"weight,omitempty" toml:"weight,omitempty" yaml:"weight,omitempty" export:"true"` // Headers defines the HTTP headers that should be added to the request when calling the service. // This is required by the Knative implementation which expects specific headers to be sent. Headers map[string]string `json:"-" toml:"-" yaml:"-" label:"-" file:"-"` // Status defines an HTTP status code that should be returned when calling the service. // This is required by the Gateway API implementation which expects specific HTTP status to be returned. Status *int `json:"-" toml:"-" yaml:"-" label:"-" file:"-"` // GRPCStatus defines a GRPC status code that should be returned when calling the service. // This is required by the Gateway API implementation which expects specific GRPC status to be returned. GRPCStatus *GRPCStatus `json:"-" toml:"-" yaml:"-" label:"-" file:"-"` } // SetDefaults Default values for a WRRService. func (w *WRRService) SetDefaults() { defaultWeight := 1 w.Weight = &defaultWeight } // +k8s:deepcopy-gen=true // HRWService is a reference to a service load-balanced with highest random weight. type HRWService struct { Name string `json:"name,omitempty" toml:"name,omitempty" yaml:"name,omitempty" export:"true"` Weight *int `json:"weight,omitempty" toml:"weight,omitempty" yaml:"weight,omitempty" export:"true"` } // SetDefaults Default values for a HRWService. func (w *HRWService) SetDefaults() { defaultWeight := 1 w.Weight = &defaultWeight } // +k8s:deepcopy-gen=true type GRPCStatus struct { Code codes.Code `json:"code,omitempty" toml:"code,omitempty" yaml:"code,omitempty" export:"true"` Msg string `json:"msg,omitempty" toml:"msg,omitempty" yaml:"msg,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // Sticky holds the sticky configuration. type Sticky struct { // Cookie defines the sticky cookie configuration. Cookie *Cookie `json:"cookie,omitempty" toml:"cookie,omitempty" yaml:"cookie,omitempty" label:"allowEmpty" file:"allowEmpty" kv:"allowEmpty" export:"true"` } // +k8s:deepcopy-gen=true // Cookie holds the sticky configuration based on cookie. type Cookie struct { // Name defines the Cookie name. Name string `json:"name,omitempty" toml:"name,omitempty" yaml:"name,omitempty" export:"true"` // Secure defines whether the cookie can only be transmitted over an encrypted connection (i.e. HTTPS). Secure bool `json:"secure,omitempty" toml:"secure,omitempty" yaml:"secure,omitempty" export:"true"` // HTTPOnly defines whether the cookie can be accessed by client-side APIs, such as JavaScript. HTTPOnly bool `json:"httpOnly,omitempty" toml:"httpOnly,omitempty" yaml:"httpOnly,omitempty" export:"true"` // SameSite defines the same site policy. // More info: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite // +kubebuilder:validation:Enum=none;lax;strict SameSite string `json:"sameSite,omitempty" toml:"sameSite,omitempty" yaml:"sameSite,omitempty" export:"true"` // MaxAge defines the number of seconds until the cookie expires. // When set to a negative number, the cookie expires immediately. // When set to zero, the cookie never expires. MaxAge int `json:"maxAge,omitempty" toml:"maxAge,omitempty" yaml:"maxAge,omitempty" export:"true"` // Path defines the path that must exist in the requested URL for the browser to send the Cookie header. // When not provided the cookie will be sent on every request to the domain. // More info: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#pathpath-value Path *string `json:"path,omitempty" toml:"path,omitempty" yaml:"path,omitempty" export:"true"` // Domain defines the host to which the cookie will be sent. // More info: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#domaindomain-value Domain string `json:"domain,omitempty" toml:"domain,omitempty" yaml:"domain,omitempty"` } // SetDefaults set the default values for a Cookie. func (c *Cookie) SetDefaults() { defaultPath := "/" c.Path = &defaultPath } type BalancerStrategy string const ( // BalancerStrategyWRR is the weighted round-robin strategy. BalancerStrategyWRR BalancerStrategy = "wrr" // BalancerStrategyP2C is the power of two choices strategy. BalancerStrategyP2C BalancerStrategy = "p2c" // BalancerStrategyHRW is the highest random weight strategy. BalancerStrategyHRW BalancerStrategy = "hrw" // BalancerStrategyLeastTime is the least-time strategy. BalancerStrategyLeastTime BalancerStrategy = "leasttime" ) // +k8s:deepcopy-gen=true // ServersLoadBalancer holds the ServersLoadBalancer configuration. type ServersLoadBalancer struct { Sticky *Sticky `json:"sticky,omitempty" toml:"sticky,omitempty" yaml:"sticky,omitempty" label:"allowEmpty" file:"allowEmpty" kv:"allowEmpty" export:"true"` Servers []Server `json:"servers,omitempty" toml:"servers,omitempty" yaml:"servers,omitempty" label-slice-as-struct:"server" export:"true"` Strategy BalancerStrategy `json:"strategy,omitempty" toml:"strategy,omitempty" yaml:"strategy,omitempty" export:"true"` // HealthCheck enables regular active checks of the responsiveness of the // children servers of this load-balancer. To propagate status changes (e.g. all // servers of this service are down) upwards, HealthCheck must also be enabled on // the parent(s) of this service. HealthCheck *ServerHealthCheck `json:"healthCheck,omitempty" toml:"healthCheck,omitempty" yaml:"healthCheck,omitempty" export:"true"` // PassiveHealthCheck enables passive health checks for children servers of this load-balancer. PassiveHealthCheck *PassiveServerHealthCheck `json:"passiveHealthCheck,omitempty" toml:"passiveHealthCheck,omitempty" yaml:"passiveHealthCheck,omitempty" export:"true"` PassHostHeader *bool `json:"passHostHeader" toml:"passHostHeader" yaml:"passHostHeader" export:"true"` ResponseForwarding *ResponseForwarding `json:"responseForwarding,omitempty" toml:"responseForwarding,omitempty" yaml:"responseForwarding,omitempty" export:"true"` ServersTransport string `json:"serversTransport,omitempty" toml:"serversTransport,omitempty" yaml:"serversTransport,omitempty" export:"true"` } // Mergeable tells if the given service is mergeable. func (l *ServersLoadBalancer) Mergeable(loadBalancer *ServersLoadBalancer) bool { savedServers := l.Servers defer func() { l.Servers = savedServers }() l.Servers = nil savedServersLB := loadBalancer.Servers defer func() { loadBalancer.Servers = savedServersLB }() loadBalancer.Servers = nil return reflect.DeepEqual(l, loadBalancer) } // SetDefaults Default values for a ServersLoadBalancer. func (l *ServersLoadBalancer) SetDefaults() { defaultPassHostHeader := DefaultPassHostHeader l.PassHostHeader = &defaultPassHostHeader l.Strategy = BalancerStrategyWRR l.ResponseForwarding = &ResponseForwarding{} l.ResponseForwarding.SetDefaults() } // +k8s:deepcopy-gen=true // ResponseForwarding holds the response forwarding configuration. type ResponseForwarding struct { // FlushInterval defines the interval, in milliseconds, in between flushes to the client while copying the response body. // A negative value means to flush immediately after each write to the client. // This configuration is ignored when ReverseProxy recognizes a response as a streaming response; // for such responses, writes are flushed to the client immediately. // Default: 100ms FlushInterval ptypes.Duration `json:"flushInterval,omitempty" toml:"flushInterval,omitempty" yaml:"flushInterval,omitempty" export:"true"` } // SetDefaults Default values for a ResponseForwarding. func (r *ResponseForwarding) SetDefaults() { r.FlushInterval = DefaultFlushInterval } // +k8s:deepcopy-gen=true // Server holds the server configuration. type Server struct { URL string `json:"url,omitempty" toml:"url,omitempty" yaml:"url,omitempty"` Weight *int `json:"weight,omitempty" toml:"weight,omitempty" yaml:"weight,omitempty" export:"true"` PreservePath bool `json:"preservePath,omitempty" toml:"preservePath,omitempty" yaml:"preservePath,omitempty" export:"true"` Fenced bool `json:"fenced,omitempty" toml:"-" yaml:"-" label:"-" file:"-" kv:"-"` // Scheme can only be defined with label Providers. Scheme string `json:"-" toml:"-" yaml:"-" file:"-" kv:"-"` Port string `json:"-" toml:"-" yaml:"-" file:"-" kv:"-"` } // +k8s:deepcopy-gen=true // ServerHealthCheck holds the HealthCheck configuration. type ServerHealthCheck struct { Scheme string `json:"scheme,omitempty" toml:"scheme,omitempty" yaml:"scheme,omitempty" export:"true"` Mode string `json:"mode,omitempty" toml:"mode,omitempty" yaml:"mode,omitempty" export:"true"` Path string `json:"path,omitempty" toml:"path,omitempty" yaml:"path,omitempty" export:"true"` Method string `json:"method,omitempty" toml:"method,omitempty" yaml:"method,omitempty" export:"true"` Status int `json:"status,omitempty" toml:"status,omitempty" yaml:"status,omitempty" export:"true"` Port int `json:"port,omitempty" toml:"port,omitempty,omitzero" yaml:"port,omitempty" export:"true"` Interval ptypes.Duration `json:"interval,omitempty" toml:"interval,omitempty" yaml:"interval,omitempty" export:"true"` UnhealthyInterval *ptypes.Duration `json:"unhealthyInterval,omitempty" toml:"unhealthyInterval,omitempty" yaml:"unhealthyInterval,omitempty" export:"true"` Timeout ptypes.Duration `json:"timeout,omitempty" toml:"timeout,omitempty" yaml:"timeout,omitempty" export:"true"` Hostname string `json:"hostname,omitempty" toml:"hostname,omitempty" yaml:"hostname,omitempty"` FollowRedirects *bool `json:"followRedirects,omitempty" toml:"followRedirects,omitempty" yaml:"followRedirects,omitempty" export:"true"` Headers map[string]string `json:"headers,omitempty" toml:"headers,omitempty" yaml:"headers,omitempty" export:"true"` } // SetDefaults Default values for a HealthCheck. func (h *ServerHealthCheck) SetDefaults() { fr := true h.FollowRedirects = &fr h.Mode = "http" h.Interval = DefaultHealthCheckInterval h.Timeout = DefaultHealthCheckTimeout } // +k8s:deepcopy-gen=true type PassiveServerHealthCheck struct { // FailureWindow defines the time window during which the failed attempts must occur for the server to be marked as unhealthy. It also defines for how long the server will be considered unhealthy. FailureWindow ptypes.Duration `json:"failureWindow,omitempty" toml:"failureWindow,omitempty" yaml:"failureWindow,omitempty" export:"true"` // MaxFailedAttempts is the number of consecutive failed attempts allowed within the failure window before marking the server as unhealthy. MaxFailedAttempts int `json:"maxFailedAttempts,omitempty" toml:"maxFailedAttempts,omitempty" yaml:"maxFailedAttempts,omitempty" export:"true"` } func (p *PassiveServerHealthCheck) SetDefaults() { p.FailureWindow = ptypes.Duration(10 * time.Second) p.MaxFailedAttempts = 1 } // +k8s:deepcopy-gen=true // HealthCheck controls healthcheck awareness and propagation at the services level. type HealthCheck struct{} // +k8s:deepcopy-gen=true // ServersTransport options to configure communication between Traefik and the servers. type ServersTransport struct { ServerName string `description:"Defines the serverName used to contact the server." json:"serverName,omitempty" toml:"serverName,omitempty" yaml:"serverName,omitempty"` InsecureSkipVerify bool `description:"Disables SSL certificate verification." json:"insecureSkipVerify,omitempty" toml:"insecureSkipVerify,omitempty" yaml:"insecureSkipVerify,omitempty" export:"true"` RootCAs []types.FileOrContent `description:"Defines a list of CA certificates used to validate server certificates." json:"rootCAs,omitempty" toml:"rootCAs,omitempty" yaml:"rootCAs,omitempty"` Certificates traefiktls.Certificates `description:"Defines a list of client certificates for mTLS." json:"certificates,omitempty" toml:"certificates,omitempty" yaml:"certificates,omitempty" export:"true"` MaxIdleConnsPerHost int `description:"If non-zero, controls the maximum idle (keep-alive) to keep per-host. If zero, DefaultMaxIdleConnsPerHost is used. If negative, disables connection reuse." json:"maxIdleConnsPerHost,omitempty" toml:"maxIdleConnsPerHost,omitempty" yaml:"maxIdleConnsPerHost,omitempty" export:"true"` ForwardingTimeouts *ForwardingTimeouts `description:"Defines the timeouts for requests forwarded to the backend servers." json:"forwardingTimeouts,omitempty" toml:"forwardingTimeouts,omitempty" yaml:"forwardingTimeouts,omitempty" export:"true"` DisableHTTP2 bool `description:"Disables HTTP/2 for connections with backend servers." json:"disableHTTP2,omitempty" toml:"disableHTTP2,omitempty" yaml:"disableHTTP2,omitempty" export:"true"` PeerCertURI string `description:"Defines the URI used to match against SAN URI during the peer certificate verification." json:"peerCertURI,omitempty" toml:"peerCertURI,omitempty" yaml:"peerCertURI,omitempty" export:"true"` Spiffe *Spiffe `description:"Defines the SPIFFE configuration." json:"spiffe,omitempty" toml:"spiffe,omitempty" yaml:"spiffe,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` } // +k8s:deepcopy-gen=true // Spiffe holds the SPIFFE configuration. type Spiffe struct { // IDs defines the allowed SPIFFE IDs (takes precedence over the SPIFFE TrustDomain). IDs []string `description:"Defines the allowed SPIFFE IDs (takes precedence over the SPIFFE TrustDomain)." json:"ids,omitempty" toml:"ids,omitempty" yaml:"ids,omitempty"` // TrustDomain defines the allowed SPIFFE trust domain. TrustDomain string `description:"Defines the allowed SPIFFE trust domain." json:"trustDomain,omitempty" toml:"trustDomain,omitempty" yaml:"trustDomain,omitempty"` } // +k8s:deepcopy-gen=true // ForwardingTimeouts contains timeout configurations for forwarding requests to the backend servers. type ForwardingTimeouts struct { DialTimeout ptypes.Duration `description:"The amount of time to wait until a connection to a backend server can be established. If zero, no timeout exists." json:"dialTimeout,omitempty" toml:"dialTimeout,omitempty" yaml:"dialTimeout,omitempty" export:"true"` ResponseHeaderTimeout ptypes.Duration `description:"The amount of time to wait for a server's response headers after fully writing the request (including its body, if any). If zero, no timeout exists." json:"responseHeaderTimeout,omitempty" toml:"responseHeaderTimeout,omitempty" yaml:"responseHeaderTimeout,omitempty" export:"true"` IdleConnTimeout ptypes.Duration `description:"The maximum period for which an idle HTTP keep-alive connection will remain open before closing itself." json:"idleConnTimeout,omitempty" toml:"idleConnTimeout,omitempty" yaml:"idleConnTimeout,omitempty" export:"true"` ReadIdleTimeout ptypes.Duration `description:"The timeout after which a health check using ping frame will be carried out if no frame is received on the HTTP/2 connection. If zero, no health check is performed." json:"readIdleTimeout,omitempty" toml:"readIdleTimeout,omitempty" yaml:"readIdleTimeout,omitempty" export:"true"` PingTimeout ptypes.Duration `description:"The timeout after which the HTTP/2 connection will be closed if a response to ping is not received." json:"pingTimeout,omitempty" toml:"pingTimeout,omitempty" yaml:"pingTimeout,omitempty" export:"true"` } // SetDefaults sets the default values. func (f *ForwardingTimeouts) SetDefaults() { f.DialTimeout = ptypes.Duration(30 * time.Second) f.IdleConnTimeout = ptypes.Duration(90 * time.Second) f.PingTimeout = ptypes.Duration(15 * time.Second) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/dynamic/http_config_test.go
pkg/config/dynamic/http_config_test.go
package dynamic import ( "testing" "github.com/stretchr/testify/require" ) func TestEncodedCharactersMap(t *testing.T) { tests := []struct { name string config RouterDeniedEncodedPathCharacters expected map[string]struct{} }{ { name: "Handles empty configuration", expected: map[string]struct{}{ "%2F": {}, "%2f": {}, "%5C": {}, "%5c": {}, "%00": {}, "%3B": {}, "%3b": {}, "%25": {}, "%3F": {}, "%3f": {}, "%23": {}, }, }, { name: "Exclude encoded slash when allowed", config: RouterDeniedEncodedPathCharacters{ AllowEncodedSlash: true, }, expected: map[string]struct{}{ "%5C": {}, "%5c": {}, "%00": {}, "%3B": {}, "%3b": {}, "%25": {}, "%3F": {}, "%3f": {}, "%23": {}, }, }, { name: "Exclude encoded backslash when allowed", config: RouterDeniedEncodedPathCharacters{ AllowEncodedBackSlash: true, }, expected: map[string]struct{}{ "%2F": {}, "%2f": {}, "%00": {}, "%3B": {}, "%3b": {}, "%25": {}, "%3F": {}, "%3f": {}, "%23": {}, }, }, { name: "Exclude encoded null character when allowed", config: RouterDeniedEncodedPathCharacters{ AllowEncodedNullCharacter: true, }, expected: map[string]struct{}{ "%2F": {}, "%2f": {}, "%5C": {}, "%5c": {}, "%3B": {}, "%3b": {}, "%25": {}, "%3F": {}, "%3f": {}, "%23": {}, }, }, { name: "Exclude encoded semicolon when allowed", config: RouterDeniedEncodedPathCharacters{ AllowEncodedSemicolon: true, }, expected: map[string]struct{}{ "%2F": {}, "%2f": {}, "%5C": {}, "%5c": {}, "%00": {}, "%25": {}, "%3F": {}, "%3f": {}, "%23": {}, }, }, { name: "Exclude encoded percent when allowed", config: RouterDeniedEncodedPathCharacters{ AllowEncodedPercent: true, }, expected: map[string]struct{}{ "%2F": {}, "%2f": {}, "%5C": {}, "%5c": {}, "%00": {}, "%3B": {}, "%3b": {}, "%3F": {}, "%3f": {}, "%23": {}, }, }, { name: "Exclude encoded question mark when allowed", config: RouterDeniedEncodedPathCharacters{ AllowEncodedQuestionMark: true, }, expected: map[string]struct{}{ "%2F": {}, "%2f": {}, "%5C": {}, "%5c": {}, "%00": {}, "%3B": {}, "%3b": {}, "%25": {}, "%23": {}, }, }, { name: "Exclude encoded hash when allowed", config: RouterDeniedEncodedPathCharacters{ AllowEncodedHash: true, }, expected: map[string]struct{}{ "%2F": {}, "%2f": {}, "%5C": {}, "%5c": {}, "%00": {}, "%3B": {}, "%3b": {}, "%25": {}, "%3F": {}, "%3f": {}, }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { t.Parallel() result := test.config.Map() require.Equal(t, test.expected, result) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/dynamic/udp_config.go
pkg/config/dynamic/udp_config.go
package dynamic import ( "reflect" ) // +k8s:deepcopy-gen=true // UDPConfiguration contains all the UDP configuration parameters. type UDPConfiguration struct { Routers map[string]*UDPRouter `json:"routers,omitempty" toml:"routers,omitempty" yaml:"routers,omitempty" export:"true"` Services map[string]*UDPService `json:"services,omitempty" toml:"services,omitempty" yaml:"services,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // UDPService defines the configuration for a UDP service. All fields are mutually exclusive. type UDPService struct { LoadBalancer *UDPServersLoadBalancer `json:"loadBalancer,omitempty" toml:"loadBalancer,omitempty" yaml:"loadBalancer,omitempty" export:"true"` Weighted *UDPWeightedRoundRobin `json:"weighted,omitempty" toml:"weighted,omitempty" yaml:"weighted,omitempty" label:"-" export:"true"` } // +k8s:deepcopy-gen=true // UDPWeightedRoundRobin is a weighted round robin UDP load-balancer of services. type UDPWeightedRoundRobin struct { Services []UDPWRRService `json:"services,omitempty" toml:"services,omitempty" yaml:"services,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // UDPWRRService is a reference to a UDP service load-balanced with weighted round robin. type UDPWRRService struct { Name string `json:"name,omitempty" toml:"name,omitempty" yaml:"name,omitempty" export:"true"` Weight *int `json:"weight,omitempty" toml:"weight,omitempty" yaml:"weight,omitempty" export:"true"` } // SetDefaults sets the default values for a UDPWRRService. func (w *UDPWRRService) SetDefaults() { defaultWeight := 1 w.Weight = &defaultWeight } // +k8s:deepcopy-gen=true // UDPRouter defines the configuration for an UDP router. type UDPRouter struct { EntryPoints []string `json:"entryPoints,omitempty" toml:"entryPoints,omitempty" yaml:"entryPoints,omitempty" export:"true"` Service string `json:"service,omitempty" toml:"service,omitempty" yaml:"service,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // UDPServersLoadBalancer defines the configuration for a load-balancer of UDP servers. type UDPServersLoadBalancer struct { Servers []UDPServer `json:"servers,omitempty" toml:"servers,omitempty" yaml:"servers,omitempty" label-slice-as-struct:"server" export:"true"` } // Mergeable reports whether the given load-balancer can be merged with the receiver. func (l *UDPServersLoadBalancer) Mergeable(loadBalancer *UDPServersLoadBalancer) bool { savedServers := l.Servers defer func() { l.Servers = savedServers }() l.Servers = nil savedServersLB := loadBalancer.Servers defer func() { loadBalancer.Servers = savedServersLB }() loadBalancer.Servers = nil return reflect.DeepEqual(l, loadBalancer) } // +k8s:deepcopy-gen=true // UDPServer defines a UDP server configuration. type UDPServer struct { Address string `json:"address,omitempty" toml:"address,omitempty" yaml:"address,omitempty" label:"-"` Port string `json:"-" toml:"-" yaml:"-" file:"-"` }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/label/label_test.go
pkg/config/label/label_test.go
package label import ( "fmt" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" ) func pointer[T any](v T) *T { return &v } func TestDecodeConfiguration(t *testing.T) { labels := map[string]string{ "traefik.http.middlewares.Middleware0.addprefix.prefix": "foobar", "traefik.http.middlewares.Middleware1.basicauth.headerfield": "foobar", "traefik.http.middlewares.Middleware1.basicauth.realm": "foobar", "traefik.http.middlewares.Middleware1.basicauth.removeheader": "true", "traefik.http.middlewares.Middleware1.basicauth.users": "foobar, fiibar", "traefik.http.middlewares.Middleware1.basicauth.usersfile": "foobar", "traefik.http.middlewares.Middleware2.buffering.maxrequestbodybytes": "42", "traefik.http.middlewares.Middleware2.buffering.maxresponsebodybytes": "42", "traefik.http.middlewares.Middleware2.buffering.memrequestbodybytes": "42", "traefik.http.middlewares.Middleware2.buffering.memresponsebodybytes": "42", "traefik.http.middlewares.Middleware2.buffering.retryexpression": "foobar", "traefik.http.middlewares.Middleware3.chain.middlewares": "foobar, fiibar", "traefik.http.middlewares.Middleware4.circuitbreaker.expression": "foobar", "traefik.HTTP.Middlewares.Middleware4.circuitbreaker.checkperiod": "1s", "traefik.HTTP.Middlewares.Middleware4.circuitbreaker.fallbackduration": "1s", "traefik.HTTP.Middlewares.Middleware4.circuitbreaker.recoveryduration": "1s", "traefik.HTTP.Middlewares.Middleware4.circuitbreaker.responsecode": "403", "traefik.http.middlewares.Middleware5.digestauth.headerfield": "foobar", "traefik.http.middlewares.Middleware5.digestauth.realm": "foobar", "traefik.http.middlewares.Middleware5.digestauth.removeheader": "true", "traefik.http.middlewares.Middleware5.digestauth.users": "foobar, fiibar", "traefik.http.middlewares.Middleware5.digestauth.usersfile": "foobar", "traefik.http.middlewares.Middleware6.errors.query": "foobar", "traefik.http.middlewares.Middleware6.errors.service": "foobar", "traefik.http.middlewares.Middleware6.errors.status": "foobar, fiibar", "traefik.http.middlewares.Middleware7.forwardauth.address": "foobar", "traefik.http.middlewares.Middleware7.forwardauth.authresponseheaders": "foobar, fiibar", "traefik.http.middlewares.Middleware7.forwardauth.authrequestheaders": "foobar, fiibar", "traefik.http.middlewares.Middleware7.forwardauth.tls.ca": "foobar", "traefik.http.middlewares.Middleware7.forwardauth.tls.caoptional": "true", "traefik.http.middlewares.Middleware7.forwardauth.tls.cert": "foobar", "traefik.http.middlewares.Middleware7.forwardauth.tls.insecureskipverify": "true", "traefik.http.middlewares.Middleware7.forwardauth.tls.key": "foobar", "traefik.http.middlewares.Middleware7.forwardauth.trustforwardheader": "true", "traefik.http.middlewares.Middleware7.forwardauth.forwardbody": "true", "traefik.http.middlewares.Middleware7.forwardauth.maxbodysize": "42", "traefik.http.middlewares.Middleware7.forwardauth.preserveRequestMethod": "true", "traefik.http.middlewares.Middleware8.headers.accesscontrolallowcredentials": "true", "traefik.http.middlewares.Middleware8.headers.allowedhosts": "foobar, fiibar", "traefik.http.middlewares.Middleware8.headers.accesscontrolallowheaders": "X-foobar, X-fiibar", "traefik.http.middlewares.Middleware8.headers.accesscontrolallowmethods": "GET, PUT", "traefik.http.middlewares.Middleware8.headers.accesscontrolalloworiginList": "foobar, fiibar", "traefik.http.middlewares.Middleware8.headers.accesscontrolalloworiginListRegex": "foobar, fiibar", "traefik.http.middlewares.Middleware8.headers.accesscontrolexposeheaders": "X-foobar, X-fiibar", "traefik.http.middlewares.Middleware8.headers.accesscontrolmaxage": "200", "traefik.http.middlewares.Middleware8.headers.addvaryheader": "true", "traefik.http.middlewares.Middleware8.headers.browserxssfilter": "true", "traefik.http.middlewares.Middleware8.headers.contentsecuritypolicy": "foobar", "traefik.http.middlewares.Middleware8.headers.contentsecuritypolicyreportonly": "foobar", "traefik.http.middlewares.Middleware8.headers.contenttypenosniff": "true", "traefik.http.middlewares.Middleware8.headers.custombrowserxssvalue": "foobar", "traefik.http.middlewares.Middleware8.headers.customframeoptionsvalue": "foobar", "traefik.http.middlewares.Middleware8.headers.customrequestheaders.name0": "foobar", "traefik.http.middlewares.Middleware8.headers.customrequestheaders.name1": "foobar", "traefik.http.middlewares.Middleware8.headers.customresponseheaders.name0": "foobar", "traefik.http.middlewares.Middleware8.headers.customresponseheaders.name1": "foobar", "traefik.http.middlewares.Middleware8.headers.forcestsheader": "true", "traefik.http.middlewares.Middleware8.headers.framedeny": "true", "traefik.http.middlewares.Middleware8.headers.hostsproxyheaders": "foobar, fiibar", "traefik.http.middlewares.Middleware8.headers.isdevelopment": "true", "traefik.http.middlewares.Middleware8.headers.publickey": "foobar", "traefik.http.middlewares.Middleware8.headers.referrerpolicy": "foobar", "traefik.http.middlewares.Middleware8.headers.featurepolicy": "foobar", "traefik.http.middlewares.Middleware8.headers.permissionspolicy": "foobar", "traefik.http.middlewares.Middleware8.headers.sslforcehost": "true", "traefik.http.middlewares.Middleware8.headers.sslhost": "foobar", "traefik.http.middlewares.Middleware8.headers.sslproxyheaders.name0": "foobar", "traefik.http.middlewares.Middleware8.headers.sslproxyheaders.name1": "foobar", "traefik.http.middlewares.Middleware8.headers.sslredirect": "true", "traefik.http.middlewares.Middleware8.headers.ssltemporaryredirect": "true", "traefik.http.middlewares.Middleware8.headers.stsincludesubdomains": "true", "traefik.http.middlewares.Middleware8.headers.stspreload": "true", "traefik.http.middlewares.Middleware8.headers.stsseconds": "42", "traefik.http.middlewares.Middleware9.ipallowlist.ipstrategy.depth": "42", "traefik.http.middlewares.Middleware9.ipallowlist.ipstrategy.excludedips": "foobar, fiibar", "traefik.http.middlewares.Middleware9.ipallowlist.ipstrategy.ipv6subnet": "42", "traefik.http.middlewares.Middleware9.ipallowlist.sourcerange": "foobar, fiibar", "traefik.http.middlewares.Middleware10.inflightreq.amount": "42", "traefik.http.middlewares.Middleware10.inflightreq.sourcecriterion.ipstrategy.depth": "42", "traefik.http.middlewares.Middleware10.inflightreq.sourcecriterion.ipstrategy.excludedips": "foobar, fiibar", "traefik.http.middlewares.Middleware10.inflightreq.sourcecriterion.ipstrategy.ipv6subnet": "42", "traefik.http.middlewares.Middleware10.inflightreq.sourcecriterion.requestheadername": "foobar", "traefik.http.middlewares.Middleware10.inflightreq.sourcecriterion.requesthost": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.notafter": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.notbefore": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.sans": "true", "traefik.http.middlewares.Middleware11.passTLSClientCert.info.serialNumber": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.commonname": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.country": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.domaincomponent": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.locality": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.organization": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.organizationalunit": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.province": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.serialnumber": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.commonname": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.country": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.domaincomponent": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.locality": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.organization": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.province": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.serialnumber": "true", "traefik.http.middlewares.Middleware11.passtlsclientcert.pem": "true", "traefik.http.middlewares.Middleware12.ratelimit.average": "42", "traefik.http.middlewares.Middleware12.ratelimit.period": "1s", "traefik.http.middlewares.Middleware12.ratelimit.burst": "42", "traefik.http.middlewares.Middleware12.ratelimit.sourcecriterion.requestheadername": "foobar", "traefik.http.middlewares.Middleware12.ratelimit.sourcecriterion.requesthost": "true", "traefik.http.middlewares.Middleware12.ratelimit.sourcecriterion.ipstrategy.depth": "42", "traefik.http.middlewares.Middleware12.ratelimit.sourcecriterion.ipstrategy.excludedips": "foobar, foobar", "traefik.http.middlewares.Middleware12.ratelimit.sourcecriterion.ipstrategy.ipv6subnet": "42", "traefik.http.middlewares.Middleware13.redirectregex.permanent": "true", "traefik.http.middlewares.Middleware13.redirectregex.regex": "foobar", "traefik.http.middlewares.Middleware13.redirectregex.replacement": "foobar", "traefik.http.middlewares.Middleware13b.redirectscheme.scheme": "https", "traefik.http.middlewares.Middleware13b.redirectscheme.port": "80", "traefik.http.middlewares.Middleware13b.redirectscheme.permanent": "true", "traefik.http.middlewares.Middleware14.replacepath.path": "foobar", "traefik.http.middlewares.Middleware15.replacepathregex.regex": "foobar", "traefik.http.middlewares.Middleware15.replacepathregex.replacement": "foobar", "traefik.http.middlewares.Middleware16.retry.attempts": "42", "traefik.http.middlewares.Middleware16.retry.initialinterval": "1s", "traefik.http.middlewares.Middleware17.stripprefix.prefixes": "foobar, fiibar", "traefik.http.middlewares.Middleware17.stripprefix.forceslash": "true", "traefik.http.middlewares.Middleware18.stripprefixregex.regex": "foobar, fiibar", "traefik.http.middlewares.Middleware19.compress.encodings": "foobar, fiibar", "traefik.http.middlewares.Middleware19.compress.minresponsebodybytes": "42", "traefik.http.middlewares.Middleware20.plugin.tomato.aaa": "foo1", "traefik.http.middlewares.Middleware20.plugin.tomato.bbb": "foo2", "traefik.http.routers.Router0.entrypoints": "foobar, fiibar", "traefik.http.routers.Router0.middlewares": "foobar, fiibar", "traefik.http.routers.Router0.priority": "42", "traefik.http.routers.Router0.rule": "foobar", "traefik.http.routers.Router0.tls": "true", "traefik.http.routers.Router0.service": "foobar", "traefik.http.routers.Router1.entrypoints": "foobar, fiibar", "traefik.http.routers.Router1.middlewares": "foobar, fiibar", "traefik.http.routers.Router1.priority": "42", "traefik.http.routers.Router1.rule": "foobar", "traefik.http.routers.Router1.service": "foobar", "traefik.http.services.Service0.loadbalancer.healthcheck.headers.name0": "foobar", "traefik.http.services.Service0.loadbalancer.healthcheck.headers.name1": "foobar", "traefik.http.services.Service0.loadbalancer.healthcheck.hostname": "foobar", "traefik.http.services.Service0.loadbalancer.healthcheck.interval": "1s", "traefik.http.services.Service0.loadbalancer.healthcheck.unhealthyinterval": "1s", "traefik.http.services.Service0.loadbalancer.healthcheck.path": "foobar", "traefik.http.services.Service0.loadbalancer.healthcheck.method": "foobar", "traefik.http.services.Service0.loadbalancer.healthcheck.status": "401", "traefik.http.services.Service0.loadbalancer.healthcheck.port": "42", "traefik.http.services.Service0.loadbalancer.healthcheck.scheme": "foobar", "traefik.http.services.Service0.loadbalancer.healthcheck.mode": "foobar", "traefik.http.services.Service0.loadbalancer.healthcheck.timeout": "1s", "traefik.http.services.Service0.loadbalancer.healthcheck.followredirects": "true", "traefik.http.services.Service0.loadbalancer.passhostheader": "true", "traefik.http.services.Service0.loadbalancer.responseforwarding.flushinterval": "1s", "traefik.http.services.Service0.loadbalancer.strategy": "foobar", "traefik.http.services.Service0.loadbalancer.server.url": "foobar", "traefik.http.services.Service0.loadbalancer.server.preservepath": "true", "traefik.http.services.Service0.loadbalancer.server.scheme": "foobar", "traefik.http.services.Service0.loadbalancer.server.port": "8080", "traefik.http.services.Service0.loadbalancer.sticky.cookie.name": "foobar", "traefik.http.services.Service0.loadbalancer.sticky.cookie.secure": "true", "traefik.http.services.Service0.loadbalancer.sticky.cookie.path": "/foobar", "traefik.http.services.Service0.loadbalancer.sticky.cookie.domain": "foo.com", "traefik.http.services.Service0.loadbalancer.serversTransport": "foobar", "traefik.http.services.Service1.loadbalancer.healthcheck.headers.name0": "foobar", "traefik.http.services.Service1.loadbalancer.healthcheck.headers.name1": "foobar", "traefik.http.services.Service1.loadbalancer.healthcheck.hostname": "foobar", "traefik.http.services.Service1.loadbalancer.healthcheck.interval": "1s", "traefik.http.services.Service1.loadbalancer.healthcheck.unhealthyinterval": "1s", "traefik.http.services.Service1.loadbalancer.healthcheck.path": "foobar", "traefik.http.services.Service1.loadbalancer.healthcheck.method": "foobar", "traefik.http.services.Service1.loadbalancer.healthcheck.status": "401", "traefik.http.services.Service1.loadbalancer.healthcheck.port": "42", "traefik.http.services.Service1.loadbalancer.healthcheck.scheme": "foobar", "traefik.http.services.Service1.loadbalancer.healthcheck.mode": "foobar", "traefik.http.services.Service1.loadbalancer.healthcheck.timeout": "1s", "traefik.http.services.Service1.loadbalancer.healthcheck.followredirects": "true", "traefik.http.services.Service1.loadbalancer.passhostheader": "true", "traefik.http.services.Service1.loadbalancer.responseforwarding.flushinterval": "1s", "traefik.http.services.Service1.loadbalancer.strategy": "foobar", "traefik.http.services.Service1.loadbalancer.server.url": "foobar", "traefik.http.services.Service1.loadbalancer.server.preservepath": "true", "traefik.http.services.Service1.loadbalancer.server.scheme": "foobar", "traefik.http.services.Service1.loadbalancer.server.port": "8080", "traefik.http.services.Service1.loadbalancer.sticky": "false", "traefik.http.services.Service1.loadbalancer.sticky.cookie.name": "fui", "traefik.http.services.Service1.loadbalancer.serversTransport": "foobar", "traefik.tcp.middlewares.Middleware0.ipallowlist.sourcerange": "foobar, fiibar", "traefik.tcp.middlewares.Middleware2.inflightconn.amount": "42", "traefik.tcp.routers.Router0.rule": "foobar", "traefik.tcp.routers.Router0.priority": "42", "traefik.tcp.routers.Router0.entrypoints": "foobar, fiibar", "traefik.tcp.routers.Router0.service": "foobar", "traefik.tcp.routers.Router0.tls.passthrough": "false", "traefik.tcp.routers.Router0.tls.options": "foo", "traefik.tcp.routers.Router1.rule": "foobar", "traefik.tcp.routers.Router1.priority": "42", "traefik.tcp.routers.Router1.entrypoints": "foobar, fiibar", "traefik.tcp.routers.Router1.service": "foobar", "traefik.tcp.routers.Router1.tls.options": "foo", "traefik.tcp.routers.Router1.tls.passthrough": "false", "traefik.tcp.services.Service0.loadbalancer.server.Port": "42", "traefik.tcp.services.Service0.loadbalancer.TerminationDelay": "42", "traefik.tcp.services.Service0.loadbalancer.proxyProtocol.version": "42", "traefik.tcp.services.Service0.loadbalancer.serversTransport": "foo", "traefik.tcp.services.Service1.loadbalancer.server.Port": "42", "traefik.tcp.services.Service1.loadbalancer.TerminationDelay": "42", "traefik.tcp.services.Service1.loadbalancer.proxyProtocol": "true", "traefik.tcp.services.Service1.loadbalancer.serversTransport": "foo", "traefik.udp.routers.Router0.entrypoints": "foobar, fiibar", "traefik.udp.routers.Router0.service": "foobar", "traefik.udp.routers.Router1.entrypoints": "foobar, fiibar", "traefik.udp.routers.Router1.service": "foobar", "traefik.udp.services.Service0.loadbalancer.server.Port": "42", "traefik.udp.services.Service1.loadbalancer.server.Port": "42", "traefik.tls.stores.default.defaultgeneratedcert.resolver": "foobar", "traefik.tls.stores.default.defaultgeneratedcert.domain.main": "foobar", "traefik.tls.stores.default.defaultgeneratedcert.domain.sans": "foobar, fiibar", } configuration, err := DecodeConfiguration(labels) require.NoError(t, err) expected := &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "Router0": { EntryPoints: []string{ "foobar", "fiibar", }, Service: "foobar", Rule: "foobar", Priority: 42, TLS: &dynamic.RouterTCPTLSConfig{ Passthrough: false, Options: "foo", }, }, "Router1": { EntryPoints: []string{ "foobar", "fiibar", }, Service: "foobar", Rule: "foobar", Priority: 42, TLS: &dynamic.RouterTCPTLSConfig{ Passthrough: false, Options: "foo", }, }, }, Middlewares: map[string]*dynamic.TCPMiddleware{ "Middleware0": { IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"foobar", "fiibar"}, }, }, "Middleware2": { InFlightConn: &dynamic.TCPInFlightConn{ Amount: 42, }, }, }, Services: map[string]*dynamic.TCPService{ "Service0": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Port: "42", }, }, TerminationDelay: pointer(42), ProxyProtocol: &dynamic.ProxyProtocol{Version: 42}, ServersTransport: "foo", }, }, "Service1": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Port: "42", }, }, TerminationDelay: pointer(42), ProxyProtocol: &dynamic.ProxyProtocol{Version: 2}, ServersTransport: "foo", }, }, }, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{ "Router0": { EntryPoints: []string{ "foobar", "fiibar", }, Service: "foobar", }, "Router1": { EntryPoints: []string{ "foobar", "fiibar", }, Service: "foobar", }, }, Services: map[string]*dynamic.UDPService{ "Service0": { LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Port: "42", }, }, }, }, "Service1": { LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Port: "42", }, }, }, }, }, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Router0": { EntryPoints: []string{ "foobar", "fiibar", }, Middlewares: []string{ "foobar", "fiibar", }, Service: "foobar", Rule: "foobar", Priority: 42, TLS: &dynamic.RouterTLSConfig{}, }, "Router1": { EntryPoints: []string{ "foobar", "fiibar", }, Middlewares: []string{ "foobar", "fiibar", }, Service: "foobar", Rule: "foobar", Priority: 42, }, }, Middlewares: map[string]*dynamic.Middleware{ "Middleware0": { AddPrefix: &dynamic.AddPrefix{ Prefix: "foobar", }, }, "Middleware1": { BasicAuth: &dynamic.BasicAuth{ Users: []string{ "foobar", "fiibar", }, UsersFile: "foobar", Realm: "foobar", RemoveHeader: true, HeaderField: "foobar", }, }, "Middleware10": { InFlightReq: &dynamic.InFlightReq{ Amount: 42, SourceCriterion: &dynamic.SourceCriterion{ IPStrategy: &dynamic.IPStrategy{ Depth: 42, ExcludedIPs: []string{"foobar", "fiibar"}, IPv6Subnet: intPtr(42), }, RequestHeaderName: "foobar", RequestHost: true, }, }, }, "Middleware11": { PassTLSClientCert: &dynamic.PassTLSClientCert{ PEM: true, Info: &dynamic.TLSClientCertificateInfo{ NotAfter: true, NotBefore: 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, }, Sans: true, }, }, }, "Middleware12": { RateLimit: &dynamic.RateLimit{ Average: 42, Burst: 42, Period: ptypes.Duration(time.Second), SourceCriterion: &dynamic.SourceCriterion{ IPStrategy: &dynamic.IPStrategy{ Depth: 42, ExcludedIPs: []string{"foobar", "foobar"}, IPv6Subnet: intPtr(42), }, RequestHeaderName: "foobar", RequestHost: true, }, }, }, "Middleware13": { RedirectRegex: &dynamic.RedirectRegex{ Regex: "foobar", Replacement: "foobar", Permanent: true, }, }, "Middleware13b": { RedirectScheme: &dynamic.RedirectScheme{ Scheme: "https", Port: "80", Permanent: true, }, }, "Middleware14": { ReplacePath: &dynamic.ReplacePath{ Path: "foobar", }, }, "Middleware15": { ReplacePathRegex: &dynamic.ReplacePathRegex{ Regex: "foobar", Replacement: "foobar", }, }, "Middleware16": { Retry: &dynamic.Retry{ Attempts: 42, InitialInterval: ptypes.Duration(time.Second), }, }, "Middleware17": { StripPrefix: &dynamic.StripPrefix{ Prefixes: []string{ "foobar", "fiibar", }, ForceSlash: pointer(true), }, }, "Middleware18": { StripPrefixRegex: &dynamic.StripPrefixRegex{ Regex: []string{ "foobar", "fiibar", }, }, }, "Middleware19": { Compress: &dynamic.Compress{ MinResponseBodyBytes: 42, Encodings: []string{ "foobar", "fiibar", }, }, }, "Middleware2": { Buffering: &dynamic.Buffering{ MaxRequestBodyBytes: 42, MemRequestBodyBytes: 42, MaxResponseBodyBytes: 42, MemResponseBodyBytes: 42, RetryExpression: "foobar", }, }, "Middleware3": { Chain: &dynamic.Chain{ Middlewares: []string{ "foobar", "fiibar", }, }, }, "Middleware4": { CircuitBreaker: &dynamic.CircuitBreaker{ Expression: "foobar", CheckPeriod: ptypes.Duration(time.Second), FallbackDuration: ptypes.Duration(time.Second), RecoveryDuration: ptypes.Duration(time.Second), ResponseCode: 403, }, }, "Middleware5": { DigestAuth: &dynamic.DigestAuth{ Users: []string{ "foobar", "fiibar", }, UsersFile: "foobar", RemoveHeader: true, Realm: "foobar", HeaderField: "foobar", }, }, "Middleware6": { Errors: &dynamic.ErrorPage{ Status: []string{ "foobar", "fiibar", }, Service: "foobar", Query: "foobar", }, }, "Middleware7": { ForwardAuth: &dynamic.ForwardAuth{ Address: "foobar", TLS: &dynamic.ClientTLS{ CA: "foobar", Cert: "foobar", Key: "foobar", InsecureSkipVerify: true, CAOptional: pointer(true), }, TrustForwardHeader: true, AuthResponseHeaders: []string{ "foobar", "fiibar", }, AuthRequestHeaders: []string{ "foobar", "fiibar", }, ForwardBody: true, MaxBodySize: pointer(int64(42)), PreserveRequestMethod: true, }, }, "Middleware8": { Headers: &dynamic.Headers{ CustomRequestHeaders: map[string]string{ "name0": "foobar", "name1": "foobar", }, CustomResponseHeaders: map[string]string{ "name0": "foobar", "name1": "foobar", }, AccessControlAllowCredentials: true, AccessControlAllowHeaders: []string{ "X-foobar", "X-fiibar", }, AccessControlAllowMethods: []string{ "GET", "PUT", }, AccessControlAllowOriginList: []string{ "foobar", "fiibar", }, AccessControlAllowOriginListRegex: []string{ "foobar", "fiibar", }, AccessControlExposeHeaders: []string{ "X-foobar", "X-fiibar", }, AccessControlMaxAge: 200, AddVaryHeader: true, AllowedHosts: []string{ "foobar", "fiibar", }, HostsProxyHeaders: []string{ "foobar", "fiibar", }, SSLRedirect: pointer(true), SSLTemporaryRedirect: pointer(true), SSLHost: pointer("foobar"), SSLProxyHeaders: map[string]string{ "name0": "foobar", "name1": "foobar", }, SSLForceHost: pointer(true), STSSeconds: 42, STSIncludeSubdomains: true, STSPreload: true, ForceSTSHeader: true, FrameDeny: true, CustomFrameOptionsValue: "foobar", ContentTypeNosniff: true, BrowserXSSFilter: true, CustomBrowserXSSValue: "foobar", ContentSecurityPolicy: "foobar", ContentSecurityPolicyReportOnly: "foobar", PublicKey: "foobar", ReferrerPolicy: "foobar", FeaturePolicy: pointer("foobar"), PermissionsPolicy: "foobar", IsDevelopment: true, }, }, "Middleware9": { IPAllowList: &dynamic.IPAllowList{ SourceRange: []string{ "foobar", "fiibar", }, IPStrategy: &dynamic.IPStrategy{ Depth: 42, ExcludedIPs: []string{ "foobar", "fiibar", }, IPv6Subnet: intPtr(42), }, }, }, "Middleware20": { Plugin: map[string]dynamic.PluginConf{ "tomato": { "aaa": "foo1", "bbb": "foo2", }, }, }, }, Services: map[string]*dynamic.Service{ "Service0": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: "foobar", Sticky: &dynamic.Sticky{ Cookie: &dynamic.Cookie{ Name: "foobar", Secure: true, HTTPOnly: false, Domain: "foo.com", Path: func(v string) *string { return &v }("/foobar"), }, }, Servers: []dynamic.Server{ { URL: "foobar",
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/label/label.go
pkg/config/label/label.go
// Package label implements the decoding and encoding between flat labels and a typed Configuration. package label import ( "github.com/traefik/paerser/parser" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) // DecodeConfiguration converts the labels to a configuration. func DecodeConfiguration(labels map[string]string) (*dynamic.Configuration, error) { conf := &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{}, TCP: &dynamic.TCPConfiguration{}, UDP: &dynamic.UDPConfiguration{}, TLS: &dynamic.TLSConfiguration{}, } // When decoding the TLS configuration we are making sure that only the default TLS store can be configured. err := parser.Decode(labels, conf, parser.DefaultRootName, "traefik.http", "traefik.tcp", "traefik.udp", "traefik.tls.stores.default") if err != nil { return nil, err } return conf, nil } // EncodeConfiguration converts a configuration to labels. func EncodeConfiguration(conf *dynamic.Configuration) (map[string]string, error) { return parser.Encode(conf, parser.DefaultRootName) } // Decode converts the labels to an element. // labels -> [ node -> node + metadata (type) ] -> element (node). func Decode(labels map[string]string, element interface{}, filters ...string) error { return parser.Decode(labels, element, parser.DefaultRootName, filters...) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/runtime/runtime_http_test.go
pkg/config/runtime/runtime_http_test.go
package runtime import ( "testing" "github.com/stretchr/testify/assert" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) func TestGetRoutersByEntryPoints(t *testing.T) { testCases := []struct { desc string conf dynamic.Configuration entryPoints []string expected map[string]map[string]*RouterInfo }{ { desc: "Empty Configuration without entrypoint", conf: dynamic.Configuration{}, entryPoints: []string{""}, expected: map[string]map[string]*RouterInfo{}, }, { desc: "Empty Configuration with unknown entrypoints", conf: dynamic.Configuration{}, entryPoints: []string{"foo"}, expected: map[string]map[string]*RouterInfo{}, }, { desc: "Valid configuration with an unknown entrypoint", conf: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`bar.foo`)", }, }, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "HostSNI(`bar.foo`)", }, }, }, }, entryPoints: []string{"foo"}, expected: map[string]map[string]*RouterInfo{}, }, { desc: "Valid configuration with a known entrypoint", conf: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`bar.foo`)", }, "bar": { EntryPoints: []string{"webs"}, Service: "bar-service@myprovider", Rule: "Host(`foo.bar`)", }, "foobar": { EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", Rule: "Host(`bar.foobar`)", }, }, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "HostSNI(`bar.foo`)", }, "bar": { EntryPoints: []string{"webs"}, Service: "bar-service@myprovider", Rule: "HostSNI(`foo.bar`)", }, "foobar": { EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", Rule: "HostSNI(`bar.foobar`)", }, }, }, }, entryPoints: []string{"web"}, expected: map[string]map[string]*RouterInfo{ "web": { "foo": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`bar.foo`)", }, Status: "enabled", Using: []string{"web"}, }, "foobar": { Router: &dynamic.Router{ EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", Rule: "Host(`bar.foobar`)", }, Status: "warning", Err: []string{`entryPoint "webs" doesn't exist`}, Using: []string{"web"}, }, }, }, }, { desc: "Valid configuration with multiple known entrypoints", conf: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`bar.foo`)", }, "bar": { EntryPoints: []string{"webs"}, Service: "bar-service@myprovider", Rule: "Host(`foo.bar`)", }, "foobar": { EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", Rule: "Host(`bar.foobar`)", }, }, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "HostSNI(`bar.foo`)", }, "bar": { EntryPoints: []string{"webs"}, Service: "bar-service@myprovider", Rule: "HostSNI(`foo.bar`)", }, "foobar": { EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", Rule: "HostSNI(`bar.foobar`)", }, }, }, }, entryPoints: []string{"web", "webs"}, expected: map[string]map[string]*RouterInfo{ "web": { "foo": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`bar.foo`)", }, Status: "enabled", Using: []string{"web"}, }, "foobar": { Router: &dynamic.Router{ EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", Rule: "Host(`bar.foobar`)", }, Status: "enabled", Using: []string{"web", "webs"}, }, }, "webs": { "bar": { Router: &dynamic.Router{ EntryPoints: []string{"webs"}, Service: "bar-service@myprovider", Rule: "Host(`foo.bar`)", }, Status: "enabled", Using: []string{"webs"}, }, "foobar": { Router: &dynamic.Router{ EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", Rule: "Host(`bar.foobar`)", }, Status: "enabled", Using: []string{"web", "webs"}, }, }, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() runtimeConfig := NewConfig(test.conf) actual := runtimeConfig.GetRoutersByEntryPoints(t.Context(), test.entryPoints, false) 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/config/runtime/runtime_tcp_test.go
pkg/config/runtime/runtime_tcp_test.go
package runtime import ( "testing" "github.com/stretchr/testify/assert" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) func TestGetTCPRoutersByEntryPoints(t *testing.T) { testCases := []struct { desc string conf dynamic.Configuration entryPoints []string expected map[string]map[string]*TCPRouterInfo }{ { desc: "Empty Configuration without entrypoint", conf: dynamic.Configuration{}, entryPoints: []string{""}, expected: map[string]map[string]*TCPRouterInfo{}, }, { desc: "Empty Configuration with unknown entrypoints", conf: dynamic.Configuration{}, entryPoints: []string{"foo"}, expected: map[string]map[string]*TCPRouterInfo{}, }, { desc: "Valid configuration with an unknown entrypoint", conf: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`bar.foo`)", }, }, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "HostSNI(`bar.foo`)", }, }, }, }, entryPoints: []string{"foo"}, expected: map[string]map[string]*TCPRouterInfo{}, }, { desc: "Valid configuration with a known entrypoint", conf: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`bar.foo`)", }, "bar": { EntryPoints: []string{"webs"}, Service: "bar-service@myprovider", Rule: "Host(`foo.bar`)", }, "foobar": { EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", Rule: "Host(`bar.foobar`)", }, }, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "HostSNI(`bar.foo`)", }, "bar": { EntryPoints: []string{"webs"}, Service: "bar-service@myprovider", Rule: "HostSNI(`foo.bar`)", }, "foobar": { EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", Rule: "HostSNI(`bar.foobar`)", }, }, }, }, entryPoints: []string{"web"}, expected: map[string]map[string]*TCPRouterInfo{ "web": { "foo": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "HostSNI(`bar.foo`)", }, Status: "enabled", Using: []string{"web"}, }, "foobar": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", Rule: "HostSNI(`bar.foobar`)", }, Status: "warning", Err: []string{`entryPoint "webs" doesn't exist`}, Using: []string{"web"}, }, }, }, }, { desc: "Valid configuration with multiple known entrypoints", conf: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`bar.foo`)", }, "bar": { EntryPoints: []string{"webs"}, Service: "bar-service@myprovider", Rule: "Host(`foo.bar`)", }, "foobar": { EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", Rule: "Host(`bar.foobar`)", }, }, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "HostSNI(`bar.foo`)", }, "bar": { EntryPoints: []string{"webs"}, Service: "bar-service@myprovider", Rule: "HostSNI(`foo.bar`)", }, "foobar": { EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", Rule: "HostSNI(`bar.foobar`)", }, }, }, }, entryPoints: []string{"web", "webs"}, expected: map[string]map[string]*TCPRouterInfo{ "web": { "foo": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "HostSNI(`bar.foo`)", }, Status: "enabled", Using: []string{"web"}, }, "foobar": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", Rule: "HostSNI(`bar.foobar`)", }, Status: "enabled", Using: []string{"web", "webs"}, }, }, "webs": { "bar": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"webs"}, Service: "bar-service@myprovider", Rule: "HostSNI(`foo.bar`)", }, Status: "enabled", Using: []string{"webs"}, }, "foobar": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", Rule: "HostSNI(`bar.foobar`)", }, Status: "enabled", Using: []string{"web", "webs"}, }, }, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() runtimeConfig := NewConfig(test.conf) actual := runtimeConfig.GetTCPRoutersByEntryPoints(t.Context(), test.entryPoints) 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/config/runtime/runtime_test.go
pkg/config/runtime/runtime_test.go
package runtime_test import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" ) // all the Routers/Middlewares/Services are considered fully qualified. func TestPopulateUsedBy(t *testing.T) { testCases := []struct { desc string conf *runtime.Configuration expected runtime.Configuration }{ { desc: "nil config", conf: nil, expected: runtime.Configuration{}, }, { desc: "One service used by two routers", conf: &runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "foo@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`bar.foo`)", }, }, "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", }, }, }, Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ {URL: "http://127.0.0.1:8085"}, {URL: "http://127.0.0.1:8086"}, }, HealthCheck: &dynamic.ServerHealthCheck{ Interval: ptypes.Duration(500 * time.Millisecond), Path: "/health", }, }, }, }, }, }, expected: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "foo@myprovider": {}, "bar@myprovider": {}, }, Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { UsedBy: []string{"bar@myprovider", "foo@myprovider"}, }, }, }, }, { desc: "One service used by two routers, but one router with wrong rule", conf: &runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ {URL: "http://127.0.0.1"}, }, }, }, }, }, Routers: map[string]*runtime.RouterInfo{ "foo@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "WrongRule(`bar.foo`)", }, }, "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", }, }, }, }, expected: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "foo@myprovider": {}, "bar@myprovider": {}, }, Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { UsedBy: []string{"bar@myprovider", "foo@myprovider"}, }, }, }, }, { desc: "Broken Service used by one Router", conf: &runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ LoadBalancer: nil, }, }, }, Routers: map[string]*runtime.RouterInfo{ "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", }, }, }, }, expected: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "bar@myprovider": {}, }, Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { UsedBy: []string{"bar@myprovider"}, }, }, }, }, { desc: "2 different Services each used by a distinct router.", conf: &runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:8085", }, { URL: "http://127.0.0.1:8086", }, }, HealthCheck: &dynamic.ServerHealthCheck{ Interval: ptypes.Duration(500 * time.Millisecond), Path: "/health", }, }, }, }, "bar-service@myprovider": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:8087", }, { URL: "http://127.0.0.1:8088", }, }, HealthCheck: &dynamic.ServerHealthCheck{ Interval: ptypes.Duration(500 * time.Millisecond), Path: "/health", }, }, }, }, }, Routers: map[string]*runtime.RouterInfo{ "foo@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`bar.foo`)", }, }, "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "bar-service@myprovider", Rule: "Host(`foo.bar`)", }, }, }, }, expected: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "bar@myprovider": {}, "foo@myprovider": {}, }, Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { UsedBy: []string{"foo@myprovider"}, }, "bar-service@myprovider": { UsedBy: []string{"bar@myprovider"}, }, }, }, }, { desc: "2 middlewares both used by 2 Routers", conf: &runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, }, }, Middlewares: map[string]*runtime.MiddlewareInfo{ "auth@myprovider": { Middleware: &dynamic.Middleware{ BasicAuth: &dynamic.BasicAuth{ Users: []string{"admin:admin"}, }, }, }, "addPrefixTest@myprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/toto", }, }, }, }, Routers: map[string]*runtime.RouterInfo{ "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth", "addPrefixTest"}, }, }, "test@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar.other`)", Middlewares: []string{"addPrefixTest", "auth"}, }, }, }, }, expected: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "bar@myprovider": {}, "test@myprovider": {}, }, Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { UsedBy: []string{"bar@myprovider", "test@myprovider"}, }, }, Middlewares: map[string]*runtime.MiddlewareInfo{ "auth@myprovider": { UsedBy: []string{"bar@myprovider", "test@myprovider"}, }, "addPrefixTest@myprovider": { UsedBy: []string{"bar@myprovider", "test@myprovider"}, }, }, }, }, { desc: "Unknown middleware is not used by the Router", conf: &runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, }, }, Middlewares: map[string]*runtime.MiddlewareInfo{ "auth@myprovider": { Middleware: &dynamic.Middleware{ BasicAuth: &dynamic.BasicAuth{ Users: []string{"admin:admin"}, }, }, }, }, Routers: map[string]*runtime.RouterInfo{ "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", Middlewares: []string{"unknown"}, }, }, }, }, expected: runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { UsedBy: []string{"bar@myprovider"}, }, }, }, }, { desc: "Broken middleware is used by Router", conf: &runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, }, }, Middlewares: map[string]*runtime.MiddlewareInfo{ "auth@myprovider": { Middleware: &dynamic.Middleware{ BasicAuth: &dynamic.BasicAuth{ Users: []string{"badConf"}, }, }, }, }, Routers: map[string]*runtime.RouterInfo{ "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth@myprovider"}, }, }, }, }, expected: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "bar@myprovider": {}, }, Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { UsedBy: []string{"bar@myprovider"}, }, }, Middlewares: map[string]*runtime.MiddlewareInfo{ "auth@myprovider": { UsedBy: []string{"bar@myprovider"}, }, }, }, }, { desc: "2 middlewares from 2 distinct providers both used by 2 Routers", conf: &runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, }, }, Middlewares: map[string]*runtime.MiddlewareInfo{ "auth@myprovider": { Middleware: &dynamic.Middleware{ BasicAuth: &dynamic.BasicAuth{ Users: []string{"admin:admin"}, }, }, }, "addPrefixTest@myprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/titi", }, }, }, "addPrefixTest@anotherprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/toto", }, }, }, }, Routers: map[string]*runtime.RouterInfo{ "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth", "addPrefixTest@anotherprovider"}, }, }, "test@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar.other`)", Middlewares: []string{"addPrefixTest", "auth"}, }, }, }, }, expected: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "bar@myprovider": {}, "test@myprovider": {}, }, Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { UsedBy: []string{"bar@myprovider", "test@myprovider"}, }, }, Middlewares: map[string]*runtime.MiddlewareInfo{ "auth@myprovider": { UsedBy: []string{"bar@myprovider", "test@myprovider"}, }, "addPrefixTest@myprovider": { UsedBy: []string{"test@myprovider"}, }, "addPrefixTest@anotherprovider": { UsedBy: []string{"bar@myprovider"}, }, }, }, }, // TCP tests from hereon { desc: "TCP, One service used by two routers", conf: &runtime.Configuration{ TCPRouters: map[string]*runtime.TCPRouterInfo{ "foo@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`bar.foo`)", }, }, "bar@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", }, }, }, TCPServices: map[string]*runtime.TCPServiceInfo{ "foo-service@myprovider": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1", Port: "8085", }, { Address: "127.0.0.1", Port: "8086", }, }, }, }, }, }, }, expected: runtime.Configuration{ TCPRouters: map[string]*runtime.TCPRouterInfo{ "foo@myprovider": {}, "bar@myprovider": {}, }, TCPServices: map[string]*runtime.TCPServiceInfo{ "foo-service@myprovider": { UsedBy: []string{"bar@myprovider", "foo@myprovider"}, }, }, }, }, { desc: "TCP, One service used by two routers, but one router with wrong rule", conf: &runtime.Configuration{ TCPServices: map[string]*runtime.TCPServiceInfo{ "foo-service@myprovider": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1", }, }, }, }, }, }, TCPRouters: map[string]*runtime.TCPRouterInfo{ "foo@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "WrongRule(`bar.foo`)", }, }, "bar@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", }, }, }, }, expected: runtime.Configuration{ TCPRouters: map[string]*runtime.TCPRouterInfo{ "foo@myprovider": {}, "bar@myprovider": {}, }, TCPServices: map[string]*runtime.TCPServiceInfo{ "foo-service@myprovider": { UsedBy: []string{"bar@myprovider", "foo@myprovider"}, }, }, }, }, { desc: "TCP, Broken Service used by one Router", conf: &runtime.Configuration{ TCPServices: map[string]*runtime.TCPServiceInfo{ "foo-service@myprovider": { TCPService: &dynamic.TCPService{ LoadBalancer: nil, }, }, }, TCPRouters: map[string]*runtime.TCPRouterInfo{ "bar@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", }, }, }, }, expected: runtime.Configuration{ TCPRouters: map[string]*runtime.TCPRouterInfo{ "bar@myprovider": {}, }, TCPServices: map[string]*runtime.TCPServiceInfo{ "foo-service@myprovider": { UsedBy: []string{"bar@myprovider"}, }, }, }, }, { desc: "TCP, 2 different Services each used by a distinct router.", conf: &runtime.Configuration{ TCPServices: map[string]*runtime.TCPServiceInfo{ "foo-service@myprovider": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1", Port: "8085", }, { Address: "127.0.0.1", Port: "8086", }, }, }, }, }, "bar-service@myprovider": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1", Port: "8087", }, { Address: "127.0.0.1", Port: "8088", }, }, }, }, }, }, TCPRouters: map[string]*runtime.TCPRouterInfo{ "foo@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`bar.foo`)", }, }, "bar@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "bar-service@myprovider", Rule: "Host(`foo.bar`)", }, }, }, }, expected: runtime.Configuration{ TCPRouters: map[string]*runtime.TCPRouterInfo{ "bar@myprovider": {}, "foo@myprovider": {}, }, TCPServices: map[string]*runtime.TCPServiceInfo{ "foo-service@myprovider": { UsedBy: []string{"foo@myprovider"}, }, "bar-service@myprovider": { UsedBy: []string{"bar@myprovider"}, }, }, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() runtimeConf := test.conf runtimeConf.PopulateUsedBy() for key, expectedService := range test.expected.Services { require.NotNil(t, runtimeConf.Services[key]) assert.Equal(t, expectedService.UsedBy, runtimeConf.Services[key].UsedBy) } for key, expectedMiddleware := range test.expected.Middlewares { require.NotNil(t, runtimeConf.Middlewares[key]) assert.Equal(t, expectedMiddleware.UsedBy, runtimeConf.Middlewares[key].UsedBy) } for key, expectedTCPService := range test.expected.TCPServices { require.NotNil(t, runtimeConf.TCPServices[key]) assert.Equal(t, expectedTCPService.UsedBy, runtimeConf.TCPServices[key].UsedBy) } }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/runtime/runtime_tcp.go
pkg/config/runtime/runtime_tcp.go
package runtime import ( "context" "errors" "fmt" "slices" "sync" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/observability/logs" ) // GetTCPRoutersByEntryPoints returns all the tcp routers by entry points name and routers name. func (c *Configuration) GetTCPRoutersByEntryPoints(ctx context.Context, entryPoints []string) map[string]map[string]*TCPRouterInfo { entryPointsRouters := make(map[string]map[string]*TCPRouterInfo) for rtName, rt := range c.TCPRouters { logger := log.Ctx(ctx).With().Str(logs.RouterName, rtName).Logger() entryPointsCount := 0 for _, entryPointName := range rt.EntryPoints { if !slices.Contains(entryPoints, entryPointName) { rt.AddError(fmt.Errorf("entryPoint %q doesn't exist", entryPointName), false) logger.Error().Str(logs.EntryPointName, entryPointName). Msg("EntryPoint doesn't exist") continue } if _, ok := entryPointsRouters[entryPointName]; !ok { entryPointsRouters[entryPointName] = make(map[string]*TCPRouterInfo) } entryPointsCount++ rt.Using = append(rt.Using, entryPointName) entryPointsRouters[entryPointName][rtName] = rt } if entryPointsCount == 0 { rt.AddError(errors.New("no valid entryPoint for this router"), true) logger.Error().Msg("No valid entryPoint for this router") } } return entryPointsRouters } // TCPRouterInfo holds information about a currently running TCP router. type TCPRouterInfo struct { *dynamic.TCPRouter // dynamic configuration Err []string `json:"error,omitempty"` // initialization error // Status reports whether the router is disabled, in a warning state, or all good (enabled). // If not in "enabled" state, the reason for it should be in the list of Err. // It is the caller's responsibility to set the initial status. Status string `json:"status,omitempty"` Using []string `json:"using,omitempty"` // Effective entry points used by that router. } // AddError adds err to r.Err, if it does not already exist. // If critical is set, r is marked as disabled. func (r *TCPRouterInfo) AddError(err error, critical bool) { for _, value := range r.Err { if value == err.Error() { return } } r.Err = append(r.Err, err.Error()) if critical { r.Status = StatusDisabled return } // only set it to "warning" if not already in a worse state if r.Status != StatusDisabled { r.Status = StatusWarning } } // TCPServiceInfo holds information about a currently running TCP service. type TCPServiceInfo struct { *dynamic.TCPService // dynamic configuration Err []string `json:"error,omitempty"` // initialization error // Status reports whether the service is disabled, in a warning state, or all good (enabled). // If not in "enabled" state, the reason for it should be in the list of Err. // It is the caller's responsibility to set the initial status. Status string `json:"status,omitempty"` UsedBy []string `json:"usedBy,omitempty"` // list of routers using that service serverStatusMu sync.RWMutex serverStatus map[string]string // keyed by server address } // AddError adds err to s.Err, if it does not already exist. // If critical is set, s is marked as disabled. func (s *TCPServiceInfo) AddError(err error, critical bool) { for _, value := range s.Err { if value == err.Error() { return } } s.Err = append(s.Err, err.Error()) if critical { s.Status = StatusDisabled return } // only set it to "warning" if not already in a worse state if s.Status != StatusDisabled { s.Status = StatusWarning } } // UpdateServerStatus sets the status of the server in the TCPServiceInfo. func (s *TCPServiceInfo) UpdateServerStatus(server, status string) { s.serverStatusMu.Lock() defer s.serverStatusMu.Unlock() if s.serverStatus == nil { s.serverStatus = make(map[string]string) } s.serverStatus[server] = status } // GetAllStatus returns all the statuses of all the servers in TCPServiceInfo. func (s *TCPServiceInfo) GetAllStatus() map[string]string { s.serverStatusMu.RLock() defer s.serverStatusMu.RUnlock() if len(s.serverStatus) == 0 { return nil } allStatus := make(map[string]string, len(s.serverStatus)) for k, v := range s.serverStatus { allStatus[k] = v } return allStatus } // TCPMiddlewareInfo holds information about a currently running middleware. type TCPMiddlewareInfo struct { *dynamic.TCPMiddleware // dynamic configuration // Err contains all the errors that occurred during service creation. Err []string `json:"error,omitempty"` Status string `json:"status,omitempty"` UsedBy []string `json:"usedBy,omitempty"` // list of TCP routers and services using that middleware. } // AddError adds err to s.Err, if it does not already exist. // If critical is set, m is marked as disabled. func (m *TCPMiddlewareInfo) AddError(err error, critical bool) { for _, value := range m.Err { if value == err.Error() { return } } m.Err = append(m.Err, err.Error()) if critical { m.Status = StatusDisabled return } // only set it to "warning" if not already in a worse state if m.Status != StatusDisabled { m.Status = StatusWarning } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/runtime/runtime_udp_test.go
pkg/config/runtime/runtime_udp_test.go
package runtime import ( "testing" "github.com/stretchr/testify/assert" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) func TestGetUDPRoutersByEntryPoints(t *testing.T) { testCases := []struct { desc string conf dynamic.Configuration entryPoints []string expected map[string]map[string]*UDPRouterInfo }{ { desc: "Empty Configuration without entrypoint", conf: dynamic.Configuration{}, entryPoints: []string{""}, expected: map[string]map[string]*UDPRouterInfo{}, }, { desc: "Empty Configuration with unknown entrypoints", conf: dynamic.Configuration{}, entryPoints: []string{"foo"}, expected: map[string]map[string]*UDPRouterInfo{}, }, { desc: "Valid configuration with an unknown entrypoint", conf: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`bar.foo`)", }, }, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, }, }, }, entryPoints: []string{"foo"}, expected: map[string]map[string]*UDPRouterInfo{}, }, { desc: "Valid configuration with a known entrypoint", conf: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, "bar": { EntryPoints: []string{"webs"}, Service: "bar-service@myprovider", }, "foobar": { EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", }, }, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, "bar": { EntryPoints: []string{"webs"}, Service: "bar-service@myprovider", }, "foobar": { EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", }, }, }, }, entryPoints: []string{"web"}, expected: map[string]map[string]*UDPRouterInfo{ "web": { "foo": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, Status: "enabled", Using: []string{"web"}, }, "foobar": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", }, Status: "warning", Err: []string{`entryPoint "webs" doesn't exist`}, Using: []string{"web"}, }, }, }, }, { desc: "Valid configuration with multiple known entrypoints", conf: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, "bar": { EntryPoints: []string{"webs"}, Service: "bar-service@myprovider", }, "foobar": { EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", }, }, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{ "foo": { EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, "bar": { EntryPoints: []string{"webs"}, Service: "bar-service@myprovider", }, "foobar": { EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", }, }, }, }, entryPoints: []string{"web", "webs"}, expected: map[string]map[string]*UDPRouterInfo{ "web": { "foo": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, Status: "enabled", Using: []string{"web"}, }, "foobar": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", }, Status: "enabled", Using: []string{"web", "webs"}, }, }, "webs": { "bar": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"webs"}, Service: "bar-service@myprovider", }, Status: "enabled", Using: []string{"webs"}, }, "foobar": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web", "webs"}, Service: "foobar-service@myprovider", }, Status: "enabled", Using: []string{"web", "webs"}, }, }, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() runtimeConfig := NewConfig(test.conf) actual := runtimeConfig.GetUDPRoutersByEntryPoints(t.Context(), test.entryPoints) 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/config/runtime/runtime_http.go
pkg/config/runtime/runtime_http.go
package runtime import ( "context" "errors" "fmt" "slices" "sort" "sync" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/observability/logs" ) // GetRoutersByEntryPoints returns all the http routers by entry points name and routers name. func (c *Configuration) GetRoutersByEntryPoints(ctx context.Context, entryPoints []string, tls bool) map[string]map[string]*RouterInfo { entryPointsRouters := make(map[string]map[string]*RouterInfo) for rtName, rt := range c.Routers { if (tls && rt.TLS == nil) || (!tls && rt.TLS != nil) { continue } logger := log.Ctx(ctx).With().Str(logs.RouterName, rtName).Logger() entryPointsCount := 0 for _, entryPointName := range rt.EntryPoints { if !slices.Contains(entryPoints, entryPointName) { rt.AddError(fmt.Errorf("entryPoint %q doesn't exist", entryPointName), false) logger.Error().Str(logs.EntryPointName, entryPointName). Msg("EntryPoint doesn't exist") continue } if _, ok := entryPointsRouters[entryPointName]; !ok { entryPointsRouters[entryPointName] = make(map[string]*RouterInfo) } entryPointsCount++ rt.Using = append(rt.Using, entryPointName) entryPointsRouters[entryPointName][rtName] = rt } // Root routers must have at least one entry point. if entryPointsCount == 0 && rt.ParentRefs == nil { rt.AddError(errors.New("no valid entryPoint for this router"), true) logger.Error().Msg("No valid entryPoint for this router") } rt.Using = unique(rt.Using) } return entryPointsRouters } func unique(src []string) []string { var uniq []string set := make(map[string]struct{}) for _, v := range src { if _, exist := set[v]; !exist { set[v] = struct{}{} uniq = append(uniq, v) } } sort.Strings(uniq) return uniq } // RouterInfo holds information about a currently running HTTP router. type RouterInfo struct { *dynamic.Router // dynamic configuration // Err contains all the errors that occurred during router's creation. Err []string `json:"error,omitempty"` // Status reports whether the router is disabled, in a warning state, or all good (enabled). // If not in "enabled" state, the reason for it should be in the list of Err. // It is the caller's responsibility to set the initial status. Status string `json:"status,omitempty"` Using []string `json:"using,omitempty"` // Effective entry points used by that router. // ChildRefs contains the names of child routers. // This field is only filled during multi-layer routing computation of parentRefs, // and used when building the runtime configuration. ChildRefs []string `json:"-"` } // AddError adds err to r.Err, if it does not already exist. // If critical is set, r is marked as disabled. func (r *RouterInfo) AddError(err error, critical bool) { for _, value := range r.Err { if value == err.Error() { return } } r.Err = append(r.Err, err.Error()) if critical { r.Status = StatusDisabled return } // only set it to "warning" if not already in a worse state if r.Status != StatusDisabled { r.Status = StatusWarning } } // MiddlewareInfo holds information about a currently running middleware. type MiddlewareInfo struct { *dynamic.Middleware // dynamic configuration // Err contains all the errors that occurred during service creation. Err []string `json:"error,omitempty"` Status string `json:"status,omitempty"` UsedBy []string `json:"usedBy,omitempty"` // list of routers and services using that middleware. } // AddError adds err to s.Err, if it does not already exist. // If critical is set, m is marked as disabled. func (m *MiddlewareInfo) AddError(err error, critical bool) { for _, value := range m.Err { if value == err.Error() { return } } m.Err = append(m.Err, err.Error()) if critical { m.Status = StatusDisabled return } // only set it to "warning" if not already in a worse state if m.Status != StatusDisabled { m.Status = StatusWarning } } // ServiceInfo holds information about a currently running service. type ServiceInfo struct { *dynamic.Service // dynamic configuration // Err contains all the errors that occurred during service creation. Err []string `json:"error,omitempty"` // Status reports whether the service is disabled, in a warning state, or all good (enabled). // If not in "enabled" state, the reason for it should be in the list of Err. // It is the caller's responsibility to set the initial status. Status string `json:"status,omitempty"` UsedBy []string `json:"usedBy,omitempty"` // list of routers using that service serverStatusMu sync.RWMutex serverStatus map[string]string // keyed by server URL } // AddError adds err to s.Err, if it does not already exist. // If critical is set, s is marked as disabled. func (s *ServiceInfo) AddError(err error, critical bool) { for _, value := range s.Err { if value == err.Error() { return } } s.Err = append(s.Err, err.Error()) if critical { s.Status = StatusDisabled return } // only set it to "warning" if not already in a worse state if s.Status != StatusDisabled { s.Status = StatusWarning } } // UpdateServerStatus sets the status of the server in the ServiceInfo. // It is the responsibility of the caller to check that s is not nil. func (s *ServiceInfo) UpdateServerStatus(server, status string) { s.serverStatusMu.Lock() defer s.serverStatusMu.Unlock() if s.serverStatus == nil { s.serverStatus = make(map[string]string) } s.serverStatus[server] = status } // GetAllStatus returns all the statuses of all the servers in ServiceInfo. // It is the responsibility of the caller to check that s is not nil. func (s *ServiceInfo) GetAllStatus() map[string]string { s.serverStatusMu.RLock() defer s.serverStatusMu.RUnlock() if len(s.serverStatus) == 0 { return nil } allStatus := make(map[string]string, len(s.serverStatus)) for k, v := range s.serverStatus { allStatus[k] = v } return allStatus }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/runtime/runtime_udp.go
pkg/config/runtime/runtime_udp.go
package runtime import ( "context" "errors" "fmt" "slices" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/observability/logs" ) // GetUDPRoutersByEntryPoints returns all the UDP routers by entry points name and routers name. func (c *Configuration) GetUDPRoutersByEntryPoints(ctx context.Context, entryPoints []string) map[string]map[string]*UDPRouterInfo { entryPointsRouters := make(map[string]map[string]*UDPRouterInfo) for rtName, rt := range c.UDPRouters { logger := log.Ctx(ctx).With().Str(logs.RouterName, rtName).Logger() eps := rt.EntryPoints if len(eps) == 0 { logger.Debug().Msgf("No entryPoint defined for this router, using the default one(s) instead: %+v", entryPoints) eps = entryPoints } entryPointsCount := 0 for _, entryPointName := range eps { if !slices.Contains(entryPoints, entryPointName) { rt.AddError(fmt.Errorf("entryPoint %q doesn't exist", entryPointName), false) logger.Error().Str(logs.EntryPointName, entryPointName). Msg("EntryPoint doesn't exist") continue } if _, ok := entryPointsRouters[entryPointName]; !ok { entryPointsRouters[entryPointName] = make(map[string]*UDPRouterInfo) } entryPointsCount++ rt.Using = append(rt.Using, entryPointName) entryPointsRouters[entryPointName][rtName] = rt } if entryPointsCount == 0 { rt.AddError(errors.New("no valid entryPoint for this router"), true) logger.Error().Msg("No valid entryPoint for this router") } } return entryPointsRouters } // UDPRouterInfo holds information about a currently running UDP router. type UDPRouterInfo struct { *dynamic.UDPRouter // dynamic configuration Err []string `json:"error,omitempty"` // initialization error // Status reports whether the router is disabled, in a warning state, or all good (enabled). // If not in "enabled" state, the reason for it should be in the list of Err. // It is the caller's responsibility to set the initial status. Status string `json:"status,omitempty"` Using []string `json:"using,omitempty"` // Effective entry points used by that router. } // AddError adds err to r.Err, if it does not already exist. // If critical is set, r is marked as disabled. func (r *UDPRouterInfo) AddError(err error, critical bool) { for _, value := range r.Err { if value == err.Error() { return } } r.Err = append(r.Err, err.Error()) if critical { r.Status = StatusDisabled return } // only set it to "warning" if not already in a worse state if r.Status != StatusDisabled { r.Status = StatusWarning } } // UDPServiceInfo holds information about a currently running UDP service. type UDPServiceInfo struct { *dynamic.UDPService // dynamic configuration Err []string `json:"error,omitempty"` // initialization error // Status reports whether the service is disabled, in a warning state, or all good (enabled). // If not in "enabled" state, the reason for it should be in the list of Err. // It is the caller's responsibility to set the initial status. Status string `json:"status,omitempty"` UsedBy []string `json:"usedBy,omitempty"` // list of routers using that service } // AddError adds err to s.Err, if it does not already exist. // If critical is set, s is marked as disabled. func (s *UDPServiceInfo) AddError(err error, critical bool) { for _, value := range s.Err { if value == err.Error() { return } } s.Err = append(s.Err, err.Error()) if critical { s.Status = StatusDisabled return } // only set it to "warning" if not already in a worse state if s.Status != StatusDisabled { s.Status = StatusWarning } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/runtime/runtime.go
pkg/config/runtime/runtime.go
package runtime import ( "sort" "strings" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/observability/logs" ) // Status of the router/service. const ( StatusEnabled = "enabled" StatusDisabled = "disabled" StatusWarning = "warning" ) // Status of the servers. const ( StatusUp = "UP" StatusDown = "DOWN" ) // Configuration holds the information about the currently running traefik instance. type Configuration struct { Routers map[string]*RouterInfo `json:"routers,omitempty"` Middlewares map[string]*MiddlewareInfo `json:"middlewares,omitempty"` Services map[string]*ServiceInfo `json:"services,omitempty"` Models map[string]*dynamic.Model `json:"-"` TCPRouters map[string]*TCPRouterInfo `json:"tcpRouters,omitempty"` TCPMiddlewares map[string]*TCPMiddlewareInfo `json:"tcpMiddlewares,omitempty"` TCPServices map[string]*TCPServiceInfo `json:"tcpServices,omitempty"` UDPRouters map[string]*UDPRouterInfo `json:"udpRouters,omitempty"` UDPServices map[string]*UDPServiceInfo `json:"udpServices,omitempty"` } // NewConfig returns a Configuration initialized with the given conf. It never returns nil. func NewConfig(conf dynamic.Configuration) *Configuration { if conf.HTTP == nil && conf.TCP == nil && conf.UDP == nil { return &Configuration{} } runtimeConfig := &Configuration{} if conf.HTTP != nil { routers := conf.HTTP.Routers if len(routers) > 0 { runtimeConfig.Routers = make(map[string]*RouterInfo, len(routers)) for k, v := range routers { runtimeConfig.Routers[k] = &RouterInfo{Router: v, Status: StatusEnabled} } } services := conf.HTTP.Services if len(services) > 0 { runtimeConfig.Services = make(map[string]*ServiceInfo, len(services)) for k, v := range services { runtimeConfig.Services[k] = &ServiceInfo{Service: v, Status: StatusEnabled} } } middlewares := conf.HTTP.Middlewares if len(middlewares) > 0 { runtimeConfig.Middlewares = make(map[string]*MiddlewareInfo, len(middlewares)) for k, v := range middlewares { runtimeConfig.Middlewares[k] = &MiddlewareInfo{Middleware: v, Status: StatusEnabled} } } runtimeConfig.Models = conf.HTTP.Models } if conf.TCP != nil { if len(conf.TCP.Routers) > 0 { runtimeConfig.TCPRouters = make(map[string]*TCPRouterInfo, len(conf.TCP.Routers)) for k, v := range conf.TCP.Routers { runtimeConfig.TCPRouters[k] = &TCPRouterInfo{TCPRouter: v, Status: StatusEnabled} } } if len(conf.TCP.Services) > 0 { runtimeConfig.TCPServices = make(map[string]*TCPServiceInfo, len(conf.TCP.Services)) for k, v := range conf.TCP.Services { runtimeConfig.TCPServices[k] = &TCPServiceInfo{TCPService: v, Status: StatusEnabled} } } if len(conf.TCP.Middlewares) > 0 { runtimeConfig.TCPMiddlewares = make(map[string]*TCPMiddlewareInfo, len(conf.TCP.Middlewares)) for k, v := range conf.TCP.Middlewares { runtimeConfig.TCPMiddlewares[k] = &TCPMiddlewareInfo{TCPMiddleware: v, Status: StatusEnabled} } } } if conf.UDP != nil { if len(conf.UDP.Routers) > 0 { runtimeConfig.UDPRouters = make(map[string]*UDPRouterInfo, len(conf.UDP.Routers)) for k, v := range conf.UDP.Routers { runtimeConfig.UDPRouters[k] = &UDPRouterInfo{UDPRouter: v, Status: StatusEnabled} } } if len(conf.UDP.Services) > 0 { runtimeConfig.UDPServices = make(map[string]*UDPServiceInfo, len(conf.UDP.Services)) for k, v := range conf.UDP.Services { runtimeConfig.UDPServices[k] = &UDPServiceInfo{UDPService: v, Status: StatusEnabled} } } } return runtimeConfig } // PopulateUsedBy populates all the UsedBy lists of the underlying fields of r, // based on the relations between the included services, routers, and middlewares. func (c *Configuration) PopulateUsedBy() { if c == nil { return } for routerName, routerInfo := range c.Routers { // lazily initialize Status in case caller forgot to do it if routerInfo.Status == "" { routerInfo.Status = StatusEnabled } providerName := getProviderName(routerName) if providerName == "" { log.Error().Str(logs.RouterName, routerName).Msg("Router name is not fully qualified") continue } for _, midName := range routerInfo.Router.Middlewares { fullMidName := getQualifiedName(providerName, midName) if _, ok := c.Middlewares[fullMidName]; !ok { continue } c.Middlewares[fullMidName].UsedBy = append(c.Middlewares[fullMidName].UsedBy, routerName) } serviceName := getQualifiedName(providerName, routerInfo.Router.Service) if _, ok := c.Services[serviceName]; !ok { continue } c.Services[serviceName].UsedBy = append(c.Services[serviceName].UsedBy, routerName) } for k, serviceInfo := range c.Services { // lazily initialize Status in case caller forgot to do it if serviceInfo.Status == "" { serviceInfo.Status = StatusEnabled } sort.Strings(c.Services[k].UsedBy) } for midName, mid := range c.Middlewares { // lazily initialize Status in case caller forgot to do it if mid.Status == "" { mid.Status = StatusEnabled } sort.Strings(c.Middlewares[midName].UsedBy) } for routerName, routerInfo := range c.TCPRouters { // lazily initialize Status in case caller forgot to do it if routerInfo.Status == "" { routerInfo.Status = StatusEnabled } providerName := getProviderName(routerName) if providerName == "" { log.Error().Str(logs.RouterName, routerName).Msg("TCP router name is not fully qualified") continue } serviceName := getQualifiedName(providerName, routerInfo.TCPRouter.Service) if _, ok := c.TCPServices[serviceName]; !ok { continue } c.TCPServices[serviceName].UsedBy = append(c.TCPServices[serviceName].UsedBy, routerName) } for k, serviceInfo := range c.TCPServices { // lazily initialize Status in case caller forgot to do it if serviceInfo.Status == "" { serviceInfo.Status = StatusEnabled } sort.Strings(c.TCPServices[k].UsedBy) } for midName, mid := range c.TCPMiddlewares { // lazily initialize Status in case caller forgot to do it if mid.Status == "" { mid.Status = StatusEnabled } sort.Strings(c.TCPMiddlewares[midName].UsedBy) } for routerName, routerInfo := range c.UDPRouters { // lazily initialize Status in case caller forgot to do it if routerInfo.Status == "" { routerInfo.Status = StatusEnabled } providerName := getProviderName(routerName) if providerName == "" { log.Error().Str(logs.RouterName, routerName).Msg("UDP router name is not fully qualified") continue } serviceName := getQualifiedName(providerName, routerInfo.UDPRouter.Service) if _, ok := c.UDPServices[serviceName]; !ok { continue } c.UDPServices[serviceName].UsedBy = append(c.UDPServices[serviceName].UsedBy, routerName) } for k, serviceInfo := range c.UDPServices { // lazily initialize Status in case caller forgot to do it if serviceInfo.Status == "" { serviceInfo.Status = StatusEnabled } sort.Strings(c.UDPServices[k].UsedBy) } } func getProviderName(elementName string) string { parts := strings.Split(elementName, "@") if len(parts) > 1 { return parts[1] } return "" } func getQualifiedName(provider, elementName string) string { parts := strings.Split(elementName, "@") if len(parts) == 1 { return elementName + "@" + provider } return elementName }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/kv/kv.go
pkg/config/kv/kv.go
package kv import ( "path" "reflect" "github.com/kvtools/valkeyrie/store" "github.com/traefik/paerser/parser" ) // Decode decodes the given KV pairs into the given element. // The operation goes through three stages roughly summarized as: // KV pairs -> tree of untyped nodes // untyped nodes -> nodes augmented with metadata such as kind (inferred from element) // "typed" nodes -> typed element. func Decode(pairs []*store.KVPair, element interface{}, rootName string) error { if element == nil { return nil } filters := getRootFieldNames(rootName, element) node, err := DecodeToNode(pairs, rootName, filters...) if err != nil { return err } metaOpts := parser.MetadataOpts{TagName: "kv", AllowSliceAsStruct: false} err = parser.AddMetadata(element, node, metaOpts) if err != nil { return err } return parser.Fill(element, node, parser.FillerOpts{AllowSliceAsStruct: false}) } func getRootFieldNames(rootName string, element interface{}) []string { if element == nil { return nil } rootType := reflect.TypeOf(element) return getFieldNames(rootName, rootType) } func getFieldNames(rootName string, rootType reflect.Type) []string { var names []string if rootType.Kind() == reflect.Ptr { rootType = rootType.Elem() } if rootType.Kind() != reflect.Struct { return nil } for i := range rootType.NumField() { field := rootType.Field(i) if !parser.IsExported(field) { continue } if field.Anonymous && (field.Type.Kind() == reflect.Ptr && field.Type.Elem().Kind() == reflect.Struct || field.Type.Kind() == reflect.Struct) { names = append(names, getFieldNames(rootName, field.Type)...) continue } names = append(names, path.Join(rootName, field.Name)) } return names }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/kv/kv_node.go
pkg/config/kv/kv_node.go
package kv import ( "fmt" "regexp" "sort" "strings" "github.com/kvtools/valkeyrie/store" "github.com/traefik/paerser/parser" ) // DecodeToNode converts the labels to a tree of nodes. // If any filters are present, labels which do not match the filters are skipped. func DecodeToNode(pairs []*store.KVPair, rootName string, filters ...string) (*parser.Node, error) { sortedPairs := filterPairs(pairs, filters) exp := regexp.MustCompile(`^\d+$`) var node *parser.Node for i, pair := range sortedPairs { if !strings.HasPrefix(pair.Key, rootName+"/") { return nil, fmt.Errorf("invalid label root %s", rootName) } split := strings.FieldsFunc(pair.Key[len(rootName)+1:], func(c rune) bool { return c == '/' }) parts := []string{rootName} for _, fragment := range split { if exp.MatchString(fragment) { parts = append(parts, "["+fragment+"]") } else { parts = append(parts, fragment) } } if i == 0 { node = &parser.Node{} } decodeToNode(node, parts, string(pair.Value)) } return node, nil } func decodeToNode(root *parser.Node, path []string, value string) { if len(root.Name) == 0 { root.Name = path[0] } // it's a leaf or not -> children if len(path) > 1 { if n := containsNode(root.Children, path[1]); n != nil { // the child already exists decodeToNode(n, path[1:], value) } else { // new child child := &parser.Node{Name: path[1]} decodeToNode(child, path[1:], value) root.Children = append(root.Children, child) } } else { root.Value = value } } func containsNode(nodes []*parser.Node, name string) *parser.Node { for _, n := range nodes { if strings.EqualFold(name, n.Name) { return n } } return nil } func filterPairs(pairs []*store.KVPair, filters []string) []*store.KVPair { exp := regexp.MustCompile(`^(.+)/\d+$`) sort.Slice(pairs, func(i, j int) bool { return pairs[i].Key < pairs[j].Key }) simplePairs := map[string]*store.KVPair{} slicePairs := map[string][]string{} for _, pair := range pairs { if len(filters) == 0 { // Slice of simple type if exp.MatchString(pair.Key) { sanitizedKey := exp.FindStringSubmatch(pair.Key)[1] slicePairs[sanitizedKey] = append(slicePairs[sanitizedKey], string(pair.Value)) } else { simplePairs[pair.Key] = pair } continue } for _, filter := range filters { if len(pair.Key) >= len(filter) && strings.EqualFold(pair.Key[:len(filter)], filter) { // Slice of simple type if exp.MatchString(pair.Key) { sanitizedKey := exp.FindStringSubmatch(pair.Key)[1] slicePairs[sanitizedKey] = append(slicePairs[sanitizedKey], string(pair.Value)) } else { simplePairs[pair.Key] = pair } continue } } } var sortedPairs []*store.KVPair for k, v := range slicePairs { delete(simplePairs, k) sortedPairs = append(sortedPairs, &store.KVPair{Key: k, Value: []byte(strings.Join(v, ","))}) } for _, v := range simplePairs { sortedPairs = append(sortedPairs, v) } sort.Slice(sortedPairs, func(i, j int) bool { return sortedPairs[i].Key < sortedPairs[j].Key }) return sortedPairs }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/kv/kv_node_test.go
pkg/config/kv/kv_node_test.go
package kv import ( "encoding/json" "fmt" "testing" "github.com/kvtools/valkeyrie/store" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/paerser/parser" ) func TestDecodeToNode(t *testing.T) { type expected struct { error bool node *parser.Node } testCases := []struct { desc string in map[string]string filters []string expected expected }{ { desc: "no label", in: map[string]string{}, expected: expected{node: nil}, }, { desc: "level 1", in: map[string]string{ "traefik/foo": "bar", }, expected: expected{node: &parser.Node{ Name: "traefik", Children: []*parser.Node{ {Name: "foo", Value: "bar"}, }, }}, }, { desc: "level 1 empty value", in: map[string]string{ "traefik/foo": "", }, expected: expected{node: &parser.Node{ Name: "traefik", Children: []*parser.Node{ {Name: "foo", Value: ""}, }, }}, }, { desc: "level 2", in: map[string]string{ "traefik/foo/bar": "bar", }, expected: expected{node: &parser.Node{ Name: "traefik", Children: []*parser.Node{{ Name: "foo", Children: []*parser.Node{ {Name: "bar", Value: "bar"}, }, }}, }}, }, { desc: "several entries, level 0", in: map[string]string{ "traefik": "bar", "traefik_": "bur", }, expected: expected{error: true}, }, { desc: "several entries, prefix filter", in: map[string]string{ "traefik/foo": "bar", "traefik/fii": "bir", }, filters: []string{"traefik/Foo"}, expected: expected{node: &parser.Node{ Name: "traefik", Children: []*parser.Node{ {Name: "foo", Value: "bar"}, }, }}, }, { desc: "several entries, level 1", in: map[string]string{ "traefik/foo": "bar", "traefik/fii": "bur", }, expected: expected{node: &parser.Node{ Name: "traefik", Children: []*parser.Node{ {Name: "fii", Value: "bur"}, {Name: "foo", Value: "bar"}, }, }}, }, { desc: "several entries, level 2", in: map[string]string{ "traefik/foo/aaa": "bar", "traefik/foo/bbb": "bur", }, expected: expected{node: &parser.Node{ Name: "traefik", Children: []*parser.Node{ {Name: "foo", Children: []*parser.Node{ {Name: "aaa", Value: "bar"}, {Name: "bbb", Value: "bur"}, }}, }, }}, }, { desc: "several entries, level 2, case-insensitive", in: map[string]string{ "traefik/foo/aaa": "bar", "traefik/Foo/bbb": "bur", }, expected: expected{node: &parser.Node{ Name: "traefik", Children: []*parser.Node{ {Name: "Foo", Children: []*parser.Node{ {Name: "bbb", Value: "bur"}, {Name: "aaa", Value: "bar"}, }}, }, }}, }, { desc: "several entries, level 2, 3 children", in: map[string]string{ "traefik/foo/aaa": "bar", "traefik/foo/bbb": "bur", "traefik/foo/ccc": "bir", }, expected: expected{node: &parser.Node{ Name: "traefik", Children: []*parser.Node{ {Name: "foo", Children: []*parser.Node{ {Name: "aaa", Value: "bar"}, {Name: "bbb", Value: "bur"}, {Name: "ccc", Value: "bir"}, }}, }, }}, }, { desc: "several entries, level 3", in: map[string]string{ "traefik/foo/bar/aaa": "bar", "traefik/foo/bar/bbb": "bur", }, expected: expected{node: &parser.Node{ Name: "traefik", Children: []*parser.Node{ {Name: "foo", Children: []*parser.Node{ {Name: "bar", Children: []*parser.Node{ {Name: "aaa", Value: "bar"}, {Name: "bbb", Value: "bur"}, }}, }}, }, }}, }, { desc: "several entries, level 3, 2 children level 1", in: map[string]string{ "traefik/foo/bar/aaa": "bar", "traefik/foo/bar/bbb": "bur", "traefik/bar/foo/bbb": "bir", }, expected: expected{node: &parser.Node{ Name: "traefik", Children: []*parser.Node{ {Name: "bar", Children: []*parser.Node{ {Name: "foo", Children: []*parser.Node{ {Name: "bbb", Value: "bir"}, }}, }}, {Name: "foo", Children: []*parser.Node{ {Name: "bar", Children: []*parser.Node{ {Name: "aaa", Value: "bar"}, {Name: "bbb", Value: "bur"}, }}, }}, }, }}, }, { desc: "several entries, slice syntax", in: map[string]string{ "traefik/foo/0/aaa": "bar0", "traefik/foo/0/bbb": "bur0", "traefik/foo/1/aaa": "bar1", "traefik/foo/1/bbb": "bur1", }, expected: expected{node: &parser.Node{ Name: "traefik", Children: []*parser.Node{ {Name: "foo", Children: []*parser.Node{ {Name: "[0]", Children: []*parser.Node{ {Name: "aaa", Value: "bar0"}, {Name: "bbb", Value: "bur0"}, }}, {Name: "[1]", Children: []*parser.Node{ {Name: "aaa", Value: "bar1"}, {Name: "bbb", Value: "bur1"}, }}, }}, }, }}, }, { desc: "several entries, slice in slice of struct", in: map[string]string{ "traefik/foo/0/aaa/0": "bar0", "traefik/foo/0/aaa/1": "bar1", "traefik/foo/1/aaa/0": "bar2", "traefik/foo/1/aaa/1": "bar3", }, expected: expected{node: &parser.Node{ Name: "traefik", Children: []*parser.Node{ {Name: "foo", Children: []*parser.Node{ {Name: "[0]", Children: []*parser.Node{ {Name: "aaa", Value: "bar0,bar1"}, }}, {Name: "[1]", Children: []*parser.Node{ {Name: "aaa", Value: "bar2,bar3"}, }}, }}, }, }}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() out, err := DecodeToNode(mapToPairs(test.in), "traefik", test.filters...) if test.expected.error { require.Error(t, err) } else { require.NoError(t, err) if !assert.Equal(t, test.expected.node, out) { bytes, err := json.MarshalIndent(out, "", " ") require.NoError(t, err) fmt.Println(string(bytes)) } } }) } } func mapToPairs(in map[string]string) []*store.KVPair { var out []*store.KVPair for k, v := range in { out = append(out, &store.KVPair{Key: k, Value: []byte(v)}) } return out }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/config/kv/kv_test.go
pkg/config/kv/kv_test.go
package kv import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestDecode(t *testing.T) { testCases := []struct { desc string rootName string pairs map[string]string expected *sample }{ { desc: "simple case", rootName: "traefik", pairs: map[string]string{ "traefik/fielda": "bar", "traefik/fieldb": "1", "traefik/fieldc": "true", "traefik/fieldd/0": "one", "traefik/fieldd/1": "two", "traefik/fielde": "", "traefik/fieldf/Test1": "A", "traefik/fieldf/Test2": "B", "traefik/fieldg/0/name": "A", "traefik/fieldg/1/name": "B", "traefik/fieldh/": "foo", }, expected: &sample{ FieldA: "bar", FieldB: 1, FieldC: true, FieldD: []string{"one", "two"}, FieldE: &struct { Name string }{}, FieldF: map[string]string{ "Test1": "A", "Test2": "B", }, FieldG: []sub{ {Name: "A"}, {Name: "B"}, }, FieldH: "foo", }, }, { desc: "multi-level root name", rootName: "foo/bar/traefik", pairs: map[string]string{ "foo/bar/traefik/fielda": "bar", "foo/bar/traefik/fieldb": "2", "foo/bar/traefik/fieldc": "true", "foo/bar/traefik/fieldd/0": "one", "foo/bar/traefik/fieldd/1": "two", "foo/bar/traefik/fielde": "", "foo/bar/traefik/fieldf/Test1": "A", "foo/bar/traefik/fieldf/Test2": "B", "foo/bar/traefik/fieldg/0/name": "A", "foo/bar/traefik/fieldg/1/name": "B", "foo/bar/traefik/fieldh/": "foo", }, expected: &sample{ FieldA: "bar", FieldB: 2, FieldC: true, FieldD: []string{"one", "two"}, FieldE: &struct { Name string }{}, FieldF: map[string]string{ "Test1": "A", "Test2": "B", }, FieldG: []sub{ {Name: "A"}, {Name: "B"}, }, FieldH: "foo", }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() element := &sample{} err := Decode(mapToPairs(test.pairs), element, test.rootName) require.NoError(t, err) assert.Equal(t, test.expected, element) }) } } type sample struct { FieldA string FieldB int FieldC bool FieldD []string FieldE *struct { Name string } `kv:"allowEmpty"` FieldF map[string]string FieldG []sub FieldH string } type sub struct { Name string }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/cli/loader_env.go
pkg/cli/loader_env.go
package cli import ( "fmt" "os" "strings" "github.com/rs/zerolog/log" "github.com/traefik/paerser/cli" "github.com/traefik/paerser/env" ) // EnvLoader loads a configuration from all the environment variables prefixed with "TRAEFIK_". type EnvLoader struct{} // Load loads the command's configuration from the environment variables. func (e *EnvLoader) Load(_ []string, cmd *cli.Command) (bool, error) { vars := env.FindPrefixedEnvVars(os.Environ(), env.DefaultNamePrefix, cmd.Configuration) if len(vars) == 0 { return false, nil } if err := env.Decode(vars, env.DefaultNamePrefix, cmd.Configuration); err != nil { log.Debug().Msgf("environment variables: %s", strings.Join(vars, ", ")) return false, fmt.Errorf("failed to decode configuration from environment variables: %w", err) } log.Print("Configuration loaded from environment variables") return true, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/cli/loader_flag.go
pkg/cli/loader_flag.go
package cli import ( "fmt" "github.com/rs/zerolog/log" "github.com/traefik/paerser/cli" "github.com/traefik/paerser/flag" ) // FlagLoader loads configuration from flags. type FlagLoader struct{} // Load loads the command's configuration from flag arguments. func (*FlagLoader) Load(args []string, cmd *cli.Command) (bool, error) { if len(args) == 0 { return false, nil } if err := flag.Decode(args, cmd.Configuration); err != nil { return false, fmt.Errorf("failed to decode configuration from flags: %w", err) } log.Print("Configuration loaded from flags") return true, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/cli/deprecation.go
pkg/cli/deprecation.go
package cli import ( "errors" "fmt" "os" "reflect" "strconv" "strings" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/traefik/paerser/cli" "github.com/traefik/paerser/env" "github.com/traefik/paerser/file" "github.com/traefik/paerser/flag" "github.com/traefik/paerser/parser" ) type DeprecationLoader struct{} func (d DeprecationLoader) Load(args []string, _ *cli.Command) (bool, error) { hasIncompatibleOptions, err := logDeprecations(args) if err != nil { log.Error().Err(err).Msg("Deprecated install configuration options analysis failed") return false, nil } if hasIncompatibleOptions { return true, errors.New("incompatible deprecated install configuration option found") } return false, nil } // logDeprecations prints deprecation hints and returns whether incompatible deprecated options need to be removed. func logDeprecations(arguments []string) (bool, error) { // This part doesn't handle properly a flag defined like this: --accesslog true // where `true` could be considered as a new argument. // This is not really an issue with the deprecation loader since it will filter the unknown nodes later in this function. var args []string for _, arg := range arguments { if !strings.Contains(arg, "=") { args = append(args, arg+"=true") continue } args = append(args, arg) } // ARGS // Parse arguments to labels. argsLabels, err := flag.Parse(args, nil) if err != nil { return false, fmt.Errorf("parsing arguments to labels: %w", err) } config, err := parseDeprecatedConfig(argsLabels) if err != nil { return false, fmt.Errorf("parsing deprecated config from args: %w", err) } if config.deprecationNotice(log.With().Str("loader", "args").Logger()) { return true, nil } // FILE // Find the config file using the same logic as the normal file loader. finder := cli.Finder{ BasePaths: []string{"/etc/traefik/traefik", "$XDG_CONFIG_HOME/traefik", "$HOME/.config/traefik", "./traefik"}, Extensions: []string{"toml", "yaml", "yml"}, } configFile, ok := argsLabels["traefik.configfile"] if !ok { configFile = argsLabels["traefik.configFile"] } filePath, err := finder.Find(configFile) if err != nil { return false, fmt.Errorf("finding configuration file: %w", err) } if filePath != "" { // We don't rely on the Parser file loader here to avoid issues with unknown fields. // Parse file content into a generic map. var fileConfig map[string]interface{} if err := file.Decode(filePath, &fileConfig); err != nil { return false, fmt.Errorf("decoding configuration file %s: %w", filePath, err) } // Convert the file config to label format. fileLabels := make(map[string]string) flattenToLabels(fileConfig, "", fileLabels) config, err := parseDeprecatedConfig(fileLabels) if err != nil { return false, fmt.Errorf("parsing deprecated config from file: %w", err) } if config.deprecationNotice(log.With().Str("loader", "file").Logger()) { return true, nil } } // ENV vars := env.FindPrefixedEnvVars(os.Environ(), env.DefaultNamePrefix, &configuration{}) if len(vars) > 0 { // We don't rely on the Parser env loader here to avoid issues with unknown fields. // Decode environment variables to a generic map. var envConfig map[string]interface{} if err := env.Decode(vars, env.DefaultNamePrefix, &envConfig); err != nil { return false, fmt.Errorf("decoding environment variables: %w", err) } // Convert the env config to label format. envLabels := make(map[string]string) flattenToLabels(envConfig, "", envLabels) config, err := parseDeprecatedConfig(envLabels) if err != nil { return false, fmt.Errorf("parsing deprecated config from environment variables: %w", err) } if config.deprecationNotice(log.With().Str("loader", "env").Logger()) { return true, nil } } return false, nil } // flattenToLabels recursively flattens a nested map into label key-value pairs. // Example: {"experimental": {"http3": true}} -> {"traefik.experimental.http3": "true"}. func flattenToLabels(config interface{}, currKey string, labels map[string]string) { switch v := config.(type) { case map[string]interface{}: for key, value := range v { newKey := key if currKey != "" { newKey = currKey + "." + key } flattenToLabels(value, newKey, labels) } case []interface{}: for i, item := range v { newKey := currKey + "[" + strconv.Itoa(i) + "]" flattenToLabels(item, newKey, labels) } default: // Convert value to string and create label with traefik prefix. labels["traefik."+currKey] = fmt.Sprintf("%v", v) } } // parseDeprecatedConfig parses command-line arguments using the deprecation configuration struct, // filtering unknown nodes and checking for deprecated options. // Returns true if incompatible deprecated options are found. func parseDeprecatedConfig(labels map[string]string) (*configuration, error) { // If no config, we can return without error to allow other loaders to proceed. if len(labels) == 0 { return nil, nil } // Convert labels to node tree. node, err := parser.DecodeToNode(labels, "traefik") if err != nil { return nil, fmt.Errorf("decoding to node: %w", err) } // Filter unknown nodes and check for deprecated options. config := &configuration{} filterUnknownNodes(reflect.TypeOf(config), node) // If no config remains we can return without error, to allow other loaders to proceed. if node == nil || len(node.Children) == 0 { return nil, nil } // Telling parser to look for the label struct tag to allow empty values. err = parser.AddMetadata(config, node, parser.MetadataOpts{TagName: "label"}) if err != nil { return nil, fmt.Errorf("adding metadata to node: %w", err) } err = parser.Fill(config, node, parser.FillerOpts{}) if err != nil { return nil, fmt.Errorf("filling configuration: %w", err) } return config, nil } // filterUnknownNodes removes from the node tree all nodes that do not correspond to any field in the given type. func filterUnknownNodes(fType reflect.Type, node *parser.Node) bool { var children []*parser.Node for _, child := range node.Children { if hasKnownNodes(fType, child) { children = append(children, child) } } node.Children = children return len(node.Children) > 0 } // hasKnownNodes checks whether the given node corresponds to a known field in the given type. func hasKnownNodes(rootType reflect.Type, node *parser.Node) bool { rType := rootType if rootType.Kind() == reflect.Pointer { rType = rootType.Elem() } // unstructured type fitting anything, considering the current node as known. if rType.Kind() == reflect.Map && rType.Elem().Kind() == reflect.Interface { return true } // unstructured type fitting anything, considering the current node as known. if rType.Kind() == reflect.Interface { return true } // find matching field in struct type. field, b := findTypedField(rType, node) if !b { return b } if len(node.Children) > 0 { return filterUnknownNodes(field.Type, node) } return true } func findTypedField(rType reflect.Type, node *parser.Node) (reflect.StructField, bool) { // avoid panicking. if rType.Kind() != reflect.Struct { return reflect.StructField{}, false } for i := range rType.NumField() { cField := rType.Field(i) // ignore unexported fields. if cField.PkgPath == "" { if strings.EqualFold(cField.Name, node.Name) { node.FieldName = cField.Name return cField, true } } } return reflect.StructField{}, false } // configuration holds the install configuration removed/deprecated options. type configuration struct { Core *core `json:"core,omitempty" toml:"core,omitempty" yaml:"core,omitempty" label:"allowEmpty" file:"allowEmpty"` Experimental *experimental `json:"experimental,omitempty" toml:"experimental,omitempty" yaml:"experimental,omitempty" label:"allowEmpty" file:"allowEmpty"` Pilot map[string]any `json:"pilot,omitempty" toml:"pilot,omitempty" yaml:"pilot,omitempty" label:"allowEmpty" file:"allowEmpty"` Providers *providers `json:"providers,omitempty" toml:"providers,omitempty" yaml:"providers,omitempty" label:"allowEmpty" file:"allowEmpty"` Tracing *tracing `json:"tracing,omitempty" toml:"tracing,omitempty" yaml:"tracing,omitempty" label:"allowEmpty" file:"allowEmpty"` } func (c *configuration) deprecationNotice(logger zerolog.Logger) bool { if c == nil { return false } var incompatible bool if c.Pilot != nil { incompatible = true logger.Error().Msg("Pilot configuration has been removed in v3, please remove all Pilot-related install configuration for Traefik to start." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#pilot") } incompatibleCore := c.Core.deprecationNotice(logger) incompatibleExperimental := c.Experimental.deprecationNotice(logger) incompatibleProviders := c.Providers.deprecationNotice(logger) incompatibleTracing := c.Tracing.deprecationNotice(logger) return incompatible || incompatibleCore || incompatibleExperimental || incompatibleProviders || incompatibleTracing } type core struct { DefaultRuleSyntax string `json:"defaultRuleSyntax,omitempty" toml:"defaultRuleSyntax,omitempty" yaml:"defaultRuleSyntax,omitempty" label:"allowEmpty" file:"allowEmpty"` } func (c *core) deprecationNotice(logger zerolog.Logger) bool { if c != nil && c.DefaultRuleSyntax != "" { logger.Error().Msg("`Core.DefaultRuleSyntax` option has been deprecated in v3.4, and will be removed in the next major version." + " Please consider migrating all router rules to v3 syntax." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v3/#rule-syntax") } return false } type providers struct { Docker *docker `json:"docker,omitempty" toml:"docker,omitempty" yaml:"docker,omitempty" label:"allowEmpty" file:"allowEmpty"` Swarm *swarm `json:"swarm,omitempty" toml:"swarm,omitempty" yaml:"swarm,omitempty" label:"allowEmpty" file:"allowEmpty"` Consul *consul `json:"consul,omitempty" toml:"consul,omitempty" yaml:"consul,omitempty" label:"allowEmpty" file:"allowEmpty"` ConsulCatalog *consulCatalog `json:"consulCatalog,omitempty" toml:"consulCatalog,omitempty" yaml:"consulCatalog,omitempty" label:"allowEmpty" file:"allowEmpty"` Nomad *nomad `json:"nomad,omitempty" toml:"nomad,omitempty" yaml:"nomad,omitempty" label:"allowEmpty" file:"allowEmpty"` Marathon map[string]any `json:"marathon,omitempty" toml:"marathon,omitempty" yaml:"marathon,omitempty" label:"allowEmpty" file:"allowEmpty"` Rancher map[string]any `json:"rancher,omitempty" toml:"rancher,omitempty" yaml:"rancher,omitempty" label:"allowEmpty" file:"allowEmpty"` ETCD *etcd `json:"etcd,omitempty" toml:"etcd,omitempty" yaml:"etcd,omitempty" label:"allowEmpty" file:"allowEmpty"` Redis *redis `json:"redis,omitempty" toml:"redis,omitempty" yaml:"redis,omitempty" label:"allowEmpty" file:"allowEmpty"` HTTP *http `json:"http,omitempty" toml:"http,omitempty" yaml:"http,omitempty" label:"allowEmpty" file:"allowEmpty"` KubernetesIngress *ingress `json:"kubernetesIngress,omitempty" toml:"kubernetesIngress,omitempty" yaml:"kubernetesIngress,omitempty" label:"allowEmpty" file:"allowEmpty"` } func (p *providers) deprecationNotice(logger zerolog.Logger) bool { if p == nil { return false } var incompatible bool if p.Marathon != nil { incompatible = true logger.Error().Msg("Marathon provider has been removed in v3, please remove all Marathon-related install configuration for Traefik to start." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#marathon-provider") } if p.Rancher != nil { incompatible = true logger.Error().Msg("Rancher provider has been removed in v3, please remove all Rancher-related install configuration for Traefik to start." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#rancher-v1-provider") } dockerIncompatible := p.Docker.deprecationNotice(logger) consulIncompatible := p.Consul.deprecationNotice(logger) consulCatalogIncompatible := p.ConsulCatalog.deprecationNotice(logger) nomadIncompatible := p.Nomad.deprecationNotice(logger) swarmIncompatible := p.Swarm.deprecationNotice(logger) etcdIncompatible := p.ETCD.deprecationNotice(logger) redisIncompatible := p.Redis.deprecationNotice(logger) httpIncompatible := p.HTTP.deprecationNotice(logger) p.KubernetesIngress.deprecationNotice(logger) return incompatible || dockerIncompatible || consulIncompatible || consulCatalogIncompatible || nomadIncompatible || swarmIncompatible || etcdIncompatible || redisIncompatible || httpIncompatible } type tls struct { CAOptional *bool `json:"caOptional,omitempty" toml:"caOptional,omitempty" yaml:"caOptional,omitempty"` } type docker struct { SwarmMode *bool `json:"swarmMode,omitempty" toml:"swarmMode,omitempty" yaml:"swarmMode,omitempty"` TLS *tls `json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" label:"allowEmpty" file:"allowEmpty"` } func (d *docker) deprecationNotice(logger zerolog.Logger) bool { if d == nil { return false } var incompatible bool if d.SwarmMode != nil { incompatible = true logger.Error().Msg("Docker provider `swarmMode` option has been removed in v3, please use the Swarm Provider instead." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#docker-docker-swarm") } if d.TLS != nil && d.TLS.CAOptional != nil { incompatible = true logger.Error().Msg("Docker provider `tls.CAOptional` option has been removed in v3, as TLS client authentication is a server side option (see https://github.com/golang/go/blob/740a490f71d026bb7d2d13cb8fa2d6d6e0572b70/src/crypto/tls/common.go#L634)." + " Please remove all occurrences from the install configuration for Traefik to start." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#tlscaoptional") } return incompatible } type swarm struct { TLS *tls `json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" label:"allowEmpty" file:"allowEmpty"` } func (s *swarm) deprecationNotice(logger zerolog.Logger) bool { if s == nil { return false } var incompatible bool if s.TLS != nil && s.TLS.CAOptional != nil { incompatible = true logger.Error().Msg("Swarm provider `tls.CAOptional` option does not exist, as TLS client authentication is a server side option (see https://github.com/golang/go/blob/740a490f71d026bb7d2d13cb8fa2d6d6e0572b70/src/crypto/tls/common.go#L634)." + " Please remove all occurrences from the install configuration for Traefik to start.") } return incompatible } type etcd struct { TLS *tls `json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" label:"allowEmpty" file:"allowEmpty"` } func (e *etcd) deprecationNotice(logger zerolog.Logger) bool { if e == nil { return false } var incompatible bool if e.TLS != nil && e.TLS.CAOptional != nil { incompatible = true logger.Error().Msg("ETCD provider `tls.CAOptional` option has been removed in v3, as TLS client authentication is a server side option (see https://github.com/golang/go/blob/740a490f71d026bb7d2d13cb8fa2d6d6e0572b70/src/crypto/tls/common.go#L634)." + " Please remove all occurrences from the install configuration for Traefik to start." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#tlscaoptional_3") } return incompatible } type redis struct { TLS *tls `json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" label:"allowEmpty" file:"allowEmpty"` } func (r *redis) deprecationNotice(logger zerolog.Logger) bool { if r == nil { return false } var incompatible bool if r.TLS != nil && r.TLS.CAOptional != nil { incompatible = true logger.Error().Msg("Redis provider `tls.CAOptional` option has been removed in v3, as TLS client authentication is a server side option (see https://github.com/golang/go/blob/740a490f71d026bb7d2d13cb8fa2d6d6e0572b70/src/crypto/tls/common.go#L634)." + " Please remove all occurrences from the install configuration for Traefik to start." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#tlscaoptional_4") } return incompatible } type consul struct { Namespace *string `json:"namespace,omitempty" toml:"namespace,omitempty" yaml:"namespace,omitempty"` TLS *tls `json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" label:"allowEmpty" file:"allowEmpty"` } func (c *consul) deprecationNotice(logger zerolog.Logger) bool { if c == nil { return false } var incompatible bool if c.Namespace != nil { incompatible = true logger.Error().Msg("Consul provider `namespace` option has been removed, please use the `namespaces` option instead." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#consul-provider") } if c.TLS != nil && c.TLS.CAOptional != nil { incompatible = true logger.Error().Msg("Consul provider `tls.CAOptional` option has been removed in v3, as TLS client authentication is a server side option (see https://github.com/golang/go/blob/740a490f71d026bb7d2d13cb8fa2d6d6e0572b70/src/crypto/tls/common.go#L634)." + " Please remove all occurrences from the install configuration for Traefik to start." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#tlscaoptional_1") } return incompatible } type consulCatalog struct { Namespace *string `json:"namespace,omitempty" toml:"namespace,omitempty" yaml:"namespace,omitempty"` Endpoint *endpointConfig `json:"endpoint,omitempty" toml:"endpoint,omitempty" yaml:"endpoint,omitempty" label:"allowEmpty" file:"allowEmpty"` } type endpointConfig struct { TLS *tls `json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty"` } func (c *consulCatalog) deprecationNotice(logger zerolog.Logger) bool { if c == nil { return false } var incompatible bool if c.Namespace != nil { incompatible = true logger.Error().Msg("ConsulCatalog provider `namespace` option has been removed, please use the `namespaces` option instead." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#consulcatalog-provider") } if c.Endpoint != nil && c.Endpoint.TLS != nil && c.Endpoint.TLS.CAOptional != nil { incompatible = true logger.Error().Msg("ConsulCatalog provider `tls.CAOptional` option has been removed in v3, as TLS client authentication is a server side option (see https://github.com/golang/go/blob/740a490f71d026bb7d2d13cb8fa2d6d6e0572b70/src/crypto/tls/common.go#L634)." + " Please remove all occurrences from the install configuration for Traefik to start." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#endpointtlscaoptional") } return incompatible } type nomad struct { Namespace *string `json:"namespace,omitempty" toml:"namespace,omitempty" yaml:"namespace,omitempty"` Endpoint *endpointConfig `json:"endpoint,omitempty" toml:"endpoint,omitempty" yaml:"endpoint,omitempty" label:"allowEmpty" file:"allowEmpty"` } func (n *nomad) deprecationNotice(logger zerolog.Logger) bool { if n == nil { return false } var incompatible bool if n.Namespace != nil { incompatible = true logger.Error().Msg("Nomad provider `namespace` option has been removed, please use the `namespaces` option instead." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#nomad-provider") } if n.Endpoint != nil && n.Endpoint.TLS != nil && n.Endpoint.TLS.CAOptional != nil { incompatible = true logger.Error().Msg("Nomad provider `tls.CAOptional` option has been removed in v3, as TLS client authentication is a server side option (see https://github.com/golang/go/blob/740a490f71d026bb7d2d13cb8fa2d6d6e0572b70/src/crypto/tls/common.go#L634)." + " Please remove all occurrences from the install configuration for Traefik to start." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#endpointtlscaoptional_1") } return incompatible } type http struct { TLS *tls `json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" label:"allowEmpty" file:"allowEmpty"` } func (h *http) deprecationNotice(logger zerolog.Logger) bool { if h == nil { return false } var incompatible bool if h.TLS != nil && h.TLS.CAOptional != nil { incompatible = true logger.Error().Msg("HTTP provider `tls.CAOptional` option has been removed in v3, as TLS client authentication is a server side option (see https://github.com/golang/go/blob/740a490f71d026bb7d2d13cb8fa2d6d6e0572b70/src/crypto/tls/common.go#L634)." + " Please remove all occurrences from the install configuration for Traefik to start." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#tlscaoptional_2") } return incompatible } type ingress struct { DisableIngressClassLookup *bool `json:"disableIngressClassLookup,omitempty" toml:"disableIngressClassLookup,omitempty" yaml:"disableIngressClassLookup,omitempty"` } func (i *ingress) deprecationNotice(logger zerolog.Logger) { if i == nil { return } if i.DisableIngressClassLookup != nil { logger.Error().Msg("Kubernetes Ingress provider `disableIngressClassLookup` option has been deprecated in v3.1, and will be removed in the next major version." + " Please use the `disableClusterScopeResources` option instead." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v3/#ingressclasslookup") } } type experimental struct { HTTP3 *bool `json:"http3,omitempty" toml:"http3,omitempty" yaml:"http3,omitempty"` KubernetesGateway *bool `json:"kubernetesGateway,omitempty" toml:"kubernetesGateway,omitempty" yaml:"kubernetesGateway,omitempty"` KubernetesIngressNGINX *bool `json:"kubernetesIngressNGINX,omitempty" toml:"kubernetesIngressNGINX,omitempty" yaml:"kubernetesIngressNGINX,omitempty"` } func (e *experimental) deprecationNotice(logger zerolog.Logger) bool { if e == nil { return false } if e.HTTP3 != nil { logger.Error().Msg("HTTP3 is not an experimental feature in v3 and the associated enablement has been removed." + " Please remove its usage from the install configuration for Traefik to start." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3-details/#http3") return true } if e.KubernetesGateway != nil { logger.Error().Msg("KubernetesGateway provider is not an experimental feature starting with v3.1." + " Please remove its usage from the install configuration." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v3/#gateway-api-kubernetesgateway-provider") } if e.KubernetesIngressNGINX != nil { logger.Error().Msg("KubernetesIngressNGINX provider is not an experimental feature starting with v3.6.2." + " Please remove its usage from the install configuration." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v3/#ingress-nginx-provider") } return false } // type tracing struct { SpanNameLimit *int `json:"spanNameLimit,omitempty" toml:"spanNameLimit,omitempty" yaml:"spanNameLimit,omitempty"` GlobalAttributes map[string]string `json:"globalAttributes,omitempty" toml:"globalAttributes,omitempty" yaml:"globalAttributes,omitempty" export:"true"` Jaeger map[string]any `json:"jaeger,omitempty" toml:"jaeger,omitempty" yaml:"jaeger,omitempty" label:"allowEmpty" file:"allowEmpty"` Zipkin map[string]any `json:"zipkin,omitempty" toml:"zipkin,omitempty" yaml:"zipkin,omitempty" label:"allowEmpty" file:"allowEmpty"` Datadog map[string]any `json:"datadog,omitempty" toml:"datadog,omitempty" yaml:"datadog,omitempty" label:"allowEmpty" file:"allowEmpty"` Instana map[string]any `json:"instana,omitempty" toml:"instana,omitempty" yaml:"instana,omitempty" label:"allowEmpty" file:"allowEmpty"` Haystack map[string]any `json:"haystack,omitempty" toml:"haystack,omitempty" yaml:"haystack,omitempty" label:"allowEmpty" file:"allowEmpty"` Elastic map[string]any `json:"elastic,omitempty" toml:"elastic,omitempty" yaml:"elastic,omitempty" label:"allowEmpty" file:"allowEmpty"` } func (t *tracing) deprecationNotice(logger zerolog.Logger) bool { if t == nil { return false } var incompatible bool if t.SpanNameLimit != nil { incompatible = true logger.Error().Msg("SpanNameLimit option for Tracing has been removed in v3, as Span names are now of a fixed length." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#tracing") } if t.GlobalAttributes != nil { log.Warn().Msgf("tracing.globalAttributes option is now deprecated, please use tracing.resourceAttributes instead.") logger.Error().Msg("`tracing.globalAttributes` option has been deprecated in v3.3, and will be removed in the next major version." + " Please use the `tracing.resourceAttributes` option instead." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v3/#tracing-global-attributes") } if t.Jaeger != nil { incompatible = true logger.Error().Msg("Jaeger Tracing backend has been removed in v3, please remove all Jaeger-related Tracing install configuration for Traefik to start." + " In v3, Open Telemetry replaces specific tracing backend implementations, and an collector/exporter can be used to export metrics in a vendor specific format." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#tracing") } if t.Zipkin != nil { incompatible = true logger.Error().Msg("Zipkin Tracing backend has been removed in v3, please remove all Zipkin-related Tracing install configuration for Traefik to start." + " In v3, Open Telemetry replaces specific tracing backend implementations, and an collector/exporter can be used to export metrics in a vendor specific format." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#tracing") } if t.Datadog != nil { incompatible = true logger.Error().Msg("Datadog Tracing backend has been removed in v3, please remove all Datadog-related Tracing install configuration for Traefik to start." + " In v3, Open Telemetry replaces specific tracing backend implementations, and an collector/exporter can be used to export metrics in a vendor specific format." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#tracing") } if t.Instana != nil { incompatible = true logger.Error().Msg("Instana Tracing backend has been removed in v3, please remove all Instana-related Tracing install configuration for Traefik to start." + " In v3, Open Telemetry replaces specific tracing backend implementations, and an collector/exporter can be used to export metrics in a vendor specific format." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#tracing") } if t.Haystack != nil { incompatible = true logger.Error().Msg("Haystack Tracing backend has been removed in v3, please remove all Haystack-related Tracing install configuration for Traefik to start." + " In v3, Open Telemetry replaces specific tracing backend implementations, and an collector/exporter can be used to export metrics in a vendor specific format." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#tracing") } if t.Elastic != nil { incompatible = true logger.Error().Msg("Elastic Tracing backend has been removed in v3, please remove all Elastic-related Tracing install configuration for Traefik to start." + " In v3, Open Telemetry replaces specific tracing backend implementations, and an collector/exporter can be used to export metrics in a vendor specific format." + " For more information please read the migration guide: https://doc.traefik.io/traefik/v3.6/migration/v2-to-v3/#tracing") } return incompatible }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/cli/deprecation_test.go
pkg/cli/deprecation_test.go
package cli import ( "testing" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/paerser/cli" "github.com/traefik/traefik/v3/cmd" ) func ptr[T any](t T) *T { return &t } func TestDeprecationNotice(t *testing.T) { tests := []struct { desc string config configuration wantCompatible bool }{ { desc: "Docker provider swarmMode option is incompatible", config: configuration{ Providers: &providers{ Docker: &docker{ SwarmMode: ptr(true), }, }, }, }, { desc: "Docker provider tls.CAOptional option is incompatible", config: configuration{ Providers: &providers{ Docker: &docker{ TLS: &tls{ CAOptional: ptr(true), }, }, }, }, }, { desc: "Swarm provider tls.CAOptional option is incompatible", config: configuration{ Providers: &providers{ Swarm: &swarm{ TLS: &tls{ CAOptional: ptr(true), }, }, }, }, }, { desc: "Consul provider namespace option is incompatible", config: configuration{ Providers: &providers{ Consul: &consul{ Namespace: ptr("foobar"), }, }, }, }, { desc: "Consul provider tls.CAOptional option is incompatible", config: configuration{ Providers: &providers{ Consul: &consul{ TLS: &tls{ CAOptional: ptr(true), }, }, }, }, }, { desc: "ConsulCatalog provider namespace option is incompatible", config: configuration{ Providers: &providers{ ConsulCatalog: &consulCatalog{ Namespace: ptr("foobar"), }, }, }, }, { desc: "ConsulCatalog provider tls.CAOptional option is incompatible", config: configuration{ Providers: &providers{ ConsulCatalog: &consulCatalog{ Endpoint: &endpointConfig{ TLS: &tls{ CAOptional: ptr(true), }, }, }, }, }, }, { desc: "Nomad provider namespace option is incompatible", config: configuration{ Providers: &providers{ Nomad: &nomad{ Namespace: ptr("foobar"), }, }, }, }, { desc: "Nomad provider tls.CAOptional option is incompatible", config: configuration{ Providers: &providers{ Nomad: &nomad{ Endpoint: &endpointConfig{ TLS: &tls{ CAOptional: ptr(true), }, }, }, }, }, }, { desc: "Marathon configuration is incompatible", config: configuration{ Providers: &providers{ Marathon: map[string]any{ "foo": "bar", }, }, }, }, { desc: "Rancher configuration is incompatible", config: configuration{ Providers: &providers{ Rancher: map[string]any{ "foo": "bar", }, }, }, }, { desc: "ETCD provider tls.CAOptional option is incompatible", config: configuration{ Providers: &providers{ ETCD: &etcd{ TLS: &tls{ CAOptional: ptr(true), }, }, }, }, }, { desc: "Redis provider tls.CAOptional option is incompatible", config: configuration{ Providers: &providers{ Redis: &redis{ TLS: &tls{ CAOptional: ptr(true), }, }, }, }, }, { desc: "HTTP provider tls.CAOptional option is incompatible", config: configuration{ Providers: &providers{ HTTP: &http{ TLS: &tls{ CAOptional: ptr(true), }, }, }, }, }, { desc: "Pilot configuration is incompatible", config: configuration{ Pilot: map[string]any{ "foo": "bar", }, }, }, { desc: "Experimental HTTP3 enablement configuration is incompatible", config: configuration{ Experimental: &experimental{ HTTP3: ptr(true), }, }, }, { desc: "Experimental KubernetesGateway enablement configuration is compatible", config: configuration{ Experimental: &experimental{ KubernetesGateway: ptr(true), }, }, wantCompatible: true, }, { desc: "Tracing SpanNameLimit option is incompatible", config: configuration{ Tracing: &tracing{ SpanNameLimit: ptr(42), }, }, }, { desc: "Tracing Jaeger configuration is incompatible", config: configuration{ Tracing: &tracing{ Jaeger: map[string]any{ "foo": "bar", }, }, }, }, { desc: "Tracing Zipkin configuration is incompatible", config: configuration{ Tracing: &tracing{ Zipkin: map[string]any{ "foo": "bar", }, }, }, }, { desc: "Tracing Datadog configuration is incompatible", config: configuration{ Tracing: &tracing{ Datadog: map[string]any{ "foo": "bar", }, }, }, }, { desc: "Tracing Instana configuration is incompatible", config: configuration{ Tracing: &tracing{ Instana: map[string]any{ "foo": "bar", }, }, }, }, { desc: "Tracing Haystack configuration is incompatible", config: configuration{ Tracing: &tracing{ Haystack: map[string]any{ "foo": "bar", }, }, }, }, { desc: "Tracing Elastic configuration is incompatible", config: configuration{ Tracing: &tracing{ Elastic: map[string]any{ "foo": "bar", }, }, }, }, { desc: "Core DefaultRuleSyntax configuration is compatible", config: configuration{ Core: &core{ DefaultRuleSyntax: "foobar", }, }, wantCompatible: true, }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { t.Parallel() var gotLog bool var gotLevel zerolog.Level testHook := zerolog.HookFunc(func(e *zerolog.Event, level zerolog.Level, message string) { gotLog = true gotLevel = level }) logger := log.With().Logger().Hook(testHook) assert.Equal(t, !test.wantCompatible, test.config.deprecationNotice(logger)) assert.True(t, gotLog) assert.Equal(t, zerolog.ErrorLevel, gotLevel) }) } } func TestLoad(t *testing.T) { testCases := []struct { desc string args []string env map[string]string wantDeprecated bool }{ { desc: "Empty", args: []string{}, wantDeprecated: false, }, { desc: "[FLAG] providers.marathon is deprecated", args: []string{ "--access-log", "--log.level=DEBUG", "--entrypoints.test.http.tls", "--providers.nomad.endpoint.tls.insecureskipverify=true", "--providers.marathon", }, wantDeprecated: true, }, { desc: "[FLAG] multiple deprecated", args: []string{ "--access-log", "--log.level=DEBUG", "--entrypoints.test.http.tls", "--providers.marathon", "--pilot.token=XXX", }, wantDeprecated: true, }, { desc: "[FLAG] no deprecated", args: []string{ "--access-log", "--log.level=DEBUG", "--entrypoints.test.http.tls", "--providers.docker", }, wantDeprecated: false, }, { desc: "[ENV] providers.marathon is deprecated", env: map[string]string{ "TRAEFIK_ACCESS_LOG": "", "TRAEFIK_LOG_LEVEL": "DEBUG", "TRAEFIK_ENTRYPOINT_TEST_HTTP_TLS": "true", "TRAEFIK_PROVIDERS_MARATHON": "true", }, wantDeprecated: true, }, { desc: "[ENV] multiple deprecated", env: map[string]string{ "TRAEFIK_ACCESS_LOG": "true", "TRAEFIK_LOG_LEVEL": "DEBUG", "TRAEFIK_ENTRYPOINT_TEST_HTTP_TLS": "true", "TRAEFIK_PROVIDERS_MARATHON": "true", "TRAEFIK_PILOT_TOKEN": "xxx", }, wantDeprecated: true, }, { desc: "[ENV] no deprecated", env: map[string]string{ "TRAEFIK_ACCESS_LOG": "true", "TRAEFIK_LOG_LEVEL": "DEBUG", "TRAEFIK_ENTRYPOINT_TEST_HTTP_TLS": "true", }, wantDeprecated: false, }, { desc: "[FILE] providers.marathon is deprecated", args: []string{ "--configfile=./fixtures/traefik_deprecated.toml", }, wantDeprecated: true, }, { desc: "[FILE] multiple deprecated", args: []string{ "--configfile=./fixtures/traefik_multiple_deprecated.toml", }, wantDeprecated: true, }, { desc: "[FILE] no deprecated", args: []string{ "--configfile=./fixtures/traefik_no_deprecated.toml", }, wantDeprecated: false, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { tconfig := cmd.NewTraefikConfiguration() c := &cli.Command{Configuration: tconfig} l := DeprecationLoader{} for name, val := range test.env { t.Setenv(name, val) } deprecated, err := l.Load(test.args, c) assert.Equal(t, test.wantDeprecated, deprecated) if !test.wantDeprecated { require.NoError(t, err) } }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/cli/loader_file.go
pkg/cli/loader_file.go
package cli import ( "os" "strings" "github.com/rs/zerolog/log" "github.com/traefik/paerser/cli" "github.com/traefik/paerser/file" "github.com/traefik/paerser/flag" ) // FileLoader loads a configuration from a file. type FileLoader struct { ConfigFileFlag string filename string } // GetFilename returns the configuration file if any. func (f *FileLoader) GetFilename() string { return f.filename } // Load loads the command's configuration from a file either specified with the -traefik.configfile flag, or from default locations. func (f *FileLoader) Load(args []string, cmd *cli.Command) (bool, error) { ref, err := flag.Parse(args, cmd.Configuration) if err != nil { _ = cmd.PrintHelp(os.Stdout) return false, err } configFileFlag := "traefik.configfile" if _, ok := ref["traefik.configFile"]; ok { configFileFlag = "traefik.configFile" } if f.ConfigFileFlag != "" { configFileFlag = "traefik." + f.ConfigFileFlag if _, ok := ref[strings.ToLower(configFileFlag)]; ok { configFileFlag = "traefik." + strings.ToLower(f.ConfigFileFlag) } } configFile, err := loadConfigFiles(ref[configFileFlag], cmd.Configuration) if err != nil { return false, err } f.filename = configFile if configFile == "" { return false, nil } log.Printf("Configuration loaded from file: %s", configFile) content, _ := os.ReadFile(configFile) log.Debug().Str("configFile", configFile).Bytes("content", content).Send() return true, nil } // loadConfigFiles tries to decode the given configuration file and all default locations for the configuration file. // It stops as soon as decoding one of them is successful. func loadConfigFiles(configFile string, element interface{}) (string, error) { finder := cli.Finder{ BasePaths: []string{"/etc/traefik/traefik", "$XDG_CONFIG_HOME/traefik", "$HOME/.config/traefik", "./traefik"}, Extensions: []string{"toml", "yaml", "yml"}, } filePath, err := finder.Find(configFile) if err != nil { return "", err } if len(filePath) == 0 { return "", nil } if err := file.Decode(filePath, element); err != nil { return "", err } return filePath, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/job/job_test.go
pkg/job/job_test.go
package job import ( "testing" "time" "github.com/cenkalti/backoff/v4" ) func TestJobBackOff(t *testing.T) { var ( testInitialInterval = 500 * time.Millisecond testRandomizationFactor = 0.1 testMultiplier = 2.0 testMaxInterval = 5 * time.Second testMinJobInterval = 1 * time.Second ) exp := NewBackOff(backoff.NewExponentialBackOff()) exp.InitialInterval = testInitialInterval exp.RandomizationFactor = testRandomizationFactor exp.Multiplier = testMultiplier exp.MaxInterval = testMaxInterval exp.MinJobInterval = testMinJobInterval exp.Reset() expectedResults := []time.Duration{ 500 * time.Millisecond, 500 * time.Millisecond, 500 * time.Millisecond, 1 * time.Second, 2 * time.Second, 4 * time.Second, 5 * time.Second, 5 * time.Second, 500 * time.Millisecond, 1 * time.Second, 2 * time.Second, 4 * time.Second, 5 * time.Second, 5 * time.Second, } for i, expected := range expectedResults { // Assert that the next backoff falls in the expected range. minInterval := expected - time.Duration(testRandomizationFactor*float64(expected)) maxInterval := expected + time.Duration(testRandomizationFactor*float64(expected)) if i < 3 || i == 8 { time.Sleep(2 * time.Second) } actualInterval := exp.NextBackOff() if !(minInterval <= actualInterval && actualInterval <= maxInterval) { t.Error("error") } } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/job/job.go
pkg/job/job.go
package job import ( "time" "github.com/cenkalti/backoff/v4" ) var _ backoff.BackOff = (*BackOff)(nil) const ( defaultMinJobInterval = 30 * time.Second ) // BackOff is an exponential backoff implementation for long running jobs. // In long running jobs, an operation() that fails after a long Duration should not increments the backoff period. // If operation() takes more than MinJobInterval, Reset() is called in NextBackOff(). type BackOff struct { *backoff.ExponentialBackOff MinJobInterval time.Duration } // NewBackOff creates an instance of BackOff using default values. func NewBackOff(backOff *backoff.ExponentialBackOff) *BackOff { backOff.MaxElapsedTime = 0 return &BackOff{ ExponentialBackOff: backOff, MinJobInterval: defaultMinJobInterval, } } // NextBackOff calculates the next backoff interval. func (b *BackOff) NextBackOff() time.Duration { if b.GetElapsedTime() >= b.MinJobInterval { b.Reset() } return b.ExponentialBackOff.NextBackOff() }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/cmd/configuration.go
cmd/configuration.go
package cmd import ( "time" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/static" ) // TraefikCmdConfiguration wraps the static configuration and extra parameters. type TraefikCmdConfiguration struct { static.Configuration `export:"true"` // ConfigFile is the path to the configuration file. ConfigFile string `description:"Configuration file to use. If specified all other flags are ignored." export:"true"` } // NewTraefikConfiguration creates a TraefikCmdConfiguration with default values. func NewTraefikConfiguration() *TraefikCmdConfiguration { return &TraefikCmdConfiguration{ Configuration: static.Configuration{ Global: &static.Global{ CheckNewVersion: true, }, EntryPoints: make(static.EntryPoints), Providers: &static.Providers{ ProvidersThrottleDuration: ptypes.Duration(2 * time.Second), }, ServersTransport: &static.ServersTransport{ MaxIdleConnsPerHost: 200, }, TCPServersTransport: &static.TCPServersTransport{ DialTimeout: ptypes.Duration(30 * time.Second), DialKeepAlive: ptypes.Duration(15 * time.Second), }, }, ConfigFile: "", } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/cmd/traefik/plugins.go
cmd/traefik/plugins.go
package main import ( "fmt" "net/http" "path/filepath" "time" "github.com/hashicorp/go-retryablehttp" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/plugins" ) const outputDir = "./plugins-storage/" func createPluginBuilder(staticConfiguration *static.Configuration) (*plugins.Builder, error) { manager, plgs, localPlgs, err := initPlugins(staticConfiguration) if err != nil { return nil, err } return plugins.NewBuilder(manager, plgs, localPlgs) } func initPlugins(staticCfg *static.Configuration) (*plugins.Manager, map[string]plugins.Descriptor, map[string]plugins.LocalDescriptor, error) { err := checkUniquePluginNames(staticCfg.Experimental) if err != nil { return nil, nil, nil, err } var manager *plugins.Manager plgs := map[string]plugins.Descriptor{} if hasPlugins(staticCfg) { httpClient := retryablehttp.NewClient() httpClient.Logger = logs.NewRetryableHTTPLogger(log.Logger) httpClient.HTTPClient = &http.Client{Timeout: 10 * time.Second} httpClient.RetryMax = 3 // Create separate downloader for HTTP operations archivesPath := filepath.Join(outputDir, "archives") downloader, err := plugins.NewRegistryDownloader(plugins.RegistryDownloaderOptions{ HTTPClient: httpClient.HTTPClient, ArchivesPath: archivesPath, }) if err != nil { return nil, nil, nil, fmt.Errorf("unable to create plugin downloader: %w", err) } opts := plugins.ManagerOptions{ Output: outputDir, } manager, err = plugins.NewManager(downloader, opts) if err != nil { return nil, nil, nil, fmt.Errorf("unable to create plugins manager: %w", err) } err = plugins.SetupRemotePlugins(manager, staticCfg.Experimental.Plugins) if err != nil { return nil, nil, nil, fmt.Errorf("unable to set up plugins environment: %w", err) } plgs = staticCfg.Experimental.Plugins } localPlgs := map[string]plugins.LocalDescriptor{} if hasLocalPlugins(staticCfg) { err := plugins.SetupLocalPlugins(staticCfg.Experimental.LocalPlugins) if err != nil { return nil, nil, nil, err } localPlgs = staticCfg.Experimental.LocalPlugins } return manager, plgs, localPlgs, nil } func checkUniquePluginNames(e *static.Experimental) error { if e == nil { return nil } for s := range e.LocalPlugins { if _, ok := e.Plugins[s]; ok { return fmt.Errorf("the plugin's name %q must be unique", s) } } return nil } func hasPlugins(staticCfg *static.Configuration) bool { return staticCfg.Experimental != nil && len(staticCfg.Experimental.Plugins) > 0 } func hasLocalPlugins(staticCfg *static.Configuration) bool { return staticCfg.Experimental != nil && len(staticCfg.Experimental.LocalPlugins) > 0 }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/cmd/traefik/traefik.go
cmd/traefik/traefik.go
package main import ( "context" "crypto/x509" "fmt" "io" stdlog "log" "maps" "net/http" "os" "os/signal" "slices" "strings" "syscall" "time" "github.com/coreos/go-systemd/v22/daemon" "github.com/go-acme/lego/v4/challenge" gokitmetrics "github.com/go-kit/kit/metrics" "github.com/rs/zerolog/log" "github.com/sirupsen/logrus" "github.com/spiffe/go-spiffe/v2/workloadapi" "github.com/traefik/paerser/cli" "github.com/traefik/traefik/v3/cmd" "github.com/traefik/traefik/v3/cmd/healthcheck" cmdVersion "github.com/traefik/traefik/v3/cmd/version" tcli "github.com/traefik/traefik/v3/pkg/cli" "github.com/traefik/traefik/v3/pkg/collector" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/middlewares/accesslog" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/observability/metrics" "github.com/traefik/traefik/v3/pkg/observability/tracing" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "github.com/traefik/traefik/v3/pkg/provider/acme" "github.com/traefik/traefik/v3/pkg/provider/aggregator" "github.com/traefik/traefik/v3/pkg/provider/tailscale" "github.com/traefik/traefik/v3/pkg/provider/traefik" "github.com/traefik/traefik/v3/pkg/proxy" "github.com/traefik/traefik/v3/pkg/proxy/httputil" "github.com/traefik/traefik/v3/pkg/redactor" "github.com/traefik/traefik/v3/pkg/safe" "github.com/traefik/traefik/v3/pkg/server" "github.com/traefik/traefik/v3/pkg/server/middleware" "github.com/traefik/traefik/v3/pkg/server/service" "github.com/traefik/traefik/v3/pkg/tcp" traefiktls "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/version" ) func main() { // traefik config inits tConfig := cmd.NewTraefikConfiguration() loaders := []cli.ResourceLoader{&tcli.DeprecationLoader{}, &tcli.FileLoader{}, &tcli.FlagLoader{}, &tcli.EnvLoader{}} cmdTraefik := &cli.Command{ Name: "traefik", Description: `Traefik is a modern HTTP reverse proxy and load balancer made to deploy microservices with ease. Complete documentation is available at https://traefik.io`, Configuration: tConfig, Resources: loaders, Run: func(_ []string) error { return runCmd(&tConfig.Configuration) }, } err := cmdTraefik.AddCommand(healthcheck.NewCmd(&tConfig.Configuration, loaders)) if err != nil { stdlog.Println(err) os.Exit(1) } err = cmdTraefik.AddCommand(cmdVersion.NewCmd()) if err != nil { stdlog.Println(err) os.Exit(1) } err = cli.Execute(cmdTraefik) if err != nil { log.Error().Err(err).Msg("Command error") logrus.Exit(1) } logrus.Exit(0) } func runCmd(staticConfiguration *static.Configuration) error { ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer cancel() if err := setupLogger(ctx, staticConfiguration); err != nil { return fmt.Errorf("setting up logger: %w", err) } // Display warning to advertise for new behavior of rejecting encoded characters in the request path. // Deprecated: this has to be removed in the next minor/major version. log.Warn().Msg("Starting with v3.6.4, Traefik now rejects some encoded characters in the request path by default. " + "Refer to the documentation for more details: https://doc.traefik.io/traefik/migrate/v3/#encoded-characters-in-request-path") http.DefaultTransport.(*http.Transport).Proxy = http.ProxyFromEnvironment staticConfiguration.SetEffectiveConfiguration() if err := staticConfiguration.ValidateConfiguration(); err != nil { return err } log.Info().Str("version", version.Version). Msgf("Traefik version %s built on %s", version.Version, version.BuildDate) redactedStaticConfiguration, err := redactor.RemoveCredentials(staticConfiguration) if err != nil { log.Error().Err(err).Msg("Could not redact static configuration") } else { log.Debug().RawJSON("staticConfiguration", []byte(redactedStaticConfiguration)).Msg("Static configuration loaded [json]") } checkNewVersion(staticConfiguration) stats(staticConfiguration) svr, err := setupServer(staticConfiguration) if err != nil { return err } if staticConfiguration.Ping != nil { staticConfiguration.Ping.WithContext(ctx) } svr.Start(ctx) defer svr.Close() sent, err := daemon.SdNotify(false, "READY=1") if !sent && err != nil { log.Error().Err(err).Msg("Failed to notify") } t, err := daemon.SdWatchdogEnabled(false) if err != nil { log.Error().Err(err).Msg("Could not enable Watchdog") } else if t != 0 { // Send a ping each half time given t /= 2 log.Info().Msgf("Watchdog activated with timer duration %s", t) safe.Go(func() { tick := time.Tick(t) for range tick { resp, errHealthCheck := healthcheck.Do(*staticConfiguration) if resp != nil { _ = resp.Body.Close() } if staticConfiguration.Ping == nil || errHealthCheck == nil { if ok, _ := daemon.SdNotify(false, "WATCHDOG=1"); !ok { log.Error().Msg("Fail to tick watchdog") } } else { log.Error().Err(errHealthCheck).Send() } } }) } svr.Wait() log.Info().Msg("Shutting down") return nil } func setupServer(staticConfiguration *static.Configuration) (*server.Server, error) { providerAggregator := aggregator.NewProviderAggregator(*staticConfiguration.Providers) ctx := context.Background() routinesPool := safe.NewPool(ctx) // adds internal provider err := providerAggregator.AddProvider(traefik.New(*staticConfiguration)) if err != nil { return nil, err } // ACME tlsManager := traefiktls.NewManager(staticConfiguration.OCSP) routinesPool.GoCtx(tlsManager.Run) httpChallengeProvider := acme.NewChallengeHTTP() tlsChallengeProvider := acme.NewChallengeTLSALPN() err = providerAggregator.AddProvider(tlsChallengeProvider) if err != nil { return nil, err } acmeProviders := initACMEProvider(staticConfiguration, providerAggregator, tlsManager, httpChallengeProvider, tlsChallengeProvider, routinesPool) // Tailscale tsProviders := initTailscaleProviders(staticConfiguration, providerAggregator) // Observability metricRegistries := registerMetricClients(staticConfiguration.Metrics) var semConvMetricRegistry *metrics.SemConvMetricsRegistry if staticConfiguration.Metrics != nil && staticConfiguration.Metrics.OTLP != nil { semConvMetricRegistry, err = metrics.NewSemConvMetricRegistry(ctx, staticConfiguration.Metrics.OTLP) if err != nil { return nil, fmt.Errorf("unable to create SemConv metric registry: %w", err) } } metricsRegistry := metrics.NewMultiRegistry(metricRegistries) accessLog := setupAccessLog(ctx, staticConfiguration.AccessLog) tracer, tracerCloser := setupTracing(ctx, staticConfiguration.Tracing) observabilityMgr := middleware.NewObservabilityMgr(*staticConfiguration, metricsRegistry, semConvMetricRegistry, accessLog, tracer, tracerCloser) // Entrypoints serverEntryPointsTCP, err := server.NewTCPEntryPoints(staticConfiguration.EntryPoints, staticConfiguration.HostResolver, metricsRegistry) if err != nil { return nil, err } serverEntryPointsUDP, err := server.NewUDPEntryPoints(staticConfiguration.EntryPoints) if err != nil { return nil, err } if staticConfiguration.API != nil { version.DisableDashboardAd = staticConfiguration.API.DisableDashboardAd version.DashboardName = staticConfiguration.API.DashboardName } // Plugins pluginLogger := log.Ctx(ctx).With().Logger() hasPlugins := staticConfiguration.Experimental != nil && (staticConfiguration.Experimental.Plugins != nil || staticConfiguration.Experimental.LocalPlugins != nil) if hasPlugins { pluginsList := slices.Collect(maps.Keys(staticConfiguration.Experimental.Plugins)) pluginsList = append(pluginsList, slices.Collect(maps.Keys(staticConfiguration.Experimental.LocalPlugins))...) pluginLogger = pluginLogger.With().Strs("plugins", pluginsList).Logger() pluginLogger.Info().Msg("Loading plugins...") } pluginBuilder, err := createPluginBuilder(staticConfiguration) if err != nil && staticConfiguration.Experimental != nil && staticConfiguration.Experimental.AbortOnPluginFailure { return nil, fmt.Errorf("plugin: failed to create plugin builder: %w", err) } if err != nil { pluginLogger.Err(err).Msg("Plugins are disabled because an error has occurred.") } else if hasPlugins { pluginLogger.Info().Msg("Plugins loaded.") } // Providers plugins for name, conf := range staticConfiguration.Providers.Plugin { if pluginBuilder == nil { break } p, err := pluginBuilder.BuildProvider(name, conf) if err != nil { return nil, fmt.Errorf("plugin: failed to build provider: %w", err) } err = providerAggregator.AddProvider(p) if err != nil { return nil, fmt.Errorf("plugin: failed to add provider: %w", err) } } // Service manager factory var spiffeX509Source *workloadapi.X509Source if staticConfiguration.Spiffe != nil && staticConfiguration.Spiffe.WorkloadAPIAddr != "" { log.Info().Str("workloadAPIAddr", staticConfiguration.Spiffe.WorkloadAPIAddr). Msg("Waiting on SPIFFE SVID delivery") spiffeX509Source, err = workloadapi.NewX509Source( ctx, workloadapi.WithClientOptions( workloadapi.WithAddr( staticConfiguration.Spiffe.WorkloadAPIAddr, ), ), ) if err != nil { return nil, fmt.Errorf("unable to create SPIFFE x509 source: %w", err) } log.Info().Msg("Successfully obtained SPIFFE SVID.") } transportManager := service.NewTransportManager(spiffeX509Source) var proxyBuilder service.ProxyBuilder = httputil.NewProxyBuilder(transportManager, semConvMetricRegistry) if staticConfiguration.Experimental != nil && staticConfiguration.Experimental.FastProxy != nil { proxyBuilder = proxy.NewSmartBuilder(transportManager, proxyBuilder, *staticConfiguration.Experimental.FastProxy) } dialerManager := tcp.NewDialerManager(spiffeX509Source) acmeHTTPHandler := getHTTPChallengeHandler(acmeProviders, httpChallengeProvider) managerFactory := service.NewManagerFactory(*staticConfiguration, routinesPool, observabilityMgr, transportManager, proxyBuilder, acmeHTTPHandler) // Router factory routerFactory, err := server.NewRouterFactory(*staticConfiguration, managerFactory, tlsManager, observabilityMgr, pluginBuilder, dialerManager) if err != nil { return nil, fmt.Errorf("creating router factory: %w", err) } // Watcher watcher := server.NewConfigurationWatcher( routinesPool, providerAggregator, getDefaultsEntrypoints(staticConfiguration), "internal", ) // TLS watcher.AddListener(func(conf dynamic.Configuration) { ctx := context.Background() tlsManager.UpdateConfigs(ctx, conf.TLS.Stores, conf.TLS.Options, conf.TLS.Certificates) gauge := metricsRegistry.TLSCertsNotAfterTimestampGauge() for _, certificate := range tlsManager.GetServerCertificates() { appendCertMetric(gauge, certificate) } }) // Metrics watcher.AddListener(func(_ dynamic.Configuration) { metricsRegistry.ConfigReloadsCounter().Add(1) metricsRegistry.LastConfigReloadSuccessGauge().Set(float64(time.Now().Unix())) }) // Server Transports watcher.AddListener(func(conf dynamic.Configuration) { transportManager.Update(conf.HTTP.ServersTransports) proxyBuilder.Update(conf.HTTP.ServersTransports) dialerManager.Update(conf.TCP.ServersTransports) }) // Switch router watcher.AddListener(switchRouter(routerFactory, serverEntryPointsTCP, serverEntryPointsUDP)) // Metrics if metricsRegistry.IsEpEnabled() || metricsRegistry.IsRouterEnabled() || metricsRegistry.IsSvcEnabled() { var eps []string for key := range serverEntryPointsTCP { eps = append(eps, key) } watcher.AddListener(func(conf dynamic.Configuration) { metrics.OnConfigurationUpdate(conf, eps) }) } // TLS challenge watcher.AddListener(tlsChallengeProvider.ListenConfiguration) // Certificate Resolvers resolverNames := map[string]struct{}{} // ACME for _, p := range acmeProviders { resolverNames[p.ResolverName] = struct{}{} watcher.AddListener(p.ListenConfiguration) } // Tailscale for _, p := range tsProviders { resolverNames[p.ResolverName] = struct{}{} watcher.AddListener(p.HandleConfigUpdate) } // Certificate resolver logs watcher.AddListener(func(config dynamic.Configuration) { for rtName, rt := range config.HTTP.Routers { if rt.TLS == nil || rt.TLS.CertResolver == "" { continue } if _, ok := resolverNames[rt.TLS.CertResolver]; !ok { log.Error().Err(err).Str(logs.RouterName, rtName).Str("certificateResolver", rt.TLS.CertResolver). Msg("Router uses a nonexistent certificate resolver") } } }) return server.NewServer(routinesPool, serverEntryPointsTCP, serverEntryPointsUDP, watcher, observabilityMgr), nil } func getHTTPChallengeHandler(acmeProviders []*acme.Provider, httpChallengeProvider http.Handler) http.Handler { var acmeHTTPHandler http.Handler for _, p := range acmeProviders { if p != nil && p.HTTPChallenge != nil { acmeHTTPHandler = httpChallengeProvider break } } return acmeHTTPHandler } func getDefaultsEntrypoints(staticConfiguration *static.Configuration) []string { var defaultEntryPoints []string // Determines if at least one EntryPoint is configured to be used by default. var hasDefinedDefaults bool for _, ep := range staticConfiguration.EntryPoints { if ep.AsDefault { hasDefinedDefaults = true break } } for name, cfg := range staticConfiguration.EntryPoints { // By default all entrypoints are considered. // If at least one is flagged, then only flagged entrypoints are included. if hasDefinedDefaults && !cfg.AsDefault { continue } protocol, err := cfg.GetProtocol() if err != nil { // Should never happen because Traefik should not start if protocol is invalid. log.Error().Err(err).Msg("Invalid protocol") } if protocol != "udp" && name != static.DefaultInternalEntryPointName { defaultEntryPoints = append(defaultEntryPoints, name) } } slices.Sort(defaultEntryPoints) return defaultEntryPoints } func switchRouter(routerFactory *server.RouterFactory, serverEntryPointsTCP server.TCPEntryPoints, serverEntryPointsUDP server.UDPEntryPoints) func(conf dynamic.Configuration) { return func(conf dynamic.Configuration) { rtConf := runtime.NewConfig(conf) routers, udpRouters := routerFactory.CreateRouters(rtConf) serverEntryPointsTCP.Switch(routers) serverEntryPointsUDP.Switch(udpRouters) } } // initACMEProvider creates and registers acme.Provider instances corresponding to the configured ACME certificate resolvers. func initACMEProvider(c *static.Configuration, providerAggregator *aggregator.ProviderAggregator, tlsManager *traefiktls.Manager, httpChallengeProvider, tlsChallengeProvider challenge.Provider, routinesPool *safe.Pool) []*acme.Provider { localStores := map[string]*acme.LocalStore{} var resolvers []*acme.Provider for name, resolver := range c.CertificatesResolvers { if resolver.ACME == nil { continue } if localStores[resolver.ACME.Storage] == nil { localStores[resolver.ACME.Storage] = acme.NewLocalStore(resolver.ACME.Storage, routinesPool) } p := &acme.Provider{ Configuration: resolver.ACME, Store: localStores[resolver.ACME.Storage], ResolverName: name, HTTPChallengeProvider: httpChallengeProvider, TLSChallengeProvider: tlsChallengeProvider, } if err := providerAggregator.AddProvider(p); err != nil { log.Error().Err(err).Str("resolver", name).Msg("The ACME resolve is skipped from the resolvers list") continue } p.SetTLSManager(tlsManager) p.SetConfigListenerChan(make(chan dynamic.Configuration)) resolvers = append(resolvers, p) } return resolvers } // initTailscaleProviders creates and registers tailscale.Provider instances corresponding to the configured Tailscale certificate resolvers. func initTailscaleProviders(cfg *static.Configuration, providerAggregator *aggregator.ProviderAggregator) []*tailscale.Provider { var providers []*tailscale.Provider for name, resolver := range cfg.CertificatesResolvers { if resolver.Tailscale == nil { continue } tsProvider := &tailscale.Provider{ResolverName: name} if err := providerAggregator.AddProvider(tsProvider); err != nil { log.Error().Err(err).Str(logs.ProviderName, name).Msg("Unable to create Tailscale provider") continue } providers = append(providers, tsProvider) } return providers } func registerMetricClients(metricsConfig *otypes.Metrics) []metrics.Registry { if metricsConfig == nil { return nil } var registries []metrics.Registry if metricsConfig.Prometheus != nil { logger := log.With().Str(logs.MetricsProviderName, "prometheus").Logger() prometheusRegister := metrics.RegisterPrometheus(logger.WithContext(context.Background()), metricsConfig.Prometheus) if prometheusRegister != nil { registries = append(registries, prometheusRegister) logger.Debug().Msg("Configured Prometheus metrics") } } if metricsConfig.Datadog != nil { logger := log.With().Str(logs.MetricsProviderName, "datadog").Logger() registries = append(registries, metrics.RegisterDatadog(logger.WithContext(context.Background()), metricsConfig.Datadog)) logger.Debug(). Str("address", metricsConfig.Datadog.Address). Str("pushInterval", metricsConfig.Datadog.PushInterval.String()). Msgf("Configured Datadog metrics") } if metricsConfig.StatsD != nil { logger := log.With().Str(logs.MetricsProviderName, "statsd").Logger() registries = append(registries, metrics.RegisterStatsd(logger.WithContext(context.Background()), metricsConfig.StatsD)) logger.Debug(). Str("address", metricsConfig.StatsD.Address). Str("pushInterval", metricsConfig.StatsD.PushInterval.String()). Msg("Configured StatsD metrics") } if metricsConfig.InfluxDB2 != nil { logger := log.With().Str(logs.MetricsProviderName, "influxdb2").Logger() influxDB2Register := metrics.RegisterInfluxDB2(logger.WithContext(context.Background()), metricsConfig.InfluxDB2) if influxDB2Register != nil { registries = append(registries, influxDB2Register) logger.Debug(). Str("address", metricsConfig.InfluxDB2.Address). Str("bucket", metricsConfig.InfluxDB2.Bucket). Str("organization", metricsConfig.InfluxDB2.Org). Str("pushInterval", metricsConfig.InfluxDB2.PushInterval.String()). Msg("Configured InfluxDB v2 metrics") } } if metricsConfig.OTLP != nil { logger := log.With().Str(logs.MetricsProviderName, "openTelemetry").Logger() openTelemetryRegistry := metrics.RegisterOpenTelemetry(logger.WithContext(context.Background()), metricsConfig.OTLP) if openTelemetryRegistry != nil { registries = append(registries, openTelemetryRegistry) logger.Debug(). Str("pushInterval", metricsConfig.OTLP.PushInterval.String()). Msg("Configured OpenTelemetry metrics") } } return registries } func appendCertMetric(gauge gokitmetrics.Gauge, certificate *x509.Certificate) { slices.Sort(certificate.DNSNames) labels := []string{ "cn", certificate.Subject.CommonName, "serial", certificate.SerialNumber.String(), "sans", strings.Join(certificate.DNSNames, ","), } notAfter := float64(certificate.NotAfter.Unix()) gauge.With(labels...).Set(notAfter) } func setupAccessLog(ctx context.Context, conf *otypes.AccessLog) *accesslog.Handler { if conf == nil { return nil } accessLoggerMiddleware, err := accesslog.NewHandler(ctx, conf) if err != nil { log.Warn().Err(err).Msg("Unable to create access logger") return nil } return accessLoggerMiddleware } func setupTracing(ctx context.Context, conf *static.Tracing) (*tracing.Tracer, io.Closer) { if conf == nil { return nil, nil } tracer, closer, err := tracing.NewTracing(ctx, conf) if err != nil { log.Warn().Err(err).Msg("Unable to create tracer") return nil, nil } return tracer, closer } func checkNewVersion(staticConfiguration *static.Configuration) { logger := log.With().Logger() if staticConfiguration.Global.CheckNewVersion { logger.Info().Msg(`Version check is enabled.`) logger.Info().Msg(`Traefik checks for new releases to notify you if your version is out of date.`) logger.Info().Msg(`It also collects usage data during this process.`) logger.Info().Msg(`Check the documentation to get more info: https://doc.traefik.io/traefik/contributing/data-collection/`) ticker := time.Tick(24 * time.Hour) safe.Go(func() { for time.Sleep(10 * time.Minute); ; <-ticker { version.CheckNewVersion() } }) } else { logger.Info().Msg(` Version check is disabled. You will not be notified if a new version is available. More details: https://doc.traefik.io/traefik/contributing/data-collection/ `) } } func stats(staticConfiguration *static.Configuration) { logger := log.With().Logger() if staticConfiguration.Global.SendAnonymousUsage { logger.Info().Msg(`Stats collection is enabled.`) logger.Info().Msg(`Many thanks for contributing to Traefik's improvement by allowing us to receive anonymous information from your configuration.`) logger.Info().Msg(`Help us improve Traefik by leaving this feature on :)`) logger.Info().Msg(`More details on: https://doc.traefik.io/traefik/contributing/data-collection/`) collect(staticConfiguration) } else { logger.Info().Msg(` Stats collection is disabled. Help us improve Traefik by turning this feature on :) More details on: https://doc.traefik.io/traefik/contributing/data-collection/ `) } } func collect(staticConfiguration *static.Configuration) { ticker := time.Tick(24 * time.Hour) safe.Go(func() { for time.Sleep(10 * time.Minute); ; <-ticker { if err := collector.Collect(staticConfiguration); err != nil { log.Debug().Err(err).Send() } } }) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/cmd/traefik/logger.go
cmd/traefik/logger.go
package main import ( "context" "errors" "fmt" "io" stdlog "log" "os" "strings" "time" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/sirupsen/logrus" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/observability/logs" "gopkg.in/natefinch/lumberjack.v2" ) func init() { // hide the first logs before the setup of the logger. zerolog.SetGlobalLevel(zerolog.ErrorLevel) } func setupLogger(ctx context.Context, staticConfiguration *static.Configuration) error { // Validate that the experimental flag is set up at this point, // rather than validating the static configuration before the setupLogger call. // This ensures that validation messages are not logged using an un-configured logger. if staticConfiguration.Log != nil && staticConfiguration.Log.OTLP != nil && (staticConfiguration.Experimental == nil || !staticConfiguration.Experimental.OTLPLogs) { return errors.New("the experimental OTLPLogs feature must be enabled to use OTLP logging") } // configure log format w := getLogWriter(staticConfiguration) // configure log level logLevel := getLogLevel(staticConfiguration) zerolog.SetGlobalLevel(logLevel) // create logger logger := zerolog.New(w).With().Timestamp() if logLevel <= zerolog.DebugLevel { logger = logger.Caller() } log.Logger = logger.Logger().Level(logLevel) if staticConfiguration.Log != nil && staticConfiguration.Log.OTLP != nil { var err error log.Logger, err = logs.SetupOTelLogger(ctx, log.Logger, staticConfiguration.Log.OTLP) if err != nil { return fmt.Errorf("setting up OpenTelemetry logger: %w", err) } } zerolog.DefaultContextLogger = &log.Logger // Global logrus replacement (related to lib like go-rancher-metadata, docker, etc.) logrus.StandardLogger().Out = logs.NoLevel(log.Logger, zerolog.DebugLevel) // configure default standard log. stdlog.SetFlags(stdlog.Lshortfile | stdlog.LstdFlags) stdlog.SetOutput(logs.NoLevel(log.Logger, zerolog.DebugLevel)) return nil } func getLogWriter(staticConfiguration *static.Configuration) io.Writer { var w io.Writer = os.Stdout if staticConfiguration.Log != nil && len(staticConfiguration.Log.FilePath) > 0 { _, _ = os.OpenFile(staticConfiguration.Log.FilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o666) w = &lumberjack.Logger{ Filename: staticConfiguration.Log.FilePath, MaxSize: staticConfiguration.Log.MaxSize, MaxBackups: staticConfiguration.Log.MaxBackups, MaxAge: staticConfiguration.Log.MaxAge, Compress: true, } } if staticConfiguration.Log == nil || staticConfiguration.Log.Format != "json" { w = zerolog.ConsoleWriter{ Out: w, TimeFormat: time.RFC3339, NoColor: staticConfiguration.Log != nil && (staticConfiguration.Log.NoColor || len(staticConfiguration.Log.FilePath) > 0), } } return w } func getLogLevel(staticConfiguration *static.Configuration) zerolog.Level { levelStr := "error" if staticConfiguration.Log != nil && staticConfiguration.Log.Level != "" { levelStr = strings.ToLower(staticConfiguration.Log.Level) } logLevel, err := zerolog.ParseLevel(strings.ToLower(levelStr)) if err != nil { log.Error().Err(err). Str("logLevel", levelStr). Msg("Unspecified or invalid log level, setting the level to default (ERROR)...") logLevel = zerolog.ErrorLevel } return logLevel }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/cmd/traefik/traefik_test.go
cmd/traefik/traefik_test.go
package main import ( "crypto/x509" "encoding/pem" "strings" "testing" "github.com/go-kit/kit/metrics" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/static" ) // FooCert is a PEM-encoded TLS cert. // generated from src/crypto/tls: // go run generate_cert.go --rsa-bits 1024 --host foo.org,foo.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h const fooCert = `-----BEGIN CERTIFICATE----- MIICHzCCAYigAwIBAgIQXQFLeYRwc5X21t457t2xADANBgkqhkiG9w0BAQsFADAS MRAwDgYDVQQKEwdBY21lIENvMCAXDTcwMDEwMTAwMDAwMFoYDzIwODQwMTI5MTYw MDAwWjASMRAwDgYDVQQKEwdBY21lIENvMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB iQKBgQDCjn67GSs/khuGC4GNN+tVo1S+/eSHwr/hWzhfMqO7nYiXkFzmxi+u14CU Pda6WOeps7T2/oQEFMxKKg7zYOqkLSbjbE0ZfosopaTvEsZm/AZHAAvoOrAsIJOn SEiwy8h0tLA4z1SNR6rmIVQWyqBZEPAhBTQM1z7tFp48FakCFwIDAQABo3QwcjAO BgNVHQ8BAf8EBAMCAqQwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDwYDVR0TAQH/BAUw AwEB/zAdBgNVHQ4EFgQUDHG3ASzeUezElup9zbPpBn/vjogwGwYDVR0RBBQwEoIH Zm9vLm9yZ4IHZm9vLmNvbTANBgkqhkiG9w0BAQsFAAOBgQBT+VLMbB9u27tBX8Aw ZrGY3rbNdBGhXVTksrjiF+6ZtDpD3iI56GH9zLxnqvXkgn3u0+Ard5TqF/xmdwVw NY0V/aWYfcL2G2auBCQrPvM03ozRnVUwVfP23eUzX2ORNHCYhd2ObQx4krrhs7cJ SWxtKwFlstoXY3K2g9oRD9UxdQ== -----END CERTIFICATE-----` // BarCert is a PEM-encoded TLS cert. // generated from src/crypto/tls: // go run generate_cert.go --rsa-bits 1024 --host bar.org,bar.com --ca --start-date "Jan 1 00:00:00 1970" --duration=10000h const barCert = `-----BEGIN CERTIFICATE----- MIICHTCCAYagAwIBAgIQcuIcNEXzBHPoxna5S6wG4jANBgkqhkiG9w0BAQsFADAS MRAwDgYDVQQKEwdBY21lIENvMB4XDTcwMDEwMTAwMDAwMFoXDTcxMDIyMTE2MDAw MFowEjEQMA4GA1UEChMHQWNtZSBDbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC gYEAqtcrP+KA7D6NjyztGNIPMup9KiBMJ8QL+preog/YHR7SQLO3kGFhpS3WKMab SzMypC3ZX1PZjBP5ZzwaV3PFbuwlCkPlyxR2lOWmullgI7mjY0TBeYLDIclIzGRp mpSDDSpkW1ay2iJDSpXjlhmwZr84hrCU7BRTQJo91fdsRTsCAwEAAaN0MHIwDgYD VR0PAQH/BAQDAgKkMBMGA1UdJQQMMAoGCCsGAQUFBwMBMA8GA1UdEwEB/wQFMAMB Af8wHQYDVR0OBBYEFK8jnzFQvBAgWtfzOyXY4VSkwrTXMBsGA1UdEQQUMBKCB2Jh ci5vcmeCB2Jhci5jb20wDQYJKoZIhvcNAQELBQADgYEAJz0ifAExisC/ZSRhWuHz 7qs1i6Nd4+YgEVR8dR71MChP+AMxucY1/ajVjb9xlLys3GPE90TWSdVppabEVjZY Oq11nPKc50ItTt8dMku6t0JHBmzoGdkN0V4zJCBqdQJxhop8JpYJ0S9CW0eT93h3 ipYQSsmIINGtMXJ8VkP/MlM= -----END CERTIFICATE-----` type gaugeMock struct { metrics map[string]float64 labels string } func (g gaugeMock) With(labelValues ...string) metrics.Gauge { g.labels = strings.Join(labelValues, ",") return g } func (g gaugeMock) Set(value float64) { g.metrics[g.labels] = value } func (g gaugeMock) Add(delta float64) { panic("implement me") } func TestAppendCertMetric(t *testing.T) { testCases := []struct { desc string certs []string expected map[string]float64 }{ { desc: "No certs", certs: []string{}, expected: map[string]float64{}, }, { desc: "One cert", certs: []string{fooCert}, expected: map[string]float64{ "cn,,serial,123624926713171615935660664614975025408,sans,foo.com,foo.org": 3.6e+09, }, }, { desc: "Two certs", certs: []string{fooCert, barCert}, expected: map[string]float64{ "cn,,serial,123624926713171615935660664614975025408,sans,foo.com,foo.org": 3.6e+09, "cn,,serial,152706022658490889223053211416725817058,sans,bar.com,bar.org": 3.6e+07, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() gauge := &gaugeMock{ metrics: map[string]float64{}, } for _, cert := range test.certs { block, _ := pem.Decode([]byte(cert)) parsedCert, err := x509.ParseCertificate(block.Bytes) require.NoError(t, err) appendCertMetric(gauge, parsedCert) } assert.Equal(t, test.expected, gauge.metrics) }) } } func TestGetDefaultsEntrypoints(t *testing.T) { testCases := []struct { desc string entrypoints static.EntryPoints expected []string }{ { desc: "Skips special names", entrypoints: map[string]*static.EntryPoint{ "web": { Address: ":80", }, "traefik": { Address: ":8080", }, }, expected: []string{"web"}, }, { desc: "Two EntryPoints not attachable", entrypoints: map[string]*static.EntryPoint{ "web": { Address: ":80", }, "websecure": { Address: ":443", }, }, expected: []string{"web", "websecure"}, }, { desc: "Two EntryPoints only one attachable", entrypoints: map[string]*static.EntryPoint{ "web": { Address: ":80", }, "websecure": { Address: ":443", AsDefault: true, }, }, expected: []string{"websecure"}, }, { desc: "Two attachable EntryPoints", entrypoints: map[string]*static.EntryPoint{ "web": { Address: ":80", AsDefault: true, }, "websecure": { Address: ":443", AsDefault: true, }, }, expected: []string{"web", "websecure"}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { actual := getDefaultsEntrypoints(&static.Configuration{ EntryPoints: test.entrypoints, }) assert.ElementsMatch(t, test.expected, actual) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/cmd/version/version.go
cmd/version/version.go
package version import ( "fmt" "io" "os" "runtime" "text/template" "github.com/traefik/paerser/cli" "github.com/traefik/traefik/v3/pkg/version" ) var versionTemplate = `Version: {{.Version}} Codename: {{.Codename}} Go version: {{.GoVersion}} Built: {{.BuildTime}} OS/Arch: {{.Os}}/{{.Arch}}` // NewCmd builds a new Version command. func NewCmd() *cli.Command { return &cli.Command{ Name: "version", Description: `Shows the current Traefik version.`, Configuration: nil, Run: func(_ []string) error { if err := GetPrint(os.Stdout); err != nil { return err } fmt.Print("\n") return nil }, } } // GetPrint write Printable version. func GetPrint(wr io.Writer) error { tmpl, err := template.New("").Parse(versionTemplate) if err != nil { return err } v := struct { Version string Codename string GoVersion string BuildTime string Os string Arch string }{ Version: version.Version, Codename: version.Codename, GoVersion: runtime.Version(), BuildTime: version.BuildDate, Os: runtime.GOOS, Arch: runtime.GOARCH, } return tmpl.Execute(wr, v) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/cmd/internal/gen/centrifuge.go
cmd/internal/gen/centrifuge.go
package main import ( "bytes" "fmt" "go/format" "go/importer" "go/token" "go/types" "io" "log" "os" "path" "path/filepath" "reflect" "slices" "sort" "strings" "golang.org/x/tools/imports" ) // File a kind of AST element that represents a file. type File struct { Package string Imports []string Elements []Element } // Element is a simplified version of a symbol. type Element struct { Name string Value string } // Centrifuge a centrifuge. // Generate Go Structures from Go structures. type Centrifuge struct { IncludedImports []string ExcludedTypes []string ExcludedFiles []string TypeCleaner func(types.Type, string) string PackageCleaner func(string) string rootPkg string fileSet *token.FileSet pkg *types.Package } // NewCentrifuge creates a new Centrifuge. func NewCentrifuge(rootPkg string) (*Centrifuge, error) { fileSet := token.NewFileSet() pkg, err := importer.ForCompiler(fileSet, "source", nil).Import(rootPkg) if err != nil { return nil, err } return &Centrifuge{ fileSet: fileSet, pkg: pkg, rootPkg: rootPkg, TypeCleaner: func(typ types.Type, _ string) string { return typ.String() }, PackageCleaner: func(s string) string { return s }, }, nil } // Run runs the code extraction and the code generation. func (c Centrifuge) Run(dest string, pkgName string) error { files := c.run(c.pkg.Scope(), c.rootPkg, pkgName) err := fileWriter{baseDir: dest}.Write(files) if err != nil { return err } for _, p := range c.pkg.Imports() { if slices.Contains(c.IncludedImports, p.Path()) { fls := c.run(p.Scope(), p.Path(), p.Name()) err = fileWriter{baseDir: filepath.Join(dest, p.Name())}.Write(fls) if err != nil { return err } } } return err } func (c Centrifuge) run(sc *types.Scope, rootPkg string, pkgName string) map[string]*File { files := map[string]*File{} for _, name := range sc.Names() { if slices.Contains(c.ExcludedTypes, name) { continue } o := sc.Lookup(name) if !o.Exported() { continue } filename := filepath.Base(c.fileSet.File(o.Pos()).Name()) if slices.Contains(c.ExcludedFiles, path.Join(rootPkg, filename)) { continue } fl, ok := files[filename] if !ok { files[filename] = &File{Package: pkgName} fl = files[filename] } elt := Element{ Name: name, } switch ob := o.(type) { case *types.TypeName: switch obj := ob.Type().(*types.Named).Underlying().(type) { case *types.Struct: elt.Value = c.writeStruct(name, obj, rootPkg, fl) case *types.Map: elt.Value = fmt.Sprintf("type %s map[%s]%s\n", name, obj.Key().String(), c.TypeCleaner(obj.Elem(), rootPkg)) case *types.Slice: elt.Value = fmt.Sprintf("type %s []%v\n", name, c.TypeCleaner(obj.Elem(), rootPkg)) case *types.Basic: elt.Value = fmt.Sprintf("type %s %v\n", name, obj.Name()) default: log.Printf("OTHER TYPE::: %s %T\n", name, o.Type().(*types.Named).Underlying()) continue } default: log.Printf("OTHER::: %s %T\n", name, o) continue } if len(elt.Value) > 0 { fl.Elements = append(fl.Elements, elt) } } return files } func (c Centrifuge) writeStruct(name string, obj *types.Struct, rootPkg string, elt *File) string { b := strings.Builder{} b.WriteString(fmt.Sprintf("type %s struct {\n", name)) for i := range obj.NumFields() { field := obj.Field(i) if !field.Exported() { continue } fPkg := c.PackageCleaner(extractPackage(field.Type())) if fPkg != "" && fPkg != rootPkg { elt.Imports = append(elt.Imports, fPkg) } fType := c.TypeCleaner(field.Type(), rootPkg) if field.Embedded() { b.WriteString(fmt.Sprintf("\t%s\n", fType)) continue } values, ok := lookupTagValue(obj.Tag(i), "json") if len(values) > 0 && values[0] == "-" { continue } b.WriteString(fmt.Sprintf("\t%s %s", field.Name(), fType)) if ok { b.WriteString(fmt.Sprintf(" `json:\"%s\"`", strings.Join(values, ","))) } b.WriteString("\n") } b.WriteString("}\n") return b.String() } func lookupTagValue(raw, key string) ([]string, bool) { value, ok := reflect.StructTag(raw).Lookup(key) if !ok { return nil, ok } values := strings.Split(value, ",") if len(values) < 1 { return nil, true } return values, true } func extractPackage(t types.Type) string { switch tu := t.(type) { case *types.Named: return tu.Obj().Pkg().Path() case *types.Slice: if v, ok := tu.Elem().(*types.Named); ok { return v.Obj().Pkg().Path() } return "" case *types.Map: if v, ok := tu.Elem().(*types.Named); ok { return v.Obj().Pkg().Path() } return "" case *types.Pointer: return extractPackage(tu.Elem()) default: return "" } } type fileWriter struct { baseDir string } func (f fileWriter) Write(files map[string]*File) error { err := os.MkdirAll(f.baseDir, 0o755) if err != nil { return err } for name, file := range files { err = f.writeFile(name, file) if err != nil { return err } } return nil } func (f fileWriter) writeFile(name string, desc *File) error { if len(desc.Elements) == 0 { return nil } filename := filepath.Join(f.baseDir, name) file, err := os.Create(filename) if err != nil { return fmt.Errorf("failed to create file: %w", err) } defer func() { _ = file.Close() }() b := bytes.NewBufferString("package ") b.WriteString(desc.Package) b.WriteString("\n") b.WriteString("// Code generated by centrifuge. DO NOT EDIT.\n") b.WriteString("\n") f.writeImports(b, desc.Imports) b.WriteString("\n") for _, elt := range desc.Elements { b.WriteString(elt.Value) b.WriteString("\n") } // gofmt source, err := format.Source(b.Bytes()) if err != nil { log.Println(b.String()) return fmt.Errorf("failed to format sources: %w", err) } // goimports process, err := imports.Process(filename, source, nil) if err != nil { log.Println(string(source)) return fmt.Errorf("failed to format imports: %w", err) } _, err = file.Write(process) if err != nil { return err } return nil } func (f fileWriter) writeImports(b io.StringWriter, imports []string) { if len(imports) == 0 { return } uniq := map[string]struct{}{} sort.Strings(imports) _, _ = b.WriteString("import (\n") for _, s := range imports { if _, exist := uniq[s]; exist { continue } uniq[s] = struct{}{} _, _ = b.WriteString(fmt.Sprintf(` "%s"`+"\n", s)) } _, _ = b.WriteString(")\n") }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/cmd/internal/gen/main.go
cmd/internal/gen/main.go
package main import ( "fmt" "go/build" "go/types" "log" "os" "path" "path/filepath" "strings" ) const rootPkg = "github.com/traefik/traefik/v3/pkg/config/dynamic" const ( destModuleName = "github.com/traefik/genconf" destPkg = "dynamic" ) const marsh = `package %s import "encoding/json" type JSONPayload struct { *Configuration } func (c JSONPayload) MarshalJSON() ([]byte, error) { if c.Configuration == nil { return nil, nil } return json.Marshal(c.Configuration) } ` // main generate Go Structures from Go structures. // Allows to create an external module (destModuleName) used by the plugin's providers // that contains Go structs of the dynamic configuration and nothing else. // These Go structs do not have any non-exported fields and do not rely on any external dependencies. func main() { dest := filepath.Join(path.Join(build.Default.GOPATH, "src"), destModuleName, destPkg) log.Println("Output:", dest) err := run(dest) if err != nil { log.Fatal(err) } } func run(dest string) error { centrifuge, err := NewCentrifuge(rootPkg) if err != nil { return err } centrifuge.IncludedImports = []string{ "github.com/traefik/traefik/v3/pkg/tls", "github.com/traefik/traefik/v3/pkg/types", } centrifuge.ExcludedTypes = []string{ // tls "CertificateStore", "Manager", // dynamic "Message", "Configurations", // types "HTTPCodeRanges", "HostResolverConfig", } centrifuge.ExcludedFiles = []string{ "github.com/traefik/traefik/v3/pkg/types/logs.go", "github.com/traefik/traefik/v3/pkg/types/metrics.go", } centrifuge.TypeCleaner = cleanType centrifuge.PackageCleaner = cleanPackage err = centrifuge.Run(dest, destPkg) if err != nil { return err } return os.WriteFile(filepath.Join(dest, "marshaler.go"), []byte(fmt.Sprintf(marsh, destPkg)), 0o666) } func cleanType(typ types.Type, base string) string { if typ.String() == "github.com/traefik/traefik/v3/pkg/types.FileOrContent" { return "string" } if typ.String() == "[]github.com/traefik/traefik/v3/pkg/types.FileOrContent" { return "[]string" } if typ.String() == "github.com/traefik/paerser/types.Duration" { return "string" } if strings.Contains(typ.String(), base) { return strings.ReplaceAll(typ.String(), base+".", "") } if strings.Contains(typ.String(), "github.com/traefik/traefik/v3/pkg/") { return strings.ReplaceAll(typ.String(), "github.com/traefik/traefik/v3/pkg/", "") } return typ.String() } func cleanPackage(src string) string { switch src { case "github.com/traefik/paerser/types": return "" case "github.com/traefik/traefik/v3/pkg/tls": return path.Join(destModuleName, destPkg, "tls") case "github.com/traefik/traefik/v3/pkg/types": return path.Join(destModuleName, destPkg, "types") default: return src } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/cmd/healthcheck/healthcheck.go
cmd/healthcheck/healthcheck.go
package healthcheck import ( "errors" "fmt" "net/http" "os" "time" "github.com/traefik/paerser/cli" "github.com/traefik/traefik/v3/pkg/config/static" ) // NewCmd builds a new HealthCheck command. func NewCmd(traefikConfiguration *static.Configuration, loaders []cli.ResourceLoader) *cli.Command { return &cli.Command{ Name: "healthcheck", Description: `Calls Traefik /ping endpoint (disabled by default) to check the health of Traefik.`, Configuration: traefikConfiguration, Run: runCmd(traefikConfiguration), Resources: loaders, } } func runCmd(traefikConfiguration *static.Configuration) func(_ []string) error { return func(_ []string) error { traefikConfiguration.SetEffectiveConfiguration() resp, errPing := Do(*traefikConfiguration) if resp != nil { resp.Body.Close() } if errPing != nil { fmt.Printf("Error calling healthcheck: %s\n", errPing) os.Exit(1) } if resp.StatusCode != http.StatusOK { fmt.Printf("Bad healthcheck status: %s\n", resp.Status) os.Exit(1) } fmt.Printf("OK: %s\n", resp.Request.URL) os.Exit(0) return nil } } // Do try to do a healthcheck. func Do(staticConfiguration static.Configuration) (*http.Response, error) { if staticConfiguration.Ping == nil { return nil, errors.New("please enable `ping` to use health check") } ep := staticConfiguration.Ping.EntryPoint if ep == "" { ep = "traefik" } pingEntryPoint, ok := staticConfiguration.EntryPoints[ep] if !ok { return nil, fmt.Errorf("ping: missing %s entry point", ep) } client := &http.Client{Timeout: 5 * time.Second} protocol := "http" // TODO Handle TLS on ping etc... // if pingEntryPoint.TLS != nil { // protocol = "https" // tr := &http.Transport{ // TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // } // client.Transport = tr // } path := "/" return client.Head(protocol + "://" + pingEntryPoint.GetAddress() + path + "ping") }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/docker_compose_test.go
integration/docker_compose_test.go
package integration import ( "encoding/json" "net/http" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" "github.com/traefik/traefik/v3/pkg/api" "github.com/traefik/traefik/v3/pkg/testhelpers" ) // Docker tests suite. type DockerComposeSuite struct { BaseSuite } func TestDockerComposeSuite(t *testing.T) { suite.Run(t, new(DockerComposeSuite)) } func (s *DockerComposeSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("minimal") s.composeUp() } func (s *DockerComposeSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *DockerComposeSuite) TestComposeScale() { tempObjects := struct { DockerHost string DefaultRule string }{ DockerHost: s.getDockerHost(), DefaultRule: "Host(`{{ normalize .Name }}.docker.localhost`)", } file := s.adaptFile("fixtures/docker/minimal.toml", tempObjects) s.traefikCmd(withConfigFile(file)) req := testhelpers.MustNewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil) req.Host = "my.super.host" _, err := try.ResponseUntilStatusCode(req, 5*time.Second, http.StatusOK) require.NoError(s.T(), err) resp, err := http.Get("http://127.0.0.1:8080/api/rawdata") require.NoError(s.T(), err) defer resp.Body.Close() var rtconf api.RunTimeRepresentation err = json.NewDecoder(resp.Body).Decode(&rtconf) require.NoError(s.T(), err) // check that we have only three routers (the one from this test + 2 unrelated internal ones) assert.Len(s.T(), rtconf.Routers, 3) // check that we have only one service (not counting the internal ones) with n servers services := rtconf.Services assert.Len(s.T(), services, 4) for name, service := range services { if strings.HasSuffix(name, "@internal") { continue } assert.Equal(s.T(), "service-mini@docker", name) assert.Len(s.T(), service.LoadBalancer.Servers, 2) // We could break here, but we don't just to keep us honest. } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/routing_test.go
integration/routing_test.go
package integration import ( "net" "net/http" "strings" "testing" "time" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) // RoutingSuite tests multi-layer routing with authentication middleware. type RoutingSuite struct{ BaseSuite } func TestRoutingSuite(t *testing.T) { suite.Run(t, new(RoutingSuite)) } func (s *RoutingSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("routing") s.composeUp() } func (s *RoutingSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } // authHandler implements the ForwardAuth protocol. // It validates Bearer tokens and adds X-User-Role and X-User-Name headers. func authHandler(w http.ResponseWriter, r *http.Request) { authHeader := r.Header.Get("Authorization") if authHeader == "" { w.WriteHeader(http.StatusUnauthorized) return } if !strings.HasPrefix(authHeader, "Bearer ") { w.WriteHeader(http.StatusUnauthorized) return } token := strings.TrimPrefix(authHeader, "Bearer ") role, username, ok := getUserByToken(token) if !ok { w.WriteHeader(http.StatusUnauthorized) return } // Set headers that will be forwarded by Traefik w.Header().Set("X-User-Role", role) w.Header().Set("X-User-Name", username) w.WriteHeader(http.StatusOK) } // getUserByToken returns the role and username for a given token. func getUserByToken(token string) (role, username string, ok bool) { users := map[string]struct { role string username string }{ "bob-token": {role: "admin", username: "bob"}, "jack-token": {role: "developer", username: "jack"}, "alice-token": {role: "guest", username: "alice"}, } u, exists := users[token] return u.role, u.username, exists } // TestMultiLayerRoutingWithAuth tests the complete multi layer routing scenario: // - Parent router matches path and applies authentication middleware // - Auth middleware validates token and adds role header // - Child routers route based on the role header added by the middleware func (s *RoutingSuite) TestMultiLayerRoutingWithAuth() { listener, err := net.Listen("tcp", "127.0.0.1:0") require.NoError(s.T(), err) defer listener.Close() _, authPort, err := net.SplitHostPort(listener.Addr().String()) require.NoError(s.T(), err) go func() { _ = http.Serve(listener, http.HandlerFunc(authHandler)) }() adminIP := s.getComposeServiceIP("whoami-admin") require.NotEmpty(s.T(), adminIP) developerIP := s.getComposeServiceIP("whoami-developer") require.NotEmpty(s.T(), developerIP) file := s.adaptFile("fixtures/routing/multi_layer_auth.toml", struct { AuthPort string AdminIP string DeveloperIP string }{ AuthPort: authPort, AdminIP: adminIP, DeveloperIP: developerIP, }) s.traefikCmd(withConfigFile(file)) err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 2*time.Second, try.BodyContains("parent-router")) require.NoError(s.T(), err) // Test 1: bob (admin role) routes to admin-service req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil) require.NoError(s.T(), err) req.Header.Set("Authorization", "Bearer bob-token") err = try.Request(req, 2*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("whoami-admin")) require.NoError(s.T(), err) // Test 2: jack (developer role) routes to developer-service req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil) require.NoError(s.T(), err) req.Header.Set("Authorization", "Bearer jack-token") err = try.Request(req, 2*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("whoami-developer")) require.NoError(s.T(), err) // Test 3: Invalid token returns 401 req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil) require.NoError(s.T(), err) req.Header.Set("Authorization", "Bearer invalid-token") err = try.Request(req, 2*time.Second, try.StatusCodeIs(http.StatusUnauthorized)) require.NoError(s.T(), err) // Test 4: Missing token returns 401 req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil) require.NoError(s.T(), err) err = try.Request(req, 2*time.Second, try.StatusCodeIs(http.StatusUnauthorized)) require.NoError(s.T(), err) // Test 5: Valid auth but role has no matching child router returns 404 req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil) require.NoError(s.T(), err) req.Header.Set("Authorization", "Bearer alice-token") err = try.Request(req, 2*time.Second, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/redis_test.go
integration/redis_test.go
package integration import ( "bytes" "encoding/json" "net" "net/http" "os" "path/filepath" "strings" "testing" "time" "github.com/kvtools/redis" "github.com/kvtools/valkeyrie" "github.com/kvtools/valkeyrie/store" "github.com/pmezard/go-difflib/difflib" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" "github.com/traefik/traefik/v3/pkg/api" ) // Redis test suites. type RedisSuite struct { BaseSuite kvClient store.Store redisEndpoints []string } func TestRedisSuite(t *testing.T) { suite.Run(t, new(RedisSuite)) } func (s *RedisSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("redis") s.composeUp() s.redisEndpoints = []string{} s.redisEndpoints = append(s.redisEndpoints, net.JoinHostPort(s.getComposeServiceIP("redis"), "6379")) kv, err := valkeyrie.NewStore( s.T().Context(), redis.StoreName, s.redisEndpoints, &redis.Config{}, ) require.NoError(s.T(), err, "Cannot create store redis") s.kvClient = kv // wait for redis err = try.Do(60*time.Second, try.KVExists(kv, "test")) require.NoError(s.T(), err) } func (s *RedisSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *RedisSuite) TestSimpleConfiguration() { file := s.adaptFile("fixtures/redis/simple.toml", struct{ RedisAddress string }{ RedisAddress: strings.Join(s.redisEndpoints, ","), }) data := map[string]string{ "traefik/http/routers/Router0/entryPoints/0": "web", "traefik/http/routers/Router0/middlewares/0": "compressor", "traefik/http/routers/Router0/middlewares/1": "striper", "traefik/http/routers/Router0/service": "simplesvc", "traefik/http/routers/Router0/rule": "Host(`kv1.localhost`)", "traefik/http/routers/Router0/priority": "42", "traefik/http/routers/Router0/tls": "true", "traefik/http/routers/Router1/rule": "Host(`kv2.localhost`)", "traefik/http/routers/Router1/priority": "42", "traefik/http/routers/Router1/tls/domains/0/main": "aaa.localhost", "traefik/http/routers/Router1/tls/domains/0/sans/0": "aaa.aaa.localhost", "traefik/http/routers/Router1/tls/domains/0/sans/1": "bbb.aaa.localhost", "traefik/http/routers/Router1/tls/domains/1/main": "bbb.localhost", "traefik/http/routers/Router1/tls/domains/1/sans/0": "aaa.bbb.localhost", "traefik/http/routers/Router1/tls/domains/1/sans/1": "bbb.bbb.localhost", "traefik/http/routers/Router1/entryPoints/0": "web", "traefik/http/routers/Router1/service": "simplesvc", "traefik/http/services/simplesvc/loadBalancer/servers/0/url": "http://10.0.1.1:8888", "traefik/http/services/simplesvc/loadBalancer/servers/1/url": "http://10.0.1.1:8889", "traefik/http/services/srvcA/loadBalancer/servers/0/url": "http://10.0.1.2:8888", "traefik/http/services/srvcA/loadBalancer/servers/1/url": "http://10.0.1.2:8889", "traefik/http/services/srvcB/loadBalancer/servers/0/url": "http://10.0.1.3:8888", "traefik/http/services/srvcB/loadBalancer/servers/1/url": "http://10.0.1.3:8889", "traefik/http/services/mirror/mirroring/service": "simplesvc", "traefik/http/services/mirror/mirroring/mirrors/0/name": "srvcA", "traefik/http/services/mirror/mirroring/mirrors/0/percent": "42", "traefik/http/services/mirror/mirroring/mirrors/1/name": "srvcB", "traefik/http/services/mirror/mirroring/mirrors/1/percent": "42", "traefik/http/services/Service03/weighted/services/0/name": "srvcA", "traefik/http/services/Service03/weighted/services/0/weight": "42", "traefik/http/services/Service03/weighted/services/1/name": "srvcB", "traefik/http/services/Service03/weighted/services/1/weight": "42", "traefik/http/middlewares/compressor/compress": "true", "traefik/http/middlewares/striper/stripPrefix/prefixes/0": "foo", "traefik/http/middlewares/striper/stripPrefix/prefixes/1": "bar", } for k, v := range data { err := s.kvClient.Put(s.T().Context(), k, []byte(v), nil) require.NoError(s.T(), err) } s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 2*time.Second, try.BodyContains(`"striper@redis":`, `"compressor@redis":`, `"srvcA@redis":`, `"srvcB@redis":`), ) require.NoError(s.T(), err) resp, err := http.Get("http://127.0.0.1:8080/api/rawdata") require.NoError(s.T(), err) var obtained api.RunTimeRepresentation err = json.NewDecoder(resp.Body).Decode(&obtained) require.NoError(s.T(), err) got, err := json.MarshalIndent(obtained, "", " ") require.NoError(s.T(), err) expectedJSON := filepath.FromSlash("testdata/rawdata-redis.json") if *updateExpected { err = os.WriteFile(expectedJSON, got, 0o666) require.NoError(s.T(), err) } expected, err := os.ReadFile(expectedJSON) require.NoError(s.T(), err) if !bytes.Equal(expected, got) { diff := difflib.UnifiedDiff{ FromFile: "Expected", A: difflib.SplitLines(string(expected)), ToFile: "Got", B: difflib.SplitLines(string(got)), Context: 3, } text, err := difflib.GetUnifiedDiffString(diff) require.NoError(s.T(), err, text) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/ratelimit_test.go
integration/ratelimit_test.go
package integration import ( "net" "net/http" "testing" "time" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) type RateLimitSuite struct { BaseSuite ServerIP string RedisEndpoint string } func TestRateLimitSuite(t *testing.T) { suite.Run(t, new(RateLimitSuite)) } func (s *RateLimitSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("ratelimit") s.composeUp() s.ServerIP = s.getComposeServiceIP("whoami1") s.RedisEndpoint = net.JoinHostPort(s.getComposeServiceIP("redis"), "6379") } func (s *RateLimitSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *RateLimitSuite) TestSimpleConfiguration() { file := s.adaptFile("fixtures/ratelimit/simple.toml", struct { Server1 string }{s.ServerIP}) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("ratelimit")) require.NoError(s.T(), err) start := time.Now() count := 0 for { err = try.GetRequest("http://127.0.0.1:8081/", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) count++ if count > 100 { break } } stop := time.Now() elapsed := stop.Sub(start) if elapsed < time.Second*99/100 { s.T().Fatalf("requests throughput was too fast wrt to rate limiting: 100 requests in %v", elapsed) } } func (s *RateLimitSuite) TestRedisRateLimitSimpleConfiguration() { file := s.adaptFile("fixtures/ratelimit/simple_redis.toml", struct { Server1 string RedisEndpoint string }{ Server1: s.ServerIP, RedisEndpoint: s.RedisEndpoint, }) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("ratelimit", "redis")) require.NoError(s.T(), err) start := time.Now() count := 0 for { err = try.GetRequest("http://127.0.0.1:8081/", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) count++ if count > 100 { break } } stop := time.Now() elapsed := stop.Sub(start) if elapsed < time.Second*99/100 { s.T().Fatalf("requests throughput was too fast wrt to rate limiting: 100 requests in %v", elapsed) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/tcp_healthcheck_test.go
integration/tcp_healthcheck_test.go
package integration import ( "net" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) // TCPHealthCheckSuite test suite for TCP health checks. type TCPHealthCheckSuite struct { BaseSuite whoamitcp1IP string whoamitcp2IP string } func TestTCPHealthCheckSuite(t *testing.T) { suite.Run(t, new(TCPHealthCheckSuite)) } func (s *TCPHealthCheckSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("tcp_healthcheck") s.composeUp() s.whoamitcp1IP = s.getComposeServiceIP("whoamitcp1") s.whoamitcp2IP = s.getComposeServiceIP("whoamitcp2") } func (s *TCPHealthCheckSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *TCPHealthCheckSuite) TestSimpleConfiguration() { file := s.adaptFile("fixtures/tcp_healthcheck/simple.toml", struct { Server1 string Server2 string }{s.whoamitcp1IP, s.whoamitcp2IP}) s.traefikCmd(withConfigFile(file)) // Wait for Traefik. err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("HostSNI(`*`)")) require.NoError(s.T(), err) // Test that we can consistently reach servers through load balancing. var ( successfulConnectionsWhoamitcp1 int successfulConnectionsWhoamitcp2 int ) for range 4 { out := s.whoIs("127.0.0.1:8093") require.NoError(s.T(), err) if strings.Contains(out, "whoamitcp1") { successfulConnectionsWhoamitcp1++ } if strings.Contains(out, "whoamitcp2") { successfulConnectionsWhoamitcp2++ } } assert.Equal(s.T(), 2, successfulConnectionsWhoamitcp1) assert.Equal(s.T(), 2, successfulConnectionsWhoamitcp2) // Stop one whoamitcp2 containers to simulate health check failure. conn, err := net.DialTimeout("tcp", s.whoamitcp2IP+":8080", time.Second) require.NoError(s.T(), err) s.T().Cleanup(func() { _ = conn.Close() }) s.composeStop("whoamitcp2") // Wait for the health check to detect the failure. time.Sleep(1 * time.Second) // Verify that the remaining server still responds. for range 3 { out := s.whoIs("127.0.0.1:8093") require.NoError(s.T(), err) assert.Contains(s.T(), out, "whoamitcp1") } } // connectTCP connects to the given TCP address and returns the response. func (s *TCPHealthCheckSuite) whoIs(addr string) string { s.T().Helper() conn, err := net.DialTimeout("tcp", addr, time.Second) require.NoError(s.T(), err) s.T().Cleanup(func() { _ = conn.Close() }) _, err = conn.Write([]byte("WHO")) require.NoError(s.T(), err) _ = conn.SetReadDeadline(time.Now().Add(2 * time.Second)) buffer := make([]byte, 1024) n, err := conn.Read(buffer) require.NoError(s.T(), err) return string(buffer[:n]) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/healthcheck_test.go
integration/healthcheck_test.go
package integration import ( "bytes" "fmt" "io" "net/http" "os" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) // HealthCheck test suites. type HealthCheckSuite struct { BaseSuite whoami1IP string whoami2IP string whoami3IP string whoami4IP string } func TestHealthCheckSuite(t *testing.T) { suite.Run(t, new(HealthCheckSuite)) } func (s *HealthCheckSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("healthcheck") s.composeUp() s.whoami1IP = s.getComposeServiceIP("whoami1") s.whoami2IP = s.getComposeServiceIP("whoami2") s.whoami3IP = s.getComposeServiceIP("whoami3") s.whoami4IP = s.getComposeServiceIP("whoami4") } func (s *HealthCheckSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *HealthCheckSuite) TestSimpleConfiguration() { file := s.adaptFile("fixtures/healthcheck/simple.toml", struct { Server1 string Server2 string }{s.whoami1IP, s.whoami2IP}) s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("Host(`test.localhost`)")) require.NoError(s.T(), err) frontendHealthReq, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/health", nil) require.NoError(s.T(), err) frontendHealthReq.Host = "test.localhost" err = try.Request(frontendHealthReq, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) // Fix all whoami health to 500 client := &http.Client{} whoamiHosts := []string{s.whoami1IP, s.whoami2IP} for _, whoami := range whoamiHosts { statusInternalServerErrorReq, err := http.NewRequest(http.MethodPost, "http://"+whoami+"/health", bytes.NewBufferString("500")) require.NoError(s.T(), err) _, err = client.Do(statusInternalServerErrorReq) require.NoError(s.T(), err) } // Verify no backend service is available due to failing health checks err = try.Request(frontendHealthReq, 3*time.Second, try.StatusCodeIs(http.StatusServiceUnavailable)) require.NoError(s.T(), err) // Change one whoami health to 200 statusOKReq1, err := http.NewRequest(http.MethodPost, "http://"+s.whoami1IP+"/health", bytes.NewBufferString("200")) require.NoError(s.T(), err) _, err = client.Do(statusOKReq1) require.NoError(s.T(), err) // Verify frontend health : after err = try.Request(frontendHealthReq, 3*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) frontendReq, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) frontendReq.Host = "test.localhost" // Check if whoami1 responds err = try.Request(frontendReq, 500*time.Millisecond, try.BodyContains(s.whoami1IP)) require.NoError(s.T(), err) // Check if the service with bad health check (whoami2) never respond. err = try.Request(frontendReq, 2*time.Second, try.BodyContains(s.whoami2IP)) assert.Error(s.T(), err) // TODO validate : run on 80 resp, err := http.Get("http://127.0.0.1:8000/") // Expected a 404 as we did not configure anything require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusNotFound, resp.StatusCode) } func (s *HealthCheckSuite) TestSimpleConfiguration_Passive() { file := s.adaptFile("fixtures/healthcheck/simple_passive.toml", struct { Server1 string }{s.whoami1IP}) s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("Host(`test.localhost`)")) require.NoError(s.T(), err) frontendHealthReq, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/health", nil) require.NoError(s.T(), err) frontendHealthReq.Host = "test.localhost" err = try.Request(frontendHealthReq, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) // Fix all whoami health to 500 client := &http.Client{} whoamiHosts := []string{s.whoami1IP, s.whoami2IP} for _, whoami := range whoamiHosts { statusInternalServerErrorReq, err := http.NewRequest(http.MethodPost, "http://"+whoami+"/health", bytes.NewBufferString("500")) require.NoError(s.T(), err) _, err = client.Do(statusInternalServerErrorReq) require.NoError(s.T(), err) } // First call, the passive health check is not yet triggered, so we expect a 500. err = try.Request(frontendHealthReq, 3*time.Second, try.StatusCodeIs(http.StatusInternalServerError)) require.NoError(s.T(), err) // Verify no backend service is available due to failing health checks err = try.Request(frontendHealthReq, 3*time.Second, try.StatusCodeIs(http.StatusServiceUnavailable)) require.NoError(s.T(), err) // Change one whoami health to 200 statusOKReq1, err := http.NewRequest(http.MethodPost, "http://"+s.whoami1IP+"/health", bytes.NewBufferString("200")) require.NoError(s.T(), err) _, err = client.Do(statusOKReq1) require.NoError(s.T(), err) // Verify frontend health : after err = try.Request(frontendHealthReq, 3*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) } func (s *HealthCheckSuite) TestMultipleEntrypoints() { file := s.adaptFile("fixtures/healthcheck/multiple-entrypoints.toml", struct { Server1 string Server2 string }{s.whoami1IP, s.whoami2IP}) s.traefikCmd(withConfigFile(file)) // Wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("Host(`test.localhost`)")) require.NoError(s.T(), err) // Check entrypoint http1 frontendHealthReq, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/health", nil) require.NoError(s.T(), err) frontendHealthReq.Host = "test.localhost" err = try.Request(frontendHealthReq, 5*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) // Check entrypoint http2 frontendHealthReq, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:9000/health", nil) require.NoError(s.T(), err) frontendHealthReq.Host = "test.localhost" err = try.Request(frontendHealthReq, 5*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) // Set the both whoami health to 500 client := &http.Client{} whoamiHosts := []string{s.whoami1IP, s.whoami2IP} for _, whoami := range whoamiHosts { statusInternalServerErrorReq, err := http.NewRequest(http.MethodPost, "http://"+whoami+"/health", bytes.NewBufferString("500")) require.NoError(s.T(), err) _, err = client.Do(statusInternalServerErrorReq) require.NoError(s.T(), err) } // Verify no backend service is available due to failing health checks err = try.Request(frontendHealthReq, 5*time.Second, try.StatusCodeIs(http.StatusServiceUnavailable)) require.NoError(s.T(), err) // reactivate the whoami2 statusInternalServerOkReq, err := http.NewRequest(http.MethodPost, "http://"+s.whoami2IP+"/health", bytes.NewBufferString("200")) require.NoError(s.T(), err) _, err = client.Do(statusInternalServerOkReq) require.NoError(s.T(), err) frontend1Req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) frontend1Req.Host = "test.localhost" frontend2Req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:9000/", nil) require.NoError(s.T(), err) frontend2Req.Host = "test.localhost" // Check if whoami1 never responds err = try.Request(frontend2Req, 2*time.Second, try.BodyContains(s.whoami1IP)) assert.Error(s.T(), err) // Check if whoami1 never responds err = try.Request(frontend1Req, 2*time.Second, try.BodyContains(s.whoami1IP)) assert.Error(s.T(), err) } func (s *HealthCheckSuite) TestPortOverload() { // Set one whoami health to 200 client := &http.Client{} statusInternalServerErrorReq, err := http.NewRequest(http.MethodPost, "http://"+s.whoami1IP+"/health", bytes.NewBufferString("200")) require.NoError(s.T(), err) _, err = client.Do(statusInternalServerErrorReq) require.NoError(s.T(), err) file := s.adaptFile("fixtures/healthcheck/port_overload.toml", struct { Server1 string }{s.whoami1IP}) s.traefikCmd(withConfigFile(file)) // wait for traefik err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("Host(`test.localhost`)")) require.NoError(s.T(), err) frontendHealthReq, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/health", nil) require.NoError(s.T(), err) frontendHealthReq.Host = "test.localhost" // We test bad gateway because we use an invalid port for the backend err = try.Request(frontendHealthReq, 500*time.Millisecond, try.StatusCodeIs(http.StatusBadGateway)) require.NoError(s.T(), err) // Set one whoami health to 500 statusInternalServerErrorReq, err = http.NewRequest(http.MethodPost, "http://"+s.whoami1IP+"/health", bytes.NewBufferString("500")) require.NoError(s.T(), err) _, err = client.Do(statusInternalServerErrorReq) require.NoError(s.T(), err) // Verify no backend service is available due to failing health checks err = try.Request(frontendHealthReq, 3*time.Second, try.StatusCodeIs(http.StatusServiceUnavailable)) require.NoError(s.T(), err) } // Checks if all the loadbalancers created will correctly update the server status. func (s *HealthCheckSuite) TestMultipleRoutersOnSameService() { file := s.adaptFile("fixtures/healthcheck/multiple-routers-one-same-service.toml", struct { Server1 string }{s.whoami1IP}) s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("Host(`test.localhost`)")) require.NoError(s.T(), err) // Set whoami health to 200 to be sure to start with the wanted status client := &http.Client{} statusOkReq, err := http.NewRequest(http.MethodPost, "http://"+s.whoami1IP+"/health", bytes.NewBufferString("200")) require.NoError(s.T(), err) _, err = client.Do(statusOkReq) require.NoError(s.T(), err) // check healthcheck on web1 entrypoint healthReqWeb1, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/health", nil) require.NoError(s.T(), err) healthReqWeb1.Host = "test.localhost" err = try.Request(healthReqWeb1, 1*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) // check healthcheck on web2 entrypoint healthReqWeb2, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:9000/health", nil) require.NoError(s.T(), err) healthReqWeb2.Host = "test.localhost" err = try.Request(healthReqWeb2, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) // Set whoami health to 500 statusInternalServerErrorReq, err := http.NewRequest(http.MethodPost, "http://"+s.whoami1IP+"/health", bytes.NewBufferString("500")) require.NoError(s.T(), err) _, err = client.Do(statusInternalServerErrorReq) require.NoError(s.T(), err) // Verify no backend service is available due to failing health checks err = try.Request(healthReqWeb1, 3*time.Second, try.StatusCodeIs(http.StatusServiceUnavailable)) require.NoError(s.T(), err) err = try.Request(healthReqWeb2, 3*time.Second, try.StatusCodeIs(http.StatusServiceUnavailable)) require.NoError(s.T(), err) // Change one whoami health to 200 statusOKReq1, err := http.NewRequest(http.MethodPost, "http://"+s.whoami1IP+"/health", bytes.NewBufferString("200")) require.NoError(s.T(), err) _, err = client.Do(statusOKReq1) require.NoError(s.T(), err) // Verify health check err = try.Request(healthReqWeb1, 3*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) err = try.Request(healthReqWeb2, 3*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) } func (s *HealthCheckSuite) TestPropagate() { file := s.adaptFile("fixtures/healthcheck/propagate.toml", struct { Server1 string Server2 string Server3 string Server4 string }{s.whoami1IP, s.whoami2IP, s.whoami3IP, s.whoami4IP}) s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("Host(`root.localhost`)")) require.NoError(s.T(), err) rootReq, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000", nil) require.NoError(s.T(), err) rootReq.Host = "root.localhost" err = try.Request(rootReq, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) // Bring whoami1 and whoami3 down client := http.Client{ Timeout: 10 * time.Second, } whoamiHosts := []string{s.whoami1IP, s.whoami3IP} for _, whoami := range whoamiHosts { statusInternalServerErrorReq, err := http.NewRequest(http.MethodPost, "http://"+whoami+"/health", bytes.NewBufferString("500")) require.NoError(s.T(), err) _, err = client.Do(statusInternalServerErrorReq) require.NoError(s.T(), err) } try.Sleep(time.Second) want2 := `IP: ` + s.whoami2IP want4 := `IP: ` + s.whoami4IP // Verify load-balancing on root still works, and that we're getting an alternation between wsp2, and wsp4. reachedServers := make(map[string]int) for range 4 { resp, err := client.Do(rootReq) require.NoError(s.T(), err) body, err := io.ReadAll(resp.Body) require.NoError(s.T(), err) if reachedServers[s.whoami4IP] > reachedServers[s.whoami2IP] { assert.Contains(s.T(), string(body), want2) reachedServers[s.whoami2IP]++ continue } if reachedServers[s.whoami2IP] > reachedServers[s.whoami4IP] { assert.Contains(s.T(), string(body), want4) reachedServers[s.whoami4IP]++ continue } // First iteration, so we can't tell whether it's going to be wsp2, or wsp4. if strings.Contains(string(body), `IP: `+s.whoami4IP) { reachedServers[s.whoami4IP]++ continue } if strings.Contains(string(body), `IP: `+s.whoami2IP) { reachedServers[s.whoami2IP]++ continue } } assert.Equal(s.T(), 2, reachedServers[s.whoami2IP]) assert.Equal(s.T(), 2, reachedServers[s.whoami4IP]) fooReq, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000", nil) require.NoError(s.T(), err) fooReq.Host = "foo.localhost" // Verify load-balancing on foo still works, and that we're getting wsp2, wsp2, wsp2, wsp2, etc. want := `IP: ` + s.whoami2IP for range 4 { resp, err := client.Do(fooReq) require.NoError(s.T(), err) body, err := io.ReadAll(resp.Body) require.NoError(s.T(), err) assert.Contains(s.T(), string(body), want) } barReq, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000", nil) require.NoError(s.T(), err) barReq.Host = "bar.localhost" // Verify load-balancing on bar still works, and that we're getting wsp2, wsp2, wsp2, wsp2, etc. want = `IP: ` + s.whoami2IP for range 4 { resp, err := client.Do(barReq) require.NoError(s.T(), err) body, err := io.ReadAll(resp.Body) require.NoError(s.T(), err) assert.Contains(s.T(), string(body), want) } // Bring whoami2 and whoami4 down whoamiHosts = []string{s.whoami2IP, s.whoami4IP} for _, whoami := range whoamiHosts { statusInternalServerErrorReq, err := http.NewRequest(http.MethodPost, "http://"+whoami+"/health", bytes.NewBufferString("500")) require.NoError(s.T(), err) _, err = client.Do(statusInternalServerErrorReq) require.NoError(s.T(), err) } try.Sleep(time.Second) // Verify that everything is down, and that we get 503s everywhere. for range 2 { resp, err := client.Do(rootReq) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusServiceUnavailable, resp.StatusCode) resp, err = client.Do(fooReq) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusServiceUnavailable, resp.StatusCode) resp, err = client.Do(barReq) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusServiceUnavailable, resp.StatusCode) } // Bring everything back up. whoamiHosts = []string{s.whoami1IP, s.whoami2IP, s.whoami3IP, s.whoami4IP} for _, whoami := range whoamiHosts { statusOKReq, err := http.NewRequest(http.MethodPost, "http://"+whoami+"/health", bytes.NewBufferString("200")) require.NoError(s.T(), err) _, err = client.Do(statusOKReq) require.NoError(s.T(), err) } try.Sleep(time.Second) // Verify everything is up on root router. reachedServers = make(map[string]int) for range 4 { resp, err := client.Do(rootReq) require.NoError(s.T(), err) body, err := io.ReadAll(resp.Body) require.NoError(s.T(), err) if strings.Contains(string(body), `IP: `+s.whoami1IP) { reachedServers[s.whoami1IP]++ continue } if strings.Contains(string(body), `IP: `+s.whoami2IP) { reachedServers[s.whoami2IP]++ continue } if strings.Contains(string(body), `IP: `+s.whoami3IP) { reachedServers[s.whoami3IP]++ continue } if strings.Contains(string(body), `IP: `+s.whoami4IP) { reachedServers[s.whoami4IP]++ continue } } assert.Equal(s.T(), 1, reachedServers[s.whoami1IP]) assert.Equal(s.T(), 1, reachedServers[s.whoami2IP]) assert.Equal(s.T(), 1, reachedServers[s.whoami3IP]) assert.Equal(s.T(), 1, reachedServers[s.whoami4IP]) // Verify everything is up on foo router. reachedServers = make(map[string]int) for range 4 { resp, err := client.Do(fooReq) require.NoError(s.T(), err) body, err := io.ReadAll(resp.Body) require.NoError(s.T(), err) if strings.Contains(string(body), `IP: `+s.whoami1IP) { reachedServers[s.whoami1IP]++ continue } if strings.Contains(string(body), `IP: `+s.whoami2IP) { reachedServers[s.whoami2IP]++ continue } if strings.Contains(string(body), `IP: `+s.whoami3IP) { reachedServers[s.whoami3IP]++ continue } if strings.Contains(string(body), `IP: `+s.whoami4IP) { reachedServers[s.whoami4IP]++ continue } } assert.Equal(s.T(), 2, reachedServers[s.whoami1IP]) assert.Equal(s.T(), 1, reachedServers[s.whoami2IP]) assert.Equal(s.T(), 1, reachedServers[s.whoami3IP]) assert.Equal(s.T(), 0, reachedServers[s.whoami4IP]) // Verify everything is up on bar router. reachedServers = make(map[string]int) for range 4 { resp, err := client.Do(barReq) require.NoError(s.T(), err) body, err := io.ReadAll(resp.Body) require.NoError(s.T(), err) if strings.Contains(string(body), `IP: `+s.whoami1IP) { reachedServers[s.whoami1IP]++ continue } if strings.Contains(string(body), `IP: `+s.whoami2IP) { reachedServers[s.whoami2IP]++ continue } if strings.Contains(string(body), `IP: `+s.whoami3IP) { reachedServers[s.whoami3IP]++ continue } if strings.Contains(string(body), `IP: `+s.whoami4IP) { reachedServers[s.whoami4IP]++ continue } } assert.Equal(s.T(), 2, reachedServers[s.whoami1IP]) assert.Equal(s.T(), 1, reachedServers[s.whoami2IP]) assert.Equal(s.T(), 1, reachedServers[s.whoami3IP]) assert.Equal(s.T(), 0, reachedServers[s.whoami4IP]) } func (s *HealthCheckSuite) TestPropagateNoHealthCheck() { file := s.adaptFile("fixtures/healthcheck/propagate_no_healthcheck.toml", struct { Server1 string }{s.whoami1IP}) s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("Host(`noop.localhost`)"), try.BodyNotContains("Host(`root.localhost`)")) require.NoError(s.T(), err) rootReq, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000", nil) require.NoError(s.T(), err) rootReq.Host = "root.localhost" err = try.Request(rootReq, 500*time.Millisecond, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) } func (s *HealthCheckSuite) TestPropagateReload() { // Setup a WSP service without the healthcheck enabled (wsp-service1) withoutHealthCheck := s.adaptFile("fixtures/healthcheck/reload_without_healthcheck.toml", struct { Server1 string Server2 string }{s.whoami1IP, s.whoami2IP}) withHealthCheck := s.adaptFile("fixtures/healthcheck/reload_with_healthcheck.toml", struct { Server1 string Server2 string }{s.whoami1IP, s.whoami2IP}) s.traefikCmd(withConfigFile(withoutHealthCheck)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("Host(`root.localhost`)")) require.NoError(s.T(), err) // Allow one of the underlying services on it to fail all servers HC (whoami2) client := http.Client{ Timeout: 10 * time.Second, } statusOKReq, err := http.NewRequest(http.MethodPost, "http://"+s.whoami2IP+"/health", bytes.NewBufferString("500")) require.NoError(s.T(), err) _, err = client.Do(statusOKReq) require.NoError(s.T(), err) rootReq, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000", nil) require.NoError(s.T(), err) rootReq.Host = "root.localhost" // Check the failed service (whoami2) is getting requests, but answer 500 err = try.Request(rootReq, 500*time.Millisecond, try.StatusCodeIs(http.StatusServiceUnavailable)) require.NoError(s.T(), err) // Enable the healthcheck on the root WSP (wsp-service1) and let Traefik reload the config fr1, err := os.OpenFile(withoutHealthCheck, os.O_APPEND|os.O_WRONLY, 0o644) assert.NotNil(s.T(), fr1) require.NoError(s.T(), err) err = fr1.Truncate(0) require.NoError(s.T(), err) fr2, err := os.ReadFile(withHealthCheck) require.NoError(s.T(), err) _, err = fmt.Fprint(fr1, string(fr2)) require.NoError(s.T(), err) err = fr1.Close() require.NoError(s.T(), err) // Waiting for the reflected change. err = try.Request(rootReq, 5*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) // Check the failed service (whoami2) is not getting requests wantIPs := []string{s.whoami1IP, s.whoami1IP, s.whoami1IP, s.whoami1IP} for _, ip := range wantIPs { err = try.Request(rootReq, 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("IP: "+ip)) require.NoError(s.T(), err) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/simple_test.go
integration/simple_test.go
package integration import ( "bufio" "bytes" "crypto" "crypto/rand" "crypto/tls" "encoding/json" "fmt" "io" "net" "net/http" "net/http/httptest" "os" "regexp" "strings" "sync/atomic" "syscall" "testing" "time" "github.com/rs/zerolog/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" "github.com/traefik/traefik/v3/pkg/config/dynamic" "golang.org/x/crypto/ocsp" ) // SimpleSuite tests suite. type SimpleSuite struct{ BaseSuite } func TestSimpleSuite(t *testing.T) { suite.Run(t, new(SimpleSuite)) } func (s *SimpleSuite) SetupSuite() { s.BaseSuite.SetupSuite() } func (s *SimpleSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *SimpleSuite) TestInvalidConfigShouldFail() { _, output := s.cmdTraefik(withConfigFile("fixtures/invalid_configuration.toml")) err := try.Do(500*time.Millisecond, func() error { expected := "expected '.' or '=', but got '{' instead" actual := output.String() if !strings.Contains(actual, expected) { return fmt.Errorf("got %s, wanted %s", actual, expected) } return nil }) require.NoError(s.T(), err) } func (s *SimpleSuite) TestSimpleDefaultConfig() { s.cmdTraefik(withConfigFile("fixtures/simple_default.toml")) // Expected a 404 as we did not configure anything err := try.GetRequest("http://127.0.0.1:8000/", 1*time.Second, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) } func (s *SimpleSuite) TestSimpleFastProxy() { var callCount int srv1 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { assert.Contains(s.T(), req.Header, "X-Traefik-Fast-Proxy") callCount++ })) defer srv1.Close() file := s.adaptFile("fixtures/simple_fastproxy.toml", struct { Server string }{ Server: srv1.URL, }) s.traefikCmd(withConfigFile(file), "--log.level=DEBUG") // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("127.0.0.1")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/", time.Second) require.NoError(s.T(), err) assert.GreaterOrEqual(s.T(), 1, callCount) } func (s *SimpleSuite) TestXForwardedForDisabled() { srv1 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { // Echo back the X-Forwarded-For header xff := req.Header.Get("X-Forwarded-For") _, _ = rw.Write([]byte(xff)) })) defer srv1.Close() dynamicConf := s.adaptFile("resources/compose/x_forwarded_for.toml", struct { Server string }{ Server: srv1.URL, }) staticConf := s.adaptFile("fixtures/x_forwarded_for.toml", struct { DynamicConfPath string }{ DynamicConfPath: dynamicConf, }) s.traefikCmd(withConfigFile(staticConf)) // Wait for Traefik to start err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("service1")) require.NoError(s.T(), err) // Test with appendXForwardedFor = false req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) // Set an existing X-Forwarded-For header req.Header.Set("X-Forwarded-For", "1.2.3.4") resp, err := http.DefaultClient.Do(req) require.NoError(s.T(), err) defer resp.Body.Close() body, err := io.ReadAll(resp.Body) require.NoError(s.T(), err) // The backend should receive the original X-Forwarded-For header unchanged // (Traefik should NOT append RemoteAddr when appendXForwardedFor = false) assert.Equal(s.T(), "1.2.3.4", string(body)) } func (s *SimpleSuite) TestXForwardedForEnabled() { srv1 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { // Echo back the X-Forwarded-For header xff := req.Header.Get("X-Forwarded-For") _, _ = rw.Write([]byte(xff)) })) defer srv1.Close() dynamicConf := s.adaptFile("resources/compose/x_forwarded_for.toml", struct { Server string }{ Server: srv1.URL, }) // Use a config with appendXForwardedFor = true staticConf := s.adaptFile("fixtures/x_forwarded_for_enabled.toml", struct { DynamicConfPath string }{ DynamicConfPath: dynamicConf, }) s.traefikCmd(withConfigFile(staticConf)) // Wait for Traefik to start err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("service1")) require.NoError(s.T(), err) // Test with default appendXForwardedFor = true req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) // Set an existing X-Forwarded-For header req.Header.Set("X-Forwarded-For", "1.2.3.4") resp, err := http.DefaultClient.Do(req) require.NoError(s.T(), err) defer resp.Body.Close() body, err := io.ReadAll(resp.Body) require.NoError(s.T(), err) // The backend should receive the X-Forwarded-For header with RemoteAddr appended // (should be "1.2.3.4, 127.0.0.1" since the request comes from localhost) assert.Contains(s.T(), string(body), "1.2.3.4,") assert.Contains(s.T(), string(body), "127.0.0.1") } func (s *SimpleSuite) TestXForwardedForDisabledFastProxy() { srv1 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { // Verify FastProxy is being used assert.Contains(s.T(), req.Header, "X-Traefik-Fast-Proxy") // Echo back the X-Forwarded-For header xff := req.Header.Get("X-Forwarded-For") _, _ = rw.Write([]byte(xff)) })) defer srv1.Close() dynamicConf := s.adaptFile("resources/compose/x_forwarded_for.toml", struct { Server string }{ Server: srv1.URL, }) staticConf := s.adaptFile("fixtures/x_forwarded_for_fastproxy.toml", struct { DynamicConfPath string }{ DynamicConfPath: dynamicConf, }) s.traefikCmd(withConfigFile(staticConf)) // Wait for Traefik to start err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("service1")) require.NoError(s.T(), err) // Test with appendXForwardedFor = false req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) // Set an existing X-Forwarded-For header req.Header.Set("X-Forwarded-For", "1.2.3.4") resp, err := http.DefaultClient.Do(req) require.NoError(s.T(), err) defer resp.Body.Close() body, err := io.ReadAll(resp.Body) require.NoError(s.T(), err) // The backend should receive the original X-Forwarded-For header unchanged // (FastProxy should NOT append RemoteAddr when notAppendXForwardedFor = true) assert.Equal(s.T(), "1.2.3.4", string(body)) } func (s *SimpleSuite) TestXForwardedForEnabledFastProxy() { srv1 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { // Verify FastProxy is being used assert.Contains(s.T(), req.Header, "X-Traefik-Fast-Proxy") // Echo back the X-Forwarded-For header xff := req.Header.Get("X-Forwarded-For") _, _ = rw.Write([]byte(xff)) })) defer srv1.Close() dynamicConf := s.adaptFile("resources/compose/x_forwarded_for.toml", struct { Server string }{ Server: srv1.URL, }) // Use a config with appendXForwardedFor = false (default) staticConf := s.adaptFile("fixtures/x_forwarded_for_fastproxy_enabled.toml", struct { DynamicConfPath string }{ DynamicConfPath: dynamicConf, }) s.traefikCmd(withConfigFile(staticConf)) // Wait for Traefik to start err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("service1")) require.NoError(s.T(), err) // Test with default appendXForwardedFor = true req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) // Set an existing X-Forwarded-For header req.Header.Set("X-Forwarded-For", "1.2.3.4") resp, err := http.DefaultClient.Do(req) require.NoError(s.T(), err) defer resp.Body.Close() body, err := io.ReadAll(resp.Body) require.NoError(s.T(), err) // The backend should receive the X-Forwarded-For header with RemoteAddr appended // (FastProxy should append RemoteAddr when notAppendXForwardedFor = false) // (should be "1.2.3.4, 127.0.0.1" since the request comes from localhost) assert.Contains(s.T(), string(body), "1.2.3.4,") assert.Contains(s.T(), string(body), "127.0.0.1") } func (s *SimpleSuite) TestWithWebConfig() { s.cmdTraefik(withConfigFile("fixtures/simple_web.toml")) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) } func (s *SimpleSuite) TestPrintHelp() { _, output := s.cmdTraefik("--help") err := try.Do(500*time.Millisecond, func() error { expected := "Usage:" notExpected := "panic:" actual := output.String() if strings.Contains(actual, notExpected) { return fmt.Errorf("got %s", actual) } if !strings.Contains(actual, expected) { return fmt.Errorf("got %s, wanted %s", actual, expected) } return nil }) require.NoError(s.T(), err) } func (s *SimpleSuite) TestRequestAcceptGraceTimeout() { s.createComposeProject("reqacceptgrace") s.composeUp() defer s.composeDown() whoamiURL := "http://" + net.JoinHostPort(s.getComposeServiceIP("whoami"), "80") file := s.adaptFile("fixtures/reqacceptgrace.toml", struct { Server string }{whoamiURL}) cmd, _ := s.cmdTraefik(withConfigFile(file)) // Wait for Traefik to turn ready. err := try.GetRequest("http://127.0.0.1:8000/", 2*time.Second, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) // Make sure exposed service is ready. err = try.GetRequest("http://127.0.0.1:8000/service", 3*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) // Check that /ping endpoint is responding with 200. err = try.GetRequest("http://127.0.0.1:8001/ping", 3*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) // Send SIGTERM to Traefik. proc, err := os.FindProcess(cmd.Process.Pid) require.NoError(s.T(), err) err = proc.Signal(syscall.SIGTERM) require.NoError(s.T(), err) // Give Traefik time to process the SIGTERM and send a request half-way // into the request accepting grace period, by which requests should // still get served. time.Sleep(5 * time.Second) resp, err := http.Get("http://127.0.0.1:8000/service") require.NoError(s.T(), err) defer resp.Body.Close() assert.Equal(s.T(), http.StatusOK, resp.StatusCode) // ping endpoint should now return a Service Unavailable. resp, err = http.Get("http://127.0.0.1:8001/ping") require.NoError(s.T(), err) defer resp.Body.Close() assert.Equal(s.T(), http.StatusServiceUnavailable, resp.StatusCode) // Expect Traefik to shut down gracefully once the request accepting grace // period has elapsed. waitErr := make(chan error) go func() { waitErr <- cmd.Wait() }() select { case err := <-waitErr: require.NoError(s.T(), err) case <-time.After(10 * time.Second): // By now we are ~5 seconds out of the request accepting grace period // (start + 5 seconds sleep prior to the mid-grace period request + // 10 seconds timeout = 15 seconds > 10 seconds grace period). // Something must have gone wrong if we still haven't terminated at // this point. s.T().Fatal("Traefik did not terminate in time") } } func (s *SimpleSuite) TestCustomPingTerminationStatusCode() { file := s.adaptFile("fixtures/custom_ping_termination_status_code.toml", struct{}{}) cmd, _ := s.cmdTraefik(withConfigFile(file)) // Wait for Traefik to turn ready. err := try.GetRequest("http://127.0.0.1:8001/", 2*time.Second, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) // Check that /ping endpoint is responding with 200. err = try.GetRequest("http://127.0.0.1:8001/ping", 3*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) // Send SIGTERM to Traefik. proc, err := os.FindProcess(cmd.Process.Pid) require.NoError(s.T(), err) err = proc.Signal(syscall.SIGTERM) require.NoError(s.T(), err) // ping endpoint should now return a Service Unavailable. err = try.GetRequest("http://127.0.0.1:8001/ping", 2*time.Second, try.StatusCodeIs(http.StatusNoContent)) require.NoError(s.T(), err) } func (s *SimpleSuite) TestStatsWithMultipleEntryPoint() { s.T().Skip("Stats is missing") s.createComposeProject("stats") s.composeUp() defer s.composeDown() whoami1URL := "http://" + net.JoinHostPort(s.getComposeServiceIP("whoami1"), "80") whoami2URL := "http://" + net.JoinHostPort(s.getComposeServiceIP("whoami2"), "80") file := s.adaptFile("fixtures/simple_stats.toml", struct { Server1 string Server2 string }{whoami1URL, whoami2URL}) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api", 1*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("PathPrefix")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/whoami", 1*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8080/whoami", 1*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8080/health", 1*time.Second, try.BodyContains(`"total_status_code_count":{"200":2}`)) require.NoError(s.T(), err) } func (s *SimpleSuite) TestNoAuthOnPing() { s.T().Skip("Waiting for new api handler implementation") s.createComposeProject("base") s.composeUp() defer s.composeDown() file := s.adaptFile("./fixtures/simple_auth.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8001/api/rawdata", 2*time.Second, try.StatusCodeIs(http.StatusUnauthorized)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8001/ping", 1*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) } func (s *SimpleSuite) TestDefaultEntryPointHTTP() { s.createComposeProject("base") s.composeUp() defer s.composeDown() s.traefikCmd("--entryPoints.http.Address=:8000", "--log.level=DEBUG", "--providers.docker", "--api.insecure") err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("PathPrefix")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/whoami", 1*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) } func (s *SimpleSuite) TestWithNonExistingEntryPoint() { s.createComposeProject("base") s.composeUp() defer s.composeDown() s.traefikCmd("--entryPoints.http.Address=:8000", "--log.level=DEBUG", "--providers.docker", "--api.insecure") err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("PathPrefix")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/whoami", 1*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) } func (s *SimpleSuite) TestMetricsPrometheusDefaultEntryPoint() { s.createComposeProject("base") s.composeUp() defer s.composeDown() s.traefikCmd("--entryPoints.http.Address=:8000", "--api.insecure", "--metrics.prometheus.buckets=0.1,0.3,1.2,5.0", "--providers.docker", "--metrics.prometheus.addrouterslabels=true", "--log.level=DEBUG") err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("PathPrefix(`/whoami`)")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/whoami", 1*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8080/metrics", 1*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8080/metrics", 1*time.Second, try.BodyContains("_router_")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8080/metrics", 1*time.Second, try.BodyContains("_entrypoint_")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8080/metrics", 1*time.Second, try.BodyContains("_service_")) require.NoError(s.T(), err) // No metrics for internals. err = try.GetRequest("http://127.0.0.1:8080/metrics", 1*time.Second, try.BodyNotContains("router=\"api@internal\"", "service=\"api@internal\"")) require.NoError(s.T(), err) } func (s *SimpleSuite) TestMetricsPrometheusTwoRoutersOneService() { s.createComposeProject("base") s.composeUp() defer s.composeDown() s.traefikCmd("--entryPoints.http.Address=:8000", "--api.insecure", "--metrics.prometheus.buckets=0.1,0.3,1.2,5.0", "--providers.docker", "--metrics.prometheus.addentrypointslabels=false", "--metrics.prometheus.addrouterslabels=true", "--log.level=DEBUG") err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("PathPrefix")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/whoami", 1*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/whoami2", 1*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) // adding a loop to test if metrics are not deleted for range 10 { request, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/metrics", nil) require.NoError(s.T(), err) response, err := http.DefaultClient.Do(request) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusOK, response.StatusCode) body, err := io.ReadAll(response.Body) require.NoError(s.T(), err) // Reqs count of 1 for both routers assert.Contains(s.T(), string(body), "traefik_router_requests_total{code=\"200\",method=\"GET\",protocol=\"http\",router=\"router1@docker\",service=\"whoami1@docker\"} 1") assert.Contains(s.T(), string(body), "traefik_router_requests_total{code=\"200\",method=\"GET\",protocol=\"http\",router=\"router2@docker\",service=\"whoami1@docker\"} 1") // Reqs count of 2 for service behind both routers assert.Contains(s.T(), string(body), "traefik_service_requests_total{code=\"200\",method=\"GET\",protocol=\"http\",service=\"whoami1@docker\"} 2") } } // TestMetricsWithBufferingMiddleware checks that the buffering middleware // (which introduces its own response writer in the chain), does not interfere with // the capture middleware on which the metrics mechanism relies. func (s *SimpleSuite) TestMetricsWithBufferingMiddleware() { s.createComposeProject("base") s.composeUp() defer s.composeDown() server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte("MORE THAN TEN BYTES IN RESPONSE")) })) server.Start() defer server.Close() file := s.adaptFile("fixtures/simple_metrics_with_buffer_middleware.toml", struct{ IP string }{IP: strings.TrimPrefix(server.URL, "http://")}) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("PathPrefix(`/without`)")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8001/without", 1*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8002/with-req", strings.NewReader("MORE THAN TEN BYTES IN REQUEST")) require.NoError(s.T(), err) // The request should fail because the body is too large. err = try.Request(req, 1*time.Second, try.StatusCodeIs(http.StatusRequestEntityTooLarge)) require.NoError(s.T(), err) // The request should fail because the response exceeds the configured limit. err = try.GetRequest("http://127.0.0.1:8003/with-resp", 1*time.Second, try.StatusCodeIs(http.StatusInternalServerError)) require.NoError(s.T(), err) request, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/metrics", nil) require.NoError(s.T(), err) response, err := http.DefaultClient.Do(request) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusOK, response.StatusCode) body, err := io.ReadAll(response.Body) require.NoError(s.T(), err) // For allowed requests and responses, the entrypoint and service metrics have the same status code. assert.Contains(s.T(), string(body), "traefik_entrypoint_requests_total{code=\"200\",entrypoint=\"webA\",method=\"GET\",protocol=\"http\"} 1") assert.Contains(s.T(), string(body), "traefik_entrypoint_requests_bytes_total{code=\"200\",entrypoint=\"webA\",method=\"GET\",protocol=\"http\"} 0") assert.Contains(s.T(), string(body), "traefik_entrypoint_responses_bytes_total{code=\"200\",entrypoint=\"webA\",method=\"GET\",protocol=\"http\"} 31") assert.Contains(s.T(), string(body), "traefik_service_requests_total{code=\"200\",method=\"GET\",protocol=\"http\",service=\"service-without@file\"} 1") assert.Contains(s.T(), string(body), "traefik_service_requests_bytes_total{code=\"200\",method=\"GET\",protocol=\"http\",service=\"service-without@file\"} 0") assert.Contains(s.T(), string(body), "traefik_service_responses_bytes_total{code=\"200\",method=\"GET\",protocol=\"http\",service=\"service-without@file\"} 31") // For forbidden requests, the entrypoints have metrics, the services don't. assert.Contains(s.T(), string(body), "traefik_entrypoint_requests_total{code=\"413\",entrypoint=\"webB\",method=\"GET\",protocol=\"http\"} 1") assert.Contains(s.T(), string(body), "traefik_entrypoint_requests_bytes_total{code=\"413\",entrypoint=\"webB\",method=\"GET\",protocol=\"http\"} 0") assert.Contains(s.T(), string(body), "traefik_entrypoint_responses_bytes_total{code=\"413\",entrypoint=\"webB\",method=\"GET\",protocol=\"http\"} 24") // For disallowed responses, the entrypoint and service metrics don't have the same status code. assert.Contains(s.T(), string(body), "traefik_entrypoint_requests_bytes_total{code=\"500\",entrypoint=\"webC\",method=\"GET\",protocol=\"http\"} 0") assert.Contains(s.T(), string(body), "traefik_entrypoint_requests_total{code=\"500\",entrypoint=\"webC\",method=\"GET\",protocol=\"http\"} 1") assert.Contains(s.T(), string(body), "traefik_entrypoint_responses_bytes_total{code=\"500\",entrypoint=\"webC\",method=\"GET\",protocol=\"http\"} 21") assert.Contains(s.T(), string(body), "traefik_service_requests_bytes_total{code=\"200\",method=\"GET\",protocol=\"http\",service=\"service-resp@file\"} 0") assert.Contains(s.T(), string(body), "traefik_service_requests_total{code=\"200\",method=\"GET\",protocol=\"http\",service=\"service-resp@file\"} 1") assert.Contains(s.T(), string(body), "traefik_service_responses_bytes_total{code=\"200\",method=\"GET\",protocol=\"http\",service=\"service-resp@file\"} 31") } func (s *SimpleSuite) TestMultipleProviderSameBackendName() { s.createComposeProject("base") s.composeUp() defer s.composeDown() whoami1IP := s.getComposeServiceIP("whoami1") whoami2IP := s.getComposeServiceIP("whoami2") file := s.adaptFile("fixtures/multiple_provider.toml", struct{ IP string }{IP: whoami2IP}) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("PathPrefix")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/whoami", 1*time.Second, try.BodyContains(whoami1IP)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/file", 1*time.Second, try.BodyContains(whoami2IP)) require.NoError(s.T(), err) } func (s *SimpleSuite) TestIPStrategyAllowlist() { s.createComposeProject("allowlist") s.composeUp() defer s.composeDown() s.traefikCmd(withConfigFile("fixtures/simple_allowlist.toml")) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 2*time.Second, try.BodyContains("override")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 2*time.Second, try.BodyContains("override.remoteaddr.allowlist.docker.local")) require.NoError(s.T(), err) testCases := []struct { desc string xForwardedFor string host string expectedStatusCode int }{ { desc: "override remote addr reject", xForwardedFor: "8.8.8.8,8.8.8.8", host: "override.remoteaddr.allowlist.docker.local", expectedStatusCode: 403, }, { desc: "override depth accept", xForwardedFor: "8.8.8.8,10.0.0.1,127.0.0.1", host: "override.depth.allowlist.docker.local", expectedStatusCode: 200, }, { desc: "override depth reject", xForwardedFor: "10.0.0.1,8.8.8.8,127.0.0.1", host: "override.depth.allowlist.docker.local", expectedStatusCode: 403, }, { desc: "override excludedIPs reject", xForwardedFor: "10.0.0.3,10.0.0.1,10.0.0.2", host: "override.excludedips.allowlist.docker.local", expectedStatusCode: 403, }, { desc: "override excludedIPs accept", xForwardedFor: "8.8.8.8,10.0.0.1,10.0.0.2", host: "override.excludedips.allowlist.docker.local", expectedStatusCode: 200, }, } for _, test := range testCases { req := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:8000", nil) req.Header.Set("X-Forwarded-For", test.xForwardedFor) req.Host = test.host req.RequestURI = "" err = try.Request(req, 1*time.Second, try.StatusCodeIs(test.expectedStatusCode)) require.NoErrorf(s.T(), err, "Error during %s: %v", test.desc, err) } } func (s *SimpleSuite) TestIPStrategyWhitelist() { s.createComposeProject("whitelist") s.composeUp() defer s.composeDown() s.traefikCmd(withConfigFile("fixtures/simple_whitelist.toml")) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 2*time.Second, try.BodyContains("override")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 2*time.Second, try.BodyContains("override.remoteaddr.whitelist.docker.local")) require.NoError(s.T(), err) testCases := []struct { desc string xForwardedFor string host string expectedStatusCode int }{ { desc: "override remote addr reject", xForwardedFor: "8.8.8.8,8.8.8.8", host: "override.remoteaddr.whitelist.docker.local", expectedStatusCode: 403, }, { desc: "override depth accept", xForwardedFor: "8.8.8.8,10.0.0.1,127.0.0.1", host: "override.depth.whitelist.docker.local", expectedStatusCode: 200, }, { desc: "override depth reject", xForwardedFor: "10.0.0.1,8.8.8.8,127.0.0.1", host: "override.depth.whitelist.docker.local", expectedStatusCode: 403, }, { desc: "override excludedIPs reject", xForwardedFor: "10.0.0.3,10.0.0.1,10.0.0.2", host: "override.excludedips.whitelist.docker.local", expectedStatusCode: 403, }, { desc: "override excludedIPs accept", xForwardedFor: "8.8.8.8,10.0.0.1,10.0.0.2", host: "override.excludedips.whitelist.docker.local", expectedStatusCode: 200, }, } for _, test := range testCases { req := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:8000", nil) req.Header.Set("X-Forwarded-For", test.xForwardedFor) req.Host = test.host req.RequestURI = "" err = try.Request(req, 1*time.Second, try.StatusCodeIs(test.expectedStatusCode)) require.NoErrorf(s.T(), err, "Error during %s: %v", test.desc, err) } } func (s *SimpleSuite) TestXForwardedHeaders() { s.createComposeProject("allowlist") s.composeUp() defer s.composeDown() s.traefikCmd(withConfigFile("fixtures/simple_allowlist.toml")) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 2*time.Second, try.BodyContains("override.remoteaddr.allowlist.docker.local")) require.NoError(s.T(), err) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000", nil) require.NoError(s.T(), err) req.Host = "override.depth.allowlist.docker.local" req.Header.Set("X-Forwarded-For", "8.8.8.8,10.0.0.1,127.0.0.1") err = try.Request(req, 1*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("X-Forwarded-Proto", "X-Forwarded-For", "X-Forwarded-Host", "X-Forwarded-Host", "X-Forwarded-Port", "X-Forwarded-Server", "X-Real-Ip")) require.NoError(s.T(), err) } func (s *SimpleSuite) TestMultiProvider() { s.createComposeProject("base") s.composeUp() defer s.composeDown() whoamiURL := "http://" + net.JoinHostPort(s.getComposeServiceIP("whoami1"), "80") file := s.adaptFile("fixtures/multiprovider.toml", struct{ Server string }{Server: whoamiURL}) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1000*time.Millisecond, try.BodyContains("service")) require.NoError(s.T(), err) config := dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "router1": { EntryPoints: []string{"web"}, Middlewares: []string{"customheader@file"}, Service: "service@file", Rule: "PathPrefix(`/`)", }, }, }, } jsonContent, err := json.Marshal(config) require.NoError(s.T(), err) request, err := http.NewRequest(http.MethodPut, "http://127.0.0.1:8080/api/providers/rest", bytes.NewReader(jsonContent)) require.NoError(s.T(), err) response, err := http.DefaultClient.Do(request) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusOK, response.StatusCode) err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1000*time.Millisecond, try.BodyContains("PathPrefix(`/`)")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/", 1*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("CustomValue")) require.NoError(s.T(), err) } func (s *SimpleSuite) TestSimpleConfigurationHostRequestTrailingPeriod() { s.createComposeProject("base") s.composeUp() defer s.composeDown() whoamiURL := "http://" + net.JoinHostPort(s.getComposeServiceIP("whoami1"), "80") file := s.adaptFile("fixtures/file/simple-hosts.toml", struct{ Server string }{Server: whoamiURL}) s.traefikCmd(withConfigFile(file)) testCases := []struct { desc string requestHost string }{ { desc: "Request host without trailing period, rule without trailing period", requestHost: "test.localhost", }, { desc: "Request host with trailing period, rule without trailing period", requestHost: "test.localhost.", }, { desc: "Request host without trailing period, rule with trailing period", requestHost: "test.foo.localhost", }, { desc: "Request host with trailing period, rule with trailing period", requestHost: "test.foo.localhost.", }, } for _, test := range testCases { req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000", nil) require.NoError(s.T(), err) req.Host = test.requestHost err = try.Request(req, 1*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoErrorf(s.T(), err, "Error while testing %s: %v", test.desc, err) } } func (s *SimpleSuite) TestWithDefaultRuleSyntax() { file := s.adaptFile("fixtures/with_default_rule_syntax.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("PathPrefix")) require.NoError(s.T(), err) // router1 has no error err = try.GetRequest("http://127.0.0.1:8080/api/http/routers/router1@file", 1*time.Second, try.BodyContains(`"status":"enabled"`)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/notfound", 1*time.Second, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/foo", 1*time.Second, try.StatusCodeIs(http.StatusServiceUnavailable)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/bar", 1*time.Second, try.StatusCodeIs(http.StatusServiceUnavailable)) require.NoError(s.T(), err) // router2 has an error because it uses the wrong rule syntax (v3 instead of v2) err = try.GetRequest("http://127.0.0.1:8080/api/http/routers/router2@file", 1*time.Second, try.BodyContains("parsing rule QueryRegexp(`foo`, `bar`): unsupported function: QueryRegexp")) require.NoError(s.T(), err) // router3 has an error because it uses the wrong rule syntax (v2 instead of v3) err = try.GetRequest("http://127.0.0.1:8080/api/http/routers/router3@file", 1*time.Second, try.BodyContains("adding rule PathPrefix: unexpected number of parameters; got 2, expected one of [1]")) require.NoError(s.T(), err) } func (s *SimpleSuite) TestWithoutDefaultRuleSyntax() { file := s.adaptFile("fixtures/without_default_rule_syntax.toml", struct{}{}) s.traefikCmd(withConfigFile(file))
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/udp_test.go
integration/udp_test.go
package integration import ( "net" "net/http" "strings" "testing" "time" "github.com/rs/zerolog/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) type UDPSuite struct{ BaseSuite } func TestUDPSuite(t *testing.T) { suite.Run(t, new(UDPSuite)) } func (s *UDPSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("udp") s.composeUp() } func (s *UDPSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func guessWhoUDP(addr string) (string, error) { var conn net.Conn var err error udpAddr, err2 := net.ResolveUDPAddr("udp", addr) if err2 != nil { return "", err2 } conn, err = net.DialUDP("udp", nil, udpAddr) if err != nil { return "", err } _, err = conn.Write([]byte("WHO")) if err != nil { return "", err } out := make([]byte, 2048) n, err := conn.Read(out) if err != nil { return "", err } return string(out[:n]), nil } func (s *UDPSuite) TestWRR() { file := s.adaptFile("fixtures/udp/wrr.toml", struct { WhoamiAIP string WhoamiBIP string WhoamiCIP string WhoamiDIP string }{ WhoamiAIP: s.getComposeServiceIP("whoami-a"), WhoamiBIP: s.getComposeServiceIP("whoami-b"), WhoamiCIP: s.getComposeServiceIP("whoami-c"), WhoamiDIP: s.getComposeServiceIP("whoami-d"), }) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("whoami-a")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8093/who", 5*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) stop := make(chan struct{}) go func() { call := map[string]int{} for range 8 { out, err := guessWhoUDP("127.0.0.1:8093") require.NoError(s.T(), err) switch { case strings.Contains(out, "whoami-a"): call["whoami-a"]++ case strings.Contains(out, "whoami-b"): call["whoami-b"]++ case strings.Contains(out, "whoami-c"): call["whoami-c"]++ default: call["unknown"]++ } } assert.Equal(s.T(), map[string]int{"whoami-a": 3, "whoami-b": 2, "whoami-c": 3}, call) close(stop) }() select { case <-stop: case <-time.Tick(5 * time.Second): log.Info().Msg("Timeout") } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/tracing_test.go
integration/tracing_test.go
package integration import ( "encoding/json" "fmt" "io" "net" "net/http" "net/url" "os" "strings" "testing" "time" "github.com/rs/zerolog/log" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/tidwall/gjson" "github.com/traefik/traefik/v3/integration/try" ) type TracingSuite struct { BaseSuite whoamiIP string whoamiPort int tempoIP string otelCollectorIP string } func TestTracingSuite(t *testing.T) { suite.Run(t, new(TracingSuite)) } type TracingTemplate struct { WhoamiIP string WhoamiPort int IP string TraceContextHeaderName string IsHTTP bool } func (s *TracingSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("tracing") s.composeUp() s.whoamiIP = s.getComposeServiceIP("whoami") s.whoamiPort = 80 // Wait for whoami to turn ready. err := try.GetRequest("http://"+s.whoamiIP+":80", 30*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) s.otelCollectorIP = s.getComposeServiceIP("otel-collector") // Wait for otel collector to turn ready. err = try.GetRequest("http://"+s.otelCollectorIP+":13133/", 30*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) } func (s *TracingSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *TracingSuite) SetupTest() { s.composeUp("tempo") s.tempoIP = s.getComposeServiceIP("tempo") // Wait for tempo to turn ready. err := try.GetRequest("http://"+s.tempoIP+":3200/ready", 30*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) } func (s *TracingSuite) TearDownTest() { s.composeStop("tempo") } func (s *TracingSuite) TestOpenTelemetryBasic_HTTP_router_minimalVerbosity() { file := s.adaptFile("fixtures/tracing/simple-opentelemetry.toml", TracingTemplate{ WhoamiIP: s.whoamiIP, WhoamiPort: s.whoamiPort, IP: s.otelCollectorIP, IsHTTP: true, }) s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", time.Second, try.BodyContains("basic-auth")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/basic-minimal", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) contains := []map[string]string{ { "batches.0.scopeSpans.0.scope.name": "github.com/traefik/traefik", "batches.0.scopeSpans.0.spans.0.name": "ReverseProxy", "batches.0.scopeSpans.0.spans.0.kind": "SPAN_KIND_CLIENT", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"http.request.method\").value.stringValue": "GET", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.protocol.version\").value.stringValue": "1.1", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"url.full\").value.stringValue": fmt.Sprintf("http://%s/basic-minimal", net.JoinHostPort(s.whoamiIP, "80")), "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"user_agent.original\").value.stringValue": "Go-http-client/1.1", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.peer.address\").value.stringValue": s.whoamiIP, "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.peer.port\").value.intValue": "80", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"server.address\").value.stringValue": s.whoamiIP, "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"server.port\").value.intValue": "80", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"http.response.status_code\").value.intValue": "200", "batches.0.scopeSpans.0.spans.1.name": "GET", "batches.0.scopeSpans.0.spans.1.kind": "SPAN_KIND_SERVER", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"entry_point\").value.stringValue": "web", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"http.request.method\").value.stringValue": "GET", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"url.path\").value.stringValue": "/basic-minimal", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"url.query\").value.stringValue": "", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"user_agent.original\").value.stringValue": "Go-http-client/1.1", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"server.address\").value.stringValue": "127.0.0.1:8000", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"network.peer.address\").value.stringValue": "127.0.0.1", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"http.response.status_code\").value.intValue": "200", }, } s.checkTraceContent(contains) } func (s *TracingSuite) TestOpenTelemetryBasic_HTTP_entrypoint_minimalVerbosity() { file := s.adaptFile("fixtures/tracing/simple-opentelemetry.toml", TracingTemplate{ WhoamiIP: s.whoamiIP, WhoamiPort: s.whoamiPort, IP: s.otelCollectorIP, IsHTTP: true, }) s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", time.Second, try.BodyContains("basic-auth")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8001/basic", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) contains := []map[string]string{ { "batches.0.scopeSpans.0.scope.name": "github.com/traefik/traefik", "batches.0.scopeSpans.0.spans.0.name": "ReverseProxy", "batches.0.scopeSpans.0.spans.0.kind": "SPAN_KIND_CLIENT", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"http.request.method\").value.stringValue": "GET", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.protocol.version\").value.stringValue": "1.1", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"url.full\").value.stringValue": fmt.Sprintf("http://%s/basic", net.JoinHostPort(s.whoamiIP, "80")), "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"user_agent.original\").value.stringValue": "Go-http-client/1.1", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.peer.address\").value.stringValue": s.whoamiIP, "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.peer.port\").value.intValue": "80", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"server.address\").value.stringValue": s.whoamiIP, "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"server.port\").value.intValue": "80", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"http.response.status_code\").value.intValue": "200", "batches.0.scopeSpans.0.spans.1.name": "GET", "batches.0.scopeSpans.0.spans.1.kind": "SPAN_KIND_SERVER", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"entry_point\").value.stringValue": "web-minimal", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"http.request.method\").value.stringValue": "GET", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"url.path\").value.stringValue": "/basic", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"url.query\").value.stringValue": "", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"user_agent.original\").value.stringValue": "Go-http-client/1.1", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"server.address\").value.stringValue": "127.0.0.1:8001", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"network.peer.address\").value.stringValue": "127.0.0.1", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"http.response.status_code\").value.intValue": "200", }, } s.checkTraceContent(contains) } func (s *TracingSuite) TestOpenTelemetryBasic_HTTP() { file := s.adaptFile("fixtures/tracing/simple-opentelemetry.toml", TracingTemplate{ WhoamiIP: s.whoamiIP, WhoamiPort: s.whoamiPort, IP: s.otelCollectorIP, IsHTTP: true, }) s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", time.Second, try.BodyContains("basic-auth")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/basic", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) contains := []map[string]string{ { "batches.0.scopeSpans.0.scope.name": "github.com/traefik/traefik", "batches.0.scopeSpans.0.spans.0.name": "ReverseProxy", "batches.0.scopeSpans.0.spans.0.kind": "SPAN_KIND_CLIENT", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"http.request.method\").value.stringValue": "GET", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.protocol.version\").value.stringValue": "1.1", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"url.full\").value.stringValue": fmt.Sprintf("http://%s/basic", net.JoinHostPort(s.whoamiIP, "80")), "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"user_agent.original\").value.stringValue": "Go-http-client/1.1", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.peer.address\").value.stringValue": s.whoamiIP, "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.peer.port\").value.intValue": "80", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"server.address\").value.stringValue": s.whoamiIP, "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"server.port\").value.intValue": "80", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"http.response.status_code\").value.intValue": "200", "batches.0.scopeSpans.0.spans.1.name": "Metrics", "batches.0.scopeSpans.0.spans.1.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"traefik.middleware.name\").value.stringValue": "metrics-service", "batches.0.scopeSpans.0.spans.2.name": "Service", "batches.0.scopeSpans.0.spans.2.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.2.attributes.#(key=\"traefik.service.name\").value.stringValue": "service0@file", "batches.0.scopeSpans.0.spans.3.name": "Router", "batches.0.scopeSpans.0.spans.3.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.3.attributes.#(key=\"traefik.service.name\").value.stringValue": "service0@file", "batches.0.scopeSpans.0.spans.3.attributes.#(key=\"traefik.router.name\").value.stringValue": "web-router0@file", "batches.0.scopeSpans.0.spans.3.attributes.#(key=\"http.route\").value.stringValue": "Path(`/basic`)", "batches.0.scopeSpans.0.spans.4.name": "Metrics", "batches.0.scopeSpans.0.spans.4.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.4.attributes.#(key=\"traefik.middleware.name\").value.stringValue": "metrics-entrypoint", "batches.0.scopeSpans.0.spans.5.name": "GET", "batches.0.scopeSpans.0.spans.5.kind": "SPAN_KIND_SERVER", "batches.0.scopeSpans.0.spans.5.attributes.#(key=\"entry_point\").value.stringValue": "web", "batches.0.scopeSpans.0.spans.5.attributes.#(key=\"http.request.method\").value.stringValue": "GET", "batches.0.scopeSpans.0.spans.5.attributes.#(key=\"url.path\").value.stringValue": "/basic", "batches.0.scopeSpans.0.spans.5.attributes.#(key=\"url.query\").value.stringValue": "", "batches.0.scopeSpans.0.spans.5.attributes.#(key=\"user_agent.original\").value.stringValue": "Go-http-client/1.1", "batches.0.scopeSpans.0.spans.5.attributes.#(key=\"server.address\").value.stringValue": "127.0.0.1:8000", "batches.0.scopeSpans.0.spans.5.attributes.#(key=\"network.peer.address\").value.stringValue": "127.0.0.1", "batches.0.scopeSpans.0.spans.5.attributes.#(key=\"http.response.status_code\").value.intValue": "200", }, } s.checkTraceContent(contains) } func (s *TracingSuite) TestOpenTelemetryBasic_gRPC() { file := s.adaptFile("fixtures/tracing/simple-opentelemetry.toml", TracingTemplate{ WhoamiIP: s.whoamiIP, WhoamiPort: s.whoamiPort, IP: s.otelCollectorIP, IsHTTP: false, }) defer os.Remove(file) s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", time.Second, try.BodyContains("basic-auth")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/basic", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) contains := []map[string]string{ { "batches.0.scopeSpans.0.scope.name": "github.com/traefik/traefik", "batches.0.scopeSpans.0.spans.0.name": "ReverseProxy", "batches.0.scopeSpans.0.spans.0.kind": "SPAN_KIND_CLIENT", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"http.request.method\").value.stringValue": "GET", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.protocol.version\").value.stringValue": "1.1", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"url.full\").value.stringValue": fmt.Sprintf("http://%s/basic", net.JoinHostPort(s.whoamiIP, "80")), "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"user_agent.original\").value.stringValue": "Go-http-client/1.1", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.peer.address\").value.stringValue": s.whoamiIP, "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.peer.port\").value.intValue": "80", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"server.address\").value.stringValue": s.whoamiIP, "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"server.port\").value.intValue": "80", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"http.response.status_code\").value.intValue": "200", "batches.0.scopeSpans.0.spans.1.name": "Metrics", "batches.0.scopeSpans.0.spans.1.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"traefik.middleware.name\").value.stringValue": "metrics-service", "batches.0.scopeSpans.0.spans.2.name": "Service", "batches.0.scopeSpans.0.spans.2.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.2.attributes.#(key=\"traefik.service.name\").value.stringValue": "service0@file", "batches.0.scopeSpans.0.spans.3.name": "Router", "batches.0.scopeSpans.0.spans.3.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.3.attributes.#(key=\"traefik.service.name\").value.stringValue": "service0@file", "batches.0.scopeSpans.0.spans.3.attributes.#(key=\"traefik.router.name\").value.stringValue": "web-router0@file", "batches.0.scopeSpans.0.spans.3.attributes.#(key=\"http.route\").value.stringValue": "Path(`/basic`)", "batches.0.scopeSpans.0.spans.4.name": "Metrics", "batches.0.scopeSpans.0.spans.4.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.4.attributes.#(key=\"traefik.middleware.name\").value.stringValue": "metrics-entrypoint", }, } s.checkTraceContent(contains) } func (s *TracingSuite) TestOpenTelemetryRateLimit() { file := s.adaptFile("fixtures/tracing/simple-opentelemetry.toml", TracingTemplate{ WhoamiIP: s.whoamiIP, WhoamiPort: s.whoamiPort, IP: s.otelCollectorIP, }) defer os.Remove(file) s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", time.Second, try.BodyContains("basic-auth")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/ratelimit", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/ratelimit", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/ratelimit", 500*time.Millisecond, try.StatusCodeIs(http.StatusTooManyRequests)) require.NoError(s.T(), err) // sleep for 4 seconds to be certain the configured time period has elapsed // then test another request and verify a 200 status code time.Sleep(4 * time.Second) err = try.GetRequest("http://127.0.0.1:8000/ratelimit", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) // continue requests at 3 second intervals to test the other rate limit time period time.Sleep(3 * time.Second) err = try.GetRequest("http://127.0.0.1:8000/ratelimit", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) time.Sleep(3 * time.Second) err = try.GetRequest("http://127.0.0.1:8000/ratelimit", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/ratelimit", 500*time.Millisecond, try.StatusCodeIs(http.StatusTooManyRequests)) require.NoError(s.T(), err) contains := []map[string]string{ { "batches.0.scopeSpans.0.scope.name": "github.com/traefik/traefik", "batches.0.scopeSpans.0.spans.0.name": "RateLimiter", "batches.0.scopeSpans.0.spans.0.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"traefik.middleware.name\").value.stringValue": "ratelimit-1@file", "batches.0.scopeSpans.0.spans.1.name": "Router", "batches.0.scopeSpans.0.spans.1.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"traefik.service.name\").value.stringValue": "service1@file", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"traefik.router.name\").value.stringValue": "web-router1@file", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"http.route\").value.stringValue": "Path(`/ratelimit`)", "batches.0.scopeSpans.0.spans.2.name": "Metrics", "batches.0.scopeSpans.0.spans.2.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.2.attributes.#(key=\"traefik.middleware.name\").value.stringValue": "metrics-entrypoint", "batches.0.scopeSpans.0.spans.3.name": "GET", "batches.0.scopeSpans.0.spans.3.kind": "SPAN_KIND_SERVER", "batches.0.scopeSpans.0.spans.3.attributes.#(key=\"entry_point\").value.stringValue": "web", "batches.0.scopeSpans.0.spans.3.attributes.#(key=\"http.request.method\").value.stringValue": "GET", "batches.0.scopeSpans.0.spans.3.attributes.#(key=\"url.path\").value.stringValue": "/ratelimit", "batches.0.scopeSpans.0.spans.3.attributes.#(key=\"url.query\").value.stringValue": "", "batches.0.scopeSpans.0.spans.3.attributes.#(key=\"user_agent.original\").value.stringValue": "Go-http-client/1.1", "batches.0.scopeSpans.0.spans.3.attributes.#(key=\"server.address\").value.stringValue": "127.0.0.1:8000", "batches.0.scopeSpans.0.spans.3.attributes.#(key=\"network.peer.address\").value.stringValue": "127.0.0.1", "batches.0.scopeSpans.0.spans.3.attributes.#(key=\"http.response.status_code\").value.intValue": "429", }, { "batches.0.scopeSpans.0.scope.name": "github.com/traefik/traefik", "batches.0.scopeSpans.0.spans.0.name": "ReverseProxy", "batches.0.scopeSpans.0.spans.0.kind": "SPAN_KIND_CLIENT", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"http.request.method\").value.stringValue": "GET", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.protocol.version\").value.stringValue": "1.1", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"url.full\").value.stringValue": fmt.Sprintf("http://%s/ratelimit", net.JoinHostPort(s.whoamiIP, "80")), "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"user_agent.original\").value.stringValue": "Go-http-client/1.1", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.peer.address\").value.stringValue": s.whoamiIP, "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.peer.port\").value.intValue": "80", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"server.address\").value.stringValue": s.whoamiIP, "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"server.port\").value.intValue": "80", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"http.response.status_code\").value.intValue": "200", "batches.0.scopeSpans.0.spans.1.name": "Metrics", "batches.0.scopeSpans.0.spans.1.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"traefik.middleware.name\").value.stringValue": "metrics-service", "batches.0.scopeSpans.0.spans.2.name": "Service", "batches.0.scopeSpans.0.spans.2.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.2.attributes.#(key=\"traefik.service.name\").value.stringValue": "service1@file", "batches.0.scopeSpans.0.spans.3.name": "RateLimiter", "batches.0.scopeSpans.0.spans.3.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.3.attributes.#(key=\"traefik.middleware.name\").value.stringValue": "ratelimit-1@file", "batches.0.scopeSpans.0.spans.4.name": "Router", "batches.0.scopeSpans.0.spans.4.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.4.attributes.#(key=\"traefik.service.name\").value.stringValue": "service1@file", "batches.0.scopeSpans.0.spans.4.attributes.#(key=\"traefik.router.name\").value.stringValue": "web-router1@file", "batches.0.scopeSpans.0.spans.4.attributes.#(key=\"http.route\").value.stringValue": "Path(`/ratelimit`)", "batches.0.scopeSpans.0.spans.5.name": "Metrics", "batches.0.scopeSpans.0.spans.5.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.5.attributes.#(key=\"traefik.middleware.name\").value.stringValue": "metrics-entrypoint", "batches.0.scopeSpans.0.spans.6.name": "GET", "batches.0.scopeSpans.0.spans.6.kind": "SPAN_KIND_SERVER", "batches.0.scopeSpans.0.spans.6.attributes.#(key=\"entry_point\").value.stringValue": "web", "batches.0.scopeSpans.0.spans.6.attributes.#(key=\"http.request.method\").value.stringValue": "GET", "batches.0.scopeSpans.0.spans.6.attributes.#(key=\"url.path\").value.stringValue": "/ratelimit", "batches.0.scopeSpans.0.spans.6.attributes.#(key=\"url.query\").value.stringValue": "", "batches.0.scopeSpans.0.spans.6.attributes.#(key=\"user_agent.original\").value.stringValue": "Go-http-client/1.1", "batches.0.scopeSpans.0.spans.6.attributes.#(key=\"server.address\").value.stringValue": "127.0.0.1:8000", "batches.0.scopeSpans.0.spans.6.attributes.#(key=\"network.peer.address\").value.stringValue": "127.0.0.1", "batches.0.scopeSpans.0.spans.6.attributes.#(key=\"http.response.status_code\").value.intValue": "200", }, } s.checkTraceContent(contains) } func (s *TracingSuite) TestOpenTelemetryRetry() { file := s.adaptFile("fixtures/tracing/simple-opentelemetry.toml", TracingTemplate{ WhoamiIP: s.whoamiIP, WhoamiPort: 81, IP: s.otelCollectorIP, }) defer os.Remove(file) s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 2*time.Second, try.BodyContains("basic-auth")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/retry", 500*time.Millisecond, try.StatusCodeIs(http.StatusBadGateway)) require.NoError(s.T(), err) contains := []map[string]string{ { "batches.0.scopeSpans.0.scope.name": "github.com/traefik/traefik", "batches.0.scopeSpans.0.spans.0.name": "ReverseProxy", "batches.0.scopeSpans.0.spans.0.kind": "SPAN_KIND_CLIENT", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"http.request.method\").value.stringValue": "GET", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.protocol.version\").value.stringValue": "1.1", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"url.full\").value.stringValue": fmt.Sprintf("http://%s/retry", net.JoinHostPort(s.whoamiIP, "81")), "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"user_agent.original\").value.stringValue": "Go-http-client/1.1", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.peer.address\").value.stringValue": s.whoamiIP, "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"network.peer.port\").value.intValue": "81", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"server.address\").value.stringValue": s.whoamiIP, "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"server.port\").value.intValue": "81", "batches.0.scopeSpans.0.spans.0.attributes.#(key=\"http.response.status_code\").value.intValue": "502", "batches.0.scopeSpans.0.spans.0.status.code": "STATUS_CODE_ERROR", "batches.0.scopeSpans.0.spans.1.name": "Metrics", "batches.0.scopeSpans.0.spans.1.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.1.attributes.#(key=\"traefik.middleware.name\").value.stringValue": "metrics-service", "batches.0.scopeSpans.0.spans.2.name": "Service", "batches.0.scopeSpans.0.spans.2.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.2.attributes.#(key=\"traefik.service.name\").value.stringValue": "service2@file", "batches.0.scopeSpans.0.spans.3.name": "Retry", "batches.0.scopeSpans.0.spans.3.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.3.attributes.#(key=\"traefik.middleware.name\").value.stringValue": "retry@file", "batches.0.scopeSpans.0.spans.4.name": "ReverseProxy", "batches.0.scopeSpans.0.spans.4.kind": "SPAN_KIND_CLIENT", "batches.0.scopeSpans.0.spans.4.attributes.#(key=\"http.request.method\").value.stringValue": "GET", "batches.0.scopeSpans.0.spans.4.attributes.#(key=\"network.protocol.version\").value.stringValue": "1.1", "batches.0.scopeSpans.0.spans.4.attributes.#(key=\"url.full\").value.stringValue": fmt.Sprintf("http://%s/retry", net.JoinHostPort(s.whoamiIP, "81")), "batches.0.scopeSpans.0.spans.4.attributes.#(key=\"user_agent.original\").value.stringValue": "Go-http-client/1.1", "batches.0.scopeSpans.0.spans.4.attributes.#(key=\"network.peer.address\").value.stringValue": s.whoamiIP, "batches.0.scopeSpans.0.spans.4.attributes.#(key=\"network.peer.port\").value.intValue": "81", "batches.0.scopeSpans.0.spans.4.attributes.#(key=\"server.address\").value.stringValue": s.whoamiIP, "batches.0.scopeSpans.0.spans.4.attributes.#(key=\"server.port\").value.intValue": "81", "batches.0.scopeSpans.0.spans.4.attributes.#(key=\"http.response.status_code\").value.intValue": "502", "batches.0.scopeSpans.0.spans.4.status.code": "STATUS_CODE_ERROR", "batches.0.scopeSpans.0.spans.5.name": "Metrics", "batches.0.scopeSpans.0.spans.5.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.5.attributes.#(key=\"traefik.middleware.name\").value.stringValue": "metrics-service", "batches.0.scopeSpans.0.spans.6.name": "Service", "batches.0.scopeSpans.0.spans.6.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.6.attributes.#(key=\"traefik.service.name\").value.stringValue": "service2@file", "batches.0.scopeSpans.0.spans.7.name": "Retry", "batches.0.scopeSpans.0.spans.7.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.7.attributes.#(key=\"traefik.middleware.name\").value.stringValue": "retry@file", "batches.0.scopeSpans.0.spans.7.attributes.#(key=\"http.request.resend_count\").value.intValue": "1", "batches.0.scopeSpans.0.spans.8.name": "ReverseProxy", "batches.0.scopeSpans.0.spans.8.kind": "SPAN_KIND_CLIENT", "batches.0.scopeSpans.0.spans.8.attributes.#(key=\"http.request.method\").value.stringValue": "GET", "batches.0.scopeSpans.0.spans.8.attributes.#(key=\"network.protocol.version\").value.stringValue": "1.1", "batches.0.scopeSpans.0.spans.8.attributes.#(key=\"url.full\").value.stringValue": fmt.Sprintf("http://%s/retry", net.JoinHostPort(s.whoamiIP, "81")), "batches.0.scopeSpans.0.spans.8.attributes.#(key=\"user_agent.original\").value.stringValue": "Go-http-client/1.1", "batches.0.scopeSpans.0.spans.8.attributes.#(key=\"network.peer.address\").value.stringValue": s.whoamiIP, "batches.0.scopeSpans.0.spans.8.attributes.#(key=\"network.peer.port\").value.intValue": "81", "batches.0.scopeSpans.0.spans.8.attributes.#(key=\"server.address\").value.stringValue": s.whoamiIP, "batches.0.scopeSpans.0.spans.8.attributes.#(key=\"server.port\").value.intValue": "81", "batches.0.scopeSpans.0.spans.8.attributes.#(key=\"http.response.status_code\").value.intValue": "502", "batches.0.scopeSpans.0.spans.8.status.code": "STATUS_CODE_ERROR", "batches.0.scopeSpans.0.spans.9.name": "Metrics", "batches.0.scopeSpans.0.spans.9.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.9.attributes.#(key=\"traefik.middleware.name\").value.stringValue": "metrics-service", "batches.0.scopeSpans.0.spans.10.name": "Service", "batches.0.scopeSpans.0.spans.10.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.10.attributes.#(key=\"traefik.service.name\").value.stringValue": "service2@file", "batches.0.scopeSpans.0.spans.11.name": "Retry", "batches.0.scopeSpans.0.spans.11.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.11.attributes.#(key=\"traefik.middleware.name\").value.stringValue": "retry@file", "batches.0.scopeSpans.0.spans.11.attributes.#(key=\"http.request.resend_count\").value.intValue": "2", "batches.0.scopeSpans.0.spans.12.name": "Router", "batches.0.scopeSpans.0.spans.12.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.12.attributes.#(key=\"traefik.service.name\").value.stringValue": "service2@file", "batches.0.scopeSpans.0.spans.12.attributes.#(key=\"traefik.router.name\").value.stringValue": "web-router2@file", "batches.0.scopeSpans.0.spans.13.name": "Metrics", "batches.0.scopeSpans.0.spans.13.kind": "SPAN_KIND_INTERNAL", "batches.0.scopeSpans.0.spans.13.attributes.#(key=\"traefik.middleware.name\").value.stringValue": "metrics-entrypoint", "batches.0.scopeSpans.0.spans.14.name": "GET", "batches.0.scopeSpans.0.spans.14.kind": "SPAN_KIND_SERVER", "batches.0.scopeSpans.0.spans.14.attributes.#(key=\"entry_point\").value.stringValue": "web", "batches.0.scopeSpans.0.spans.14.attributes.#(key=\"http.request.method\").value.stringValue": "GET", "batches.0.scopeSpans.0.spans.14.attributes.#(key=\"url.path\").value.stringValue": "/retry", "batches.0.scopeSpans.0.spans.14.attributes.#(key=\"url.query\").value.stringValue": "", "batches.0.scopeSpans.0.spans.14.attributes.#(key=\"user_agent.original\").value.stringValue": "Go-http-client/1.1", "batches.0.scopeSpans.0.spans.14.attributes.#(key=\"server.address\").value.stringValue": "127.0.0.1:8000", "batches.0.scopeSpans.0.spans.14.attributes.#(key=\"network.peer.address\").value.stringValue": "127.0.0.1",
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/rest_test.go
integration/rest_test.go
package integration import ( "bytes" "encoding/json" "net" "net/http" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) type RestSuite struct { BaseSuite whoamiAddr string } func TestRestSuite(t *testing.T) { suite.Run(t, new(RestSuite)) } func (s *RestSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("rest") s.composeUp() s.whoamiAddr = net.JoinHostPort(s.getComposeServiceIP("whoami1"), "80") } func (s *RestSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *RestSuite) TestSimpleConfigurationInsecure() { s.traefikCmd(withConfigFile("fixtures/rest/simple.toml")) // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1000*time.Millisecond, try.BodyContains("rest@internal")) require.NoError(s.T(), err) // Expected a 404 as we did not configure anything. err = try.GetRequest("http://127.0.0.1:8000/", 1000*time.Millisecond, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) testCase := []struct { desc string config *dynamic.Configuration ruleMatch string }{ { desc: "deploy http configuration", config: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "routerHTTP": { EntryPoints: []string{"web"}, Middlewares: []string{}, Service: "serviceHTTP", Rule: "PathPrefix(`/`)", }, }, Services: map[string]*dynamic.Service{ "serviceHTTP": { LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://" + s.whoamiAddr, }, }, }, }, }, }, }, ruleMatch: "PathPrefix(`/`)", }, { desc: "deploy tcp configuration", config: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "routerTCP": { EntryPoints: []string{"web"}, Service: "serviceTCP", Rule: "HostSNI(`*`)", }, }, Services: map[string]*dynamic.TCPService{ "serviceTCP": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: s.whoamiAddr, }, }, }, }, }, }, }, ruleMatch: "HostSNI(`*`)", }, } for _, test := range testCase { data, err := json.Marshal(test.config) require.NoError(s.T(), err) request, err := http.NewRequest(http.MethodPut, "http://127.0.0.1:8080/api/providers/rest", bytes.NewReader(data)) require.NoError(s.T(), err) response, err := http.DefaultClient.Do(request) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusOK, response.StatusCode) err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 3*time.Second, try.BodyContains(test.ruleMatch)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/", 1000*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) } } func (s *RestSuite) TestSimpleConfiguration() { file := s.adaptFile("fixtures/rest/simple_secure.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) // Expected a 404 as we did not configure anything. err := try.GetRequest("http://127.0.0.1:8000/", 1000*time.Millisecond, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 2000*time.Millisecond, try.BodyContains("PathPrefix(`/secure`)")) require.NoError(s.T(), err) request, err := http.NewRequest(http.MethodPut, "http://127.0.0.1:8080/api/providers/rest", strings.NewReader("{}")) require.NoError(s.T(), err) response, err := http.DefaultClient.Do(request) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusNotFound, response.StatusCode) testCase := []struct { desc string config *dynamic.Configuration ruleMatch string }{ { desc: "deploy http configuration", config: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "router1": { EntryPoints: []string{"web"}, Middlewares: []string{}, Service: "service1", Rule: "PathPrefix(`/`)", }, }, Services: map[string]*dynamic.Service{ "service1": { LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://" + s.whoamiAddr, }, }, }, }, }, }, }, ruleMatch: "PathPrefix(`/`)", }, { desc: "deploy tcp configuration", config: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "router1": { EntryPoints: []string{"web"}, Service: "service1", Rule: "HostSNI(`*`)", }, }, Services: map[string]*dynamic.TCPService{ "service1": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: s.whoamiAddr, }, }, }, }, }, }, }, ruleMatch: "HostSNI(`*`)", }, } for _, test := range testCase { data, err := json.Marshal(test.config) require.NoError(s.T(), err) request, err := http.NewRequest(http.MethodPut, "http://127.0.0.1:8000/secure/api/providers/rest", bytes.NewReader(data)) require.NoError(s.T(), err) response, err := http.DefaultClient.Do(request) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusOK, response.StatusCode) err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", time.Second, try.BodyContains(test.ruleMatch)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/", time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/timeout_test.go
integration/timeout_test.go
package integration import ( "fmt" "net" "net/http" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) type TimeoutSuite struct{ BaseSuite } func TestTimeoutSuite(t *testing.T) { suite.Run(t, new(TimeoutSuite)) } func (s *TimeoutSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("timeout") s.composeUp() } func (s *TimeoutSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *TimeoutSuite) TestForwardingTimeouts() { timeoutEndpointIP := s.getComposeServiceIP("timeoutEndpoint") file := s.adaptFile("fixtures/timeout/forwarding_timeouts.toml", struct{ TimeoutEndpoint string }{timeoutEndpointIP}) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("Path(`/dialTimeout`)")) require.NoError(s.T(), err) // This simulates a DialTimeout when connecting to the backend server. response, err := http.Get("http://127.0.0.1:8000/dialTimeout") require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusGatewayTimeout, response.StatusCode) // Check that timeout service is available statusURL := fmt.Sprintf("http://%s/statusTest?status=200", net.JoinHostPort(timeoutEndpointIP, "9000")) assert.NoError(s.T(), try.GetRequest(statusURL, 60*time.Second, try.StatusCodeIs(http.StatusOK))) // This simulates a ResponseHeaderTimeout. response, err = http.Get("http://127.0.0.1:8000/responseHeaderTimeout?sleep=1000") require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusGatewayTimeout, response.StatusCode) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/retry_test.go
integration/retry_test.go
package integration import ( "io" "net/http" "testing" "time" "github.com/gorilla/websocket" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) type RetrySuite struct { BaseSuite whoamiIP string } func TestRetrySuite(t *testing.T) { suite.Run(t, new(RetrySuite)) } func (s *RetrySuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("retry") s.composeUp() s.whoamiIP = s.getComposeServiceIP("whoami") } func (s *RetrySuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *RetrySuite) TestRetry() { file := s.adaptFile("fixtures/retry/simple.toml", struct{ WhoamiIP string }{s.whoamiIP}) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("PathPrefix(`/`)")) require.NoError(s.T(), err) response, err := http.Get("http://127.0.0.1:8000/") require.NoError(s.T(), err) // The test only verifies that the retry middleware makes sure that the working service is eventually reached. assert.Equal(s.T(), http.StatusOK, response.StatusCode) } func (s *RetrySuite) TestRetryBackoff() { file := s.adaptFile("fixtures/retry/backoff.toml", struct{ WhoamiIP string }{s.whoamiIP}) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("PathPrefix(`/`)")) require.NoError(s.T(), err) response, err := http.Get("http://127.0.0.1:8000/") require.NoError(s.T(), err) // The test only verifies that the retry middleware allows finally to reach the working service. assert.Equal(s.T(), http.StatusOK, response.StatusCode) } func (s *RetrySuite) TestRetryWebsocket() { file := s.adaptFile("fixtures/retry/simple.toml", struct{ WhoamiIP string }{s.whoamiIP}) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("PathPrefix(`/`)")) require.NoError(s.T(), err) // The test only verifies that the retry middleware makes sure that the working service is eventually reached. _, response, err := websocket.DefaultDialer.Dial("ws://127.0.0.1:8000/echo", nil) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusSwitchingProtocols, response.StatusCode) // The test verifies a second time that the working service is eventually reached. _, response, err = websocket.DefaultDialer.Dial("ws://127.0.0.1:8000/echo", nil) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusSwitchingProtocols, response.StatusCode) } func (s *RetrySuite) TestRetryWithStripPrefix() { file := s.adaptFile("fixtures/retry/strip_prefix.toml", struct{ WhoamiIP string }{s.whoamiIP}) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("PathPrefix(`/`)")) require.NoError(s.T(), err) response, err := http.Get("http://127.0.0.1:8000/test") require.NoError(s.T(), err) body, err := io.ReadAll(response.Body) require.NoError(s.T(), err) assert.Contains(s.T(), string(body), "GET / HTTP/1.1") assert.Contains(s.T(), string(body), "X-Forwarded-Prefix: /test") }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/grpc_test.go
integration/grpc_test.go
package integration import ( "context" "crypto/tls" "crypto/x509" "errors" "math/rand" "net" "os" "testing" "time" "github.com/rs/zerolog/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/helloworld" "github.com/traefik/traefik/v3/integration/try" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" ) var ( LocalhostCert []byte LocalhostKey []byte ) const randCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" // GRPCSuite tests suite. type GRPCSuite struct{ BaseSuite } func TestGRPCSuite(t *testing.T) { suite.Run(t, new(GRPCSuite)) } type myserver struct { stopStreamExample chan bool } func (s *GRPCSuite) SetupSuite() { var err error LocalhostCert, err = os.ReadFile("./resources/tls/local.cert") assert.NoError(s.T(), err) LocalhostKey, err = os.ReadFile("./resources/tls/local.key") assert.NoError(s.T(), err) } func (s *myserver) SayHello(ctx context.Context, in *helloworld.HelloRequest) (*helloworld.HelloReply, error) { return &helloworld.HelloReply{Message: "Hello " + in.GetName()}, nil } func (s *myserver) StreamExample(in *helloworld.StreamExampleRequest, server helloworld.Greeter_StreamExampleServer) error { data := make([]byte, 512) for i := range data { data[i] = randCharset[rand.Intn(len(randCharset))] } if err := server.Send(&helloworld.StreamExampleReply{Data: string(data)}); err != nil { log.Error().Err(err).Send() } <-s.stopStreamExample return nil } func startGRPCServer(lis net.Listener, server *myserver) error { cert, err := tls.X509KeyPair(LocalhostCert, LocalhostKey) if err != nil { return err } creds := credentials.NewServerTLSFromCert(&cert) serverOption := grpc.Creds(creds) s := grpc.NewServer(serverOption) defer s.Stop() helloworld.RegisterGreeterServer(s, server) return s.Serve(lis) } func starth2cGRPCServer(lis net.Listener, server *myserver) error { s := grpc.NewServer() defer s.Stop() helloworld.RegisterGreeterServer(s, server) return s.Serve(lis) } func getHelloClientGRPC() (helloworld.GreeterClient, func() error, error) { roots := x509.NewCertPool() roots.AppendCertsFromPEM(LocalhostCert) credsClient := credentials.NewClientTLSFromCert(roots, "") conn, err := grpc.NewClient("127.0.0.1:4443", grpc.WithTransportCredentials(credsClient)) if err != nil { return nil, func() error { return nil }, err } return helloworld.NewGreeterClient(conn), conn.Close, nil } func getHelloClientGRPCh2c() (helloworld.GreeterClient, func() error, error) { conn, err := grpc.NewClient("127.0.0.1:8081", grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { return nil, func() error { return nil }, err } return helloworld.NewGreeterClient(conn), conn.Close, nil } func callHelloClientGRPC(t *testing.T, name string, secure bool) (string, error) { t.Helper() var client helloworld.GreeterClient var closer func() error var err error if secure { client, closer, err = getHelloClientGRPC() } else { client, closer, err = getHelloClientGRPCh2c() } defer func() { _ = closer() }() if err != nil { return "", err } r, err := client.SayHello(t.Context(), &helloworld.HelloRequest{Name: name}) if err != nil { return "", err } return r.GetMessage(), nil } func callStreamExampleClientGRPC(t *testing.T) (helloworld.Greeter_StreamExampleClient, func() error, error) { t.Helper() client, closer, err := getHelloClientGRPC() if err != nil { return nil, closer, err } s, err := client.StreamExample(t.Context(), &helloworld.StreamExampleRequest{}) if err != nil { return nil, closer, err } return s, closer, nil } func (s *GRPCSuite) TestGRPC() { lis, err := net.Listen("tcp", ":0") assert.NoError(s.T(), err) _, port, err := net.SplitHostPort(lis.Addr().String()) assert.NoError(s.T(), err) go func() { err := startGRPCServer(lis, &myserver{}) assert.NoError(s.T(), err) }() file := s.adaptFile("fixtures/grpc/config.toml", struct { CertContent string KeyContent string GRPCServerPort string }{ CertContent: string(LocalhostCert), KeyContent: string(LocalhostKey), GRPCServerPort: port, }) s.traefikCmd(withConfigFile(file)) // wait for Traefik err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`127.0.0.1`)")) assert.NoError(s.T(), err) var response string err = try.Do(1*time.Second, func() error { response, err = callHelloClientGRPC(s.T(), "World", true) return err }) assert.NoError(s.T(), err) assert.Equal(s.T(), "Hello World", response) } func (s *GRPCSuite) TestGRPCh2c() { lis, err := net.Listen("tcp", ":0") assert.NoError(s.T(), err) _, port, err := net.SplitHostPort(lis.Addr().String()) assert.NoError(s.T(), err) go func() { err := starth2cGRPCServer(lis, &myserver{}) assert.NoError(s.T(), err) }() file := s.adaptFile("fixtures/grpc/config_h2c.toml", struct { GRPCServerPort string }{ GRPCServerPort: port, }) s.traefikCmd(withConfigFile(file)) // wait for Traefik err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`127.0.0.1`)")) assert.NoError(s.T(), err) var response string err = try.Do(1*time.Second, func() error { response, err = callHelloClientGRPC(s.T(), "World", false) return err }) assert.NoError(s.T(), err) assert.Equal(s.T(), "Hello World", response) } func (s *GRPCSuite) TestGRPCh2cTermination() { lis, err := net.Listen("tcp", ":0") assert.NoError(s.T(), err) _, port, err := net.SplitHostPort(lis.Addr().String()) assert.NoError(s.T(), err) go func() { err := starth2cGRPCServer(lis, &myserver{}) assert.NoError(s.T(), err) }() file := s.adaptFile("fixtures/grpc/config_h2c_termination.toml", struct { CertContent string KeyContent string GRPCServerPort string }{ CertContent: string(LocalhostCert), KeyContent: string(LocalhostKey), GRPCServerPort: port, }) s.traefikCmd(withConfigFile(file)) // wait for Traefik err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`127.0.0.1`)")) assert.NoError(s.T(), err) var response string err = try.Do(1*time.Second, func() error { response, err = callHelloClientGRPC(s.T(), "World", true) return err }) assert.NoError(s.T(), err) assert.Equal(s.T(), "Hello World", response) } func (s *GRPCSuite) TestGRPCInsecure() { lis, err := net.Listen("tcp", ":0") assert.NoError(s.T(), err) _, port, err := net.SplitHostPort(lis.Addr().String()) assert.NoError(s.T(), err) go func() { err := startGRPCServer(lis, &myserver{}) assert.NoError(s.T(), err) }() file := s.adaptFile("fixtures/grpc/config_insecure.toml", struct { CertContent string KeyContent string GRPCServerPort string }{ CertContent: string(LocalhostCert), KeyContent: string(LocalhostKey), GRPCServerPort: port, }) s.traefikCmd(withConfigFile(file)) // wait for Traefik err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`127.0.0.1`)")) assert.NoError(s.T(), err) var response string err = try.Do(1*time.Second, func() error { response, err = callHelloClientGRPC(s.T(), "World", true) return err }) assert.NoError(s.T(), err) assert.Equal(s.T(), "Hello World", response) } func (s *GRPCSuite) TestGRPCBuffer() { stopStreamExample := make(chan bool) defer func() { stopStreamExample <- true }() lis, err := net.Listen("tcp", ":0") assert.NoError(s.T(), err) _, port, err := net.SplitHostPort(lis.Addr().String()) assert.NoError(s.T(), err) go func() { err := startGRPCServer(lis, &myserver{ stopStreamExample: stopStreamExample, }) assert.NoError(s.T(), err) }() file := s.adaptFile("fixtures/grpc/config.toml", struct { CertContent string KeyContent string GRPCServerPort string }{ CertContent: string(LocalhostCert), KeyContent: string(LocalhostKey), GRPCServerPort: port, }) s.traefikCmd(withConfigFile(file)) // wait for Traefik err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`127.0.0.1`)")) assert.NoError(s.T(), err) var client helloworld.Greeter_StreamExampleClient client, closer, err := callStreamExampleClientGRPC(s.T()) defer func() { _ = closer() }() assert.NoError(s.T(), err) received := make(chan bool) go func() { tr, err := client.Recv() assert.NoError(s.T(), err) assert.Len(s.T(), tr.GetData(), 512) received <- true }() err = try.Do(10*time.Second, func() error { select { case <-received: return nil default: return errors.New("failed to receive stream data") } }) assert.NoError(s.T(), err) } func (s *GRPCSuite) TestGRPCBufferWithFlushInterval() { stopStreamExample := make(chan bool) lis, err := net.Listen("tcp", ":0") assert.NoError(s.T(), err) _, port, err := net.SplitHostPort(lis.Addr().String()) assert.NoError(s.T(), err) go func() { err := startGRPCServer(lis, &myserver{ stopStreamExample: stopStreamExample, }) assert.NoError(s.T(), err) }() file := s.adaptFile("fixtures/grpc/config.toml", struct { CertContent string KeyContent string GRPCServerPort string }{ CertContent: string(LocalhostCert), KeyContent: string(LocalhostKey), GRPCServerPort: port, }) s.traefikCmd(withConfigFile(file)) // wait for Traefik err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`127.0.0.1`)")) assert.NoError(s.T(), err) var client helloworld.Greeter_StreamExampleClient client, closer, err := callStreamExampleClientGRPC(s.T()) defer func() { _ = closer() stopStreamExample <- true }() assert.NoError(s.T(), err) received := make(chan bool) go func() { tr, err := client.Recv() assert.NoError(s.T(), err) assert.Len(s.T(), tr.GetData(), 512) received <- true }() err = try.Do(100*time.Millisecond, func() error { select { case <-received: return nil default: return errors.New("failed to receive stream data") } }) assert.NoError(s.T(), err) } func (s *GRPCSuite) TestGRPCWithRetry() { lis, err := net.Listen("tcp", ":0") assert.NoError(s.T(), err) _, port, err := net.SplitHostPort(lis.Addr().String()) assert.NoError(s.T(), err) go func() { err := startGRPCServer(lis, &myserver{}) assert.NoError(s.T(), err) }() file := s.adaptFile("fixtures/grpc/config_retry.toml", struct { CertContent string KeyContent string GRPCServerPort string }{ CertContent: string(LocalhostCert), KeyContent: string(LocalhostKey), GRPCServerPort: port, }) s.traefikCmd(withConfigFile(file)) // wait for Traefik err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`127.0.0.1`)")) assert.NoError(s.T(), err) var response string err = try.Do(1*time.Second, func() error { response, err = callHelloClientGRPC(s.T(), "World", true) return err }) assert.NoError(s.T(), err) assert.Equal(s.T(), "Hello World", response) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/dual_logging_test.go
integration/dual_logging_test.go
package integration import ( "compress/gzip" "encoding/json" "io" "net/http" "net/http/httptest" "os" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" "go.opentelemetry.io/collector/pdata/plog/plogotlp" ) const traefikTestOTLPLogFile = "traefik_otlp.log" // DualLoggingSuite tests that both OTLP and stdout logging can work together. type DualLoggingSuite struct { BaseSuite otlpLogs []string collector *httptest.Server } func TestDualLoggingSuite(t *testing.T) { suite.Run(t, new(DualLoggingSuite)) } func (s *DualLoggingSuite) SetupSuite() { s.BaseSuite.SetupSuite() // Clean up any existing log files os.Remove(traefikTestLogFile) os.Remove(traefikTestOTLPLogFile) } func (s *DualLoggingSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() // Clean up log files generatedFiles := []string{ traefikTestLogFile, traefikTestOTLPLogFile, } for _, filename := range generatedFiles { if err := os.Remove(filename); err != nil { s.T().Logf("Failed to remove %s: %v", filename, err) } } } func (s *DualLoggingSuite) SetupTest() { s.otlpLogs = []string{} // Create mock OTLP collector s.collector = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() gzr, err := gzip.NewReader(r.Body) if err != nil { s.T().Logf("Error creating gzip reader: %v", err) http.Error(w, err.Error(), http.StatusBadRequest) return } defer gzr.Close() body, err := io.ReadAll(gzr) if err != nil { s.T().Logf("Error reading gzipped body: %v", err) http.Error(w, err.Error(), http.StatusBadRequest) return } req := plogotlp.NewExportRequest() err = req.UnmarshalProto(body) if err != nil { s.T().Logf("Error unmarshaling protobuf: %v", err) http.Error(w, err.Error(), http.StatusBadRequest) return } marshalledReq, err := json.Marshal(req) if err != nil { s.T().Logf("Error marshaling to JSON: %v", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } s.otlpLogs = append(s.otlpLogs, string(marshalledReq)) w.WriteHeader(http.StatusOK) })) } func (s *DualLoggingSuite) TearDownTest() { if s.collector != nil { s.collector.Close() s.collector = nil } } func (s *DualLoggingSuite) TestOTLPAndStdoutLogging() { tempObjects := struct { CollectorURL string }{ CollectorURL: s.collector.URL + "/v1/logs", } file := s.adaptFile("fixtures/dual_logging/otlp_and_stdout.toml", tempObjects) cmd, display := s.cmdTraefik(withConfigFile(file)) defer s.displayTraefikLogFile(traefikTestLogFile) s.waitForTraefik("dashboard") time.Sleep(3 * time.Second) s.killCmd(cmd) time.Sleep(1 * time.Second) assert.NotEmpty(s.T(), s.otlpLogs) output := display.String() otlpOutput := strings.Join(s.otlpLogs, "\n") foundStdoutLog := strings.Contains(output, "Starting provider") assert.True(s.T(), foundStdoutLog) foundOTLPLog := strings.Contains(otlpOutput, "Starting provider") assert.True(s.T(), foundOTLPLog) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/consul_test.go
integration/consul_test.go
package integration import ( "bytes" "encoding/json" "errors" "fmt" "net" "net/http" "os" "path/filepath" "testing" "time" "github.com/kvtools/consul" "github.com/kvtools/valkeyrie" "github.com/kvtools/valkeyrie/store" "github.com/pmezard/go-difflib/difflib" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" "github.com/traefik/traefik/v3/pkg/api" ) // Consul test suites. type ConsulSuite struct { BaseSuite kvClient store.Store consulURL string } func TestConsulSuite(t *testing.T) { suite.Run(t, new(ConsulSuite)) } func (s *ConsulSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("consul") s.composeUp() consulAddr := net.JoinHostPort(s.getComposeServiceIP("consul"), "8500") s.consulURL = fmt.Sprintf("http://%s", consulAddr) kv, err := valkeyrie.NewStore( s.T().Context(), consul.StoreName, []string{consulAddr}, &consul.Config{ ConnectionTimeout: 10 * time.Second, }, ) require.NoError(s.T(), err, "Cannot create store consul") s.kvClient = kv // wait for consul err = try.Do(60*time.Second, try.KVExists(kv, "test")) require.NoError(s.T(), err) } func (s *ConsulSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *ConsulSuite) TearDownTest() { err := s.kvClient.DeleteTree(s.T().Context(), "traefik") if err != nil && !errors.Is(err, store.ErrKeyNotFound) { require.ErrorIs(s.T(), err, store.ErrKeyNotFound) } } func (s *ConsulSuite) TestSimpleConfiguration() { file := s.adaptFile("fixtures/consul/simple.toml", struct{ ConsulAddress string }{s.consulURL}) data := map[string]string{ "traefik/http/routers/Router0/entryPoints/0": "web", "traefik/http/routers/Router0/middlewares/0": "compressor", "traefik/http/routers/Router0/middlewares/1": "striper", "traefik/http/routers/Router0/service": "simplesvc", "traefik/http/routers/Router0/rule": "Host(`kv1.localhost`)", "traefik/http/routers/Router0/priority": "42", "traefik/http/routers/Router0/tls": "", "traefik/http/routers/Router1/rule": "Host(`kv2.localhost`)", "traefik/http/routers/Router1/priority": "42", "traefik/http/routers/Router1/tls/domains/0/main": "aaa.localhost", "traefik/http/routers/Router1/tls/domains/0/sans/0": "aaa.aaa.localhost", "traefik/http/routers/Router1/tls/domains/0/sans/1": "bbb.aaa.localhost", "traefik/http/routers/Router1/tls/domains/1/main": "bbb.localhost", "traefik/http/routers/Router1/tls/domains/1/sans/0": "aaa.bbb.localhost", "traefik/http/routers/Router1/tls/domains/1/sans/1": "bbb.bbb.localhost", "traefik/http/routers/Router1/entryPoints/0": "web", "traefik/http/routers/Router1/service": "simplesvc", "traefik/http/services/simplesvc/loadBalancer/servers/0/url": "http://10.0.1.1:8888", "traefik/http/services/simplesvc/loadBalancer/servers/1/url": "http://10.0.1.1:8889", "traefik/http/services/srvcA/loadBalancer/servers/0/url": "http://10.0.1.2:8888", "traefik/http/services/srvcA/loadBalancer/servers/1/url": "http://10.0.1.2:8889", "traefik/http/services/srvcB/loadBalancer/servers/0/url": "http://10.0.1.3:8888", "traefik/http/services/srvcB/loadBalancer/servers/1/url": "http://10.0.1.3:8889", "traefik/http/services/mirror/mirroring/service": "simplesvc", "traefik/http/services/mirror/mirroring/mirrors/0/name": "srvcA", "traefik/http/services/mirror/mirroring/mirrors/0/percent": "42", "traefik/http/services/mirror/mirroring/mirrors/1/name": "srvcB", "traefik/http/services/mirror/mirroring/mirrors/1/percent": "42", "traefik/http/services/Service03/weighted/services/0/name": "srvcA", "traefik/http/services/Service03/weighted/services/0/weight": "42", "traefik/http/services/Service03/weighted/services/1/name": "srvcB", "traefik/http/services/Service03/weighted/services/1/weight": "42", "traefik/http/middlewares/compressor/compress": "", "traefik/http/middlewares/striper/stripPrefix/prefixes/0": "foo", "traefik/http/middlewares/striper/stripPrefix/prefixes/1": "bar", } for k, v := range data { err := s.kvClient.Put(s.T().Context(), k, []byte(v), nil) require.NoError(s.T(), err) } s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 2*time.Second, try.BodyContains(`"striper@consul":`, `"compressor@consul":`, `"srvcA@consul":`, `"srvcB@consul":`), ) require.NoError(s.T(), err) resp, err := http.Get("http://127.0.0.1:8080/api/rawdata") require.NoError(s.T(), err) var obtained api.RunTimeRepresentation err = json.NewDecoder(resp.Body).Decode(&obtained) require.NoError(s.T(), err) got, err := json.MarshalIndent(obtained, "", " ") require.NoError(s.T(), err) expectedJSON := filepath.FromSlash("testdata/rawdata-consul.json") if *updateExpected { err = os.WriteFile(expectedJSON, got, 0o666) require.NoError(s.T(), err) } expected, err := os.ReadFile(expectedJSON) require.NoError(s.T(), err) if !bytes.Equal(expected, got) { diff := difflib.UnifiedDiff{ FromFile: "Expected", A: difflib.SplitLines(string(expected)), ToFile: "Got", B: difflib.SplitLines(string(got)), Context: 3, } text, err := difflib.GetUnifiedDiffString(diff) require.NoError(s.T(), err, text) } } func (s *ConsulSuite) assertWhoami(host string, expectedStatusCode int) { req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000", nil) require.NoError(s.T(), err) req.Host = host resp, err := try.ResponseUntilStatusCode(req, 15*time.Second, expectedStatusCode) require.NoError(s.T(), err) resp.Body.Close() } func (s *ConsulSuite) TestDeleteRootKey() { // This test case reproduce the issue: https://github.com/traefik/traefik/issues/8092 file := s.adaptFile("fixtures/consul/simple.toml", struct{ ConsulAddress string }{s.consulURL}) ctx := s.T().Context() svcaddr := net.JoinHostPort(s.getComposeServiceIP("whoami"), "80") data := map[string]string{ "traefik/http/routers/Router0/entryPoints/0": "web", "traefik/http/routers/Router0/rule": "Host(`kv1.localhost`)", "traefik/http/routers/Router0/service": "simplesvc0", "traefik/http/routers/Router1/entryPoints/0": "web", "traefik/http/routers/Router1/rule": "Host(`kv2.localhost`)", "traefik/http/routers/Router1/service": "simplesvc1", "traefik/http/services/simplesvc0/loadBalancer/servers/0/url": "http://" + svcaddr, "traefik/http/services/simplesvc1/loadBalancer/servers/0/url": "http://" + svcaddr, } for k, v := range data { err := s.kvClient.Put(ctx, k, []byte(v), nil) require.NoError(s.T(), err) } s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 2*time.Second, try.BodyContains(`"Router0@consul":`, `"Router1@consul":`, `"simplesvc0@consul":`, `"simplesvc1@consul":`), ) require.NoError(s.T(), err) s.assertWhoami("kv1.localhost", http.StatusOK) s.assertWhoami("kv2.localhost", http.StatusOK) // delete router1 err = s.kvClient.DeleteTree(ctx, "traefik/http/routers/Router1") require.NoError(s.T(), err) s.assertWhoami("kv1.localhost", http.StatusOK) s.assertWhoami("kv2.localhost", http.StatusNotFound) // delete simple services and router0 err = s.kvClient.DeleteTree(ctx, "traefik") require.NoError(s.T(), err) s.assertWhoami("kv1.localhost", http.StatusNotFound) s.assertWhoami("kv2.localhost", http.StatusNotFound) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/file_test.go
integration/file_test.go
package integration import ( "net/http" "testing" "time" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) // File tests suite. type FileSuite struct{ BaseSuite } func TestFileSuite(t *testing.T) { suite.Run(t, new(FileSuite)) } func (s *FileSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("file") s.composeUp() } func (s *FileSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *FileSuite) TestSimpleConfiguration() { file := s.adaptFile("fixtures/file/simple.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) // Expected a 404 as we did not configure anything err := try.GetRequest("http://127.0.0.1:8000/", 1000*time.Millisecond, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) } // #56 regression test, make sure it does not fail? func (s *FileSuite) TestSimpleConfigurationNoPanic() { s.traefikCmd(withConfigFile("fixtures/file/56-simple-panic.toml")) // Expected a 404 as we did not configure anything err := try.GetRequest("http://127.0.0.1:8000/", 1000*time.Millisecond, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) } func (s *FileSuite) TestDirectoryConfiguration() { s.traefikCmd(withConfigFile("fixtures/file/directory.toml")) // Expected a 404 as we did not configure anything at /test err := try.GetRequest("http://127.0.0.1:8000/test", 1000*time.Millisecond, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) // Expected a 502 as there is no backend server err = try.GetRequest("http://127.0.0.1:8000/test2", 1000*time.Millisecond, try.StatusCodeIs(http.StatusBadGateway)) require.NoError(s.T(), err) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/keepalive_test.go
integration/keepalive_test.go
package integration import ( "math" "net" "net/http" "net/http/httptest" "testing" "time" "github.com/rs/zerolog/log" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) type KeepAliveSuite struct { BaseSuite } func TestKeepAliveSuite(t *testing.T) { suite.Run(t, new(KeepAliveSuite)) } type KeepAliveConfig struct { KeepAliveServer string IdleConnTimeout string } type connStateChangeEvent struct { key string state http.ConnState } func (s *KeepAliveSuite) TestShouldRespectConfiguredBackendHttpKeepAliveTime() { idleTimeout := time.Duration(75) * time.Millisecond connStateChanges := make(chan connStateChangeEvent) noMoreRequests := make(chan bool, 1) completed := make(chan bool, 1) // keep track of HTTP connections and their status changes and measure their idle period go func() { connCount := 0 idlePeriodStartMap := make(map[string]time.Time) idlePeriodLengthMap := make(map[string]time.Duration) maxWaitDuration := 5 * time.Second maxWaitTimeExceeded := time.After(maxWaitDuration) moreRequestsExpected := true // Ensure that all idle HTTP connections are closed before verification phase for moreRequestsExpected || len(idlePeriodLengthMap) < connCount { select { case event := <-connStateChanges: switch event.state { case http.StateNew: connCount++ case http.StateIdle: idlePeriodStartMap[event.key] = time.Now() case http.StateClosed: idlePeriodLengthMap[event.key] = time.Since(idlePeriodStartMap[event.key]) } case <-noMoreRequests: moreRequestsExpected = false case <-maxWaitTimeExceeded: log.Info().Msgf("timeout waiting for all connections to close, waited for %v, configured idle timeout was %v", maxWaitDuration, idleTimeout) s.T().Fail() close(completed) return } } require.Equal(s.T(), 1, connCount) for _, idlePeriod := range idlePeriodLengthMap { // Our method of measuring the actual idle period is not precise, so allow some sub-ms deviation require.LessOrEqual(s.T(), math.Round(idlePeriod.Seconds()), idleTimeout.Seconds()) } close(completed) }() server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) server.Config.ConnState = func(conn net.Conn, state http.ConnState) { connStateChanges <- connStateChangeEvent{key: conn.RemoteAddr().String(), state: state} } server.Start() defer server.Close() config := KeepAliveConfig{KeepAliveServer: server.URL, IdleConnTimeout: idleTimeout.String()} file := s.adaptFile("fixtures/timeout/keepalive.toml", config) s.traefikCmd(withConfigFile(file)) // Wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", time.Duration(1)*time.Second, try.StatusCodeIs(200), try.BodyContains("PathPrefix(`/keepalive`)")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/keepalive", time.Duration(1)*time.Second, try.StatusCodeIs(200)) require.NoError(s.T(), err) close(noMoreRequests) <-completed }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/redis_sentinel_test.go
integration/redis_sentinel_test.go
package integration import ( "bytes" "encoding/json" "fmt" "net" "net/http" "os" "path/filepath" "strings" "testing" "text/template" "time" "github.com/fatih/structs" "github.com/kvtools/redis" "github.com/kvtools/valkeyrie" "github.com/kvtools/valkeyrie/store" "github.com/pmezard/go-difflib/difflib" "github.com/rs/zerolog/log" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" "github.com/traefik/traefik/v3/pkg/api" ) // Redis test suites. type RedisSentinelSuite struct { BaseSuite kvClient store.Store redisEndpoints []string } func TestRedisSentinelSuite(t *testing.T) { suite.Run(t, new(RedisSentinelSuite)) } func (s *RedisSentinelSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.setupSentinelConfiguration([]string{"26379", "26379", "26379"}) s.createComposeProject("redis_sentinel") s.composeUp() s.redisEndpoints = []string{ net.JoinHostPort(s.getComposeServiceIP("sentinel1"), "26379"), net.JoinHostPort(s.getComposeServiceIP("sentinel2"), "26379"), net.JoinHostPort(s.getComposeServiceIP("sentinel3"), "26379"), } kv, err := valkeyrie.NewStore( s.T().Context(), redis.StoreName, s.redisEndpoints, &redis.Config{ Sentinel: &redis.Sentinel{ MasterName: "mymaster", }, }, ) require.NoError(s.T(), err, "Cannot create store redis") s.kvClient = kv // wait for redis err = try.Do(60*time.Second, try.KVExists(kv, "test")) require.NoError(s.T(), err) } func (s *RedisSentinelSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() for _, filename := range []string{"sentinel1.conf", "sentinel2.conf", "sentinel3.conf"} { _ = os.Remove(filepath.Join(".", "resources", "compose", "config", filename)) } } func (s *RedisSentinelSuite) setupSentinelConfiguration(ports []string) { for i, port := range ports { templateValue := struct{ SentinelPort string }{SentinelPort: port} // Load file templateFile := "resources/compose/config/sentinel_template.conf" tmpl, err := template.ParseFiles(templateFile) require.NoError(s.T(), err) folder, prefix := filepath.Split(templateFile) fileName := fmt.Sprintf("%s/sentinel%d.conf", folder, i+1) tmpFile, err := os.Create(fileName) require.NoError(s.T(), err) defer tmpFile.Close() err = tmpFile.Chmod(0o666) require.NoError(s.T(), err) model := structs.Map(templateValue) model["SelfFilename"] = tmpFile.Name() err = tmpl.ExecuteTemplate(tmpFile, prefix, model) require.NoError(s.T(), err) err = tmpFile.Sync() require.NoError(s.T(), err) } } func (s *RedisSentinelSuite) TestSentinelConfiguration() { file := s.adaptFile("fixtures/redis/sentinel.toml", struct{ RedisAddress string }{ RedisAddress: strings.Join(s.redisEndpoints, `","`), }) data := map[string]string{ "traefik/http/routers/Router0/entryPoints/0": "web", "traefik/http/routers/Router0/middlewares/0": "compressor", "traefik/http/routers/Router0/middlewares/1": "striper", "traefik/http/routers/Router0/service": "simplesvc", "traefik/http/routers/Router0/rule": "Host(`kv1.localhost`)", "traefik/http/routers/Router0/priority": "42", "traefik/http/routers/Router0/tls": "true", "traefik/http/routers/Router1/rule": "Host(`kv2.localhost`)", "traefik/http/routers/Router1/priority": "42", "traefik/http/routers/Router1/tls/domains/0/main": "aaa.localhost", "traefik/http/routers/Router1/tls/domains/0/sans/0": "aaa.aaa.localhost", "traefik/http/routers/Router1/tls/domains/0/sans/1": "bbb.aaa.localhost", "traefik/http/routers/Router1/tls/domains/1/main": "bbb.localhost", "traefik/http/routers/Router1/tls/domains/1/sans/0": "aaa.bbb.localhost", "traefik/http/routers/Router1/tls/domains/1/sans/1": "bbb.bbb.localhost", "traefik/http/routers/Router1/entryPoints/0": "web", "traefik/http/routers/Router1/service": "simplesvc", "traefik/http/services/simplesvc/loadBalancer/servers/0/url": "http://10.0.1.1:8888", "traefik/http/services/simplesvc/loadBalancer/servers/1/url": "http://10.0.1.1:8889", "traefik/http/services/srvcA/loadBalancer/servers/0/url": "http://10.0.1.2:8888", "traefik/http/services/srvcA/loadBalancer/servers/1/url": "http://10.0.1.2:8889", "traefik/http/services/srvcB/loadBalancer/servers/0/url": "http://10.0.1.3:8888", "traefik/http/services/srvcB/loadBalancer/servers/1/url": "http://10.0.1.3:8889", "traefik/http/services/mirror/mirroring/service": "simplesvc", "traefik/http/services/mirror/mirroring/mirrors/0/name": "srvcA", "traefik/http/services/mirror/mirroring/mirrors/0/percent": "42", "traefik/http/services/mirror/mirroring/mirrors/1/name": "srvcB", "traefik/http/services/mirror/mirroring/mirrors/1/percent": "42", "traefik/http/services/Service03/weighted/services/0/name": "srvcA", "traefik/http/services/Service03/weighted/services/0/weight": "42", "traefik/http/services/Service03/weighted/services/1/name": "srvcB", "traefik/http/services/Service03/weighted/services/1/weight": "42", "traefik/http/middlewares/compressor/compress": "true", "traefik/http/middlewares/striper/stripPrefix/prefixes/0": "foo", "traefik/http/middlewares/striper/stripPrefix/prefixes/1": "bar", } for k, v := range data { err := s.kvClient.Put(s.T().Context(), k, []byte(v), nil) require.NoError(s.T(), err) } s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 2*time.Second, try.BodyContains(`"striper@redis":`, `"compressor@redis":`, `"srvcA@redis":`, `"srvcB@redis":`), ) require.NoError(s.T(), err) resp, err := http.Get("http://127.0.0.1:8080/api/rawdata") require.NoError(s.T(), err) var obtained api.RunTimeRepresentation err = json.NewDecoder(resp.Body).Decode(&obtained) require.NoError(s.T(), err) got, err := json.MarshalIndent(obtained, "", " ") require.NoError(s.T(), err) expectedJSON := filepath.FromSlash("testdata/rawdata-redis.json") if *updateExpected { err = os.WriteFile(expectedJSON, got, 0o666) require.NoError(s.T(), err) } expected, err := os.ReadFile(expectedJSON) require.NoError(s.T(), err) if !bytes.Equal(expected, got) { diff := difflib.UnifiedDiff{ FromFile: "Expected", A: difflib.SplitLines(string(expected)), ToFile: "Got", B: difflib.SplitLines(string(got)), Context: 3, } text, err := difflib.GetUnifiedDiffString(diff) require.NoError(s.T(), err) log.Info().Msg(text) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/headers_test.go
integration/headers_test.go
package integration import ( "net" "net/http" "net/http/httptest" "os" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) // Headers tests suite. type HeadersSuite struct{ BaseSuite } func TestHeadersSuite(t *testing.T) { suite.Run(t, new(HeadersSuite)) } func (s *HeadersSuite) TearDownTest() { s.displayTraefikLogFile(traefikTestLogFile) _ = os.Remove(traefikTestAccessLogFile) } func (s *HeadersSuite) TestSimpleConfiguration() { s.traefikCmd(withConfigFile("fixtures/headers/basic.toml")) // Expected a 404 as we did not configure anything err := try.GetRequest("http://127.0.0.1:8000/", 1000*time.Millisecond, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) } func (s *HeadersSuite) TestReverseProxyHeaderRemoved() { file := s.adaptFile("fixtures/headers/remove_reverseproxy_headers.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, found := r.Header["X-Forwarded-Host"] assert.True(s.T(), found) _, found = r.Header["Foo"] assert.False(s.T(), found) _, found = r.Header["X-Forwarded-For"] assert.False(s.T(), found) }) listener, err := net.Listen("tcp", "127.0.0.1:9000") require.NoError(s.T(), err) ts := &httptest.Server{ Listener: listener, Config: &http.Server{Handler: handler}, } ts.Start() defer ts.Close() req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = "test.localhost" req.Header = http.Header{ "Foo": {"bar"}, } err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) } func (s *HeadersSuite) TestConnectionHopByHop() { file := s.adaptFile("fixtures/headers/connection_hop_by_hop_headers.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, found := r.Header["X-Forwarded-For"] assert.True(s.T(), found) xHost, found := r.Header["X-Forwarded-Host"] assert.True(s.T(), found) assert.Equal(s.T(), "localhost", xHost[0]) _, found = r.Header["Foo"] assert.False(s.T(), found) _, found = r.Header["Bar"] assert.False(s.T(), found) }) listener, err := net.Listen("tcp", "127.0.0.1:9000") require.NoError(s.T(), err) ts := &httptest.Server{ Listener: listener, Config: &http.Server{Handler: handler}, } ts.Start() defer ts.Close() req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = "test.localhost" req.Header = http.Header{ "Connection": {"Foo,Bar,X-Forwarded-For,X-Forwarded-Host"}, "Foo": {"bar"}, "Bar": {"foo"}, "X-Forwarded-Host": {"localhost"}, } err = try.Request(req, time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) accessLog, err := os.ReadFile(traefikTestAccessLogFile) require.NoError(s.T(), err) assert.Contains(s.T(), string(accessLog), "\"request_Foo\":\"bar\"") assert.NotContains(s.T(), string(accessLog), "\"request_Bar\":\"\"") } func (s *HeadersSuite) TestCorsResponses() { file := s.adaptFile("fixtures/headers/cors.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) backend := startTestServer("9000", http.StatusOK, "") defer backend.Close() err := try.GetRequest(backend.URL, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) testCase := []struct { desc string requestHeaders http.Header expected http.Header reqHost string method string }{ { desc: "simple access control allow origin", requestHeaders: http.Header{ "Origin": {"https://foo.bar.org"}, }, expected: http.Header{ "Access-Control-Allow-Origin": {"https://foo.bar.org"}, "Vary": {"Origin"}, }, reqHost: "test.localhost", method: http.MethodGet, }, { desc: "simple preflight request", requestHeaders: http.Header{ "Access-Control-Request-Headers": {"origin"}, "Access-Control-Request-Method": {"GET", "OPTIONS"}, "Origin": {"https://foo.bar.org"}, }, expected: http.Header{ "Access-Control-Allow-Origin": {"https://foo.bar.org"}, "Access-Control-Max-Age": {"100"}, "Access-Control-Allow-Methods": {"GET,OPTIONS,PUT"}, }, reqHost: "test.localhost", method: http.MethodOptions, }, { desc: "preflight Options request with no cors configured", requestHeaders: http.Header{ "Access-Control-Request-Headers": {"origin"}, "Access-Control-Request-Method": {"GET", "OPTIONS"}, "Origin": {"https://foo.bar.org"}, }, expected: http.Header{ "X-Custom-Response-Header": {"True"}, }, reqHost: "test2.localhost", method: http.MethodOptions, }, { desc: "preflight Get request with no cors configured", requestHeaders: http.Header{ "Access-Control-Request-Headers": {"origin"}, "Access-Control-Request-Method": {"GET", "OPTIONS"}, "Origin": {"https://foo.bar.org"}, }, expected: http.Header{ "X-Custom-Response-Header": {"True"}, }, reqHost: "test2.localhost", method: http.MethodGet, }, } for _, test := range testCase { req, err := http.NewRequest(test.method, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = test.reqHost req.Header = test.requestHeaders err = try.Request(req, 500*time.Millisecond, try.HasHeaderStruct(test.expected)) require.NoError(s.T(), err) } } func (s *HeadersSuite) TestSecureHeadersResponses() { file := s.adaptFile("fixtures/headers/secure.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) backend := startTestServer("9000", http.StatusOK, "") defer backend.Close() err := try.GetRequest(backend.URL, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) testCase := []struct { desc string expected http.Header reqHost string internalReqHost string }{ { desc: "Permissions-Policy Set", expected: http.Header{ "Permissions-Policy": {"microphone=(),"}, }, reqHost: "test.localhost", internalReqHost: "internal.localhost", }, } for _, test := range testCase { req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = test.reqHost err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasHeaderStruct(test.expected)) require.NoError(s.T(), err) req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/api/rawdata", nil) require.NoError(s.T(), err) req.Host = test.internalReqHost err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasHeaderStruct(test.expected)) require.NoError(s.T(), err) } } func (s *HeadersSuite) TestMultipleSecureHeadersResponses() { file := s.adaptFile("fixtures/headers/secure_multiple.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) backend := startTestServer("9000", http.StatusOK, "") defer backend.Close() err := try.GetRequest(backend.URL, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) testCase := []struct { desc string expected http.Header reqHost string }{ { desc: "Multiple Secure Headers Set", expected: http.Header{ "X-Frame-Options": {"DENY"}, "X-Content-Type-Options": {"nosniff"}, }, reqHost: "test.localhost", }, } for _, test := range testCase { req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = test.reqHost err = try.Request(req, 500*time.Millisecond, try.HasHeaderStruct(test.expected)) require.NoError(s.T(), err) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/knative_conformance_test.go
integration/knative_conformance_test.go
// Use a build tag to include and run Knative conformance tests. // The Knative conformance toolkit redefines the skip-tests flag, // which conflicts with the testing library and causes a panic. //go:build knativeConformance package integration import ( "flag" "io" "os" "slices" "testing" "time" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/modules/k3s" "github.com/testcontainers/testcontainers-go/network" "github.com/traefik/traefik/v3/integration/try" "knative.dev/networking/test/conformance/ingress" klog "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/log/zap" ) const knativeNamespace = "knative-serving" var imageNames = []string{ traefikImage, "ko.local/grpc-ping:latest", "ko.local/httpproxy:latest", "ko.local/retry:latest", "ko.local/runtime:latest", "ko.local/wsserver:latest", "ko.local/timeout:latest", } type KnativeConformanceSuite struct { BaseSuite k3sContainer *k3s.K3sContainer } func TestKnativeConformanceSuite(t *testing.T) { suite.Run(t, new(KnativeConformanceSuite)) } func (s *KnativeConformanceSuite) SetupSuite() { s.BaseSuite.SetupSuite() // Avoid panic. klog.SetLogger(zap.New()) provider, err := testcontainers.ProviderDocker.GetProvider() if err != nil { s.T().Fatal(err) } ctx := s.T().Context() // Ensure image is available locally. images, err := provider.ListImages(ctx) if err != nil { s.T().Fatal(err) } if !slices.ContainsFunc(images, func(img testcontainers.ImageInfo) bool { return img.Name == traefikImage }) { s.T().Fatal("Traefik image is not present") } s.k3sContainer, err = k3s.Run(ctx, k3sImage, k3s.WithManifest("./fixtures/knative/00-knative-crd-v1.19.0.yml"), k3s.WithManifest("./fixtures/knative/01-rbac.yml"), k3s.WithManifest("./fixtures/knative/02-traefik.yml"), k3s.WithManifest("./fixtures/knative/03-knative-serving-v1.19.0.yaml"), k3s.WithManifest("./fixtures/knative/04-serving-tests-namespace.yaml"), network.WithNetwork(nil, s.network), ) if err != nil { s.T().Fatal(err) } for _, imageName := range imageNames { if err = s.k3sContainer.LoadImages(ctx, imageName); err != nil { s.T().Fatal(err) } } exitCode, _, err := s.k3sContainer.Exec(ctx, []string{"kubectl", "wait", "-n", traefikNamespace, traefikDeployment, "--for=condition=Available", "--timeout=10s"}) if err != nil || exitCode > 0 { s.T().Fatalf("Traefik pod is not ready: %v", err) } exitCode, _, err = s.k3sContainer.Exec(ctx, []string{"kubectl", "wait", "-n", knativeNamespace, "deployment/activator", "--for=condition=Available", "--timeout=10s"}) if err != nil || exitCode > 0 { s.T().Fatalf("Activator pod is not ready: %v", err) } exitCode, _, err = s.k3sContainer.Exec(ctx, []string{"kubectl", "wait", "-n", knativeNamespace, "deployment/controller", "--for=condition=Available", "--timeout=10s"}) if err != nil || exitCode > 0 { s.T().Fatalf("Controller pod is not ready: %v", err) } exitCode, _, err = s.k3sContainer.Exec(ctx, []string{"kubectl", "wait", "-n", knativeNamespace, "deployment/autoscaler", "--for=condition=Available", "--timeout=10s"}) if err != nil || exitCode > 0 { s.T().Fatalf("Autoscaler pod is not ready: %v", err) } exitCode, _, err = s.k3sContainer.Exec(ctx, []string{"kubectl", "wait", "-n", knativeNamespace, "deployment/webhook", "--for=condition=Available", "--timeout=10s"}) if err != nil || exitCode > 0 { s.T().Fatalf("Webhook pod is not ready: %v", err) } } func (s *KnativeConformanceSuite) TearDownSuite() { ctx := s.T().Context() if s.T().Failed() || *showLog { k3sLogs, err := s.k3sContainer.Logs(ctx) if err == nil { if res, err := io.ReadAll(k3sLogs); err == nil { s.T().Log(string(res)) } } exitCode, result, err := s.k3sContainer.Exec(ctx, []string{"kubectl", "logs", "-n", traefikNamespace, traefikDeployment}) if err == nil || exitCode == 0 { if res, err := io.ReadAll(result); err == nil { s.T().Log(string(res)) } } } if err := s.k3sContainer.Terminate(ctx); err != nil { s.T().Fatal(err) } s.BaseSuite.TearDownSuite() } func (s *KnativeConformanceSuite) TestKnativeConformance() { // Wait for traefik to start k3sContainerIP, err := s.k3sContainer.ContainerIP(s.T().Context()) require.NoError(s.T(), err) err = try.GetRequest("http://"+k3sContainerIP+":9000/api/entrypoints", 10*time.Second, try.BodyContains(`"name":"pweb"`)) require.NoError(s.T(), err) kubeconfig, err := s.k3sContainer.GetKubeConfig(s.T().Context()) if err != nil { s.T().Fatal(err) } // Write the kubeconfig.yaml in a temp file. kubeconfigFile := s.T().TempDir() + "/kubeconfig.yaml" if err = os.WriteFile(kubeconfigFile, kubeconfig, 0o644); err != nil { s.T().Fatal(err) } if err = flag.CommandLine.Set("kubeconfig", kubeconfigFile); err != nil { s.T().Fatal(err) } if err = flag.CommandLine.Set("ingressClass", "traefik.ingress.networking.knative.dev"); err != nil { s.T().Fatal(err) } if err = flag.CommandLine.Set("skip-tests", "headers/probe"); err != nil { s.T().Fatal(err) } ingress.RunConformance(s.T()) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/k8s_test.go
integration/k8s_test.go
package integration import ( "bytes" "encoding/json" "errors" "flag" "fmt" "io" "net" "net/http" "os" "path/filepath" "regexp" "strings" "testing" "time" "github.com/pmezard/go-difflib/difflib" "github.com/rs/zerolog/log" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" "github.com/traefik/traefik/v3/pkg/api" ) var updateExpected = flag.Bool("update_expected", false, "Update expected files in testdata") // K8sSuite tests suite. type K8sSuite struct{ BaseSuite } func TestK8sSuite(t *testing.T) { suite.Run(t, new(K8sSuite)) } func (s *K8sSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("k8s") s.composeUp() abs, err := filepath.Abs("./fixtures/k8s/config.skip/kubeconfig.yaml") require.NoError(s.T(), err) err = try.Do(60*time.Second, func() error { _, err := os.Stat(abs) return err }) require.NoError(s.T(), err) data, err := os.ReadFile(abs) require.NoError(s.T(), err) content := strings.ReplaceAll(string(data), "https://server:6443", fmt.Sprintf("https://%s", net.JoinHostPort(s.getComposeServiceIP("server"), "6443"))) err = os.WriteFile(abs, []byte(content), 0o644) require.NoError(s.T(), err) err = os.Setenv("KUBECONFIG", abs) require.NoError(s.T(), err) } func (s *K8sSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() generatedFiles := []string{ "./fixtures/k8s/config.skip/kubeconfig.yaml", "./fixtures/k8s/config.skip/k3s.log", "./fixtures/k8s/coredns.yaml", "./fixtures/k8s/rolebindings.yaml", "./fixtures/k8s/traefik.yaml", "./fixtures/k8s/ccm.yaml", } for _, filename := range generatedFiles { if err := os.Remove(filename); err != nil { log.Warn().Err(err).Send() } } } func (s *K8sSuite) TestIngressConfiguration() { s.traefikCmd(withConfigFile("fixtures/k8s_default.toml")) s.testConfiguration("testdata/rawdata-ingress.json", "8080") } func (s *K8sSuite) TestIngressLabelSelector() { s.traefikCmd(withConfigFile("fixtures/k8s_ingress_label_selector.toml")) s.testConfiguration("testdata/rawdata-ingress-label-selector.json", "8080") } func (s *K8sSuite) TestCRDConfiguration() { s.traefikCmd(withConfigFile("fixtures/k8s_crd.toml")) s.testConfiguration("testdata/rawdata-crd.json", "8000") } func (s *K8sSuite) TestCRDLabelSelector() { s.traefikCmd(withConfigFile("fixtures/k8s_crd_label_selector.toml")) s.testConfiguration("testdata/rawdata-crd-label-selector.json", "8000") } func (s *K8sSuite) TestGatewayConfiguration() { s.traefikCmd(withConfigFile("fixtures/k8s_gateway.toml")) s.testConfiguration("testdata/rawdata-gateway.json", "8080") } func (s *K8sSuite) TestIngressclass() { s.traefikCmd(withConfigFile("fixtures/k8s_ingressclass.toml")) s.testConfiguration("testdata/rawdata-ingressclass.json", "8080") } func (s *K8sSuite) TestDisableIngressclassLookup() { s.traefikCmd(withConfigFile("fixtures/k8s_ingressclass_disabled.toml")) s.testConfiguration("testdata/rawdata-ingressclass-disabled.json", "8080") } func (s *K8sSuite) testConfiguration(path, apiPort string) { err := try.GetRequest("http://127.0.0.1:"+apiPort+"/api/entrypoints", 20*time.Second, try.BodyContains(`"name":"web"`)) require.NoError(s.T(), err) expectedJSON := filepath.FromSlash(path) if *updateExpected { fi, err := os.Create(expectedJSON) require.NoError(s.T(), err) err = fi.Close() require.NoError(s.T(), err) } var buf bytes.Buffer err = try.GetRequest("http://127.0.0.1:"+apiPort+"/api/rawdata", 1*time.Minute, try.StatusCodeIs(http.StatusOK), matchesConfig(expectedJSON, &buf)) if !*updateExpected { require.NoError(s.T(), err) return } if err != nil { log.Info().Msgf("In file update mode, got expected error: %v", err) } var rtRepr api.RunTimeRepresentation err = json.Unmarshal(buf.Bytes(), &rtRepr) require.NoError(s.T(), err) newJSON, err := json.MarshalIndent(rtRepr, "", "\t") require.NoError(s.T(), err) err = os.WriteFile(expectedJSON, newJSON, 0o644) require.NoError(s.T(), err) s.T().Fatal("We do not want a passing test in file update mode") } func matchesConfig(wantConfig string, buf *bytes.Buffer) try.ResponseCondition { return func(res *http.Response) error { body, err := io.ReadAll(res.Body) if err != nil { return fmt.Errorf("failed to read response body: %w", err) } if err := res.Body.Close(); err != nil { return err } var obtained api.RunTimeRepresentation err = json.Unmarshal(body, &obtained) if err != nil { return err } if buf != nil { buf.Reset() if _, err := io.Copy(buf, bytes.NewReader(body)); err != nil { return err } } got, err := json.MarshalIndent(obtained, "", "\t") if err != nil { return err } expected, err := os.ReadFile(wantConfig) if err != nil { return err } // The pods IPs are dynamic, so we cannot predict them, // which is why we have to ignore them in the comparison. rxURL := regexp.MustCompile(`"(url|address)":\s+(".*")`) sanitizedExpected := rxURL.ReplaceAll(bytes.TrimSpace(expected), []byte(`"$1": "XXXX"`)) sanitizedGot := rxURL.ReplaceAll(got, []byte(`"$1": "XXXX"`)) rxServerStatus := regexp.MustCompile(`"(http://)?.*?":\s+(".*")`) sanitizedExpected = rxServerStatus.ReplaceAll(sanitizedExpected, []byte(`"XXXX": $1`)) sanitizedGot = rxServerStatus.ReplaceAll(sanitizedGot, []byte(`"XXXX": $1`)) if bytes.Equal(sanitizedExpected, sanitizedGot) { return nil } diff := difflib.UnifiedDiff{ FromFile: "Expected", A: difflib.SplitLines(string(sanitizedExpected)), ToFile: "Got", B: difflib.SplitLines(string(sanitizedGot)), Context: 3, } text, err := difflib.GetUnifiedDiffString(diff) if err != nil { return err } return errors.New(text) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/conf_throttling_test.go
integration/conf_throttling_test.go
package integration import ( "bytes" "encoding/json" "fmt" "io" "net/http" "regexp" "strconv" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) type ThrottlingSuite struct{ BaseSuite } func TestThrottlingSuite(t *testing.T) { suite.Run(t, new(ThrottlingSuite)) } func (s *ThrottlingSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("rest") s.composeUp() } func (s *ThrottlingSuite) TestThrottleConfReload() { s.traefikCmd(withConfigFile("fixtures/throttling/simple.toml")) // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.BodyContains("rest@internal")) require.NoError(s.T(), err) // Expected a 404 as we did not configure anything. err = try.GetRequest("http://127.0.0.1:8000/", 2*time.Second, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) config := &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Services: map[string]*dynamic.Service{ "serviceHTTP": { LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://" + s.getComposeServiceIP("whoami1") + ":80", }, }, }, }, }, }, } router := &dynamic.Router{ EntryPoints: []string{"web"}, Middlewares: []string{}, Service: "serviceHTTP", Rule: "PathPrefix(`/`)", } confChanges := 10 for i := range confChanges { config.HTTP.Routers[fmt.Sprintf("routerHTTP%d", i)] = router data, err := json.Marshal(config) require.NoError(s.T(), err) request, err := http.NewRequest(http.MethodPut, "http://127.0.0.1:8080/api/providers/rest", bytes.NewReader(data)) require.NoError(s.T(), err) response, err := http.DefaultClient.Do(request) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusOK, response.StatusCode) time.Sleep(200 * time.Millisecond) } reloadsRegexp := regexp.MustCompile(`traefik_config_reloads_total (\d*)\n`) resp, err := http.Get("http://127.0.0.1:8080/metrics") require.NoError(s.T(), err) defer resp.Body.Close() body, err := io.ReadAll(resp.Body) require.NoError(s.T(), err) fields := reloadsRegexp.FindStringSubmatch(string(body)) assert.Len(s.T(), fields, 2) reloads, err := strconv.Atoi(fields[1]) if err != nil { panic(err) } // The test tries to trigger a config reload with the REST API every 200ms, // 10 times (so for 2s in total). // Therefore the throttling (set at 400ms for this test) should only let // (2s / 400 ms =) 5 config reloads happen in theory. // In addition, we have to take into account the extra config reload from the internal provider (5 + 1). assert.LessOrEqual(s.T(), reloads, 6) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/zk_test.go
integration/zk_test.go
package integration import ( "bytes" "encoding/json" "net" "net/http" "os" "path/filepath" "testing" "time" "github.com/kvtools/valkeyrie" "github.com/kvtools/valkeyrie/store" "github.com/kvtools/zookeeper" "github.com/pmezard/go-difflib/difflib" "github.com/rs/zerolog/log" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" "github.com/traefik/traefik/v3/pkg/api" ) // Zk test suites. type ZookeeperSuite struct { BaseSuite kvClient store.Store zookeeperAddr string } func TestZookeeperSuite(t *testing.T) { suite.Run(t, new(ZookeeperSuite)) } func (s *ZookeeperSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("zookeeper") s.composeUp() s.zookeeperAddr = net.JoinHostPort(s.getComposeServiceIP("zookeeper"), "2181") var err error s.kvClient, err = valkeyrie.NewStore( s.T().Context(), zookeeper.StoreName, []string{s.zookeeperAddr}, &zookeeper.Config{ ConnectionTimeout: 10 * time.Second, }, ) require.NoError(s.T(), err, "Cannot create store zookeeper") // wait for zk err = try.Do(60*time.Second, try.KVExists(s.kvClient, "test")) require.NoError(s.T(), err) } func (s *ZookeeperSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *ZookeeperSuite) TestSimpleConfiguration() { file := s.adaptFile("fixtures/zookeeper/simple.toml", struct{ ZkAddress string }{s.zookeeperAddr}) data := map[string]string{ "traefik/http/routers/Router0/entryPoints/0": "web", "traefik/http/routers/Router0/middlewares/0": "compressor", "traefik/http/routers/Router0/middlewares/1": "striper", "traefik/http/routers/Router0/service": "simplesvc", "traefik/http/routers/Router0/rule": "Host(`kv1.localhost`)", "traefik/http/routers/Router0/priority": "42", "traefik/http/routers/Router0/tls": "", "traefik/http/routers/Router1/rule": "Host(`kv2.localhost`)", "traefik/http/routers/Router1/priority": "42", "traefik/http/routers/Router1/tls/domains/0/main": "aaa.localhost", "traefik/http/routers/Router1/tls/domains/0/sans/0": "aaa.aaa.localhost", "traefik/http/routers/Router1/tls/domains/0/sans/1": "bbb.aaa.localhost", "traefik/http/routers/Router1/tls/domains/1/main": "bbb.localhost", "traefik/http/routers/Router1/tls/domains/1/sans/0": "aaa.bbb.localhost", "traefik/http/routers/Router1/tls/domains/1/sans/1": "bbb.bbb.localhost", "traefik/http/routers/Router1/entryPoints/0": "web", "traefik/http/routers/Router1/service": "simplesvc", "traefik/http/services/simplesvc/loadBalancer/servers/0/url": "http://10.0.1.1:8888", "traefik/http/services/simplesvc/loadBalancer/servers/1/url": "http://10.0.1.1:8889", "traefik/http/services/srvcA/loadBalancer/servers/0/url": "http://10.0.1.2:8888", "traefik/http/services/srvcA/loadBalancer/servers/1/url": "http://10.0.1.2:8889", "traefik/http/services/srvcB/loadBalancer/servers/0/url": "http://10.0.1.3:8888", "traefik/http/services/srvcB/loadBalancer/servers/1/url": "http://10.0.1.3:8889", "traefik/http/services/mirror/mirroring/service": "simplesvc", "traefik/http/services/mirror/mirroring/mirrors/0/name": "srvcA", "traefik/http/services/mirror/mirroring/mirrors/0/percent": "42", "traefik/http/services/mirror/mirroring/mirrors/1/name": "srvcB", "traefik/http/services/mirror/mirroring/mirrors/1/percent": "42", "traefik/http/services/Service03/weighted/services/0/name": "srvcA", "traefik/http/services/Service03/weighted/services/0/weight": "42", "traefik/http/services/Service03/weighted/services/1/name": "srvcB", "traefik/http/services/Service03/weighted/services/1/weight": "42", "traefik/http/middlewares/compressor/compress": "", "traefik/http/middlewares/striper/stripPrefix/prefixes/0": "foo", "traefik/http/middlewares/striper/stripPrefix/prefixes/1": "bar", } for k, v := range data { err := s.kvClient.Put(s.T().Context(), k, []byte(v), nil) require.NoError(s.T(), err) } s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.BodyContains(`"striper@zookeeper":`, `"compressor@zookeeper":`, `"srvcA@zookeeper":`, `"srvcB@zookeeper":`), ) require.NoError(s.T(), err) resp, err := http.Get("http://127.0.0.1:8080/api/rawdata") require.NoError(s.T(), err) var obtained api.RunTimeRepresentation err = json.NewDecoder(resp.Body).Decode(&obtained) require.NoError(s.T(), err) got, err := json.MarshalIndent(obtained, "", " ") require.NoError(s.T(), err) expectedJSON := filepath.FromSlash("testdata/rawdata-zk.json") if *updateExpected { err = os.WriteFile(expectedJSON, got, 0o666) require.NoError(s.T(), err) } expected, err := os.ReadFile(expectedJSON) require.NoError(s.T(), err) if !bytes.Equal(expected, got) { diff := difflib.UnifiedDiff{ FromFile: "Expected", A: difflib.SplitLines(string(expected)), ToFile: "Got", B: difflib.SplitLines(string(got)), Context: 3, } text, err := difflib.GetUnifiedDiffString(diff) require.NoError(s.T(), err) log.Info().Msg(text) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/hostresolver_test.go
integration/hostresolver_test.go
package integration import ( "net/http" "testing" "time" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) type HostResolverSuite struct{ BaseSuite } func TestHostResolverSuite(t *testing.T) { suite.Run(t, new(HostResolverSuite)) } func (s *HostResolverSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("hostresolver") s.composeUp() } func (s *HostResolverSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *HostResolverSuite) TestSimpleConfig() { s.traefikCmd(withConfigFile("fixtures/simple_hostresolver.toml")) testCase := []struct { desc string host string status int }{ { desc: "host request is resolved", host: "www.github.com", status: http.StatusOK, }, { desc: "host request is not resolved", host: "frontend.docker.local", status: http.StatusNotFound, }, } for _, test := range testCase { req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = test.host err = try.Request(req, 5*time.Second, try.StatusCodeIs(test.status), try.HasBody()) require.NoError(s.T(), err) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/access_log_test.go
integration/access_log_test.go
package integration import ( "crypto/md5" "crypto/rand" "encoding/hex" "encoding/json" "fmt" "io" "net/http" "os" "strconv" "strings" "testing" "time" "github.com/rs/zerolog/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" "github.com/traefik/traefik/v3/pkg/middlewares/accesslog" ) const ( traefikTestLogFile = "traefik.log" traefikTestAccessLogFile = "access.log" ) // AccessLogSuite tests suite. type AccessLogSuite struct{ BaseSuite } func TestAccessLogSuite(t *testing.T) { suite.Run(t, new(AccessLogSuite)) } type accessLogValue struct { formatOnly bool code string user string routerName string serviceURL string } func (s *AccessLogSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("access_log") s.composeUp() } func (s *AccessLogSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *AccessLogSuite) TearDownTest() { s.displayTraefikLogFile(traefikTestLogFile) _ = os.Remove(traefikTestAccessLogFile) } func (s *AccessLogSuite) TestAccessLog() { ensureWorkingDirectoryIsClean() // Start Traefik s.traefikCmd(withConfigFile("fixtures/access_log/access_log_base.toml")) defer func() { traefikLog, err := os.ReadFile(traefikTestLogFile) require.NoError(s.T(), err) log.Info().Msg(string(traefikLog)) }() s.waitForTraefik("server1") s.checkStatsForLogFile() // Verify Traefik started OK s.checkTraefikStarted() // Make some requests req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = "frontend1.docker.local" err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = "frontend2.docker.local" err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) // Verify access.log output as expected count := s.checkAccessLogOutput() assert.Equal(s.T(), 3, count) // Verify no other Traefik problems s.checkNoOtherTraefikProblems() } func (s *AccessLogSuite) TestAccessLogAuthFrontend() { ensureWorkingDirectoryIsClean() expected := []accessLogValue{ { formatOnly: false, code: "401", user: "-", routerName: "rt-authFrontend", serviceURL: "-", }, { formatOnly: false, code: "401", user: "test", routerName: "rt-authFrontend", serviceURL: "-", }, { formatOnly: false, code: "200", user: "test", routerName: "rt-authFrontend", serviceURL: "http://172.31.42", }, } // Start Traefik s.traefikCmd(withConfigFile("fixtures/access_log/access_log_base.toml")) s.checkStatsForLogFile() s.waitForTraefik("authFrontend") // Verify Traefik started OK s.checkTraefikStarted() // Test auth entrypoint req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8006/", nil) require.NoError(s.T(), err) req.Host = "frontend.auth.docker.local" err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusUnauthorized), try.HasBody()) require.NoError(s.T(), err) req.SetBasicAuth("test", "") err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusUnauthorized), try.HasBody()) require.NoError(s.T(), err) req.SetBasicAuth("test", "test") err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) // Verify access.log output as expected count := s.checkAccessLogExactValuesOutput(expected) assert.GreaterOrEqual(s.T(), count, len(expected)) // Verify no other Traefik problems s.checkNoOtherTraefikProblems() } func (s *AccessLogSuite) TestAccessLogDigestAuthMiddleware() { ensureWorkingDirectoryIsClean() expected := []accessLogValue{ { formatOnly: false, code: "401", user: "-", routerName: "rt-digestAuthMiddleware", serviceURL: "-", }, { formatOnly: false, code: "401", user: "test", routerName: "rt-digestAuthMiddleware", serviceURL: "-", }, { formatOnly: false, code: "200", user: "test", routerName: "rt-digestAuthMiddleware", serviceURL: "http://172.31.42", }, } // Start Traefik s.traefikCmd(withConfigFile("fixtures/access_log/access_log_base.toml")) s.checkStatsForLogFile() s.waitForTraefik("digestAuthMiddleware") // Verify Traefik started OK s.checkTraefikStarted() // Test auth entrypoint req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8008/", nil) require.NoError(s.T(), err) req.Host = "entrypoint.digest.auth.docker.local" resp, err := try.ResponseUntilStatusCode(req, 500*time.Millisecond, http.StatusUnauthorized) require.NoError(s.T(), err) digest := digestParts(resp) digest["uri"] = "/" digest["method"] = http.MethodGet digest["username"] = "test" digest["password"] = "wrong" req.Header.Set("Authorization", getDigestAuthorization(digest)) req.Header.Set("Content-Type", "application/json") err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusUnauthorized), try.HasBody()) require.NoError(s.T(), err) digest["password"] = "test" req.Header.Set("Authorization", getDigestAuthorization(digest)) err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) // Verify access.log output as expected count := s.checkAccessLogExactValuesOutput(expected) assert.GreaterOrEqual(s.T(), count, len(expected)) // Verify no other Traefik problems s.checkNoOtherTraefikProblems() } // Thanks to mvndaai for digest authentication // https://stackoverflow.com/questions/39474284/how-do-you-do-a-http-post-with-digest-authentication-in-golang/39481441#39481441 func digestParts(resp *http.Response) map[string]string { result := map[string]string{} if len(resp.Header["Www-Authenticate"]) > 0 { wantedHeaders := []string{"nonce", "realm", "qop", "opaque"} responseHeaders := strings.Split(resp.Header["Www-Authenticate"][0], ",") for _, r := range responseHeaders { for _, w := range wantedHeaders { if strings.Contains(r, w) { result[w] = strings.Split(r, `"`)[1] } } } } return result } func getMD5(data string) string { digest := md5.New() if _, err := digest.Write([]byte(data)); err != nil { log.Error().Err(err).Send() } return hex.EncodeToString(digest.Sum(nil)) } func getCnonce() string { b := make([]byte, 8) if _, err := io.ReadFull(rand.Reader, b); err != nil { log.Error().Err(err).Send() } return hex.EncodeToString(b)[:16] } func getDigestAuthorization(digestParts map[string]string) string { d := digestParts ha1 := getMD5(d["username"] + ":" + d["realm"] + ":" + d["password"]) ha2 := getMD5(d["method"] + ":" + d["uri"]) nonceCount := "00000001" cnonce := getCnonce() response := getMD5(fmt.Sprintf("%s:%s:%s:%s:%s:%s", ha1, d["nonce"], nonceCount, cnonce, d["qop"], ha2)) authorization := fmt.Sprintf(`Digest username="%s", realm="%s", nonce="%s", uri="%s", cnonce="%s", nc=%s, qop=%s, response="%s", opaque="%s", algorithm="MD5"`, d["username"], d["realm"], d["nonce"], d["uri"], cnonce, nonceCount, d["qop"], response, d["opaque"]) return authorization } func (s *AccessLogSuite) TestAccessLogFrontendRedirect() { ensureWorkingDirectoryIsClean() expected := []accessLogValue{ { formatOnly: false, code: "302", user: "-", routerName: "rt-frontendRedirect", serviceURL: "-", }, { formatOnly: true, }, } // Start Traefik s.traefikCmd(withConfigFile("fixtures/access_log/access_log_base.toml")) s.checkStatsForLogFile() s.waitForTraefik("frontendRedirect") // Verify Traefik started OK s.checkTraefikStarted() // Test frontend redirect req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8005/test", nil) require.NoError(s.T(), err) req.Host = "" err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) // Verify access.log output as expected count := s.checkAccessLogExactValuesOutput(expected) assert.GreaterOrEqual(s.T(), count, len(expected)) // Verify no other Traefik problems s.checkNoOtherTraefikProblems() } func (s *AccessLogSuite) TestAccessLogJSONFrontendRedirect() { ensureWorkingDirectoryIsClean() type logLine struct { DownstreamStatus int `json:"downstreamStatus"` OriginStatus int `json:"originStatus"` RouterName string `json:"routerName"` ServiceName string `json:"serviceName"` } expected := []logLine{ { DownstreamStatus: 302, OriginStatus: 0, RouterName: "rt-frontendRedirect@docker", ServiceName: "", }, { DownstreamStatus: 200, OriginStatus: 200, RouterName: "rt-server0@docker", ServiceName: "service1@docker", }, } // Start Traefik s.traefikCmd(withConfigFile("fixtures/access_log_json_config.toml")) s.checkStatsForLogFile() s.waitForTraefik("frontendRedirect") // Verify Traefik started OK s.checkTraefikStarted() // Test frontend redirect req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8005/test", nil) require.NoError(s.T(), err) req.Host = "" err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) lines := s.extractLines() assert.GreaterOrEqual(s.T(), len(lines), len(expected)) for i, line := range lines { if line == "" { continue } var logline logLine err := json.Unmarshal([]byte(line), &logline) require.NoError(s.T(), err) assert.Equal(s.T(), expected[i].DownstreamStatus, logline.DownstreamStatus) assert.Equal(s.T(), expected[i].OriginStatus, logline.OriginStatus) assert.Equal(s.T(), expected[i].RouterName, logline.RouterName) assert.Equal(s.T(), expected[i].ServiceName, logline.ServiceName) } } func (s *AccessLogSuite) TestAccessLogRateLimit() { ensureWorkingDirectoryIsClean() expected := []accessLogValue{ { formatOnly: true, }, { formatOnly: true, }, { formatOnly: false, code: "429", user: "-", routerName: "rt-rateLimit", serviceURL: "-", }, } // Start Traefik s.traefikCmd(withConfigFile("fixtures/access_log/access_log_base.toml")) s.checkStatsForLogFile() s.waitForTraefik("rateLimit") // Verify Traefik started OK s.checkTraefikStarted() // Test rate limit req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8007/", nil) require.NoError(s.T(), err) req.Host = "ratelimit.docker.local" err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusTooManyRequests), try.HasBody()) require.NoError(s.T(), err) // Verify access.log output as expected count := s.checkAccessLogExactValuesOutput(expected) assert.GreaterOrEqual(s.T(), count, len(expected)) // Verify no other Traefik problems s.checkNoOtherTraefikProblems() } func (s *AccessLogSuite) TestAccessLogBackendNotFound() { ensureWorkingDirectoryIsClean() expected := []accessLogValue{ { formatOnly: false, code: "404", user: "-", routerName: "-", serviceURL: "-", }, } // Start Traefik s.traefikCmd(withConfigFile("fixtures/access_log/access_log_base.toml")) s.waitForTraefik("server1") s.checkStatsForLogFile() // Verify Traefik started OK s.checkTraefikStarted() // Test rate limit req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = "backendnotfound.docker.local" err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusNotFound), try.HasBody()) require.NoError(s.T(), err) // Verify access.log output as expected count := s.checkAccessLogExactValuesOutput(expected) assert.GreaterOrEqual(s.T(), count, len(expected)) // Verify no other Traefik problems s.checkNoOtherTraefikProblems() } func (s *AccessLogSuite) TestAccessLogFrontendAllowlist() { ensureWorkingDirectoryIsClean() expected := []accessLogValue{ { formatOnly: false, code: "403", user: "-", routerName: "rt-frontendAllowlist", serviceURL: "-", }, } // Start Traefik s.traefikCmd(withConfigFile("fixtures/access_log/access_log_base.toml")) s.checkStatsForLogFile() s.waitForTraefik("frontendAllowlist") // Verify Traefik started OK s.checkTraefikStarted() // Test rate limit req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = "frontend.allowlist.docker.local" err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusForbidden), try.HasBody()) require.NoError(s.T(), err) // Verify access.log output as expected count := s.checkAccessLogExactValuesOutput(expected) assert.GreaterOrEqual(s.T(), count, len(expected)) // Verify no other Traefik problems s.checkNoOtherTraefikProblems() } func (s *AccessLogSuite) TestAccessLogAuthFrontendSuccess() { ensureWorkingDirectoryIsClean() expected := []accessLogValue{ { formatOnly: false, code: "200", user: "test", routerName: "rt-authFrontend", serviceURL: "http://172.31.42", }, } // Start Traefik s.traefikCmd(withConfigFile("fixtures/access_log/access_log_base.toml")) s.checkStatsForLogFile() s.waitForTraefik("authFrontend") // Verify Traefik started OK s.checkTraefikStarted() // Test auth entrypoint req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8006/", nil) require.NoError(s.T(), err) req.Host = "frontend.auth.docker.local" req.SetBasicAuth("test", "test") err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) // Verify access.log output as expected count := s.checkAccessLogExactValuesOutput(expected) assert.GreaterOrEqual(s.T(), count, len(expected)) // Verify no other Traefik problems s.checkNoOtherTraefikProblems() } func (s *AccessLogSuite) TestAccessLogPreflightHeadersMiddleware() { ensureWorkingDirectoryIsClean() expected := []accessLogValue{ { formatOnly: false, code: "200", user: "-", routerName: "rt-preflightCORS", serviceURL: "-", }, } // Start Traefik s.traefikCmd(withConfigFile("fixtures/access_log/access_log_base.toml")) s.checkStatsForLogFile() s.waitForTraefik("preflightCORS") // Verify Traefik started OK s.checkTraefikStarted() // Test preflight response req, err := http.NewRequest(http.MethodOptions, "http://127.0.0.1:8009/", nil) require.NoError(s.T(), err) req.Host = "preflight.docker.local" req.Header.Set("Origin", "whatever") req.Header.Set("Access-Control-Request-Method", "GET") err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) // Verify access.log output as expected count := s.checkAccessLogExactValuesOutput(expected) assert.GreaterOrEqual(s.T(), count, len(expected)) // Verify no other Traefik problems s.checkNoOtherTraefikProblems() } func (s *AccessLogSuite) TestAccessLogDisabledForInternals() { ensureWorkingDirectoryIsClean() // Start Traefik. s.traefikCmd(withConfigFile("fixtures/access_log/access_log_base.toml")) defer func() { traefikLog, err := os.ReadFile(traefikTestLogFile) require.NoError(s.T(), err) log.Info().Msg(string(traefikLog)) }() // waitForTraefik makes at least one call to the rawdata api endpoint, // but the logs for this endpoint are ignored in checkAccessLogOutput. s.waitForTraefik("service3") s.checkStatsForLogFile() // Verify Traefik started OK. s.checkTraefikStarted() // Make some requests on the internal ping router. req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/ping", nil) require.NoError(s.T(), err) err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) // Make some requests on the custom ping router. req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8010/ping", nil) require.NoError(s.T(), err) req.Host = "ping.docker.local" err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) // Verify access.log output as expected. count := s.checkAccessLogOutput() require.Equal(s.T(), 0, count) // Verify no other Traefik problems. s.checkNoOtherTraefikProblems() } func (s *AccessLogSuite) checkNoOtherTraefikProblems() { traefikLog, err := os.ReadFile(traefikTestLogFile) require.NoError(s.T(), err) if len(traefikLog) > 0 { fmt.Printf("%s\n", string(traefikLog)) } } func (s *AccessLogSuite) checkAccessLogOutput() int { s.T().Helper() lines := s.extractLines() count := 0 for i, line := range lines { if len(line) > 0 { count++ s.CheckAccessLogFormat(line, i) } } return count } func (s *AccessLogSuite) checkAccessLogExactValuesOutput(values []accessLogValue) int { s.T().Helper() lines := s.extractLines() count := 0 for i, line := range lines { fmt.Println(line) if len(line) > 0 { count++ if values[i].formatOnly { s.CheckAccessLogFormat(line, i) } else { s.checkAccessLogExactValues(line, i, values[i]) } } } return count } func (s *AccessLogSuite) extractLines() []string { s.T().Helper() accessLog, err := os.ReadFile(traefikTestAccessLogFile) require.NoError(s.T(), err) lines := strings.Split(string(accessLog), "\n") var clean []string for _, line := range lines { if !strings.Contains(line, "/api/rawdata") { clean = append(clean, line) } } return clean } func (s *AccessLogSuite) checkStatsForLogFile() { s.T().Helper() err := try.Do(1*time.Second, func() error { if _, errStat := os.Stat(traefikTestLogFile); errStat != nil { return fmt.Errorf("could not get stats for log file: %w", errStat) } return nil }) require.NoError(s.T(), err) } func ensureWorkingDirectoryIsClean() { os.Remove(traefikTestAccessLogFile) os.Remove(traefikTestLogFile) } func (s *AccessLogSuite) checkTraefikStarted() []byte { s.T().Helper() traefikLog, err := os.ReadFile(traefikTestLogFile) require.NoError(s.T(), err) if len(traefikLog) > 0 { fmt.Printf("%s\n", string(traefikLog)) } return traefikLog } func (s *BaseSuite) CheckAccessLogFormat(line string, i int) { s.T().Helper() results, err := accesslog.ParseAccessLog(line) require.NoError(s.T(), err) assert.Len(s.T(), results, 14) assert.Regexp(s.T(), `^(-|\d{3})$`, results[accesslog.OriginStatus]) count, _ := strconv.Atoi(results[accesslog.RequestCount]) assert.GreaterOrEqual(s.T(), count, i+1) assert.Regexp(s.T(), `"(rt-.+@docker|api@internal)"`, results[accesslog.RouterName]) assert.True(s.T(), strings.HasPrefix(results[accesslog.ServiceURL], `"http://`)) assert.Regexp(s.T(), `^\d+ms$`, results[accesslog.Duration]) } func (s *AccessLogSuite) checkAccessLogExactValues(line string, i int, v accessLogValue) { s.T().Helper() results, err := accesslog.ParseAccessLog(line) require.NoError(s.T(), err) assert.Len(s.T(), results, 14) if len(v.user) > 0 { assert.Equal(s.T(), v.user, results[accesslog.ClientUsername]) } assert.Equal(s.T(), v.code, results[accesslog.OriginStatus]) count, _ := strconv.Atoi(results[accesslog.RequestCount]) assert.GreaterOrEqual(s.T(), count, i+1) assert.Regexp(s.T(), `^"?`+v.routerName+`.*(@docker)?$`, results[accesslog.RouterName]) assert.Regexp(s.T(), `^"?`+v.serviceURL+`.*$`, results[accesslog.ServiceURL]) assert.Regexp(s.T(), `^\d+ms$`, results[accesslog.Duration]) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/websocket_test.go
integration/websocket_test.go
package integration import ( "crypto/tls" "crypto/x509" "encoding/base64" "net" "net/http" "net/http/httptest" "os" "testing" "time" gorillawebsocket "github.com/gorilla/websocket" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" "golang.org/x/net/http2" "golang.org/x/net/websocket" ) // WebsocketSuite tests suite. type WebsocketSuite struct{ BaseSuite } func TestWebsocketSuite(t *testing.T) { suite.Run(t, new(WebsocketSuite)) } func (s *WebsocketSuite) TestBase() { upgrader := gorillawebsocket.Upgrader{} // use default options srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer c.Close() for { mt, message, err := c.ReadMessage() if err != nil { break } err = c.WriteMessage(mt, message) if err != nil { break } } })) file := s.adaptFile("fixtures/websocket/config.toml", struct { WebsocketServer string }{ WebsocketServer: srv.URL, }) s.traefikCmd(withConfigFile(file), "--log.level=DEBUG") // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("127.0.0.1")) require.NoError(s.T(), err) conn, _, err := gorillawebsocket.DefaultDialer.Dial("ws://127.0.0.1:8000/ws", nil) require.NoError(s.T(), err) err = conn.WriteMessage(gorillawebsocket.TextMessage, []byte("OK")) require.NoError(s.T(), err) _, msg, err := conn.ReadMessage() require.NoError(s.T(), err) assert.Equal(s.T(), "OK", string(msg)) } func (s *WebsocketSuite) TestWrongOrigin() { upgrader := gorillawebsocket.Upgrader{} // use default options srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer c.Close() for { mt, message, err := c.ReadMessage() if err != nil { break } err = c.WriteMessage(mt, message) if err != nil { break } } })) file := s.adaptFile("fixtures/websocket/config.toml", struct { WebsocketServer string }{ WebsocketServer: srv.URL, }) s.traefikCmd(withConfigFile(file), "--log.level=DEBUG") // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("127.0.0.1")) require.NoError(s.T(), err) config, err := websocket.NewConfig("ws://127.0.0.1:8000/ws", "ws://127.0.0.1:800") assert.NoError(s.T(), err) conn, err := net.DialTimeout("tcp", "127.0.0.1:8000", time.Second) require.NoError(s.T(), err) _, err = websocket.NewClient(config, conn) assert.ErrorContains(s.T(), err, "bad status") } func (s *WebsocketSuite) TestOrigin() { // use default options upgrader := gorillawebsocket.Upgrader{} srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer c.Close() for { mt, message, err := c.ReadMessage() if err != nil { break } err = c.WriteMessage(mt, message) if err != nil { break } } })) file := s.adaptFile("fixtures/websocket/config.toml", struct { WebsocketServer string }{ WebsocketServer: srv.URL, }) s.traefikCmd(withConfigFile(file), "--log.level=DEBUG") // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("127.0.0.1")) require.NoError(s.T(), err) config, err := websocket.NewConfig("ws://127.0.0.1:8000/ws", "ws://127.0.0.1:8000") assert.NoError(s.T(), err) conn, err := net.DialTimeout("tcp", "127.0.0.1:8000", time.Second) assert.NoError(s.T(), err) client, err := websocket.NewClient(config, conn) require.NoError(s.T(), err) n, err := client.Write([]byte("OK")) require.NoError(s.T(), err) assert.Equal(s.T(), 2, n) msg := make([]byte, 2) n, err = client.Read(msg) require.NoError(s.T(), err) assert.Equal(s.T(), 2, n) assert.Equal(s.T(), "OK", string(msg)) } func (s *WebsocketSuite) TestWrongOriginIgnoredByServer() { upgrader := gorillawebsocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer c.Close() for { mt, message, err := c.ReadMessage() if err != nil { break } err = c.WriteMessage(mt, message) if err != nil { break } } })) file := s.adaptFile("fixtures/websocket/config.toml", struct { WebsocketServer string }{ WebsocketServer: srv.URL, }) s.traefikCmd(withConfigFile(file), "--log.level=DEBUG") // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("127.0.0.1")) require.NoError(s.T(), err) config, err := websocket.NewConfig("ws://127.0.0.1:8000/ws", "ws://127.0.0.1:80") assert.NoError(s.T(), err) conn, err := net.DialTimeout("tcp", "127.0.0.1:8000", time.Second) require.NoError(s.T(), err) client, err := websocket.NewClient(config, conn) require.NoError(s.T(), err) n, err := client.Write([]byte("OK")) require.NoError(s.T(), err) assert.Equal(s.T(), 2, n) msg := make([]byte, 2) n, err = client.Read(msg) require.NoError(s.T(), err) assert.Equal(s.T(), 2, n) assert.Equal(s.T(), "OK", string(msg)) } func (s *WebsocketSuite) TestSSLTermination() { upgrader := gorillawebsocket.Upgrader{} // use default options srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer c.Close() for { mt, message, err := c.ReadMessage() if err != nil { break } err = c.WriteMessage(mt, message) if err != nil { break } } })) file := s.adaptFile("fixtures/websocket/config_https.toml", struct { WebsocketServer string }{ WebsocketServer: srv.URL, }) s.traefikCmd(withConfigFile(file), "--log.level=DEBUG") // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("127.0.0.1")) require.NoError(s.T(), err) // Add client self-signed cert roots := x509.NewCertPool() certContent, err := os.ReadFile("./resources/tls/local.cert") require.NoError(s.T(), err) roots.AppendCertsFromPEM(certContent) gorillawebsocket.DefaultDialer.TLSClientConfig = &tls.Config{ RootCAs: roots, } conn, _, err := gorillawebsocket.DefaultDialer.Dial("wss://127.0.0.1:8000/ws", nil) require.NoError(s.T(), err) err = conn.WriteMessage(gorillawebsocket.TextMessage, []byte("OK")) require.NoError(s.T(), err) _, msg, err := conn.ReadMessage() require.NoError(s.T(), err) assert.Equal(s.T(), "OK", string(msg)) } func (s *WebsocketSuite) TestBasicAuth() { upgrader := gorillawebsocket.Upgrader{} // use default options srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer conn.Close() user, password, _ := r.BasicAuth() assert.Equal(s.T(), "traefiker", user) assert.Equal(s.T(), "secret", password) for { mt, message, err := conn.ReadMessage() if err != nil { break } err = conn.WriteMessage(mt, message) if err != nil { break } } })) file := s.adaptFile("fixtures/websocket/config.toml", struct { WebsocketServer string }{ WebsocketServer: srv.URL, }) s.traefikCmd(withConfigFile(file), "--log.level=DEBUG") // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("127.0.0.1")) require.NoError(s.T(), err) config, err := websocket.NewConfig("ws://127.0.0.1:8000/ws", "ws://127.0.0.1:8000") auth := "traefiker:secret" config.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth))) assert.NoError(s.T(), err) conn, err := net.DialTimeout("tcp", "127.0.0.1:8000", time.Second) require.NoError(s.T(), err) client, err := websocket.NewClient(config, conn) require.NoError(s.T(), err) n, err := client.Write([]byte("OK")) require.NoError(s.T(), err) assert.Equal(s.T(), 2, n) msg := make([]byte, 2) n, err = client.Read(msg) require.NoError(s.T(), err) assert.Equal(s.T(), 2, n) assert.Equal(s.T(), "OK", string(msg)) } func (s *WebsocketSuite) TestSpecificResponseFromBackend() { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusUnauthorized) })) file := s.adaptFile("fixtures/websocket/config.toml", struct { WebsocketServer string }{ WebsocketServer: srv.URL, }) s.traefikCmd(withConfigFile(file), "--log.level=DEBUG") // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("127.0.0.1")) require.NoError(s.T(), err) _, resp, err := gorillawebsocket.DefaultDialer.Dial("ws://127.0.0.1:8000/ws", nil) assert.Error(s.T(), err) assert.Equal(s.T(), http.StatusUnauthorized, resp.StatusCode) } func (s *WebsocketSuite) TestURLWithURLEncodedChar() { upgrader := gorillawebsocket.Upgrader{} // use default options srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Equal(s.T(), "/ws/http%3A%2F%2Ftest", r.URL.EscapedPath()) conn, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer conn.Close() for { mt, message, err := conn.ReadMessage() if err != nil { break } err = conn.WriteMessage(mt, message) if err != nil { break } } })) file := s.adaptFile("fixtures/websocket/config.toml", struct { WebsocketServer string }{ WebsocketServer: srv.URL, }) s.traefikCmd(withConfigFile(file), "--log.level=DEBUG") // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("127.0.0.1")) require.NoError(s.T(), err) conn, _, err := gorillawebsocket.DefaultDialer.Dial("ws://127.0.0.1:8000/ws/http%3A%2F%2Ftest", nil) require.NoError(s.T(), err) err = conn.WriteMessage(gorillawebsocket.TextMessage, []byte("OK")) require.NoError(s.T(), err) _, msg, err := conn.ReadMessage() require.NoError(s.T(), err) assert.Equal(s.T(), "OK", string(msg)) } func (s *WebsocketSuite) TestSSLhttp2() { upgrader := gorillawebsocket.Upgrader{} // use default options ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer c.Close() for { mt, message, err := c.ReadMessage() if err != nil { break } err = c.WriteMessage(mt, message) if err != nil { break } } })) ts.TLS = &tls.Config{} ts.TLS.NextProtos = append(ts.TLS.NextProtos, `h2`, `http/1.1`) ts.StartTLS() file := s.adaptFile("fixtures/websocket/config_https.toml", struct { WebsocketServer string }{ WebsocketServer: ts.URL, }) s.traefikCmd(withConfigFile(file), "--log.level=DEBUG", "--accesslog") // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("127.0.0.1")) require.NoError(s.T(), err) // Add client self-signed cert roots := x509.NewCertPool() certContent, err := os.ReadFile("./resources/tls/local.cert") require.NoError(s.T(), err) roots.AppendCertsFromPEM(certContent) gorillawebsocket.DefaultDialer.TLSClientConfig = &tls.Config{ RootCAs: roots, } conn, _, err := gorillawebsocket.DefaultDialer.Dial("wss://127.0.0.1:8000/echo", nil) require.NoError(s.T(), err) err = conn.WriteMessage(gorillawebsocket.TextMessage, []byte("OK")) require.NoError(s.T(), err) _, msg, err := conn.ReadMessage() require.NoError(s.T(), err) assert.Equal(s.T(), "OK", string(msg)) } func (s *WebsocketSuite) TestSettingEnableConnectProtocol() { file := s.adaptFile("fixtures/websocket/config_https.toml", struct { WebsocketServer string }{ WebsocketServer: "http://127.0.0.1", }) s.traefikCmd(withConfigFile(file), "--log.level=DEBUG", "--accesslog") // Wait for traefik. err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("127.0.0.1")) require.NoError(s.T(), err) // Add client self-signed cert. roots := x509.NewCertPool() certContent, err := os.ReadFile("./resources/tls/local.cert") require.NoError(s.T(), err) roots.AppendCertsFromPEM(certContent) // Open a connection to inspect SettingsFrame. conn, err := tls.Dial("tcp", "127.0.0.1:8000", &tls.Config{ RootCAs: roots, NextProtos: []string{"h2"}, }) require.NoError(s.T(), err) framer := http2.NewFramer(nil, conn) frame, err := framer.ReadFrame() require.NoError(s.T(), err) fr, ok := frame.(*http2.SettingsFrame) require.True(s.T(), ok) _, ok = fr.Value(http2.SettingEnableConnectProtocol) assert.False(s.T(), ok) } func (s *WebsocketSuite) TestHeaderAreForwarded() { upgrader := gorillawebsocket.Upgrader{} // use default options srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Equal(s.T(), "my-token", r.Header.Get("X-Token")) c, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer c.Close() for { mt, message, err := c.ReadMessage() if err != nil { break } err = c.WriteMessage(mt, message) if err != nil { break } } })) file := s.adaptFile("fixtures/websocket/config.toml", struct { WebsocketServer string }{ WebsocketServer: srv.URL, }) s.traefikCmd(withConfigFile(file), "--log.level=DEBUG") // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("127.0.0.1")) require.NoError(s.T(), err) headers := http.Header{} headers.Add("X-Token", "my-token") conn, _, err := gorillawebsocket.DefaultDialer.Dial("ws://127.0.0.1:8000/ws", headers) require.NoError(s.T(), err) err = conn.WriteMessage(gorillawebsocket.TextMessage, []byte("OK")) require.NoError(s.T(), err) _, msg, err := conn.ReadMessage() require.NoError(s.T(), err) assert.Equal(s.T(), "OK", string(msg)) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/http_test.go
integration/http_test.go
package integration import ( "encoding/json" "net" "net/http" "net/http/httptest" "testing" "time" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" "github.com/traefik/traefik/v3/pkg/config/dynamic" ) type HTTPSuite struct{ BaseSuite } func TestHTTPSuite(t *testing.T) { suite.Run(t, new(HTTPSuite)) } func (s *HTTPSuite) TestSimpleConfiguration() { s.traefikCmd(withConfigFile("fixtures/http/simple.toml")) // Expect a 404 as we configured nothing. err := try.GetRequest("http://127.0.0.1:8000/", time.Second, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) // Provide a configuration, fetched by Traefik provider. configuration := &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "routerHTTP": { EntryPoints: []string{"web"}, Middlewares: []string{}, Service: "serviceHTTP", Rule: "PathPrefix(`/`)", }, }, Services: map[string]*dynamic.Service{ "serviceHTTP": { LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: pointer(true), Servers: []dynamic.Server{ { URL: "http://bacon:80", }, }, }, }, }, }, } configData, err := json.Marshal(configuration) require.NoError(s.T(), err) server := startTestServerWithResponse(configData) defer server.Close() // Expect configuration to be applied. err = try.GetRequest("http://127.0.0.1:9090/api/rawdata", 3*time.Second, try.BodyContains("routerHTTP@http", "serviceHTTP@http", "http://bacon:80")) require.NoError(s.T(), err) } func startTestServerWithResponse(response []byte) (ts *httptest.Server) { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write(response) }) listener, err := net.Listen("tcp", "127.0.0.1:9000") if err != nil { panic(err) } ts = &httptest.Server{ Listener: listener, Config: &http.Server{Handler: handler}, } ts.Start() return ts } func pointer[T any](v T) *T { return &v }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/integration_test.go
integration/integration_test.go
// This is the main file that sets up integration tests using go-check. package integration import ( "bytes" "context" "errors" "flag" "fmt" "io" "io/fs" stdlog "log" "net/http" "os" "os/exec" "path/filepath" "regexp" "runtime" "slices" "strings" "testing" "text/template" "time" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/mount" dockernetwork "github.com/docker/docker/api/types/network" "github.com/fatih/structs" "github.com/rs/zerolog/log" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/network" "github.com/traefik/traefik/v3/integration/try" "gopkg.in/yaml.v3" ) var ( showLog = flag.Bool("tlog", false, "always show Traefik logs") gatewayAPIConformanceRunTest = flag.String("gatewayAPIConformanceRunTest", "", "runs a specific Gateway API conformance test") traefikVersion = flag.String("traefikVersion", "dev", "defines the Traefik version") ) const ( k3sImage = "docker.io/rancher/k3s:v1.34.2-k3s1" traefikImage = "traefik/traefik:latest" traefikDeployment = "deployments/traefik" traefikNamespace = "traefik" tailscaleSecretFilePath = "tailscale.secret" ) type composeConfig struct { Services map[string]composeService `yaml:"services"` } type composeService struct { Image string `yaml:"image"` Labels map[string]string `yaml:"labels"` Hostname string `yaml:"hostname"` Volumes []string `yaml:"volumes"` CapAdd []string `yaml:"cap_add"` Command []string `yaml:"command"` Environment map[string]string `yaml:"environment"` Privileged bool `yaml:"privileged"` Deploy composeDeploy `yaml:"deploy"` } type composeDeploy struct { Replicas int `yaml:"replicas"` } type BaseSuite struct { suite.Suite containers map[string]testcontainers.Container network *testcontainers.DockerNetwork hostIP string } func (s *BaseSuite) waitForTraefik(containerName string) { time.Sleep(1 * time.Second) // Wait for Traefik to turn ready. req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/rawdata", nil) require.NoError(s.T(), err) err = try.Request(req, 2*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains(containerName)) require.NoError(s.T(), err) } func (s *BaseSuite) displayTraefikLogFile(path string) { if s.T().Failed() { if _, err := os.Stat(path); !os.IsNotExist(err) { content, errRead := os.ReadFile(path) // TODO TestName // fmt.Printf("%s: Traefik logs: \n", c.TestName()) fmt.Print("Traefik logs: \n") if errRead == nil { fmt.Println(string(content)) } else { fmt.Println(errRead) } } else { // fmt.Printf("%s: No Traefik logs.\n", c.TestName()) fmt.Print("No Traefik logs.\n") } errRemove := os.Remove(path) if errRemove != nil { fmt.Println(errRemove) } } } func (s *BaseSuite) SetupSuite() { if isDockerDesktop(s.T()) { _, err := os.Stat(tailscaleSecretFilePath) require.NoError(s.T(), err, "Tailscale need to be configured when running integration tests with Docker Desktop: (https://doc.traefik.io/traefik/v2.11/contributing/building-testing/#testing)") } // configure default standard log. stdlog.SetFlags(stdlog.Lshortfile | stdlog.LstdFlags) // TODO // stdlog.SetOutput(log.Logger) // Create docker network // docker network create traefik-test-network --driver bridge --subnet 172.31.42.0/24 var opts []network.NetworkCustomizer opts = append(opts, network.WithDriver("bridge")) opts = append(opts, network.WithIPAM(&dockernetwork.IPAM{ Driver: "default", Config: []dockernetwork.IPAMConfig{ { Subnet: "172.31.42.0/24", }, }, })) dockerNetwork, err := network.New(s.T().Context(), opts...) require.NoError(s.T(), err) s.network = dockerNetwork s.hostIP = "172.31.42.1" if isDockerDesktop(s.T()) { s.hostIP = getDockerDesktopHostIP(s.T()) s.setupVPN(tailscaleSecretFilePath) } } func getDockerDesktopHostIP(t *testing.T) string { t.Helper() req := testcontainers.ContainerRequest{ Image: "alpine", HostConfigModifier: func(config *container.HostConfig) { config.AutoRemove = true }, Cmd: []string{"getent", "hosts", "host.docker.internal"}, } con, err := testcontainers.GenericContainer(t.Context(), testcontainers.GenericContainerRequest{ ContainerRequest: req, Started: true, }) require.NoError(t, err) closer, err := con.Logs(t.Context()) require.NoError(t, err) all, err := io.ReadAll(closer) require.NoError(t, err) ipRegex := regexp.MustCompile(`\b(?:\d{1,3}\.){3}\d{1,3}\b`) matches := ipRegex.FindAllString(string(all), -1) require.Len(t, matches, 1) return matches[0] } func isDockerDesktop(t *testing.T) bool { t.Helper() cli, err := testcontainers.NewDockerClientWithOpts(t.Context()) if err != nil { t.Fatalf("failed to create docker client: %s", err) } info, err := cli.Info(t.Context()) if err != nil { t.Fatalf("failed to get docker info: %s", err) } return info.OperatingSystem == "Docker Desktop" } func (s *BaseSuite) TearDownSuite() { s.composeDown() err := try.Do(5*time.Second, func() error { if s.network != nil { err := s.network.Remove(s.T().Context()) if err != nil { return err } } return nil }) require.NoError(s.T(), err) } // createComposeProject creates the docker compose project stored as a field in the BaseSuite. // This method should be called before starting and/or stopping compose services. func (s *BaseSuite) createComposeProject(name string) { composeFile := fmt.Sprintf("resources/compose/%s.yml", name) file, err := os.ReadFile(composeFile) require.NoError(s.T(), err) var composeConfigData composeConfig err = yaml.Unmarshal(file, &composeConfigData) require.NoError(s.T(), err) if s.containers == nil { s.containers = map[string]testcontainers.Container{} } ctx := s.T().Context() for id, containerConfig := range composeConfigData.Services { var mounts []mount.Mount for _, volume := range containerConfig.Volumes { split := strings.Split(volume, ":") if len(split) != 2 { continue } if strings.HasPrefix(split[0], "./") { path, err := os.Getwd() if err != nil { log.Err(err).Msg("can't determine current directory") continue } split[0] = strings.Replace(split[0], "./", path+"/", 1) } abs, err := filepath.Abs(split[0]) require.NoError(s.T(), err) mounts = append(mounts, mount.Mount{Source: abs, Target: split[1], Type: mount.TypeBind}) } if containerConfig.Deploy.Replicas > 0 { for i := range containerConfig.Deploy.Replicas { id = fmt.Sprintf("%s-%d", id, i+1) con, err := s.createContainer(ctx, containerConfig, id, mounts) require.NoError(s.T(), err) s.containers[id] = con } continue } con, err := s.createContainer(ctx, containerConfig, id, mounts) require.NoError(s.T(), err) s.containers[id] = con } } func (s *BaseSuite) createContainer(ctx context.Context, containerConfig composeService, id string, mounts []mount.Mount) (testcontainers.Container, error) { req := testcontainers.ContainerRequest{ Image: containerConfig.Image, Env: containerConfig.Environment, Cmd: containerConfig.Command, Labels: containerConfig.Labels, Name: id, Hostname: containerConfig.Hostname, Privileged: containerConfig.Privileged, Networks: []string{s.network.Name}, HostConfigModifier: func(config *container.HostConfig) { if containerConfig.CapAdd != nil { config.CapAdd = containerConfig.CapAdd } if !isDockerDesktop(s.T()) { config.ExtraHosts = append(config.ExtraHosts, "host.docker.internal:"+s.hostIP) } config.Mounts = mounts }, } con, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ ContainerRequest: req, Started: false, }) return con, err } // composeUp starts the given services of the current docker compose project, if they are not already started. // Already running services are not affected (i.e. not stopped). func (s *BaseSuite) composeUp(services ...string) { for name, con := range s.containers { if len(services) == 0 || slices.Contains(services, name) { err := con.Start(s.T().Context()) require.NoError(s.T(), err) } } } // composeStop stops the given services of the current docker compose project and removes the corresponding containers. func (s *BaseSuite) composeStop(services ...string) { for name, con := range s.containers { if len(services) == 0 || slices.Contains(services, name) { timeout := 10 * time.Second err := con.Stop(s.T().Context(), &timeout) require.NoError(s.T(), err) } } } // composeDown stops all compose project services and removes the corresponding containers. func (s *BaseSuite) composeDown() { for _, c := range s.containers { err := c.Terminate(s.T().Context()) require.NoError(s.T(), err) } s.containers = map[string]testcontainers.Container{} } func (s *BaseSuite) cmdTraefik(args ...string) (*exec.Cmd, *bytes.Buffer) { binName := "traefik" if runtime.GOOS == "windows" { binName += ".exe" } traefikBinPath := filepath.Join("..", "dist", runtime.GOOS, runtime.GOARCH, binName) cmd := exec.Command(traefikBinPath, args...) s.T().Cleanup(func() { s.killCmd(cmd) }) var out bytes.Buffer cmd.Stdout = &out cmd.Stderr = &out err := cmd.Start() require.NoError(s.T(), err) return cmd, &out } func (s *BaseSuite) killCmd(cmd *exec.Cmd) { if cmd.Process == nil { log.Error().Msg("No process to kill") return } err := cmd.Process.Kill() if err != nil { log.Error().Err(err).Msg("Kill") } time.Sleep(100 * time.Millisecond) } func (s *BaseSuite) traefikCmd(args ...string) *exec.Cmd { cmd, out := s.cmdTraefik(args...) s.T().Cleanup(func() { if s.T().Failed() || *showLog { s.displayLogK3S() s.displayLogCompose() s.displayTraefikLog(out) } }) return cmd } func (s *BaseSuite) displayLogK3S() { filePath := "./fixtures/k8s/config.skip/k3s.log" if _, err := os.Stat(filePath); err == nil { content, errR := os.ReadFile(filePath) if errR != nil { log.Error().Err(errR).Send() } log.Print(string(content)) } log.Print() log.Print("################################") log.Print() } func (s *BaseSuite) displayLogCompose() { for name, ctn := range s.containers { readCloser, err := ctn.Logs(s.T().Context()) require.NoError(s.T(), err) for { b := make([]byte, 1024) _, err := readCloser.Read(b) if errors.Is(err, io.EOF) { break } require.NoError(s.T(), err) trimLogs := bytes.Trim(bytes.TrimSpace(b), string([]byte{0})) if len(trimLogs) > 0 { log.Info().Str("container", name).Msg(string(trimLogs)) } } } } func (s *BaseSuite) displayTraefikLog(output *bytes.Buffer) { if output == nil || output.Len() == 0 { log.Info().Msg("No Traefik logs.") } else { for _, line := range strings.Split(output.String(), "\n") { log.Info().Msg(line) } } } func (s *BaseSuite) getDockerHost() string { dockerHost := os.Getenv("DOCKER_HOST") if dockerHost == "" { // Default docker socket dockerHost = "unix:///var/run/docker.sock" } return dockerHost } func (s *BaseSuite) adaptFile(path string, tempObjects interface{}) string { // Load file tmpl, err := template.ParseFiles(path) require.NoError(s.T(), err) folder, prefix := filepath.Split(path) tmpFile, err := os.CreateTemp(folder, strings.TrimSuffix(prefix, filepath.Ext(prefix))+"_*"+filepath.Ext(prefix)) require.NoError(s.T(), err) defer tmpFile.Close() model := structs.Map(tempObjects) model["SelfFilename"] = tmpFile.Name() err = tmpl.ExecuteTemplate(tmpFile, prefix, model) require.NoError(s.T(), err) err = tmpFile.Sync() require.NoError(s.T(), err) s.T().Cleanup(func() { os.Remove(tmpFile.Name()) }) return tmpFile.Name() } func (s *BaseSuite) getComposeServiceIP(name string) string { container, ok := s.containers[name] if !ok { return "" } ip, err := container.ContainerIP(s.T().Context()) if err != nil { return "" } return ip } func withConfigFile(file string) string { return "--configFile=" + file } // setupVPN starts Tailscale on the corresponding container, and makes it a subnet // router, for all the other containers (whoamis, etc) subsequently started for the // integration tests. // It only does so if the file provided as argument exists, and contains a // Tailscale auth key (an ephemeral, but reusable, one is recommended). // // Add this section to your tailscale ACLs to auto-approve the routes for the // containers in the docker subnet: // // "autoApprovers": { // // Allow myself to automatically advertize routes for docker networks // "routes": { // "172.0.0.0/8": ["your_tailscale_identity"], // }, // }, func (s *BaseSuite) setupVPN(keyFile string) { data, err := os.ReadFile(keyFile) if err != nil { if !errors.Is(err, fs.ErrNotExist) { log.Error().Err(err).Send() } return } authKey := strings.TrimSpace(string(data)) // // TODO: copy and create versions that don't need a check.C? s.createComposeProject("tailscale") s.composeUp() time.Sleep(5 * time.Second) // If we ever change the docker subnet in the Makefile, // we need to change this one below correspondingly. s.composeExec("tailscaled", "tailscale", "up", "--authkey="+authKey, "--advertise-routes=172.31.42.0/24") } // composeExec runs the command in the given args in the given compose service container. // Already running services are not affected (i.e. not stopped). func (s *BaseSuite) composeExec(service string, args ...string) string { require.Contains(s.T(), s.containers, service) _, reader, err := s.containers[service].Exec(s.T().Context(), args) require.NoError(s.T(), err) content, err := io.ReadAll(reader) require.NoError(s.T(), err) return string(content) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/fake_dns_server.go
integration/fake_dns_server.go
package integration import ( "fmt" "net" "os" "github.com/miekg/dns" "github.com/rs/zerolog/log" ) type handler struct { traefikIP string } // ServeDNS a fake DNS server // Simplified version of the Challenge Test Server from Boulder // https://github.com/letsencrypt/boulder/blob/a6597b9f120207eff192c3e4107a7e49972a0250/test/challtestsrv/dnsone.go#L40 func (s *handler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) { m := new(dns.Msg) m.SetReply(r) m.Compress = false for _, q := range r.Question { log.Info().Msgf("Query -- [%s] %s", q.Name, dns.TypeToString[q.Qtype]) switch q.Qtype { case dns.TypeA: record := new(dns.A) record.Hdr = dns.RR_Header{ Name: q.Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 0, } record.A = net.ParseIP(s.traefikIP) m.Answer = append(m.Answer, record) case dns.TypeCAA: addCAARecord := true var value string switch q.Name { case "bad-caa-reserved.com.": value = "sad-hacker-ca.invalid" case "good-caa-reserved.com.": value = "happy-hacker-ca.invalid" case "accounturi.good-caa-reserved.com.": uri := os.Getenv("ACCOUNT_URI") value = fmt.Sprintf("happy-hacker-ca.invalid; accounturi=%s", uri) case "recheck.good-caa-reserved.com.": // Allow issuance when we're running in the past // (under FAKECLOCK), otherwise deny issuance. if os.Getenv("FAKECLOCK") != "" { value = "happy-hacker-ca.invalid" } else { value = "sad-hacker-ca.invalid" } case "dns-01-only.good-caa-reserved.com.": value = "happy-hacker-ca.invalid; validationmethods=dns-01" case "http-01-only.good-caa-reserved.com.": value = "happy-hacker-ca.invalid; validationmethods=http-01" case "dns-01-or-http-01.good-caa-reserved.com.": value = "happy-hacker-ca.invalid; validationmethods=dns-01,http-01" default: addCAARecord = false } if addCAARecord { record := new(dns.CAA) record.Hdr = dns.RR_Header{ Name: q.Name, Rrtype: dns.TypeCAA, Class: dns.ClassINET, Ttl: 0, } record.Tag = "issue" record.Value = value m.Answer = append(m.Answer, record) } } } auth := new(dns.SOA) auth.Hdr = dns.RR_Header{Name: "boulder.invalid.", Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: 0} auth.Ns = "ns.boulder.invalid." auth.Mbox = "master.boulder.invalid." auth.Serial = 1 auth.Refresh = 1 auth.Retry = 1 auth.Expire = 1 auth.Minttl = 1 m.Ns = append(m.Ns, auth) if err := w.WriteMsg(m); err != nil { log.Fatal().Err(err).Msg("Failed to write message") } } func startFakeDNSServer(traefikIP string) *dns.Server { srv := &dns.Server{ Addr: ":5053", Net: "udp", Handler: &handler{traefikIP}, } go func() { log.Info().Msg("Start a fake DNS server.") if err := srv.ListenAndServe(); err != nil { log.Fatal().Err(err).Msg("Failed to set udp listener") } }() return srv }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/log_rotation_test.go
integration/log_rotation_test.go
//go:build !windows // +build !windows package integration import ( "bufio" "net/http" "os" "strings" "syscall" "testing" "time" "github.com/rs/zerolog/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) const traefikTestAccessLogFileRotated = traefikTestAccessLogFile + ".rotated" // Log rotation integration test suite. type LogRotationSuite struct{ BaseSuite } func TestLogRotationSuite(t *testing.T) { suite.Run(t, new(LogRotationSuite)) } func (s *LogRotationSuite) SetupSuite() { s.BaseSuite.SetupSuite() os.Remove(traefikTestAccessLogFile) os.Remove(traefikTestLogFile) os.Remove(traefikTestAccessLogFileRotated) s.createComposeProject("access_log") s.composeUp() } func (s *LogRotationSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() generatedFiles := []string{ traefikTestLogFile, traefikTestAccessLogFile, traefikTestAccessLogFileRotated, } for _, filename := range generatedFiles { if err := os.Remove(filename); err != nil { log.Warn().Err(err).Send() } } } func (s *LogRotationSuite) TestAccessLogRotation() { // Start Traefik cmd, _ := s.cmdTraefik(withConfigFile("fixtures/access_log/access_log_base.toml")) defer s.displayTraefikLogFile(traefikTestLogFile) // Verify Traefik started ok s.verifyEmptyErrorLog("traefik.log") s.waitForTraefik("server1") // Make some requests req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = "frontend1.docker.local" err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) // Rename access log err = os.Rename(traefikTestAccessLogFile, traefikTestAccessLogFileRotated) require.NoError(s.T(), err) // in the midst of the requests, issue SIGUSR1 signal to server process err = cmd.Process.Signal(syscall.SIGUSR1) require.NoError(s.T(), err) // continue issuing requests err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) err = try.Request(req, 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.HasBody()) require.NoError(s.T(), err) // Verify access.log.rotated output as expected s.logAccessLogFile(traefikTestAccessLogFileRotated) lineCount := s.verifyLogLines(traefikTestAccessLogFileRotated, 0, true) assert.GreaterOrEqual(s.T(), lineCount, 1) // make sure that the access log file is at least created before we do assertions on it err = try.Do(1*time.Second, func() error { _, err := os.Stat(traefikTestAccessLogFile) return err }) assert.NoError(s.T(), err, "access log file was not created in time") // Verify access.log output as expected s.logAccessLogFile(traefikTestAccessLogFile) lineCount = s.verifyLogLines(traefikTestAccessLogFile, lineCount, true) assert.Equal(s.T(), 3, lineCount) s.verifyEmptyErrorLog(traefikTestLogFile) } func (s *LogRotationSuite) logAccessLogFile(fileName string) { output, err := os.ReadFile(fileName) require.NoError(s.T(), err) log.Info().Msgf("Contents of file %s\n%s", fileName, string(output)) } func (s *LogRotationSuite) verifyEmptyErrorLog(name string) { err := try.Do(5*time.Second, func() error { traefikLog, e2 := os.ReadFile(name) if e2 != nil { return e2 } assert.Empty(s.T(), string(traefikLog)) return nil }) require.NoError(s.T(), err) } func (s *LogRotationSuite) verifyLogLines(fileName string, countInit int, accessLog bool) int { rotated, err := os.Open(fileName) require.NoError(s.T(), err) rotatedLog := bufio.NewScanner(rotated) count := countInit for rotatedLog.Scan() { line := rotatedLog.Text() if accessLog { if len(line) > 0 { if !strings.Contains(line, "/api/rawdata") { s.CheckAccessLogFormat(line, count) count++ } } } else { count++ } } return count }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/docker_test.go
integration/docker_test.go
package integration import ( "encoding/json" "io" "net/http" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) // Docker tests suite. type DockerSuite struct { BaseSuite } func TestDockerSuite(t *testing.T) { suite.Run(t, new(DockerSuite)) } func (s *DockerSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("docker") } func (s *DockerSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *DockerSuite) TearDownTest() { s.composeStop("simple", "withtcplabels", "withlabels1", "withlabels2", "withonelabelmissing", "powpow", "nonRunning") } func (s *DockerSuite) TestSimpleConfiguration() { tempObjects := struct { DockerHost string DefaultRule string }{ DockerHost: s.getDockerHost(), DefaultRule: "Host(`{{ normalize .Name }}.docker.localhost`)", } file := s.adaptFile("fixtures/docker/simple.toml", tempObjects) s.composeUp() s.traefikCmd(withConfigFile(file)) // Expected a 404 as we did not configure anything err := try.GetRequest("http://127.0.0.1:8000/", 500*time.Millisecond, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) } func (s *DockerSuite) TestDefaultDockerContainers() { tempObjects := struct { DockerHost string DefaultRule string }{ DockerHost: s.getDockerHost(), DefaultRule: "Host(`{{ normalize .Name }}.docker.localhost`)", } file := s.adaptFile("fixtures/docker/simple.toml", tempObjects) s.composeUp("simple") // Start traefik s.traefikCmd(withConfigFile(file)) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/version", nil) require.NoError(s.T(), err) req.Host = "simple.docker.localhost" resp, err := try.ResponseUntilStatusCode(req, 3*time.Second, http.StatusOK) require.NoError(s.T(), err) body, err := io.ReadAll(resp.Body) require.NoError(s.T(), err) var version map[string]interface{} assert.NoError(s.T(), json.Unmarshal(body, &version)) assert.Equal(s.T(), "swarm/1.0.0", version["Version"]) } func (s *DockerSuite) TestDockerContainersWithTCPLabels() { tempObjects := struct { DockerHost string DefaultRule string }{ DockerHost: s.getDockerHost(), DefaultRule: "Host(`{{ normalize .Name }}.docker.localhost`)", } file := s.adaptFile("fixtures/docker/simple.toml", tempObjects) s.composeUp("withtcplabels") // Start traefik s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`my.super.host`)")) require.NoError(s.T(), err) who, err := guessWho("127.0.0.1:8000", "my.super.host", true) require.NoError(s.T(), err) assert.Contains(s.T(), who, "my.super.host") } func (s *DockerSuite) TestDockerContainersWithLabels() { tempObjects := struct { DockerHost string DefaultRule string }{ DockerHost: s.getDockerHost(), DefaultRule: "Host(`{{ normalize .Name }}.docker.localhost`)", } file := s.adaptFile("fixtures/docker/simple.toml", tempObjects) s.composeUp("withlabels1", "withlabels2") // Start traefik s.traefikCmd(withConfigFile(file)) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/version", nil) require.NoError(s.T(), err) req.Host = "my-super.host" _, err = try.ResponseUntilStatusCode(req, 3*time.Second, http.StatusOK) require.NoError(s.T(), err) req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/version", nil) require.NoError(s.T(), err) req.Host = "my.super.host" resp, err := try.ResponseUntilStatusCode(req, 3*time.Second, http.StatusOK) require.NoError(s.T(), err) body, err := io.ReadAll(resp.Body) require.NoError(s.T(), err) var version map[string]interface{} assert.NoError(s.T(), json.Unmarshal(body, &version)) assert.Equal(s.T(), "swarm/1.0.0", version["Version"]) } func (s *DockerSuite) TestDockerContainersWithOneMissingLabels() { tempObjects := struct { DockerHost string DefaultRule string }{ DockerHost: s.getDockerHost(), DefaultRule: "Host(`{{ normalize .Name }}.docker.localhost`)", } file := s.adaptFile("fixtures/docker/simple.toml", tempObjects) s.composeUp("withonelabelmissing") // Start traefik s.traefikCmd(withConfigFile(file)) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/version", nil) require.NoError(s.T(), err) req.Host = "my.super.host" // Expected a 404 as we did not configure anything err = try.Request(req, 3*time.Second, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) } func (s *DockerSuite) TestRestartDockerContainers() { tempObjects := struct { DockerHost string DefaultRule string }{ DockerHost: s.getDockerHost(), DefaultRule: "Host(`{{ normalize .Name }}.docker.localhost`)", } file := s.adaptFile("fixtures/docker/simple.toml", tempObjects) s.composeUp("powpow") // Start traefik s.traefikCmd(withConfigFile(file)) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/version", nil) require.NoError(s.T(), err) req.Host = "my.super.host" // TODO Need to wait than 500 milliseconds more (for swarm or traefik to boot up ?) resp, err := try.ResponseUntilStatusCode(req, 1500*time.Millisecond, http.StatusOK) require.NoError(s.T(), err) body, err := io.ReadAll(resp.Body) require.NoError(s.T(), err) var version map[string]interface{} assert.NoError(s.T(), json.Unmarshal(body, &version)) assert.Equal(s.T(), "swarm/1.0.0", version["Version"]) err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("powpow")) require.NoError(s.T(), err) s.composeStop("powpow") time.Sleep(5 * time.Second) err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.BodyContains("powpow")) assert.Error(s.T(), err) s.composeUp("powpow") err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 60*time.Second, try.BodyContains("powpow")) require.NoError(s.T(), err) } func (s *DockerSuite) TestDockerAllowNonRunning() { tempObjects := struct { DockerHost string DefaultRule string }{ DockerHost: s.getDockerHost(), DefaultRule: "Host(`{{ normalize .Name }}.docker.localhost`)", } file := s.adaptFile("fixtures/docker/simple.toml", tempObjects) s.composeUp("nonRunning") // Start traefik s.traefikCmd(withConfigFile(file)) // Verify the container is working when running req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = "non.running.host" resp, err := try.ResponseUntilStatusCode(req, 3*time.Second, http.StatusOK) require.NoError(s.T(), err) body, err := io.ReadAll(resp.Body) require.NoError(s.T(), err) assert.Contains(s.T(), string(body), "Hostname:") // Verify the router exists in Traefik configuration err = try.GetRequest("http://127.0.0.1:8080/api/http/routers", 1*time.Second, try.BodyContains("NonRunning")) require.NoError(s.T(), err) // Stop the container s.composeStop("nonRunning") // Wait a bit for container stop to be detected time.Sleep(2 * time.Second) // Verify the router still exists in configuration even though container is stopped // This is the key test - the router should persist due to allowNonRunning=true err = try.GetRequest("http://127.0.0.1:8080/api/http/routers", 10*time.Second, try.BodyContains("NonRunning")) require.NoError(s.T(), err) // Verify the service still exists in configuration err = try.GetRequest("http://127.0.0.1:8080/api/http/services", 1*time.Second, try.BodyContains("nonRunning")) require.NoError(s.T(), err) // HTTP requests should fail (502 Bad Gateway) since container is stopped but router exists req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = "non.running.host" err = try.Request(req, 3*time.Second, try.StatusCodeIs(http.StatusServiceUnavailable)) require.NoError(s.T(), err) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/tls_client_headers_test.go
integration/tls_client_headers_test.go
package integration import ( "crypto/tls" "net/http" "os" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) const ( rootCertPath = "./fixtures/tlsclientheaders/root.pem" certPemPath = "./fixtures/tlsclientheaders/server.pem" certKeyPath = "./fixtures/tlsclientheaders/server.key" ) type TLSClientHeadersSuite struct{ BaseSuite } func TestTLSClientHeadersSuite(t *testing.T) { suite.Run(t, new(TLSClientHeadersSuite)) } func (s *TLSClientHeadersSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("tlsclientheaders") s.composeUp() } func (s *TLSClientHeadersSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *TLSClientHeadersSuite) TestTLSClientHeaders() { rootCertContent, err := os.ReadFile(rootCertPath) assert.NoError(s.T(), err) serverCertContent, err := os.ReadFile(certPemPath) assert.NoError(s.T(), err) ServerKeyContent, err := os.ReadFile(certKeyPath) assert.NoError(s.T(), err) file := s.adaptFile("fixtures/tlsclientheaders/simple.toml", struct { RootCertContent string ServerCertContent string ServerKeyContent string }{ RootCertContent: string(rootCertContent), ServerCertContent: string(serverCertContent), ServerKeyContent: string(ServerKeyContent), }) s.traefikCmd(withConfigFile(file)) err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 2*time.Second, try.BodyContains("PathPrefix(`/foo`)")) require.NoError(s.T(), err) request, err := http.NewRequest(http.MethodGet, "https://127.0.0.1:8443/foo", nil) require.NoError(s.T(), err) certificate, err := tls.LoadX509KeyPair(certPemPath, certKeyPath) require.NoError(s.T(), err) tr := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, Certificates: []tls.Certificate{certificate}, }, } err = try.RequestWithTransport(request, 2*time.Second, tr, try.BodyContains("Forwarded-Tls-Client-Cert: MIIDNTCCAh0CFD0QQcHXUJuKwMBYDA+bBExVSP26MA0GCSqGSIb3DQEBCwUAMFYxCzAJBgNVBAYTAkZSMQ8wDQYDVQQIDAZGcmFuY2UxFTATBgNVBAoMDFRyYWVmaWsgTGFiczEQMA4GA1UECwwHdHJhZWZpazENMAsGA1UEAwwEcm9vdDAeFw0yMTAxMDgxNzQ0MjRaFw0zMTAxMDYxNzQ0MjRaMFgxCzAJBgNVBAYTAkZSMQ8wDQYDVQQIDAZGcmFuY2UxFTATBgNVBAoMDFRyYWVmaWsgTGFiczEQMA4GA1UECwwHdHJhZWZpazEPMA0GA1UEAwwGc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvYK2z8gLPOfFLgXNWP2460aeJ9vrH47x/lhKLlv4amSDHDx8Cmz/6blOUM8XOfMRW1xx++AgChWN9dx/kf7G2xlA5grZxRvUQ6xj7AvFG9TQUA3muNh2hvm9c3IjaZBNKH27bRKuDIBvZBvXdX4NL/aaFy7w7v7IKxk8j4WkfB23sgyH43g4b7NqKHJugZiedFu5GALmtLbShVOFbjWcre7Wvatdw8dIBmiFJqZQT3UjIuGAgqczIShtLxo4V+XyVkIPmzfPrRV+4zoMFIFOIaj3syyxb4krPBtxhe7nz2cWvvq0wePB2y4YbAAoVY8NYpd5JsMFwZtG6Uk59ygv4QIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQDaPg69wNeFNFisfBJTrscqVCTW+B80gMhpLdxXD+KO0/Wgc5xpB/wLSirNtRQyxAa3+EEcIwJv/wdh8EyjlDLSpFm/8ghntrKhkOfIOPDFE41M5HNfx/Fuh5btKEenOL/XdapqtNUt2ZE4RrsfbL79sPYepa9kDUVi2mCbeH5ollZ0MDU68HpB2YwHbCEuQNk5W3pjYK2NaDkVnxTkfEDM1k+3QydO1lqB5JJmcrs59BEveTqaJ3eeh/0I4OOab6OkTTZ0JNjJp1573oxO+fce/bfGud8xHY5gSN9huU7U6RsgvO7Dhmal/sDNl8XC8oU90hVDVXZdA7ewh4jjaoIv")) require.NoError(s.T(), err) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/proxy_protocol_test.go
integration/proxy_protocol_test.go
package integration import ( "bufio" "net" "testing" "time" "github.com/pires/go-proxyproto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) type ProxyProtocolSuite struct { BaseSuite whoamiIP string } func TestProxyProtocolSuite(t *testing.T) { suite.Run(t, new(ProxyProtocolSuite)) } func (s *ProxyProtocolSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("proxy-protocol") s.composeUp() s.whoamiIP = s.getComposeServiceIP("whoami") } func (s *ProxyProtocolSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *ProxyProtocolSuite) TestProxyProtocolTrusted() { file := s.adaptFile("fixtures/proxy-protocol/proxy-protocol.toml", struct { HaproxyIP string WhoamiIP string }{WhoamiIP: s.whoamiIP}) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8000/whoami", 10*time.Second) require.NoError(s.T(), err) content, err := proxyProtoRequest("127.0.0.1:8000", 1) require.NoError(s.T(), err) assert.Contains(s.T(), content, "X-Forwarded-For: 1.2.3.4") content, err = proxyProtoRequest("127.0.0.1:8000", 2) require.NoError(s.T(), err) assert.Contains(s.T(), content, "X-Forwarded-For: 1.2.3.4") } func (s *ProxyProtocolSuite) TestProxyProtocolNotTrusted() { file := s.adaptFile("fixtures/proxy-protocol/proxy-protocol.toml", struct { HaproxyIP string WhoamiIP string }{WhoamiIP: s.whoamiIP}) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:9000/whoami", 10*time.Second) require.NoError(s.T(), err) content, err := proxyProtoRequest("127.0.0.1:9000", 1) require.NoError(s.T(), err) assert.Contains(s.T(), content, "X-Forwarded-For: 127.0.0.1") content, err = proxyProtoRequest("127.0.0.1:9000", 2) require.NoError(s.T(), err) assert.Contains(s.T(), content, "X-Forwarded-For: 127.0.0.1") } func proxyProtoRequest(address string, version byte) (string, error) { // Open a TCP connection to the server conn, err := net.Dial("tcp", address) if err != nil { return "", err } defer conn.Close() // Create a Proxy Protocol header with v1 proxyHeader := &proxyproto.Header{ Version: version, Command: proxyproto.PROXY, TransportProtocol: proxyproto.TCPv4, DestinationAddr: &net.TCPAddr{ IP: net.ParseIP("127.0.0.1"), Port: 8000, }, SourceAddr: &net.TCPAddr{ IP: net.ParseIP("1.2.3.4"), Port: 62541, }, } // After the connection was created write the proxy headers first _, err = proxyHeader.WriteTo(conn) if err != nil { return "", err } // Create an HTTP request request := "GET /whoami HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n" + "Connection: close\r\n" + "\r\n" // Write the HTTP request to the TCP connection writer := bufio.NewWriter(conn) _, err = writer.WriteString(request) if err != nil { return "", err } // Flush the buffer to ensure the request is sent err = writer.Flush() if err != nil { return "", err } // Read the response from the server var content string scanner := bufio.NewScanner(conn) for scanner.Scan() { content += scanner.Text() + "\n" } if scanner.Err() != nil { return "", err } return content, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/https_test.go
integration/https_test.go
package integration import ( "bytes" "crypto/tls" "crypto/x509" "fmt" "net" "net/http" "net/http/httptest" "os" "testing" "time" "github.com/BurntSushi/toml" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" "github.com/traefik/traefik/v3/pkg/config/dynamic" traefiktls "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" "golang.org/x/net/http2" ) // HTTPSSuite tests suite. type HTTPSSuite struct{ BaseSuite } func TestHTTPSSuite(t *testing.T) { suite.Run(t, &HTTPSSuite{}) } // TestWithSNIConfigHandshake involves a client sending a SNI hostname of // "snitest.com", which happens to match the CN of 'snitest.com.crt'. The test // verifies that traefik presents the correct certificate. func (s *HTTPSSuite) TestWithSNIConfigHandshake() { file := s.adaptFile("fixtures/https/https_sni.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 500*time.Millisecond, try.BodyContains("Host(`snitest.org`)")) require.NoError(s.T(), err) tlsConfig := &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.com", NextProtos: []string{"h2", "http/1.1"}, } conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) assert.NoError(s.T(), err, "failed to connect to server") defer conn.Close() err = conn.Handshake() assert.NoError(s.T(), err, "TLS handshake error") cs := conn.ConnectionState() err = cs.PeerCertificates[0].VerifyHostname("snitest.com") assert.NoError(s.T(), err, "certificate did not match SNI servername") proto := conn.ConnectionState().NegotiatedProtocol assert.Equal(s.T(), "h2", proto) } // TestWithSNIConfigRoute involves a client sending HTTPS requests with // SNI hostnames of "snitest.org" and "snitest.com". The test verifies // that traefik routes the requests to the expected backends. func (s *HTTPSSuite) TestWithSNIConfigRoute() { file := s.adaptFile("fixtures/https/https_sni.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`snitest.org`)")) require.NoError(s.T(), err) backend1 := startTestServer("9010", http.StatusNoContent, "") backend2 := startTestServer("9020", http.StatusResetContent, "") defer backend1.Close() defer backend2.Close() err = try.GetRequest(backend1.URL, 1*time.Second, try.StatusCodeIs(http.StatusNoContent)) require.NoError(s.T(), err) err = try.GetRequest(backend2.URL, 1*time.Second, try.StatusCodeIs(http.StatusResetContent)) require.NoError(s.T(), err) tr1 := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.com", }, } tr2 := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.org", }, } req, err := http.NewRequest(http.MethodGet, "https://127.0.0.1:4443/", nil) require.NoError(s.T(), err) req.Host = tr1.TLSClientConfig.ServerName req.Header.Set("Host", tr1.TLSClientConfig.ServerName) req.Header.Set("Accept", "*/*") err = try.RequestWithTransport(req, 30*time.Second, tr1, try.HasCn(tr1.TLSClientConfig.ServerName), try.StatusCodeIs(http.StatusNoContent)) require.NoError(s.T(), err) req, err = http.NewRequest(http.MethodGet, "https://127.0.0.1:4443/", nil) require.NoError(s.T(), err) req.Host = tr2.TLSClientConfig.ServerName req.Header.Set("Host", tr2.TLSClientConfig.ServerName) req.Header.Set("Accept", "*/*") err = try.RequestWithTransport(req, 30*time.Second, tr2, try.HasCn(tr2.TLSClientConfig.ServerName), try.StatusCodeIs(http.StatusResetContent)) require.NoError(s.T(), err) } // TestWithTLSOptions verifies that traefik routes the requests with the associated tls options. func (s *HTTPSSuite) TestWithTLSOptions() { file := s.adaptFile("fixtures/https/https_tls_options.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`snitest.org`)")) require.NoError(s.T(), err) backend1 := startTestServer("9010", http.StatusNoContent, "") backend2 := startTestServer("9020", http.StatusResetContent, "") defer backend1.Close() defer backend2.Close() err = try.GetRequest(backend1.URL, 1*time.Second, try.StatusCodeIs(http.StatusNoContent)) require.NoError(s.T(), err) err = try.GetRequest(backend2.URL, 1*time.Second, try.StatusCodeIs(http.StatusResetContent)) require.NoError(s.T(), err) tr1 := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, MaxVersion: tls.VersionTLS12, ServerName: "snitest.com", }, } tr2 := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, MaxVersion: tls.VersionTLS12, ServerName: "snitest.org", }, } tr3 := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, MaxVersion: tls.VersionTLS11, ServerName: "snitest.org", }, } // With valid TLS options and request req, err := http.NewRequest(http.MethodGet, "https://127.0.0.1:4443/", nil) require.NoError(s.T(), err) req.Host = tr1.TLSClientConfig.ServerName req.Header.Set("Host", tr1.TLSClientConfig.ServerName) req.Header.Set("Accept", "*/*") err = try.RequestWithTransport(req, 30*time.Second, tr1, try.HasCn(tr1.TLSClientConfig.ServerName), try.StatusCodeIs(http.StatusNoContent)) require.NoError(s.T(), err) // With a valid TLS version req, err = http.NewRequest(http.MethodGet, "https://127.0.0.1:4443/", nil) require.NoError(s.T(), err) req.Host = tr2.TLSClientConfig.ServerName req.Header.Set("Host", tr2.TLSClientConfig.ServerName) req.Header.Set("Accept", "*/*") err = try.RequestWithTransport(req, 3*time.Second, tr2, try.HasCn(tr2.TLSClientConfig.ServerName), try.StatusCodeIs(http.StatusResetContent)) require.NoError(s.T(), err) // With a bad TLS version req, err = http.NewRequest(http.MethodGet, "https://127.0.0.1:4443/", nil) require.NoError(s.T(), err) req.Host = tr3.TLSClientConfig.ServerName req.Header.Set("Host", tr3.TLSClientConfig.ServerName) req.Header.Set("Accept", "*/*") client := http.Client{ Transport: tr3, } _, err = client.Do(req) assert.Error(s.T(), err) assert.Contains(s.T(), err.Error(), "tls: no supported versions satisfy MinVersion and MaxVersion") // with unknown tls option err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("unknown TLS options: unknown@file")) require.NoError(s.T(), err) } // TestWithConflictingTLSOptions checks that routers with same SNI but different TLS options get fallbacked to the default TLS options. func (s *HTTPSSuite) TestWithConflictingTLSOptions() { file := s.adaptFile("fixtures/https/https_tls_options.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`snitest.net`)")) require.NoError(s.T(), err) backend1 := startTestServer("9010", http.StatusNoContent, "") backend2 := startTestServer("9020", http.StatusResetContent, "") defer backend1.Close() defer backend2.Close() err = try.GetRequest(backend1.URL, 1*time.Second, try.StatusCodeIs(http.StatusNoContent)) require.NoError(s.T(), err) err = try.GetRequest(backend2.URL, 1*time.Second, try.StatusCodeIs(http.StatusResetContent)) require.NoError(s.T(), err) tr4 := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, MaxVersion: tls.VersionTLS11, ServerName: "snitest.net", }, } trDefault := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, MaxVersion: tls.VersionTLS12, ServerName: "snitest.net", }, } // With valid TLS options and request req, err := http.NewRequest(http.MethodGet, "https://127.0.0.1:4443/", nil) require.NoError(s.T(), err) req.Host = trDefault.TLSClientConfig.ServerName req.Header.Set("Host", trDefault.TLSClientConfig.ServerName) req.Header.Set("Accept", "*/*") err = try.RequestWithTransport(req, 30*time.Second, trDefault, try.StatusCodeIs(http.StatusNoContent)) require.NoError(s.T(), err) // With a bad TLS version req, err = http.NewRequest(http.MethodGet, "https://127.0.0.1:4443/", nil) require.NoError(s.T(), err) req.Host = tr4.TLSClientConfig.ServerName req.Header.Set("Host", tr4.TLSClientConfig.ServerName) req.Header.Set("Accept", "*/*") client := http.Client{ Transport: tr4, } _, err = client.Do(req) assert.ErrorContains(s.T(), err, "tls: no supported versions satisfy MinVersion and MaxVersion") // with unknown tls option err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains(fmt.Sprintf("found different TLS options for routers on the same host %v, so using the default TLS options instead", tr4.TLSClientConfig.ServerName))) require.NoError(s.T(), err) } // TestWithSNIStrictNotMatchedRequest involves a client sending a SNI hostname of // "snitest.org", which does not match the CN of 'snitest.com.crt'. The test // verifies that traefik closes the connection. func (s *HTTPSSuite) TestWithSNIStrictNotMatchedRequest() { file := s.adaptFile("fixtures/https/https_sni_strict.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 500*time.Millisecond, try.BodyContains("Host(`snitest.com`)")) require.NoError(s.T(), err) tlsConfig := &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.org", NextProtos: []string{"h2", "http/1.1"}, } // Connection with no matching certificate should fail _, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) assert.Error(s.T(), err, "failed to connect to server") } // TestWithDefaultCertificate involves a client sending a SNI hostname of // "snitest.org", which does not match the CN of 'snitest.com.crt'. The test // verifies that traefik returns the default certificate. func (s *HTTPSSuite) TestWithDefaultCertificate() { file := s.adaptFile("fixtures/https/https_sni_default_cert.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 500*time.Millisecond, try.BodyContains("Host(`snitest.com`)")) require.NoError(s.T(), err) tlsConfig := &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.org", NextProtos: []string{"h2", "http/1.1"}, } conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) assert.NoError(s.T(), err, "failed to connect to server") defer conn.Close() err = conn.Handshake() assert.NoError(s.T(), err, "TLS handshake error") cs := conn.ConnectionState() err = cs.PeerCertificates[0].VerifyHostname("snitest.com") assert.NoError(s.T(), err, "server did not serve correct default certificate") proto := cs.NegotiatedProtocol assert.Equal(s.T(), "h2", proto) } // TestWithDefaultCertificateNoSNI involves a client sending a request with no ServerName // which does not match the CN of 'snitest.com.crt'. The test // verifies that traefik returns the default certificate. func (s *HTTPSSuite) TestWithDefaultCertificateNoSNI() { file := s.adaptFile("fixtures/https/https_sni_default_cert.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 500*time.Millisecond, try.BodyContains("Host(`snitest.com`)")) require.NoError(s.T(), err) tlsConfig := &tls.Config{ InsecureSkipVerify: true, NextProtos: []string{"h2", "http/1.1"}, } conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) assert.NoError(s.T(), err, "failed to connect to server") defer conn.Close() err = conn.Handshake() assert.NoError(s.T(), err, "TLS handshake error") cs := conn.ConnectionState() err = cs.PeerCertificates[0].VerifyHostname("snitest.com") assert.NoError(s.T(), err, "server did not serve correct default certificate") proto := cs.NegotiatedProtocol assert.Equal(s.T(), "h2", proto) } // TestWithOverlappingCertificate involves a client sending a SNI hostname of // "www.snitest.com", which matches the CN of two static certificates: // 'wildcard.snitest.com.crt', and `www.snitest.com.crt`. The test // verifies that traefik returns the non-wildcard certificate. func (s *HTTPSSuite) TestWithOverlappingStaticCertificate() { file := s.adaptFile("fixtures/https/https_sni_default_cert.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 500*time.Millisecond, try.BodyContains("Host(`snitest.com`)")) require.NoError(s.T(), err) tlsConfig := &tls.Config{ InsecureSkipVerify: true, ServerName: "www.snitest.com", NextProtos: []string{"h2", "http/1.1"}, } conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) assert.NoError(s.T(), err, "failed to connect to server") defer conn.Close() err = conn.Handshake() assert.NoError(s.T(), err, "TLS handshake error") cs := conn.ConnectionState() err = cs.PeerCertificates[0].VerifyHostname("www.snitest.com") assert.NoError(s.T(), err, "server did not serve correct default certificate") proto := cs.NegotiatedProtocol assert.Equal(s.T(), "h2", proto) } // TestWithOverlappingCertificate involves a client sending a SNI hostname of // "www.snitest.com", which matches the CN of two dynamic certificates: // 'wildcard.snitest.com.crt', and `www.snitest.com.crt`. The test // verifies that traefik returns the non-wildcard certificate. func (s *HTTPSSuite) TestWithOverlappingDynamicCertificate() { file := s.adaptFile("fixtures/https/dynamic_https_sni_default_cert.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 500*time.Millisecond, try.BodyContains("Host(`snitest.com`)")) require.NoError(s.T(), err) tlsConfig := &tls.Config{ InsecureSkipVerify: true, ServerName: "www.snitest.com", NextProtos: []string{"h2", "http/1.1"}, } conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) assert.NoError(s.T(), err, "failed to connect to server") defer conn.Close() err = conn.Handshake() assert.NoError(s.T(), err, "TLS handshake error") cs := conn.ConnectionState() err = cs.PeerCertificates[0].VerifyHostname("www.snitest.com") assert.NoError(s.T(), err, "server did not serve correct default certificate") proto := cs.NegotiatedProtocol assert.Equal(s.T(), "h2", proto) } // TestWithClientCertificateAuthentication // The client can send a certificate signed by a CA trusted by the server but it's optional. func (s *HTTPSSuite) TestWithClientCertificateAuthentication() { file := s.adaptFile("fixtures/https/clientca/https_1ca1config.toml", struct{}{}) s.traefikCmd(withConfigFile(file)) // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 500*time.Millisecond, try.BodyContains("Host(`snitest.org`)")) require.NoError(s.T(), err) tlsConfig := &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.com", Certificates: []tls.Certificate{}, } // Connection without client certificate should fail _, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) assert.NoError(s.T(), err, "should be allowed to connect to server") // Connect with client certificate signed by ca1 cert, err := tls.LoadX509KeyPair("fixtures/https/clientca/client1.crt", "fixtures/https/clientca/client1.key") assert.NoError(s.T(), err, "unable to load client certificate and key") tlsConfig.Certificates = append(tlsConfig.Certificates, cert) conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) assert.NoError(s.T(), err, "failed to connect to server") conn.Close() // Connect with client certificate not signed by ca1 cert, err = tls.LoadX509KeyPair("fixtures/https/snitest.org.cert", "fixtures/https/snitest.org.key") assert.NoError(s.T(), err, "unable to load client certificate and key") tlsConfig.Certificates = append(tlsConfig.Certificates, cert) conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) assert.NoError(s.T(), err, "failed to connect to server") conn.Close() // Connect with client signed by ca2 should fail tlsConfig = &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.com", Certificates: []tls.Certificate{}, } cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client2.crt", "fixtures/https/clientca/client2.key") assert.NoError(s.T(), err, "unable to load client certificate and key") tlsConfig.Certificates = append(tlsConfig.Certificates, cert) _, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) assert.NoError(s.T(), err, "should be allowed to connect to server") } // TestWithClientCertificateAuthentication // Use two CA:s and test that clients with client signed by either of them can connect. func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipleCAs() { server1 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { _, _ = rw.Write([]byte("server1")) })) server2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { _, _ = rw.Write([]byte("server2")) })) defer func() { server1.Close() server2.Close() }() file := s.adaptFile("fixtures/https/clientca/https_2ca1config.toml", struct { Server1 string Server2 string }{ Server1: server1.URL, Server2: server2.URL, }) s.traefikCmd(withConfigFile(file)) // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`snitest.org`)")) require.NoError(s.T(), err) req, err := http.NewRequest(http.MethodGet, "https://127.0.0.1:4443", nil) require.NoError(s.T(), err) req.Host = "snitest.com" tlsConfig := &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.com", Certificates: []tls.Certificate{}, } client := http.Client{ Transport: &http.Transport{TLSClientConfig: tlsConfig}, Timeout: 1 * time.Second, } // Connection without client certificate should fail _, err = client.Do(req) assert.Error(s.T(), err) cert, err := tls.LoadX509KeyPair("fixtures/https/clientca/client1.crt", "fixtures/https/clientca/client1.key") assert.NoError(s.T(), err, "unable to load client certificate and key") tlsConfig.Certificates = append(tlsConfig.Certificates, cert) // Connect with client signed by ca1 _, err = client.Do(req) require.NoError(s.T(), err) // Connect with client signed by ca2 tlsConfig = &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.com", Certificates: []tls.Certificate{}, } cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client2.crt", "fixtures/https/clientca/client2.key") assert.NoError(s.T(), err, "unable to load client certificate and key") tlsConfig.Certificates = append(tlsConfig.Certificates, cert) client = http.Client{ Transport: &http.Transport{TLSClientConfig: tlsConfig}, Timeout: 1 * time.Second, } // Connect with client signed by ca1 _, err = client.Do(req) require.NoError(s.T(), err) // Connect with client signed by ca3 should fail tlsConfig = &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.com", Certificates: []tls.Certificate{}, } cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client3.crt", "fixtures/https/clientca/client3.key") assert.NoError(s.T(), err, "unable to load client certificate and key") tlsConfig.Certificates = append(tlsConfig.Certificates, cert) client = http.Client{ Transport: &http.Transport{TLSClientConfig: tlsConfig}, Timeout: 1 * time.Second, } // Connect with client signed by ca1 _, err = client.Do(req) assert.Error(s.T(), err) } // TestWithClientCertificateAuthentication // Use two CA:s in two different files and test that clients with client signed by either of them can connect. func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipleCAsMultipleFiles() { server1 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { _, _ = rw.Write([]byte("server1")) })) server2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { _, _ = rw.Write([]byte("server2")) })) defer func() { server1.Close() server2.Close() }() file := s.adaptFile("fixtures/https/clientca/https_2ca2config.toml", struct { Server1 string Server2 string }{ Server1: server1.URL, Server2: server2.URL, }) s.traefikCmd(withConfigFile(file)) // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`snitest.org`)")) require.NoError(s.T(), err) req, err := http.NewRequest(http.MethodGet, "https://127.0.0.1:4443", nil) require.NoError(s.T(), err) req.Host = "snitest.com" tlsConfig := &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.com", Certificates: []tls.Certificate{}, } client := http.Client{ Transport: &http.Transport{TLSClientConfig: tlsConfig}, Timeout: 1 * time.Second, } // Connection without client certificate should fail _, err = client.Do(req) assert.Error(s.T(), err) // Connect with client signed by ca1 cert, err := tls.LoadX509KeyPair("fixtures/https/clientca/client1.crt", "fixtures/https/clientca/client1.key") assert.NoError(s.T(), err, "unable to load client certificate and key") tlsConfig.Certificates = append(tlsConfig.Certificates, cert) _, err = client.Do(req) require.NoError(s.T(), err) // Connect with client signed by ca2 tlsConfig = &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.com", Certificates: []tls.Certificate{}, } cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client2.crt", "fixtures/https/clientca/client2.key") assert.NoError(s.T(), err, "unable to load client certificate and key") tlsConfig.Certificates = append(tlsConfig.Certificates, cert) client = http.Client{ Transport: &http.Transport{TLSClientConfig: tlsConfig}, Timeout: 1 * time.Second, } _, err = client.Do(req) require.NoError(s.T(), err) // Connect with client signed by ca3 should fail tlsConfig = &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.com", Certificates: []tls.Certificate{}, } cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client3.crt", "fixtures/https/clientca/client3.key") assert.NoError(s.T(), err, "unable to load client certificate and key") tlsConfig.Certificates = append(tlsConfig.Certificates, cert) client = http.Client{ Transport: &http.Transport{TLSClientConfig: tlsConfig}, Timeout: 1 * time.Second, } _, err = client.Do(req) assert.Error(s.T(), err) } func (s *HTTPSSuite) TestWithRootCAsContentForHTTPSOnBackend() { backend := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) defer backend.Close() file := s.adaptFile("fixtures/https/rootcas/https.toml", struct{ BackendHost string }{backend.URL}) s.traefikCmd(withConfigFile(file)) // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains(backend.URL)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8081/ping", 1*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) } func (s *HTTPSSuite) TestWithRootCAsFileForHTTPSOnBackend() { backend := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) defer backend.Close() file := s.adaptFile("fixtures/https/rootcas/https_with_file.toml", struct{ BackendHost string }{backend.URL}) s.traefikCmd(withConfigFile(file)) // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains(backend.URL)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8081/ping", 1*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) } func startTestServer(port string, statusCode int, textContent string) (ts *httptest.Server) { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(statusCode) if textContent != "" { _, _ = w.Write([]byte(textContent)) } }) listener, err := net.Listen("tcp", "127.0.0.1:"+port) if err != nil { panic(err) } ts = &httptest.Server{ Listener: listener, Config: &http.Server{Handler: handler}, } ts.Start() return ts } // TestWithSNIDynamicConfigRouteWithNoChange involves a client sending HTTPS requests with // SNI hostnames of "snitest.org" and "snitest.com". The test verifies // that traefik routes the requests to the expected backends thanks to given certificate if possible // otherwise thanks to the default one. func (s *HTTPSSuite) TestWithSNIDynamicConfigRouteWithNoChange() { dynamicConfFileName := s.adaptFile("fixtures/https/dynamic_https.toml", struct{}{}) confFileName := s.adaptFile("fixtures/https/dynamic_https_sni.toml", struct { DynamicConfFileName string }{ DynamicConfFileName: dynamicConfFileName, }) s.traefikCmd(withConfigFile(confFileName)) tr1 := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.org", }, } tr2 := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.com", }, } // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`"+tr1.TLSClientConfig.ServerName+"`)")) require.NoError(s.T(), err) backend1 := startTestServer("9010", http.StatusNoContent, "") backend2 := startTestServer("9020", http.StatusResetContent, "") defer backend1.Close() defer backend2.Close() err = try.GetRequest(backend1.URL, 500*time.Millisecond, try.StatusCodeIs(http.StatusNoContent)) require.NoError(s.T(), err) err = try.GetRequest(backend2.URL, 500*time.Millisecond, try.StatusCodeIs(http.StatusResetContent)) require.NoError(s.T(), err) req, err := http.NewRequest(http.MethodGet, "https://127.0.0.1:4443/", nil) require.NoError(s.T(), err) req.Host = tr1.TLSClientConfig.ServerName req.Header.Set("Host", tr1.TLSClientConfig.ServerName) req.Header.Set("Accept", "*/*") // snitest.org certificate must be used yet && Expected a 204 (from backend1) err = try.RequestWithTransport(req, 30*time.Second, tr1, try.HasCn(tr1.TLSClientConfig.ServerName), try.StatusCodeIs(http.StatusResetContent)) require.NoError(s.T(), err) req, err = http.NewRequest(http.MethodGet, "https://127.0.0.1:4443/", nil) require.NoError(s.T(), err) req.Host = tr2.TLSClientConfig.ServerName req.Header.Set("Host", tr2.TLSClientConfig.ServerName) req.Header.Set("Accept", "*/*") // snitest.com certificate does not exist, default certificate has to be used && Expected a 205 (from backend2) err = try.RequestWithTransport(req, 30*time.Second, tr2, try.HasCn("TRAEFIK DEFAULT CERT"), try.StatusCodeIs(http.StatusNoContent)) require.NoError(s.T(), err) } // TestWithSNIDynamicConfigRouteWithChange involves a client sending HTTPS requests with // SNI hostnames of "snitest.org" and "snitest.com". The test verifies // that traefik updates its configuration when the HTTPS configuration is modified and // it routes the requests to the expected backends thanks to given certificate if possible // otherwise thanks to the default one. func (s *HTTPSSuite) TestWithSNIDynamicConfigRouteWithChange() { dynamicConfFileName := s.adaptFile("fixtures/https/dynamic_https.toml", struct{}{}) confFileName := s.adaptFile("fixtures/https/dynamic_https_sni.toml", struct { DynamicConfFileName string }{ DynamicConfFileName: dynamicConfFileName, }) s.traefikCmd(withConfigFile(confFileName)) tr1 := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.com", }, } tr2 := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.org", }, } // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`"+tr2.TLSClientConfig.ServerName+"`)")) require.NoError(s.T(), err) backend1 := startTestServer("9010", http.StatusNoContent, "") backend2 := startTestServer("9020", http.StatusResetContent, "") defer backend1.Close() defer backend2.Close() err = try.GetRequest(backend1.URL, 500*time.Millisecond, try.StatusCodeIs(http.StatusNoContent)) require.NoError(s.T(), err) err = try.GetRequest(backend2.URL, 500*time.Millisecond, try.StatusCodeIs(http.StatusResetContent)) require.NoError(s.T(), err) // Change certificates configuration file content s.modifyCertificateConfFileContent(tr1.TLSClientConfig.ServerName, dynamicConfFileName) req, err := http.NewRequest(http.MethodGet, "https://127.0.0.1:4443/", nil) require.NoError(s.T(), err) req.Host = tr1.TLSClientConfig.ServerName req.Header.Set("Host", tr1.TLSClientConfig.ServerName) req.Header.Set("Accept", "*/*") err = try.RequestWithTransport(req, 30*time.Second, tr1, try.HasCn(tr1.TLSClientConfig.ServerName), try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) req, err = http.NewRequest(http.MethodGet, "https://127.0.0.1:4443/", nil) require.NoError(s.T(), err) req.Host = tr2.TLSClientConfig.ServerName req.Header.Set("Host", tr2.TLSClientConfig.ServerName) req.Header.Set("Accept", "*/*") err = try.RequestWithTransport(req, 30*time.Second, tr2, try.HasCn("TRAEFIK DEFAULT CERT"), try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) } // TestWithSNIDynamicConfigRouteWithTlsConfigurationDeletion involves a client sending HTTPS requests with // SNI hostnames of "snitest.org" and "snitest.com". The test verifies // that traefik updates its configuration when the HTTPS configuration is modified, even if it totally deleted, and // it routes the requests to the expected backends thanks to given certificate if possible // otherwise thanks to the default one. func (s *HTTPSSuite) TestWithSNIDynamicConfigRouteWithTlsConfigurationDeletion() { dynamicConfFileName := s.adaptFile("fixtures/https/dynamic_https.toml", struct{}{}) confFileName := s.adaptFile("fixtures/https/dynamic_https_sni.toml", struct { DynamicConfFileName string }{ DynamicConfFileName: dynamicConfFileName, }) s.traefikCmd(withConfigFile(confFileName)) tr2 := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.org", }, } // wait for Traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`"+tr2.TLSClientConfig.ServerName+"`)")) require.NoError(s.T(), err) backend2 := startTestServer("9020", http.StatusResetContent, "") defer backend2.Close() err = try.GetRequest(backend2.URL, 500*time.Millisecond, try.StatusCodeIs(http.StatusResetContent)) require.NoError(s.T(), err) req, err := http.NewRequest(http.MethodGet, "https://127.0.0.1:4443/", nil) require.NoError(s.T(), err) req.Host = tr2.TLSClientConfig.ServerName req.Header.Set("Host", tr2.TLSClientConfig.ServerName) req.Header.Set("Accept", "*/*") err = try.RequestWithTransport(req, 30*time.Second, tr2, try.HasCn(tr2.TLSClientConfig.ServerName), try.StatusCodeIs(http.StatusResetContent)) require.NoError(s.T(), err) // Change certificates configuration file content s.modifyCertificateConfFileContent("", dynamicConfFileName) err = try.RequestWithTransport(req, 30*time.Second, tr2, try.HasCn("TRAEFIK DEFAULT CERT"), try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) } // modifyCertificateConfFileContent replaces the content of a HTTPS configuration file. func (s *HTTPSSuite) modifyCertificateConfFileContent(certFileName, confFileName string) { file, err := os.OpenFile("./"+confFileName, os.O_WRONLY, os.ModeExclusive) require.NoError(s.T(), err) defer func() { file.Close() }() err = file.Truncate(0) require.NoError(s.T(), err) // If certificate file is not provided, just truncate the configuration file if len(certFileName) > 0 { tlsConf := dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{ Certificates: []*traefiktls.CertAndStores{ { Certificate: traefiktls.Certificate{ CertFile: types.FileOrContent("fixtures/https/" + certFileName + ".cert"),
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/tcp_test.go
integration/tcp_test.go
package integration import ( "crypto/tls" "crypto/x509" "errors" "fmt" "io" "net" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) type TCPSuite struct{ BaseSuite } func TestTCPSuite(t *testing.T) { suite.Run(t, new(TCPSuite)) } func (s *TCPSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("tcp") s.composeUp() } func (s *TCPSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *TCPSuite) TestMixed() { file := s.adaptFile("fixtures/tcp/mixed.toml", struct { Whoami string WhoamiA string WhoamiB string WhoamiNoCert string }{ Whoami: "http://" + s.getComposeServiceIP("whoami") + ":80", WhoamiA: s.getComposeServiceIP("whoami-a") + ":8080", WhoamiB: s.getComposeServiceIP("whoami-b") + ":8080", WhoamiNoCert: s.getComposeServiceIP("whoami-no-cert") + ":8080", }) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("Path(`/test`)")) require.NoError(s.T(), err) // Traefik passes through, termination handled by whoami-a out, err := guessWhoTLSPassthrough("127.0.0.1:8093", "whoami-a.test") require.NoError(s.T(), err) assert.Contains(s.T(), out, "whoami-a") // Traefik passes through, termination handled by whoami-b out, err = guessWhoTLSPassthrough("127.0.0.1:8093", "whoami-b.test") require.NoError(s.T(), err) assert.Contains(s.T(), out, "whoami-b") // Termination handled by traefik out, err = guessWho("127.0.0.1:8093", "whoami-c.test", true) require.NoError(s.T(), err) assert.Contains(s.T(), out, "whoami-no-cert") tr1 := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, }, } req, err := http.NewRequest(http.MethodGet, "https://127.0.0.1:8093/whoami/", nil) require.NoError(s.T(), err) err = try.RequestWithTransport(req, 10*time.Second, tr1, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) req, err = http.NewRequest(http.MethodGet, "https://127.0.0.1:8093/not-found/", nil) require.NoError(s.T(), err) err = try.RequestWithTransport(req, 10*time.Second, tr1, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8093/test", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8093/not-found", 500*time.Millisecond, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) } func (s *TCPSuite) TestTLSOptions() { file := s.adaptFile("fixtures/tcp/multi-tls-options.toml", struct { WhoamiNoCert string }{ WhoamiNoCert: s.getComposeServiceIP("whoami-no-cert") + ":8080", }) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`whoami-c.test`)")) require.NoError(s.T(), err) // Check that we can use a client tls version <= 1.2 with hostSNI 'whoami-c.test' out, err := guessWhoTLSMaxVersion("127.0.0.1:8093", "whoami-c.test", true, tls.VersionTLS12) require.NoError(s.T(), err) assert.Contains(s.T(), out, "whoami-no-cert") // Check that we can use a client tls version <= 1.3 with hostSNI 'whoami-d.test' out, err = guessWhoTLSMaxVersion("127.0.0.1:8093", "whoami-d.test", true, tls.VersionTLS13) require.NoError(s.T(), err) assert.Contains(s.T(), out, "whoami-no-cert") // Check that we cannot use a client tls version <= 1.2 with hostSNI 'whoami-d.test' _, err = guessWhoTLSMaxVersion("127.0.0.1:8093", "whoami-d.test", true, tls.VersionTLS12) assert.ErrorContains(s.T(), err, "protocol version not supported") // Check that we can't reach a route with an invalid mTLS configuration. conn, err := tls.Dial("tcp", "127.0.0.1:8093", &tls.Config{ ServerName: "whoami-i.test", InsecureSkipVerify: true, }) assert.Nil(s.T(), conn) assert.Error(s.T(), err) } func (s *TCPSuite) TestNonTLSFallback() { file := s.adaptFile("fixtures/tcp/non-tls-fallback.toml", struct { WhoamiA string WhoamiB string WhoamiNoCert string WhoamiNoTLS string }{ WhoamiA: s.getComposeServiceIP("whoami-a") + ":8080", WhoamiB: s.getComposeServiceIP("whoami-b") + ":8080", WhoamiNoCert: s.getComposeServiceIP("whoami-no-cert") + ":8080", WhoamiNoTLS: s.getComposeServiceIP("whoami-no-tls") + ":8080", }) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`*`)")) require.NoError(s.T(), err) // Traefik passes through, termination handled by whoami-a out, err := guessWhoTLSPassthrough("127.0.0.1:8093", "whoami-a.test") require.NoError(s.T(), err) assert.Contains(s.T(), out, "whoami-a") // Traefik passes through, termination handled by whoami-b out, err = guessWhoTLSPassthrough("127.0.0.1:8093", "whoami-b.test") require.NoError(s.T(), err) assert.Contains(s.T(), out, "whoami-b") // Termination handled by traefik out, err = guessWho("127.0.0.1:8093", "whoami-c.test", true) require.NoError(s.T(), err) assert.Contains(s.T(), out, "whoami-no-cert") out, err = guessWho("127.0.0.1:8093", "", false) require.NoError(s.T(), err) assert.Contains(s.T(), out, "whoami-no-tls") } func (s *TCPSuite) TestNonTlsTcp() { file := s.adaptFile("fixtures/tcp/non-tls.toml", struct { WhoamiNoTLS string }{ WhoamiNoTLS: s.getComposeServiceIP("whoami-no-tls") + ":8080", }) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`*`)")) require.NoError(s.T(), err) // Traefik will forward every requests on the given port to whoami-no-tls out, err := guessWho("127.0.0.1:8093", "", false) require.NoError(s.T(), err) assert.Contains(s.T(), out, "whoami-no-tls") } func (s *TCPSuite) TestCatchAllNoTLS() { file := s.adaptFile("fixtures/tcp/catch-all-no-tls.toml", struct { WhoamiBannerAddress string }{ WhoamiBannerAddress: s.getComposeServiceIP("whoami-banner") + ":8080", }) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`*`)")) require.NoError(s.T(), err) // Traefik will forward every requests on the given port to whoami-no-tls out, err := welcome("127.0.0.1:8093") require.NoError(s.T(), err) assert.Contains(s.T(), out, "Welcome") } func (s *TCPSuite) TestCatchAllNoTLSWithHTTPS() { file := s.adaptFile("fixtures/tcp/catch-all-no-tls-with-https.toml", struct { WhoamiNoTLSAddress string WhoamiURL string }{ WhoamiNoTLSAddress: s.getComposeServiceIP("whoami-no-tls") + ":8080", WhoamiURL: "http://" + s.getComposeServiceIP("whoami") + ":80", }) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`*`)")) require.NoError(s.T(), err) req := httptest.NewRequest(http.MethodGet, "https://127.0.0.1:8093/test", nil) req.RequestURI = "" err = try.RequestWithTransport(req, 500*time.Millisecond, &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, }, }, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) } func (s *TCPSuite) TestMiddlewareAllowList() { file := s.adaptFile("fixtures/tcp/ip-allowlist.toml", struct { WhoamiA string WhoamiB string }{ WhoamiA: s.getComposeServiceIP("whoami-a") + ":8080", WhoamiB: s.getComposeServiceIP("whoami-b") + ":8080", }) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`whoami-a.test`)")) require.NoError(s.T(), err) // Traefik not passes through, ipAllowList closes connection _, err = guessWhoTLSPassthrough("127.0.0.1:8093", "whoami-a.test") assert.ErrorIs(s.T(), err, io.EOF) // Traefik passes through, termination handled by whoami-b out, err := guessWhoTLSPassthrough("127.0.0.1:8093", "whoami-b.test") require.NoError(s.T(), err) assert.Contains(s.T(), out, "whoami-b") } func (s *TCPSuite) TestMiddlewareWhiteList() { file := s.adaptFile("fixtures/tcp/ip-whitelist.toml", struct { WhoamiA string WhoamiB string }{ WhoamiA: s.getComposeServiceIP("whoami-a") + ":8080", WhoamiB: s.getComposeServiceIP("whoami-b") + ":8080", }) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`whoami-a.test`)")) require.NoError(s.T(), err) // Traefik not passes through, ipWhiteList closes connection _, err = guessWhoTLSPassthrough("127.0.0.1:8093", "whoami-a.test") assert.ErrorIs(s.T(), err, io.EOF) // Traefik passes through, termination handled by whoami-b out, err := guessWhoTLSPassthrough("127.0.0.1:8093", "whoami-b.test") require.NoError(s.T(), err) assert.Contains(s.T(), out, "whoami-b") } func (s *TCPSuite) TestWRR() { file := s.adaptFile("fixtures/tcp/wrr.toml", struct { WhoamiB string WhoamiAB string }{ WhoamiB: s.getComposeServiceIP("whoami-b") + ":8080", WhoamiAB: s.getComposeServiceIP("whoami-ab") + ":8080", }) s.traefikCmd(withConfigFile(file)) err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`whoami-b.test`)")) require.NoError(s.T(), err) call := map[string]int{} for range 4 { // Traefik passes through, termination handled by whoami-b or whoami-bb out, err := guessWhoTLSPassthrough("127.0.0.1:8093", "whoami-b.test") require.NoError(s.T(), err) switch { case strings.Contains(out, "whoami-b"): call["whoami-b"]++ case strings.Contains(out, "whoami-ab"): call["whoami-ab"]++ default: call["unknown"]++ } time.Sleep(time.Second) } assert.Equal(s.T(), map[string]int{"whoami-b": 3, "whoami-ab": 1}, call) } func welcome(addr string) (string, error) { tcpAddr, err := net.ResolveTCPAddr("tcp", addr) if err != nil { return "", err } conn, err := net.DialTCP("tcp", nil, tcpAddr) if err != nil { return "", err } defer conn.Close() out := make([]byte, 2048) n, err := conn.Read(out) if err != nil { return "", err } return string(out[:n]), nil } func guessWho(addr, serverName string, tlsCall bool) (string, error) { return guessWhoTLSMaxVersion(addr, serverName, tlsCall, 0) } func guessWhoTLSMaxVersion(addr, serverName string, tlsCall bool, tlsMaxVersion uint16) (string, error) { var conn net.Conn var err error if tlsCall { conn, err = tls.Dial("tcp", addr, &tls.Config{ ServerName: serverName, InsecureSkipVerify: true, MinVersion: 0, MaxVersion: tlsMaxVersion, }) } else { tcpAddr, err2 := net.ResolveTCPAddr("tcp", addr) if err2 != nil { return "", err2 } conn, err = net.DialTCP("tcp", nil, tcpAddr) if err != nil { return "", err } } if err != nil { return "", err } defer conn.Close() _, err = conn.Write([]byte("WHO")) if err != nil { return "", err } out := make([]byte, 2048) n, err := conn.Read(out) if err != nil { return "", err } return string(out[:n]), nil } // guessWhoTLSPassthrough guesses service identity and ensures that the // certificate is valid for the given server name. func guessWhoTLSPassthrough(addr, serverName string) (string, error) { var conn net.Conn var err error conn, err = tls.Dial("tcp", addr, &tls.Config{ ServerName: serverName, InsecureSkipVerify: true, MinVersion: 0, MaxVersion: 0, VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { if len(rawCerts) > 1 { return errors.New("tls: more than one certificates from peer") } cert, err := x509.ParseCertificate(rawCerts[0]) if err != nil { return fmt.Errorf("tls: failed to parse certificate from peer: %w", err) } if cert.Subject.CommonName == serverName { return nil } if err = cert.VerifyHostname(serverName); err == nil { return nil } return fmt.Errorf("tls: no valid certificate for serverName %s", serverName) }, }) if err != nil { return "", err } defer conn.Close() _, err = conn.Write([]byte("WHO")) if err != nil { return "", err } out := make([]byte, 2048) n, err := conn.Read(out) if err != nil { return "", err } return string(out[:n]), nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/acme_test.go
integration/acme_test.go
package integration import ( "crypto/tls" "crypto/x509" "fmt" "net" "net/http" "os" "path/filepath" "testing" "time" "github.com/miekg/dns" "github.com/rs/zerolog/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/provider/acme" "github.com/traefik/traefik/v3/pkg/testhelpers" "github.com/traefik/traefik/v3/pkg/types" "k8s.io/utils/strings/slices" ) // ACME test suites. type AcmeSuite struct { BaseSuite pebbleIP string fakeDNSServer *dns.Server } func TestAcmeSuite(t *testing.T) { suite.Run(t, new(AcmeSuite)) } type subCases struct { host string expectedDomain string expectedAlgorithm x509.PublicKeyAlgorithm } type acmeTestCase struct { template templateModel traefikConfFilePath string subCases []subCases } type templateModel struct { Domain types.Domain Domains []types.Domain PortHTTP string PortHTTPS string Acme map[string]static.CertificateResolver } const ( // Domain to check acmeDomain = "traefik.acme.wtf" // Wildcard domain to check wildcardDomain = "*.acme.wtf" ) func (s *AcmeSuite) getAcmeURL() string { return fmt.Sprintf("https://%s/dir", net.JoinHostPort(s.pebbleIP, "14000")) } func setupPebbleRootCA() (*http.Transport, error) { path, err := filepath.Abs("fixtures/acme/ssl/pebble.minica.pem") if err != nil { return nil, err } os.Setenv("LEGO_CA_CERTIFICATES", path) os.Setenv("LEGO_CA_SERVER_NAME", "pebble") customCAs, err := os.ReadFile(path) if err != nil { return nil, err } certPool := x509.NewCertPool() if ok := certPool.AppendCertsFromPEM(customCAs); !ok { return nil, fmt.Errorf("error creating x509 cert pool from %q: %w", path, err) } return &http.Transport{ TLSClientConfig: &tls.Config{ ServerName: "pebble", RootCAs: certPool, }, }, nil } func (s *AcmeSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("pebble") s.composeUp() // Retrieving the Docker host ip. s.fakeDNSServer = startFakeDNSServer(s.hostIP) s.pebbleIP = s.getComposeServiceIP("pebble") pebbleTransport, err := setupPebbleRootCA() require.NoError(s.T(), err) // wait for pebble req := testhelpers.MustNewRequest(http.MethodGet, s.getAcmeURL(), nil) client := &http.Client{ Transport: pebbleTransport, } err = try.Do(5*time.Second, func() error { resp, errGet := client.Do(req) if errGet != nil { return errGet } return try.StatusCodeIs(http.StatusOK)(resp) }) require.NoError(s.T(), err) } func (s *AcmeSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() if s.fakeDNSServer != nil { err := s.fakeDNSServer.Shutdown() if err != nil { log.Info().Msg(err.Error()) } } s.composeDown() } func (s *AcmeSuite) TestHTTP01Domains() { testCase := acmeTestCase{ traefikConfFilePath: "fixtures/acme/acme_domains.toml", subCases: []subCases{{ host: acmeDomain, expectedDomain: acmeDomain, expectedAlgorithm: x509.RSA, }}, template: templateModel{ Domains: []types.Domain{{ Main: "traefik.acme.wtf", }}, Acme: map[string]static.CertificateResolver{ "default": {ACME: &acme.Configuration{ HTTPChallenge: &acme.HTTPChallenge{EntryPoint: "web"}, }}, }, }, } s.retrieveAcmeCertificate(testCase) } func (s *AcmeSuite) TestHTTP01StoreDomains() { testCase := acmeTestCase{ traefikConfFilePath: "fixtures/acme/acme_store_domains.toml", subCases: []subCases{{ host: acmeDomain, expectedDomain: acmeDomain, expectedAlgorithm: x509.RSA, }}, template: templateModel{ Domain: types.Domain{ Main: "traefik.acme.wtf", }, Acme: map[string]static.CertificateResolver{ "default": {ACME: &acme.Configuration{ HTTPChallenge: &acme.HTTPChallenge{EntryPoint: "web"}, }}, }, }, } s.retrieveAcmeCertificate(testCase) } func (s *AcmeSuite) TestHTTP01DomainsInSAN() { testCase := acmeTestCase{ traefikConfFilePath: "fixtures/acme/acme_domains.toml", subCases: []subCases{{ host: acmeDomain, expectedDomain: "acme.wtf", expectedAlgorithm: x509.RSA, }}, template: templateModel{ Domains: []types.Domain{{ Main: "acme.wtf", SANs: []string{"traefik.acme.wtf"}, }}, Acme: map[string]static.CertificateResolver{ "default": {ACME: &acme.Configuration{ HTTPChallenge: &acme.HTTPChallenge{EntryPoint: "web"}, }}, }, }, } s.retrieveAcmeCertificate(testCase) } func (s *AcmeSuite) TestHTTP01OnHostRule() { testCase := acmeTestCase{ traefikConfFilePath: "fixtures/acme/acme_base.toml", subCases: []subCases{{ host: acmeDomain, expectedDomain: acmeDomain, expectedAlgorithm: x509.RSA, }}, template: templateModel{ Acme: map[string]static.CertificateResolver{ "default": {ACME: &acme.Configuration{ HTTPChallenge: &acme.HTTPChallenge{EntryPoint: "web"}, }}, }, }, } s.retrieveAcmeCertificate(testCase) } func (s *AcmeSuite) TestMultipleResolver() { testCase := acmeTestCase{ traefikConfFilePath: "fixtures/acme/acme_multiple_resolvers.toml", subCases: []subCases{ { host: acmeDomain, expectedDomain: acmeDomain, expectedAlgorithm: x509.RSA, }, { host: "tchouk.acme.wtf", expectedDomain: "tchouk.acme.wtf", expectedAlgorithm: x509.ECDSA, }, }, template: templateModel{ Acme: map[string]static.CertificateResolver{ "default": {ACME: &acme.Configuration{ HTTPChallenge: &acme.HTTPChallenge{EntryPoint: "web"}, }}, "tchouk": {ACME: &acme.Configuration{ TLSChallenge: &acme.TLSChallenge{}, KeyType: "EC256", }}, }, }, } s.retrieveAcmeCertificate(testCase) } func (s *AcmeSuite) TestHTTP01OnHostRuleECDSA() { testCase := acmeTestCase{ traefikConfFilePath: "fixtures/acme/acme_base.toml", subCases: []subCases{{ host: acmeDomain, expectedDomain: acmeDomain, expectedAlgorithm: x509.ECDSA, }}, template: templateModel{ Acme: map[string]static.CertificateResolver{ "default": {ACME: &acme.Configuration{ HTTPChallenge: &acme.HTTPChallenge{EntryPoint: "web"}, KeyType: "EC384", }}, }, }, } s.retrieveAcmeCertificate(testCase) } func (s *AcmeSuite) TestHTTP01OnHostRuleInvalidAlgo() { testCase := acmeTestCase{ traefikConfFilePath: "fixtures/acme/acme_base.toml", subCases: []subCases{{ host: acmeDomain, expectedDomain: acmeDomain, expectedAlgorithm: x509.RSA, }}, template: templateModel{ Acme: map[string]static.CertificateResolver{ "default": {ACME: &acme.Configuration{ HTTPChallenge: &acme.HTTPChallenge{EntryPoint: "web"}, KeyType: "INVALID", }}, }, }, } s.retrieveAcmeCertificate(testCase) } // TODO: check why this test do not use the ACME cert resolver. func (s *AcmeSuite) TestHTTP01OnHostRuleDefaultDynamicCertificatesWithWildcard() { testCase := acmeTestCase{ traefikConfFilePath: "fixtures/acme/acme_tls.toml", subCases: []subCases{{ host: acmeDomain, expectedDomain: wildcardDomain, expectedAlgorithm: x509.RSA, }}, template: templateModel{ Acme: map[string]static.CertificateResolver{ "default": {ACME: &acme.Configuration{ HTTPChallenge: &acme.HTTPChallenge{EntryPoint: "web"}, }}, }, }, } s.retrieveAcmeCertificate(testCase) } // TODO: check why this test do not use the ACME cert resolver. func (s *AcmeSuite) TestHTTP01OnHostRuleDynamicCertificatesWithWildcard() { testCase := acmeTestCase{ traefikConfFilePath: "fixtures/acme/acme_tls_dynamic.toml", subCases: []subCases{{ host: acmeDomain, expectedDomain: wildcardDomain, expectedAlgorithm: x509.RSA, }}, template: templateModel{ Acme: map[string]static.CertificateResolver{ "default": {ACME: &acme.Configuration{ HTTPChallenge: &acme.HTTPChallenge{EntryPoint: "web"}, }}, }, }, } s.retrieveAcmeCertificate(testCase) } func (s *AcmeSuite) TestTLSALPN01OnHostRuleTCP() { testCase := acmeTestCase{ traefikConfFilePath: "fixtures/acme/acme_tcp.toml", subCases: []subCases{{ host: acmeDomain, expectedDomain: acmeDomain, expectedAlgorithm: x509.RSA, }}, template: templateModel{ Acme: map[string]static.CertificateResolver{ "default": {ACME: &acme.Configuration{ TLSChallenge: &acme.TLSChallenge{}, }}, }, }, } s.retrieveAcmeCertificate(testCase) } func (s *AcmeSuite) TestTLSALPN01OnHostRule() { testCase := acmeTestCase{ traefikConfFilePath: "fixtures/acme/acme_base.toml", subCases: []subCases{{ host: acmeDomain, expectedDomain: acmeDomain, expectedAlgorithm: x509.RSA, }}, template: templateModel{ Acme: map[string]static.CertificateResolver{ "default": {ACME: &acme.Configuration{ TLSChallenge: &acme.TLSChallenge{}, }}, }, }, } s.retrieveAcmeCertificate(testCase) } func (s *AcmeSuite) TestTLSALPN01Domains() { testCase := acmeTestCase{ traefikConfFilePath: "fixtures/acme/acme_domains.toml", subCases: []subCases{{ host: acmeDomain, expectedDomain: acmeDomain, expectedAlgorithm: x509.RSA, }}, template: templateModel{ Domains: []types.Domain{{ Main: "traefik.acme.wtf", }}, Acme: map[string]static.CertificateResolver{ "default": {ACME: &acme.Configuration{ TLSChallenge: &acme.TLSChallenge{}, }}, }, }, } s.retrieveAcmeCertificate(testCase) } func (s *AcmeSuite) TestTLSALPN01DomainsInSAN() { testCase := acmeTestCase{ traefikConfFilePath: "fixtures/acme/acme_domains.toml", subCases: []subCases{{ host: acmeDomain, expectedDomain: "acme.wtf", expectedAlgorithm: x509.RSA, }}, template: templateModel{ Domains: []types.Domain{{ Main: "acme.wtf", SANs: []string{"traefik.acme.wtf"}, }}, Acme: map[string]static.CertificateResolver{ "default": {ACME: &acme.Configuration{ TLSChallenge: &acme.TLSChallenge{}, }}, }, }, } s.retrieveAcmeCertificate(testCase) } // Test Let's encrypt down. func (s *AcmeSuite) TestNoValidLetsEncryptServer() { file := s.adaptFile("fixtures/acme/acme_base.toml", templateModel{ Acme: map[string]static.CertificateResolver{ "default": {ACME: &acme.Configuration{ CAServer: "http://wrongurl:4001/directory", HTTPChallenge: &acme.HTTPChallenge{EntryPoint: "web"}, }}, }, }) s.traefikCmd(withConfigFile(file)) // Expected traefik works err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 10*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) } // Doing an HTTPS request and test the response certificate. func (s *AcmeSuite) retrieveAcmeCertificate(testCase acmeTestCase) { if len(testCase.template.PortHTTP) == 0 { testCase.template.PortHTTP = ":5002" } if len(testCase.template.PortHTTPS) == 0 { testCase.template.PortHTTPS = ":5001" } for _, value := range testCase.template.Acme { if len(value.ACME.CAServer) == 0 { value.ACME.CAServer = s.getAcmeURL() } } file := s.adaptFile(testCase.traefikConfFilePath, testCase.template) s.traefikCmd(withConfigFile(file)) // A real file is needed to have the right mode on acme.json file defer os.Remove("/tmp/acme.json") backend := startTestServer("9010", http.StatusOK, "") defer backend.Close() client := &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }, } // wait for traefik (generating acme account take some seconds) err := try.Do(60*time.Second, func() error { _, errGet := client.Get("https://127.0.0.1:5001") return errGet }) require.NoError(s.T(), err) for _, sub := range testCase.subCases { client = &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, ServerName: sub.host, }, // Needed so that each subcase redoes the SSL handshake DisableKeepAlives: true, }, } req := testhelpers.MustNewRequest(http.MethodGet, "https://127.0.0.1:5001/", nil) req.Host = sub.host req.Header.Set("Host", sub.host) req.Header.Set("Accept", "*/*") var ( gotStatusCode int gotDomains []string gotPublicKeyAlgorithm x509.PublicKeyAlgorithm ) // Retry to send a Request which uses the LE generated certificate err := try.Do(60*time.Second, func() error { resp, err := client.Do(req) if err != nil { return err } gotStatusCode = resp.StatusCode gotPublicKeyAlgorithm = resp.TLS.PeerCertificates[0].PublicKeyAlgorithm // Here we are collecting the common name as it is used in wildcard tests. gotDomains = append(gotDomains, resp.TLS.PeerCertificates[0].Subject.CommonName) gotDomains = append(gotDomains, resp.TLS.PeerCertificates[0].DNSNames...) if !slices.Contains(gotDomains, sub.expectedDomain) { return fmt.Errorf("domain name %s not found in domain names: %v", sub.expectedDomain, gotDomains) } return nil }) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusOK, gotStatusCode) // Check Domain into response certificate assert.Contains(s.T(), gotDomains, sub.expectedDomain) assert.Equal(s.T(), sub.expectedAlgorithm, gotPublicKeyAlgorithm) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/gateway_api_conformance_test.go
integration/gateway_api_conformance_test.go
//go:build gatewayAPIConformance package integration import ( "fmt" "io" "io/fs" "os" "path/filepath" "slices" "strings" "testing" "time" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/modules/k3s" "github.com/testcontainers/testcontainers-go/network" "github.com/traefik/traefik/v3/integration/try" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/gateway" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" "k8s.io/apimachinery/pkg/util/sets" kclientset "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "sigs.k8s.io/controller-runtime/pkg/client" klog "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/log/zap" gatev1 "sigs.k8s.io/gateway-api/apis/v1" gatev1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" gatev1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" "sigs.k8s.io/gateway-api/conformance" v1 "sigs.k8s.io/gateway-api/conformance/apis/v1" "sigs.k8s.io/gateway-api/conformance/tests" "sigs.k8s.io/gateway-api/conformance/utils/config" ksuite "sigs.k8s.io/gateway-api/conformance/utils/suite" "sigs.k8s.io/yaml" ) // GatewayAPIConformanceSuite tests suite. type GatewayAPIConformanceSuite struct { BaseSuite k3sContainer *k3s.K3sContainer kubeClient client.Client restConfig *rest.Config clientSet *kclientset.Clientset } func TestGatewayAPIConformanceSuite(t *testing.T) { suite.Run(t, new(GatewayAPIConformanceSuite)) } func (s *GatewayAPIConformanceSuite) SetupSuite() { s.BaseSuite.SetupSuite() // Avoid panic. klog.SetLogger(zap.New()) provider, err := testcontainers.ProviderDocker.GetProvider() if err != nil { s.T().Fatal(err) } ctx := s.T().Context() // Ensure image is available locally. images, err := provider.ListImages(ctx) if err != nil { s.T().Fatal(err) } if !slices.ContainsFunc(images, func(img testcontainers.ImageInfo) bool { return img.Name == traefikImage }) { s.T().Fatal("Traefik image is not present") } s.k3sContainer, err = k3s.Run(ctx, k3sImage, k3s.WithManifest("./fixtures/gateway-api-conformance/00-experimental-v1.4.0.yml"), k3s.WithManifest("./fixtures/gateway-api-conformance/01-rbac.yml"), k3s.WithManifest("./fixtures/gateway-api-conformance/02-traefik.yml"), network.WithNetwork(nil, s.network), ) if err != nil { s.T().Fatal(err) } if err = s.k3sContainer.LoadImages(ctx, traefikImage); err != nil { s.T().Fatal(err) } exitCode, _, err := s.k3sContainer.Exec(ctx, []string{"kubectl", "wait", "-n", traefikNamespace, traefikDeployment, "--for=condition=Available", "--timeout=30s"}) if err != nil || exitCode > 0 { s.T().Fatalf("Traefik pod is not ready: %v", err) } kubeConfigYaml, err := s.k3sContainer.GetKubeConfig(ctx) if err != nil { s.T().Fatal(err) } s.restConfig, err = clientcmd.RESTConfigFromKubeConfig(kubeConfigYaml) if err != nil { s.T().Fatalf("Error loading Kubernetes config: %v", err) } s.kubeClient, err = client.New(s.restConfig, client.Options{}) if err != nil { s.T().Fatalf("Error initializing Kubernetes client: %v", err) } s.clientSet, err = kclientset.NewForConfig(s.restConfig) if err != nil { s.T().Fatalf("Error initializing Kubernetes REST client: %v", err) } if err = gatev1alpha2.Install(s.kubeClient.Scheme()); err != nil { s.T().Fatal(err) } if err = gatev1beta1.Install(s.kubeClient.Scheme()); err != nil { s.T().Fatal(err) } if err = gatev1.Install(s.kubeClient.Scheme()); err != nil { s.T().Fatal(err) } if err = apiextensionsv1.AddToScheme(s.kubeClient.Scheme()); err != nil { s.T().Fatal(err) } } func (s *GatewayAPIConformanceSuite) TearDownSuite() { ctx := s.T().Context() if s.T().Failed() || *showLog { k3sLogs, err := s.k3sContainer.Logs(ctx) if err == nil { if res, err := io.ReadAll(k3sLogs); err == nil { s.T().Log(string(res)) } } exitCode, result, err := s.k3sContainer.Exec(ctx, []string{"kubectl", "logs", "-n", traefikNamespace, traefikDeployment}) if err == nil || exitCode == 0 { if res, err := io.ReadAll(result); err == nil { s.T().Log(string(res)) } } } if err := s.k3sContainer.Terminate(ctx); err != nil { s.T().Fatal(err) } s.BaseSuite.TearDownSuite() } func (s *GatewayAPIConformanceSuite) TestK8sGatewayAPIConformance() { // Wait for traefik to start k3sContainerIP, err := s.k3sContainer.ContainerIP(s.T().Context()) require.NoError(s.T(), err) err = try.GetRequest("http://"+k3sContainerIP+":9000/api/entrypoints", 10*time.Second, try.BodyContains(`"name":"web"`)) require.NoError(s.T(), err) cSuite, err := ksuite.NewConformanceTestSuite(ksuite.ConformanceOptions{ Client: s.kubeClient, Clientset: s.clientSet, GatewayClassName: "traefik", Debug: true, CleanupBaseResources: true, RestConfig: s.restConfig, TimeoutConfig: config.DefaultTimeoutConfig(), ManifestFS: []fs.FS{&conformance.Manifests}, EnableAllSupportedFeatures: false, RunTest: *gatewayAPIConformanceRunTest, Implementation: v1.Implementation{ Organization: "traefik", Project: "traefik", URL: "https://traefik.io/", Version: *traefikVersion, Contact: []string{"@traefik/maintainers"}, }, ConformanceProfiles: sets.New( ksuite.GatewayHTTPConformanceProfileName, ksuite.GatewayGRPCConformanceProfileName, ksuite.GatewayTLSConformanceProfileName, ), SupportedFeatures: sets.New(gateway.SupportedFeatures()...), }) require.NoError(s.T(), err) cSuite.Setup(s.T(), tests.ConformanceTests) err = cSuite.Run(s.T(), tests.ConformanceTests) require.NoError(s.T(), err) report, err := cSuite.Report() require.NoError(s.T(), err, "failed generating conformance report") // Ignore report date to avoid diff with CI job. // However, we can track the date of the report thanks to the commit. // TODO: to publish this report automatically, we have to figure out how to handle the date diff. report.Date = "-" // Ordering profile reports for the serialized report to be comparable. slices.SortFunc(report.ProfileReports, func(a, b v1.ProfileReport) int { return strings.Compare(a.Name, b.Name) }) rawReport, err := yaml.Marshal(report) require.NoError(s.T(), err) s.T().Logf("Conformance report:\n%s", string(rawReport)) require.NoError(s.T(), os.MkdirAll("./gateway-api-conformance-reports/"+report.GatewayAPIVersion, 0o755)) outFile := filepath.Join("gateway-api-conformance-reports/"+report.GatewayAPIVersion, fmt.Sprintf("%s-%s-%s-report.yaml", report.GatewayAPIChannel, report.Version, report.Mode)) require.NoError(s.T(), os.WriteFile(outFile, rawReport, 0o600)) s.T().Logf("Report written to: %s", outFile) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/consul_catalog_test.go
integration/consul_catalog_test.go
package integration import ( "fmt" "net" "net/http" "testing" "time" "github.com/hashicorp/consul/api" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) type ConsulCatalogSuite struct { BaseSuite consulClient *api.Client consulAgentClient *api.Client consulURL string } func TestConsulCatalogSuite(t *testing.T) { suite.Run(t, new(ConsulCatalogSuite)) } func (s *ConsulCatalogSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("consul_catalog") s.composeUp() s.consulURL = "http://" + net.JoinHostPort(s.getComposeServiceIP("consul"), "8500") var err error s.consulClient, err = api.NewClient(&api.Config{ Address: s.consulURL, }) require.NoError(s.T(), err) // Wait for consul to elect itself leader err = s.waitToElectConsulLeader() require.NoError(s.T(), err) s.consulAgentClient, err = api.NewClient(&api.Config{ Address: "http://" + net.JoinHostPort(s.getComposeServiceIP("consul-agent"), "8500"), }) require.NoError(s.T(), err) } func (s *ConsulCatalogSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *ConsulCatalogSuite) waitToElectConsulLeader() error { return try.Do(15*time.Second, func() error { leader, err := s.consulClient.Status().Leader() if err != nil || len(leader) == 0 { return fmt.Errorf("leader not found. %w", err) } return nil }) } func (s *ConsulCatalogSuite) waitForConnectCA() error { return try.Do(15*time.Second, func() error { caroots, _, err := s.consulClient.Connect().CARoots(nil) if err != nil || len(caroots.Roots) == 0 { return fmt.Errorf("connect CA not fully initialized. %w", err) } return nil }) } func (s *ConsulCatalogSuite) registerService(reg *api.AgentServiceRegistration, onAgent bool) error { client := s.consulClient if onAgent { client = s.consulAgentClient } return client.Agent().ServiceRegister(reg) } func (s *ConsulCatalogSuite) deregisterService(id string, onAgent bool) error { client := s.consulClient if onAgent { client = s.consulAgentClient } return client.Agent().ServiceDeregister(id) } func (s *ConsulCatalogSuite) TestWithNotExposedByDefaultAndDefaultsSettings() { reg1 := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{"traefik.enable=true"}, Port: 80, Address: s.getComposeServiceIP("whoami1"), } err := s.registerService(reg1, false) require.NoError(s.T(), err) reg2 := &api.AgentServiceRegistration{ ID: "whoami2", Name: "whoami", Tags: []string{"traefik.enable=true"}, Port: 80, Address: s.getComposeServiceIP("whoami2"), } err = s.registerService(reg2, false) require.NoError(s.T(), err) reg3 := &api.AgentServiceRegistration{ ID: "whoami3", Name: "whoami", Tags: []string{"traefik.enable=true"}, Port: 80, Address: s.getComposeServiceIP("whoami3"), } err = s.registerService(reg3, false) require.NoError(s.T(), err) tempObjects := struct { ConsulAddress string }{ ConsulAddress: s.consulURL, } file := s.adaptFile("fixtures/consul_catalog/default_not_exposed.toml", tempObjects) s.traefikCmd(withConfigFile(file)) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = "whoami" err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("Hostname: whoami1", "Hostname: whoami2", "Hostname: whoami3")) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 2*time.Second, try.StatusCodeIs(200), try.BodyContains( fmt.Sprintf(`"http://%s:80":"UP"`, reg1.Address), fmt.Sprintf(`"http://%s:80":"UP"`, reg2.Address), fmt.Sprintf(`"http://%s:80":"UP"`, reg3.Address), )) require.NoError(s.T(), err) err = s.deregisterService("whoami1", false) require.NoError(s.T(), err) err = s.deregisterService("whoami2", false) require.NoError(s.T(), err) err = s.deregisterService("whoami3", false) require.NoError(s.T(), err) } func (s *ConsulCatalogSuite) TestByLabels() { containerIP := s.getComposeServiceIP("whoami1") reg := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{ "traefik.enable=true", "traefik.http.routers.router1.rule=Path(`/whoami`)", }, Port: 80, Address: containerIP, } err := s.registerService(reg, false) require.NoError(s.T(), err) tempObjects := struct { ConsulAddress string }{ ConsulAddress: s.consulURL, } file := s.adaptFile("fixtures/consul_catalog/default_not_exposed.toml", tempObjects) s.traefikCmd(withConfigFile(file)) err = try.GetRequest("http://127.0.0.1:8000/whoami", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContainsOr("Hostname: whoami1", "Hostname: whoami2", "Hostname: whoami3")) require.NoError(s.T(), err) err = s.deregisterService("whoami1", false) require.NoError(s.T(), err) } func (s *ConsulCatalogSuite) TestSimpleConfiguration() { tempObjects := struct { ConsulAddress string DefaultRule string }{ ConsulAddress: s.consulURL, DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", } file := s.adaptFile("fixtures/consul_catalog/simple.toml", tempObjects) reg := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{"traefik.enable=true"}, Port: 80, Address: s.getComposeServiceIP("whoami1"), } err := s.registerService(reg, false) require.NoError(s.T(), err) s.traefikCmd(withConfigFile(file)) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = "whoami.consul.localhost" err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("Hostname: whoami1")) require.NoError(s.T(), err) err = s.deregisterService("whoami1", false) require.NoError(s.T(), err) } func (s *ConsulCatalogSuite) TestSimpleConfigurationWithWatch() { tempObjects := struct { ConsulAddress string DefaultRule string }{ ConsulAddress: s.consulURL, DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", } file := s.adaptFile("fixtures/consul_catalog/simple_watch.toml", tempObjects) reg := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{"traefik.enable=true"}, Port: 80, Address: s.getComposeServiceIP("whoami1"), } err := s.registerService(reg, false) require.NoError(s.T(), err) s.traefikCmd(withConfigFile(file)) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = "whoami.consul.localhost" err = try.Request(req, 2*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContainsOr("Hostname: whoami1")) require.NoError(s.T(), err) err = s.deregisterService("whoami1", false) require.NoError(s.T(), err) err = try.Request(req, 2*time.Second, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) whoamiIP := s.getComposeServiceIP("whoami1") reg.Check = &api.AgentServiceCheck{ CheckID: "some-ok-check", TCP: whoamiIP + ":80", Name: "some-ok-check", Interval: "1s", Timeout: "1s", } err = s.registerService(reg, false) require.NoError(s.T(), err) err = try.Request(req, 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContainsOr("Hostname: whoami1")) require.NoError(s.T(), err) reg.Check = &api.AgentServiceCheck{ CheckID: "some-failing-check", TCP: ":80", Name: "some-failing-check", Interval: "1s", Timeout: "1s", } err = s.registerService(reg, false) require.NoError(s.T(), err) err = try.Request(req, 5*time.Second, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) err = s.deregisterService("whoami1", false) require.NoError(s.T(), err) } func (s *ConsulCatalogSuite) TestRegisterServiceWithoutIP() { tempObjects := struct { ConsulAddress string DefaultRule string }{ ConsulAddress: s.consulURL, DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", } file := s.adaptFile("fixtures/consul_catalog/simple.toml", tempObjects) reg := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{"traefik.enable=true"}, Port: 80, Address: "", } err := s.registerService(reg, false) require.NoError(s.T(), err) s.traefikCmd(withConfigFile(file)) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/http/services", nil) require.NoError(s.T(), err) err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("whoami@consulcatalog", "\"http://127.0.0.1:80\": \"UP\"")) require.NoError(s.T(), err) err = s.deregisterService("whoami1", false) require.NoError(s.T(), err) } func (s *ConsulCatalogSuite) TestDefaultConsulService() { tempObjects := struct { ConsulAddress string DefaultRule string }{ ConsulAddress: s.consulURL, DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", } file := s.adaptFile("fixtures/consul_catalog/simple.toml", tempObjects) reg := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Port: 80, Address: s.getComposeServiceIP("whoami1"), } err := s.registerService(reg, false) require.NoError(s.T(), err) // Start traefik s.traefikCmd(withConfigFile(file)) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = "whoami.consul.localhost" err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("Hostname: whoami1")) require.NoError(s.T(), err) err = s.deregisterService("whoami1", false) require.NoError(s.T(), err) } func (s *ConsulCatalogSuite) TestConsulServiceWithTCPLabels() { tempObjects := struct { ConsulAddress string DefaultRule string }{ ConsulAddress: s.consulURL, DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", } file := s.adaptFile("fixtures/consul_catalog/simple.toml", tempObjects) // Start a container with some tags reg := &api.AgentServiceRegistration{ ID: "whoamitcp", Name: "whoamitcp", Tags: []string{ "traefik.tcp.Routers.Super.Rule=HostSNI(`my.super.host`)", "traefik.tcp.Routers.Super.tls=true", "traefik.tcp.Services.Super.Loadbalancer.server.port=8080", }, Port: 8080, Address: s.getComposeServiceIP("whoamitcp"), } err := s.registerService(reg, false) require.NoError(s.T(), err) // Start traefik s.traefikCmd(withConfigFile(file)) err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`my.super.host`)")) require.NoError(s.T(), err) who, err := guessWho("127.0.0.1:8000", "my.super.host", true) require.NoError(s.T(), err) assert.Contains(s.T(), who, "whoamitcp") err = s.deregisterService("whoamitcp", false) require.NoError(s.T(), err) } func (s *ConsulCatalogSuite) TestConsulServiceWithLabels() { tempObjects := struct { ConsulAddress string DefaultRule string }{ ConsulAddress: s.consulURL, DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", } file := s.adaptFile("fixtures/consul_catalog/simple.toml", tempObjects) // Start a container with some tags reg1 := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{ "traefik.http.Routers.Super.Rule=Host(`my.super.host`)", }, Port: 80, Address: s.getComposeServiceIP("whoami1"), } err := s.registerService(reg1, false) require.NoError(s.T(), err) // Start another container by replacing a '.' by a '-' reg2 := &api.AgentServiceRegistration{ ID: "whoami2", Name: "whoami", Tags: []string{ "traefik.http.Routers.SuperHost.Rule=Host(`my-super.host`)", }, Port: 80, Address: s.getComposeServiceIP("whoami2"), } err = s.registerService(reg2, false) require.NoError(s.T(), err) // Start traefik s.traefikCmd(withConfigFile(file)) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = "my-super.host" err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("Hostname: whoami1")) require.NoError(s.T(), err) req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = "my.super.host" err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("Hostname: whoami2")) require.NoError(s.T(), err) err = s.deregisterService("whoami1", false) require.NoError(s.T(), err) err = s.deregisterService("whoami2", false) require.NoError(s.T(), err) } func (s *ConsulCatalogSuite) TestSameServiceIDOnDifferentConsulAgent() { tempObjects := struct { ConsulAddress string DefaultRule string }{ ConsulAddress: s.consulURL, DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", } file := s.adaptFile("fixtures/consul_catalog/default_not_exposed.toml", tempObjects) // Start a container with some tags tags := []string{ "traefik.enable=true", "traefik.http.Routers.Super.service=whoami", "traefik.http.Routers.Super.Rule=Host(`my.super.host`)", } reg1 := &api.AgentServiceRegistration{ ID: "whoami", Name: "whoami", Tags: tags, Port: 80, Address: s.getComposeServiceIP("whoami1"), } err := s.registerService(reg1, false) require.NoError(s.T(), err) reg2 := &api.AgentServiceRegistration{ ID: "whoami", Name: "whoami", Tags: tags, Port: 80, Address: s.getComposeServiceIP("whoami2"), } err = s.registerService(reg2, true) require.NoError(s.T(), err) // Start traefik s.traefikCmd(withConfigFile(file)) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) require.NoError(s.T(), err) req.Host = "my.super.host" err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("Hostname: whoami1", "Hostname: whoami2")) require.NoError(s.T(), err) req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/rawdata", nil) require.NoError(s.T(), err) err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr(s.getComposeServiceIP("whoami1"), s.getComposeServiceIP("whoami2"))) require.NoError(s.T(), err) err = s.deregisterService("whoami", false) require.NoError(s.T(), err) err = s.deregisterService("whoami", true) require.NoError(s.T(), err) } func (s *ConsulCatalogSuite) TestConsulServiceWithOneMissingLabels() { tempObjects := struct { ConsulAddress string DefaultRule string }{ ConsulAddress: s.consulURL, DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", } file := s.adaptFile("fixtures/consul_catalog/simple.toml", tempObjects) // Start a container with some tags reg := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{ "traefik.random.value=my.super.host", }, Port: 80, Address: s.getComposeServiceIP("whoami1"), } err := s.registerService(reg, false) require.NoError(s.T(), err) // Start traefik s.traefikCmd(withConfigFile(file)) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/version", nil) require.NoError(s.T(), err) req.Host = "my.super.host" // TODO Need to wait than 500 milliseconds more (for swarm or traefik to boot up ?) // TODO validate : run on 80 // Expected a 404 as we did not configure anything err = try.Request(req, 1500*time.Millisecond, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) } func (s *ConsulCatalogSuite) TestConsulServiceWithHealthCheck() { whoamiIP := s.getComposeServiceIP("whoami1") tags := []string{ "traefik.enable=true", "traefik.http.routers.router1.rule=Path(`/whoami`)", } reg1 := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: tags, Port: 80, Address: whoamiIP, Check: &api.AgentServiceCheck{ CheckID: "some-failed-check", TCP: "127.0.0.1:1234", Name: "some-failed-check", Interval: "1s", Timeout: "1s", }, } err := s.registerService(reg1, false) require.NoError(s.T(), err) tempObjects := struct { ConsulAddress string }{ ConsulAddress: s.consulURL, } file := s.adaptFile("fixtures/consul_catalog/simple.toml", tempObjects) s.traefikCmd(withConfigFile(file)) err = try.GetRequest("http://127.0.0.1:8000/whoami", 2*time.Second, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) err = s.deregisterService("whoami1", false) require.NoError(s.T(), err) whoami2IP := s.getComposeServiceIP("whoami2") reg2 := &api.AgentServiceRegistration{ ID: "whoami2", Name: "whoami", Tags: tags, Port: 80, Address: whoami2IP, Check: &api.AgentServiceCheck{ CheckID: "some-ok-check", TCP: whoami2IP + ":80", Name: "some-ok-check", Interval: "1s", Timeout: "1s", }, } err = s.registerService(reg2, false) require.NoError(s.T(), err) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil) require.NoError(s.T(), err) req.Host = "whoami" // TODO Need to wait for up to 10 seconds (for consul discovery or traefik to boot up ?) err = try.Request(req, 10*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("Hostname: whoami2")) require.NoError(s.T(), err) err = s.deregisterService("whoami2", false) require.NoError(s.T(), err) } func (s *ConsulCatalogSuite) TestConsulConnect() { // Wait for consul to fully initialize connect CA err := s.waitForConnectCA() require.NoError(s.T(), err) connectIP := s.getComposeServiceIP("connect") reg := &api.AgentServiceRegistration{ ID: "uuid-api1", Name: "uuid-api", Tags: []string{ "traefik.enable=true", "traefik.consulcatalog.connect=true", "traefik.http.routers.router1.rule=Path(`/`)", }, Connect: &api.AgentServiceConnect{ Native: true, }, Port: 443, Address: connectIP, } err = s.registerService(reg, false) require.NoError(s.T(), err) whoamiIP := s.getComposeServiceIP("whoami1") regWhoami := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{ "traefik.enable=true", "traefik.http.routers.router2.rule=Path(`/whoami`)", "traefik.http.routers.router2.service=whoami", }, Port: 80, Address: whoamiIP, } err = s.registerService(regWhoami, false) require.NoError(s.T(), err) tempObjects := struct { ConsulAddress string }{ ConsulAddress: s.consulURL, } file := s.adaptFile("fixtures/consul_catalog/connect.toml", tempObjects) s.traefikCmd(withConfigFile(file)) err = try.GetRequest("http://127.0.0.1:8000/", 10*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/whoami", 10*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) err = s.deregisterService("uuid-api1", false) require.NoError(s.T(), err) err = s.deregisterService("whoami1", false) require.NoError(s.T(), err) } func (s *ConsulCatalogSuite) TestConsulConnect_ByDefault() { // Wait for consul to fully initialize connect CA err := s.waitForConnectCA() require.NoError(s.T(), err) connectIP := s.getComposeServiceIP("connect") reg := &api.AgentServiceRegistration{ ID: "uuid-api1", Name: "uuid-api", Tags: []string{ "traefik.enable=true", "traefik.http.routers.router1.rule=Path(`/`)", }, Connect: &api.AgentServiceConnect{ Native: true, }, Port: 443, Address: connectIP, } err = s.registerService(reg, false) require.NoError(s.T(), err) whoamiIP := s.getComposeServiceIP("whoami1") regWhoami := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami1", Tags: []string{ "traefik.enable=true", "traefik.http.routers.router2.rule=Path(`/whoami`)", "traefik.http.routers.router2.service=whoami", }, Port: 80, Address: whoamiIP, } err = s.registerService(regWhoami, false) require.NoError(s.T(), err) whoami2IP := s.getComposeServiceIP("whoami2") regWhoami2 := &api.AgentServiceRegistration{ ID: "whoami2", Name: "whoami2", Tags: []string{ "traefik.enable=true", "traefik.consulcatalog.connect=false", "traefik.http.routers.router2.rule=Path(`/whoami2`)", "traefik.http.routers.router2.service=whoami2", }, Port: 80, Address: whoami2IP, } err = s.registerService(regWhoami2, false) require.NoError(s.T(), err) tempObjects := struct { ConsulAddress string }{ ConsulAddress: s.consulURL, } file := s.adaptFile("fixtures/consul_catalog/connect_by_default.toml", tempObjects) s.traefikCmd(withConfigFile(file)) err = try.GetRequest("http://127.0.0.1:8000/", 10*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/whoami", 10*time.Second, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/whoami2", 10*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) err = s.deregisterService("uuid-api1", false) require.NoError(s.T(), err) err = s.deregisterService("whoami1", false) require.NoError(s.T(), err) err = s.deregisterService("whoami2", false) require.NoError(s.T(), err) } func (s *ConsulCatalogSuite) TestConsulConnect_NotAware() { // Wait for consul to fully initialize connect CA err := s.waitForConnectCA() require.NoError(s.T(), err) connectIP := s.getComposeServiceIP("connect") reg := &api.AgentServiceRegistration{ ID: "uuid-api1", Name: "uuid-api", Tags: []string{ "traefik.enable=true", "traefik.consulcatalog.connect=true", "traefik.http.routers.router1.rule=Path(`/`)", }, Connect: &api.AgentServiceConnect{ Native: true, }, Port: 443, Address: connectIP, } err = s.registerService(reg, false) require.NoError(s.T(), err) whoamiIP := s.getComposeServiceIP("whoami1") regWhoami := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{ "traefik.enable=true", "traefik.http.routers.router2.rule=Path(`/whoami`)", "traefik.http.routers.router2.service=whoami", }, Port: 80, Address: whoamiIP, } err = s.registerService(regWhoami, false) require.NoError(s.T(), err) tempObjects := struct { ConsulAddress string }{ ConsulAddress: s.consulURL, } file := s.adaptFile("fixtures/consul_catalog/connect_not_aware.toml", tempObjects) s.traefikCmd(withConfigFile(file)) err = try.GetRequest("http://127.0.0.1:8000/", 10*time.Second, try.StatusCodeIs(http.StatusNotFound)) require.NoError(s.T(), err) err = try.GetRequest("http://127.0.0.1:8000/whoami", 10*time.Second, try.StatusCodeIs(http.StatusOK)) require.NoError(s.T(), err) err = s.deregisterService("uuid-api1", false) require.NoError(s.T(), err) err = s.deregisterService("whoami1", false) require.NoError(s.T(), err) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/error_pages_test.go
integration/error_pages_test.go
package integration import ( "net/http" "net/http/httptest" "testing" "time" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" ) // ErrorPagesSuite test suites. type ErrorPagesSuite struct { BaseSuite ErrorPageIP string BackendIP string } func TestErrorPagesSuite(t *testing.T) { suite.Run(t, new(ErrorPagesSuite)) } func (s *ErrorPagesSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("error_pages") s.composeUp() s.ErrorPageIP = s.getComposeServiceIP("nginx2") s.BackendIP = s.getComposeServiceIP("nginx1") } func (s *ErrorPagesSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *ErrorPagesSuite) TestSimpleConfiguration() { file := s.adaptFile("fixtures/error_pages/simple.toml", struct { Server1 string Server2 string }{"http://" + s.BackendIP + ":80", s.ErrorPageIP}) s.traefikCmd(withConfigFile(file)) frontendReq, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080", nil) require.NoError(s.T(), err) frontendReq.Host = "test.local" err = try.Request(frontendReq, 2*time.Second, try.BodyContains("nginx")) require.NoError(s.T(), err) } func (s *ErrorPagesSuite) TestErrorPage() { // error.toml contains a mis-configuration of the backend host file := s.adaptFile("fixtures/error_pages/error.toml", struct { Server1 string Server2 string }{s.BackendIP, s.ErrorPageIP}) s.traefikCmd(withConfigFile(file)) frontendReq, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080", nil) require.NoError(s.T(), err) frontendReq.Host = "test.local" err = try.Request(frontendReq, 2*time.Second, try.BodyContains("An error occurred.")) require.NoError(s.T(), err) } func (s *ErrorPagesSuite) TestStatusRewrites() { // The `statusRewrites.toml` file contains a misconfigured backend host and some status code rewrites. file := s.adaptFile("fixtures/error_pages/statusRewrites.toml", struct { Server1 string Server2 string }{s.BackendIP, s.ErrorPageIP}) s.traefikCmd(withConfigFile(file)) frontendReq, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080", nil) require.NoError(s.T(), err) frontendReq.Host = "test502.local" err = try.Request(frontendReq, 2*time.Second, try.BodyContains("An error occurred."), try.StatusCodeIs(404)) require.NoError(s.T(), err) frontendReq, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8080", nil) require.NoError(s.T(), err) frontendReq.Host = "test418.local" err = try.Request(frontendReq, 2*time.Second, try.BodyContains("An error occurred."), try.StatusCodeIs(400)) require.NoError(s.T(), err) } func (s *ErrorPagesSuite) TestErrorPageFlush() { srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { rw.Header().Add("Transfer-Encoding", "chunked") rw.WriteHeader(http.StatusInternalServerError) _, _ = rw.Write([]byte("KO")) })) file := s.adaptFile("fixtures/error_pages/simple.toml", struct { Server1 string Server2 string }{srv.URL, s.ErrorPageIP}) s.traefikCmd(withConfigFile(file)) frontendReq, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080", nil) require.NoError(s.T(), err) frontendReq.Host = "test.local" err = try.Request(frontendReq, 2*time.Second, try.BodyContains("An error occurred."), try.HasHeaderValue("Content-Type", "text/html", true), ) require.NoError(s.T(), err) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/etcd_test.go
integration/etcd_test.go
package integration import ( "bytes" "encoding/json" "net" "net/http" "os" "path/filepath" "testing" "time" "github.com/kvtools/etcdv3" "github.com/kvtools/valkeyrie" "github.com/kvtools/valkeyrie/store" "github.com/pmezard/go-difflib/difflib" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/traefik/traefik/v3/integration/try" "github.com/traefik/traefik/v3/pkg/api" ) // etcd test suites. type EtcdSuite struct { BaseSuite kvClient store.Store etcdAddr string } func TestEtcdSuite(t *testing.T) { suite.Run(t, new(EtcdSuite)) } func (s *EtcdSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.createComposeProject("etcd") s.composeUp() var err error s.etcdAddr = net.JoinHostPort(s.getComposeServiceIP("etcd"), "2379") s.kvClient, err = valkeyrie.NewStore( s.T().Context(), etcdv3.StoreName, []string{s.etcdAddr}, &etcdv3.Config{ ConnectionTimeout: 10 * time.Second, }, ) require.NoError(s.T(), err) // wait for etcd err = try.Do(60*time.Second, try.KVExists(s.kvClient, "test")) require.NoError(s.T(), err) } func (s *EtcdSuite) TearDownSuite() { s.BaseSuite.TearDownSuite() } func (s *EtcdSuite) TestSimpleConfiguration() { file := s.adaptFile("fixtures/etcd/simple.toml", struct{ EtcdAddress string }{s.etcdAddr}) data := map[string]string{ "traefik/http/routers/Router0/entryPoints/0": "web", "traefik/http/routers/Router0/middlewares/0": "compressor", "traefik/http/routers/Router0/middlewares/1": "striper", "traefik/http/routers/Router0/service": "simplesvc", "traefik/http/routers/Router0/rule": "Host(`kv1.localhost`)", "traefik/http/routers/Router0/priority": "42", "traefik/http/routers/Router0/tls": "", "traefik/http/routers/Router1/rule": "Host(`kv2.localhost`)", "traefik/http/routers/Router1/priority": "42", "traefik/http/routers/Router1/tls/domains/0/main": "aaa.localhost", "traefik/http/routers/Router1/tls/domains/0/sans/0": "aaa.aaa.localhost", "traefik/http/routers/Router1/tls/domains/0/sans/1": "bbb.aaa.localhost", "traefik/http/routers/Router1/tls/domains/1/main": "bbb.localhost", "traefik/http/routers/Router1/tls/domains/1/sans/0": "aaa.bbb.localhost", "traefik/http/routers/Router1/tls/domains/1/sans/1": "bbb.bbb.localhost", "traefik/http/routers/Router1/entryPoints/0": "web", "traefik/http/routers/Router1/service": "simplesvc", "traefik/http/services/simplesvc/loadBalancer/servers/0/url": "http://10.0.1.1:8888", "traefik/http/services/simplesvc/loadBalancer/servers/1/url": "http://10.0.1.1:8889", "traefik/http/services/srvcA/loadBalancer/servers/0/url": "http://10.0.1.2:8888", "traefik/http/services/srvcA/loadBalancer/servers/1/url": "http://10.0.1.2:8889", "traefik/http/services/srvcB/loadBalancer/servers/0/url": "http://10.0.1.3:8888", "traefik/http/services/srvcB/loadBalancer/servers/1/url": "http://10.0.1.3:8889", "traefik/http/services/mirror/mirroring/service": "simplesvc", "traefik/http/services/mirror/mirroring/mirrors/0/name": "srvcA", "traefik/http/services/mirror/mirroring/mirrors/0/percent": "42", "traefik/http/services/mirror/mirroring/mirrors/1/name": "srvcB", "traefik/http/services/mirror/mirroring/mirrors/1/percent": "42", "traefik/http/services/Service03/weighted/services/0/name": "srvcA", "traefik/http/services/Service03/weighted/services/0/weight": "42", "traefik/http/services/Service03/weighted/services/1/name": "srvcB", "traefik/http/services/Service03/weighted/services/1/weight": "42", "traefik/http/middlewares/compressor/compress": "", "traefik/http/middlewares/striper/stripPrefix/prefixes/0": "foo", "traefik/http/middlewares/striper/stripPrefix/prefixes/1": "bar", } for k, v := range data { err := s.kvClient.Put(s.T().Context(), k, []byte(v), nil) require.NoError(s.T(), err) } s.traefikCmd(withConfigFile(file)) // wait for traefik err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 2*time.Second, try.BodyContains(`"striper@etcd":`, `"compressor@etcd":`, `"srvcA@etcd":`, `"srvcB@etcd":`), ) require.NoError(s.T(), err) resp, err := http.Get("http://127.0.0.1:8080/api/rawdata") require.NoError(s.T(), err) var obtained api.RunTimeRepresentation err = json.NewDecoder(resp.Body).Decode(&obtained) require.NoError(s.T(), err) got, err := json.MarshalIndent(obtained, "", " ") require.NoError(s.T(), err) expectedJSON := filepath.FromSlash("testdata/rawdata-etcd.json") if *updateExpected { err = os.WriteFile(expectedJSON, got, 0o666) require.NoError(s.T(), err) } expected, err := os.ReadFile(expectedJSON) require.NoError(s.T(), err) if !bytes.Equal(expected, got) { diff := difflib.UnifiedDiff{ FromFile: "Expected", A: difflib.SplitLines(string(expected)), ToFile: "Got", B: difflib.SplitLines(string(got)), Context: 3, } text, err := difflib.GetUnifiedDiffString(diff) require.NoError(s.T(), err, text) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/fixtures/knative/tools.go
integration/fixtures/knative/tools.go
//go:build tools package tools // The following dependencies are required by the Knative conformance tests. // They allow to download the test_images when calling "go mod vendor". import ( _ "knative.dev/networking/test/test_images/grpc-ping" _ "knative.dev/networking/test/test_images/httpproxy" _ "knative.dev/networking/test/test_images/retry" _ "knative.dev/networking/test/test_images/runtime" _ "knative.dev/networking/test/test_images/timeout" _ "knative.dev/networking/test/test_images/wsserver" )
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/fixtures/ocsp/gencert.go
integration/fixtures/ocsp/gencert.go
package main import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "math/big" "os" "time" ) func main() { // generate CA caKey, caCert := generateCA("Test CA") saveKeyAndCert("integration/fixtures/ocsp/ca.key", "integration/fixtures/ocsp/ca.crt", caKey, caCert) // server certificate serverKey, serverCert := generateCert("server.local", caKey, caCert) saveKeyAndCert("integration/fixtures/ocsp/server.key", "integration/fixtures/ocsp/server.crt", serverKey, serverCert) // default certificate defaultKey, defaultCert := generateCert("default.local", caKey, caCert) saveKeyAndCert("integration/fixtures/ocsp/default.key", "integration/fixtures/ocsp/default.crt", defaultKey, defaultCert) } func generateCA(commonName string) (*ecdsa.PrivateKey, *x509.Certificate) { // generate a private key for the CA caKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) // create a self-signed CA certificate caTemplate := &x509.Certificate{ SerialNumber: big.NewInt(1), Subject: pkix.Name{ CommonName: commonName, }, NotBefore: time.Now(), NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour), // 10 ans KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, BasicConstraintsValid: true, IsCA: true, MaxPathLen: 1, OCSPServer: []string{"ocsp.example.com"}, } caCertDER, _ := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, &caKey.PublicKey, caKey) caCert, _ := x509.ParseCertificate(caCertDER) return caKey, caCert } func generateCert(commonName string, caKey *ecdsa.PrivateKey, caCert *x509.Certificate) (*ecdsa.PrivateKey, *x509.Certificate) { // create a private key for the certificate certKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) // create a certificate signed by the CA certTemplate := &x509.Certificate{ SerialNumber: big.NewInt(time.Now().UnixNano()), Subject: pkix.Name{ CommonName: commonName, }, NotBefore: time.Now(), NotAfter: time.Now().Add(1 * 365 * 24 * time.Hour), // 1 an KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, BasicConstraintsValid: true, OCSPServer: []string{"ocsp.example.com"}, } certDER, _ := x509.CreateCertificate(rand.Reader, certTemplate, caCert, &certKey.PublicKey, caKey) cert, _ := x509.ParseCertificate(certDER) return certKey, cert } func saveKeyAndCert(keyFile, certFile string, key *ecdsa.PrivateKey, cert *x509.Certificate) { // save the private key keyOut, _ := os.Create(keyFile) defer keyOut.Close() // Marshal the private key to ASN.1 DER format privateKey, err := x509.MarshalECPrivateKey(key) if err != nil { panic(err) } err = pem.Encode(keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: privateKey}) if err != nil { panic(err) } // save the certificate certOut, _ := os.Create(certFile) defer certOut.Close() err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}) if err != nil { panic(err) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/helloworld/helloworld.pb.go
integration/helloworld/helloworld.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: helloworld.proto /* Package helloworld is a generated protocol buffer package. It is generated from these files: helloworld.proto It has these top-level messages: HelloRequest HelloReply StreamExampleRequest StreamExampleReply */ package helloworld import ( fmt "fmt" math "math" proto "github.com/golang/protobuf/proto" context "context" grpc "google.golang.org/grpc" ) // Reference imports to suppress errors if they are not otherwise used. var ( _ = proto.Marshal _ = fmt.Errorf _ = math.Inf ) // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // The request message containing the user's name. type HelloRequest struct { Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` } func (m *HelloRequest) Reset() { *m = HelloRequest{} } func (m *HelloRequest) String() string { return proto.CompactTextString(m) } func (*HelloRequest) ProtoMessage() {} func (*HelloRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *HelloRequest) GetName() string { if m != nil { return m.Name } return "" } // The response message containing the greetings type HelloReply struct { Message string `protobuf:"bytes,1,opt,name=message" json:"message,omitempty"` } func (m *HelloReply) Reset() { *m = HelloReply{} } func (m *HelloReply) String() string { return proto.CompactTextString(m) } func (*HelloReply) ProtoMessage() {} func (*HelloReply) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *HelloReply) GetMessage() string { if m != nil { return m.Message } return "" } type StreamExampleRequest struct { } func (m *StreamExampleRequest) Reset() { *m = StreamExampleRequest{} } func (m *StreamExampleRequest) String() string { return proto.CompactTextString(m) } func (*StreamExampleRequest) ProtoMessage() {} func (*StreamExampleRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } type StreamExampleReply struct { Data string `protobuf:"bytes,1,opt,name=data" json:"data,omitempty"` } func (m *StreamExampleReply) Reset() { *m = StreamExampleReply{} } func (m *StreamExampleReply) String() string { return proto.CompactTextString(m) } func (*StreamExampleReply) ProtoMessage() {} func (*StreamExampleReply) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (m *StreamExampleReply) GetData() string { if m != nil { return m.Data } return "" } func init() { proto.RegisterType((*HelloRequest)(nil), "helloworld.HelloRequest") proto.RegisterType((*HelloReply)(nil), "helloworld.HelloReply") proto.RegisterType((*StreamExampleRequest)(nil), "helloworld.StreamExampleRequest") proto.RegisterType((*StreamExampleReply)(nil), "helloworld.StreamExampleReply") } // Reference imports to suppress errors if they are not otherwise used. var ( _ context.Context _ grpc.ClientConn ) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // Client API for Greeter service type GreeterClient interface { // Sends a greeting SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) // Tick me StreamExample(ctx context.Context, in *StreamExampleRequest, opts ...grpc.CallOption) (Greeter_StreamExampleClient, error) } type greeterClient struct { cc *grpc.ClientConn } func NewGreeterClient(cc *grpc.ClientConn) GreeterClient { return &greeterClient{cc} } func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { out := new(HelloReply) err := grpc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *greeterClient) StreamExample(ctx context.Context, in *StreamExampleRequest, opts ...grpc.CallOption) (Greeter_StreamExampleClient, error) { stream, err := grpc.NewClientStream(ctx, &_Greeter_serviceDesc.Streams[0], c.cc, "/helloworld.Greeter/StreamExample", opts...) if err != nil { return nil, err } x := &greeterStreamExampleClient{stream} if err := x.ClientStream.SendMsg(in); err != nil { return nil, err } if err := x.ClientStream.CloseSend(); err != nil { return nil, err } return x, nil } type Greeter_StreamExampleClient interface { Recv() (*StreamExampleReply, error) grpc.ClientStream } type greeterStreamExampleClient struct { grpc.ClientStream } func (x *greeterStreamExampleClient) Recv() (*StreamExampleReply, error) { m := new(StreamExampleReply) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } // Server API for Greeter service type GreeterServer interface { // Sends a greeting SayHello(context.Context, *HelloRequest) (*HelloReply, error) // Tick me StreamExample(*StreamExampleRequest, Greeter_StreamExampleServer) error } func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) { s.RegisterService(&_Greeter_serviceDesc, srv) } func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(HelloRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(GreeterServer).SayHello(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/helloworld.Greeter/SayHello", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) } return interceptor(ctx, in, info, handler) } func _Greeter_StreamExample_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(StreamExampleRequest) if err := stream.RecvMsg(m); err != nil { return err } return srv.(GreeterServer).StreamExample(m, &greeterStreamExampleServer{stream}) } type Greeter_StreamExampleServer interface { Send(*StreamExampleReply) error grpc.ServerStream } type greeterStreamExampleServer struct { grpc.ServerStream } func (x *greeterStreamExampleServer) Send(m *StreamExampleReply) error { return x.ServerStream.SendMsg(m) } var _Greeter_serviceDesc = grpc.ServiceDesc{ ServiceName: "helloworld.Greeter", HandlerType: (*GreeterServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "SayHello", Handler: _Greeter_SayHello_Handler, }, }, Streams: []grpc.StreamDesc{ { StreamName: "StreamExample", Handler: _Greeter_StreamExample_Handler, ServerStreams: true, }, }, Metadata: "helloworld.proto", } func init() { proto.RegisterFile("helloworld.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 231 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x50, 0xc1, 0x4a, 0xc4, 0x30, 0x10, 0x35, 0xb0, 0xb8, 0x3a, 0x28, 0xca, 0x20, 0x4b, 0x59, 0x41, 0x96, 0x1c, 0x64, 0x4f, 0xa1, 0xe8, 0xdd, 0x43, 0x41, 0xf4, 0x58, 0x5a, 0xc4, 0x73, 0xb4, 0x43, 0x15, 0x12, 0x13, 0x93, 0x88, 0xf6, 0x6f, 0xfc, 0x54, 0x49, 0x6c, 0x31, 0x4a, 0xf1, 0xf6, 0x66, 0xe6, 0xe5, 0xbd, 0x97, 0x07, 0xc7, 0x4f, 0xa4, 0x94, 0x79, 0x37, 0x4e, 0x75, 0xc2, 0x3a, 0x13, 0x0c, 0xc2, 0xcf, 0x86, 0x73, 0x38, 0xb8, 0x8d, 0x53, 0x43, 0xaf, 0x6f, 0xe4, 0x03, 0x22, 0x2c, 0x5e, 0xa4, 0xa6, 0x82, 0x6d, 0xd8, 0x76, 0xbf, 0x49, 0x98, 0x9f, 0x03, 0x8c, 0x1c, 0xab, 0x06, 0x2c, 0x60, 0xa9, 0xc9, 0x7b, 0xd9, 0x4f, 0xa4, 0x69, 0xe4, 0x2b, 0x38, 0x69, 0x83, 0x23, 0xa9, 0xaf, 0x3f, 0xa4, 0xb6, 0x8a, 0x46, 0x4d, 0xbe, 0x05, 0xfc, 0xb3, 0x8f, 0x3a, 0x08, 0x8b, 0x4e, 0x06, 0x39, 0x39, 0x45, 0x7c, 0xf1, 0xc9, 0x60, 0x79, 0xe3, 0x88, 0x02, 0x39, 0xbc, 0x82, 0xbd, 0x56, 0x0e, 0xc9, 0x18, 0x0b, 0x91, 0x7d, 0x22, 0xcf, 0xbb, 0x5e, 0xcd, 0x5c, 0xac, 0x1a, 0xf8, 0x0e, 0xde, 0xc1, 0xe1, 0x2f, 0x57, 0xdc, 0xe4, 0xd4, 0xb9, 0xa0, 0xeb, 0xb3, 0x7f, 0x18, 0x49, 0xb4, 0x64, 0x55, 0x09, 0xa7, 0xcf, 0x46, 0xf4, 0xce, 0x3e, 0x0a, 0xfa, 0xbe, 0xf9, 0xec, 0x55, 0x75, 0x94, 0x32, 0xdc, 0x47, 0x5c, 0xc7, 0xb2, 0x6b, 0xf6, 0xb0, 0x9b, 0x5a, 0xbf, 0xfc, 0x0a, 0x00, 0x00, 0xff, 0xff, 0x6f, 0x5f, 0xae, 0xb8, 0x89, 0x01, 0x00, 0x00, }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/try/try.go
integration/try/try.go
package try import ( "fmt" "math" "net/http" "os" "time" "github.com/rs/zerolog/log" ) const ( // CITimeoutMultiplier is the multiplier for all timeout in the CI. CITimeoutMultiplier = 3 maxInterval = 5 * time.Second ) type timedAction func(timeout time.Duration, operation DoCondition) error // Sleep pauses the current goroutine for at least the duration d. // Deprecated: Use only when use another Try[...] functions is not possible. func Sleep(d time.Duration) { d = applyCIMultiplier(d) time.Sleep(d) } // Response is like Request, but returns the response for further // processing at the call site. // Conditions are not allowed since it would complicate signaling if the // response body needs to be closed or not. Callers are expected to close on // their own if the function returns a nil error. func Response(req *http.Request, timeout time.Duration) (*http.Response, error) { return doTryRequest(req, timeout, nil) } // ResponseUntilStatusCode is like Request, but returns the response for further // processing at the call site. // Conditions are not allowed since it would complicate signaling if the // response body needs to be closed or not. Callers are expected to close on // their own if the function returns a nil error. func ResponseUntilStatusCode(req *http.Request, timeout time.Duration, statusCode int) (*http.Response, error) { return doTryRequest(req, timeout, nil, StatusCodeIs(statusCode)) } // GetRequest is like Do, but runs a request against the given URL and applies // the condition on the response. // ResponseCondition may be nil, in which case only the request against the URL must // succeed. func GetRequest(url string, timeout time.Duration, conditions ...ResponseCondition) error { resp, err := doTryGet(url, timeout, nil, conditions...) if resp != nil && resp.Body != nil { defer resp.Body.Close() } return err } // Request is like Do, but runs a request against the given URL and applies // the condition on the response. // ResponseCondition may be nil, in which case only the request against the URL must // succeed. func Request(req *http.Request, timeout time.Duration, conditions ...ResponseCondition) error { resp, err := doTryRequest(req, timeout, nil, conditions...) if resp != nil && resp.Body != nil { defer resp.Body.Close() } return err } // RequestWithTransport is like Do, but runs a request against the given URL and applies // the condition on the response. // ResponseCondition may be nil, in which case only the request against the URL must // succeed. func RequestWithTransport(req *http.Request, timeout time.Duration, transport *http.Transport, conditions ...ResponseCondition) error { resp, err := doTryRequest(req, timeout, transport, conditions...) if resp != nil && resp.Body != nil { defer resp.Body.Close() } return err } // Do repeatedly executes an operation until no error condition occurs or the // given timeout is reached, whatever comes first. func Do(timeout time.Duration, operation DoCondition) error { if timeout <= 0 { panic("timeout must be larger than zero") } interval := time.Duration(math.Ceil(float64(timeout) / 15.0)) if interval > maxInterval { interval = maxInterval } timeout = applyCIMultiplier(timeout) var err error if err = operation(); err == nil { fmt.Println("+") return nil } fmt.Print("*") stopTimer := time.NewTimer(timeout) defer stopTimer.Stop() retryTick := time.NewTicker(interval) defer retryTick.Stop() for { select { case <-stopTimer.C: fmt.Println("-") return fmt.Errorf("try operation failed: %w", err) case <-retryTick.C: fmt.Print("*") if err = operation(); err == nil { fmt.Println("+") return nil } } } } func doTryGet(url string, timeout time.Duration, transport http.RoundTripper, conditions ...ResponseCondition) (*http.Response, error) { req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return nil, err } return doTryRequest(req, timeout, transport, conditions...) } func doTryRequest(request *http.Request, timeout time.Duration, transport http.RoundTripper, conditions ...ResponseCondition) (*http.Response, error) { return doRequest(Do, timeout, request, transport, conditions...) } func doRequest(action timedAction, timeout time.Duration, request *http.Request, transport http.RoundTripper, conditions ...ResponseCondition) (*http.Response, error) { var resp *http.Response return resp, action(timeout, func() error { var err error client := http.DefaultClient if transport != nil { client.Transport = transport } resp, err = client.Do(request) if err != nil { return err } for _, condition := range conditions { if err := condition(resp); err != nil { return err } } return nil }) } func applyCIMultiplier(timeout time.Duration) time.Duration { ci := os.Getenv("CI") if len(ci) > 0 { log.Debug().Msgf("Apply CI multiplier: %d", CITimeoutMultiplier) return time.Duration(float64(timeout) * CITimeoutMultiplier) } return timeout }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/integration/try/condition.go
integration/try/condition.go
package try import ( "context" "errors" "fmt" "io" "net/http" "reflect" "strings" "github.com/kvtools/valkeyrie/store" ) // ResponseCondition is a retry condition function. // It receives a response, and returns an error if the response failed the condition. type ResponseCondition func(*http.Response) error // BodyContains returns a retry condition function. // The condition returns an error if the request body does not contain all the given strings. func BodyContains(values ...string) ResponseCondition { return func(res *http.Response) error { body, err := io.ReadAll(res.Body) if err != nil { return fmt.Errorf("failed to read response body: %w", err) } for _, value := range values { if !strings.Contains(string(body), value) { return fmt.Errorf("could not find '%s' in body '%s'", value, string(body)) } } return nil } } // BodyNotContains returns a retry condition function. // The condition returns an error if the request body contain one of the given strings. func BodyNotContains(values ...string) ResponseCondition { return func(res *http.Response) error { body, err := io.ReadAll(res.Body) if err != nil { return fmt.Errorf("failed to read response body: %w", err) } for _, value := range values { if strings.Contains(string(body), value) { return fmt.Errorf("find '%s' in body '%s'", value, string(body)) } } return nil } } // BodyContainsOr returns a retry condition function. // The condition returns an error if the request body does not contain one of the given strings. func BodyContainsOr(values ...string) ResponseCondition { return func(res *http.Response) error { body, err := io.ReadAll(res.Body) if err != nil { return fmt.Errorf("failed to read response body: %w", err) } for _, value := range values { if strings.Contains(string(body), value) { return nil } } return fmt.Errorf("could not find '%v' in body '%s'", values, string(body)) } } // HasBody returns a retry condition function. // The condition returns an error if the request body does not have body content. func HasBody() ResponseCondition { return func(res *http.Response) error { body, err := io.ReadAll(res.Body) if err != nil { return fmt.Errorf("failed to read response body: %w", err) } if len(body) == 0 { return errors.New("response doesn't have body content") } return nil } } // HasCn returns a retry condition function. // The condition returns an error if the cn is not correct. func HasCn(cn string) ResponseCondition { return func(res *http.Response) error { if res.TLS == nil { return errors.New("response doesn't have TLS") } if len(res.TLS.PeerCertificates) == 0 { return errors.New("response TLS doesn't have peer certificates") } if res.TLS.PeerCertificates[0] == nil { return errors.New("first peer certificate is nil") } commonName := res.TLS.PeerCertificates[0].Subject.CommonName if cn != commonName { return fmt.Errorf("common name don't match: %s != %s", cn, commonName) } return nil } } // StatusCodeIs returns a retry condition function. // The condition returns an error if the given response's status code is not the // given HTTP status code. func StatusCodeIs(status int) ResponseCondition { return func(res *http.Response) error { if res.StatusCode != status { return fmt.Errorf("got status code %d, wanted %d", res.StatusCode, status) } return nil } } // HasHeader returns a retry condition function. // The condition returns an error if the response does not have a header set. func HasHeader(header string) ResponseCondition { return func(res *http.Response) error { if _, ok := res.Header[header]; !ok { return errors.New("response doesn't contain header: " + header) } return nil } } // HasHeaderValue returns a retry condition function. // The condition returns an error if the response does not have a header set, and a value for that header. // Has an option to test for an exact header match only, not just contains. func HasHeaderValue(header, value string, exactMatch bool) ResponseCondition { return func(res *http.Response) error { if _, ok := res.Header[header]; !ok { return errors.New("response doesn't contain header: " + header) } matchFound := false for _, hdr := range res.Header[header] { if value != hdr && exactMatch { return fmt.Errorf("got header %s with value %s, wanted %s", header, hdr, value) } if value == hdr { matchFound = true } } if !matchFound { return fmt.Errorf("response doesn't contain header %s with value %s", header, value) } return nil } } // HasHeaderStruct returns a retry condition function. // The condition returns an error if the response does contain the headers set, and matching contents. func HasHeaderStruct(header http.Header) ResponseCondition { return func(res *http.Response) error { for key := range header { if _, ok := res.Header[key]; !ok { return fmt.Errorf("header %s not present in the response. Expected headers: %v Got response headers: %v", key, header, res.Header) } // Header exists in the response, test it. if !reflect.DeepEqual(header[key], res.Header[key]) { return fmt.Errorf("for header %s got values %v, wanted %v", key, res.Header[key], header[key]) } } return nil } } // DoCondition is a retry condition function. // It returns an error. type DoCondition func() error // KVExists is a retry condition function. // Verify if a Key exists in the store. func KVExists(kv store.Store, key string) DoCondition { return func() error { _, err := kv.Exists(context.Background(), key, nil) return err } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/internal/gendoc.go
internal/gendoc.go
package main import ( "bytes" "fmt" "io" "os" "reflect" "sort" "strings" "github.com/BurntSushi/toml" "github.com/rs/zerolog/log" "github.com/traefik/paerser/flag" "github.com/traefik/paerser/generator" "github.com/traefik/traefik/v3/cmd" "github.com/traefik/traefik/v3/pkg/collector/hydratation" "github.com/traefik/traefik/v3/pkg/config/dynamic" "gopkg.in/yaml.v3" ) var commentGenerated = `## CODE GENERATED AUTOMATICALLY ## THIS FILE MUST NOT BE EDITED BY HAND ` func main() { genRoutingConfDoc() genInstallConfDoc() genAnchors() } // Generate the Routing Configuration YAML and TOML files. func genRoutingConfDoc() { logger := log.With().Logger() dynConf := &dynamic.Configuration{} err := hydratation.Hydrate(dynConf) if err != nil { logger.Fatal().Err(err).Send() } dynConf.HTTP.Models = map[string]*dynamic.Model{} clean(dynConf.HTTP.Middlewares) clean(dynConf.TCP.Middlewares) clean(dynConf.HTTP.Services) clean(dynConf.TCP.Services) clean(dynConf.UDP.Services) err = tomlWrite("./docs/content/reference/routing-configuration/other-providers/file.toml", dynConf) if err != nil { logger.Fatal().Err(err).Send() } err = yamlWrite("./docs/content/reference/routing-configuration/other-providers/file.yaml", dynConf) if err != nil { logger.Fatal().Err(err).Send() } } func yamlWrite(outputFile string, element any) error { file, err := os.OpenFile(outputFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o666) if err != nil { return err } defer file.Close() // Write the comment at the beginning of the file. if _, err := file.WriteString(commentGenerated); err != nil { return err } buf := new(bytes.Buffer) encoder := yaml.NewEncoder(buf) encoder.SetIndent(2) err = encoder.Encode(element) if err != nil { return err } _, err = file.Write(buf.Bytes()) return err } func tomlWrite(outputFile string, element any) error { file, err := os.OpenFile(outputFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o666) if err != nil { return err } defer file.Close() // Write the comment at the beginning of the file. if _, err := file.WriteString(commentGenerated); err != nil { return err } return toml.NewEncoder(file).Encode(element) } func clean(element any) { valSvcs := reflect.ValueOf(element) key := valSvcs.MapKeys()[0] valueSvcRoot := valSvcs.MapIndex(key).Elem() var svcFieldNames []string for i := range valueSvcRoot.NumField() { field := valueSvcRoot.Type().Field(i) // do not create empty node for hidden config. if field.Tag.Get("file") == "-" && field.Tag.Get("kv") == "-" && field.Tag.Get("label") == "-" { continue } svcFieldNames = append(svcFieldNames, field.Name) } sort.Strings(svcFieldNames) for i, fieldName := range svcFieldNames { v := reflect.New(valueSvcRoot.Type()) v.Elem().FieldByName(fieldName).Set(valueSvcRoot.FieldByName(fieldName)) valSvcs.SetMapIndex(reflect.ValueOf(fmt.Sprintf("%s%.2d", valueSvcRoot.Type().Name(), i+1)), v) } valSvcs.SetMapIndex(reflect.ValueOf(fmt.Sprintf("%s0", valueSvcRoot.Type().Name())), reflect.Value{}) valSvcs.SetMapIndex(reflect.ValueOf(fmt.Sprintf("%s1", valueSvcRoot.Type().Name())), reflect.Value{}) } // Generate the Install Configuration in a table. func genInstallConfDoc() { outputFile := "./docs/content/reference/install-configuration/configuration-options.md" logger := log.With().Str("file", outputFile).Logger() element := &cmd.NewTraefikConfiguration().Configuration generator.Generate(element) flats, err := flag.Encode(element) if err != nil { logger.Fatal().Err(err).Send() } err = os.RemoveAll(outputFile) if err != nil { logger.Fatal().Err(err).Send() } file, err := os.OpenFile(outputFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o666) if err != nil { logger.Fatal().Err(err).Send() } defer file.Close() w := errWriter{w: file} w.writeln(`<!-- CODE GENERATED AUTOMATICALLY THIS FILE MUST NOT BE EDITED BY HAND -->`) w.writeln(`# Install Configuration Options`) w.writeln(`## Configuration Options`) w.writeln(` | Field | Description | Default | |:-------|:------------|:-------|`) for _, flat := range flats { // TODO must be move into the flats creation. if flat.Name == "experimental.plugins.<name>" || flat.Name == "TRAEFIK_EXPERIMENTAL_PLUGINS_<NAME>" { continue } if strings.HasPrefix(flat.Name, "pilot.") || strings.HasPrefix(flat.Name, "TRAEFIK_PILOT_") { continue } line := "| " + strings.ReplaceAll(strings.ReplaceAll(flat.Name, "<", "_"), ">", "_") + " | " + flat.Description + " | " if flat.Default == "" { line += "|" } else { line += flat.Default + " |" } w.writeln(line) } if w.err != nil { logger.Fatal().Err(err).Send() } } type errWriter struct { w io.Writer err error } func (ew *errWriter) writeln(a ...interface{}) { if ew.err != nil { return } _, ew.err = fmt.Fprintln(ew.w, a...) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/internal/anchors.go
internal/anchors.go
package main import ( "bufio" "fmt" "log" "os" "path/filepath" "regexp" "strings" ) var ( // detect any existing <a ...> tag in the cell (case-insensitive). reExistingAnchor = regexp.MustCompile(`(?i)<\s*a\b[^>]*>.*?</\s*a\s*>`) // separator cell like --- or :---: (3+ dashes, optional leading/trailing colon). reSepCell = regexp.MustCompile(`^\s*:?-{3,}:?\s*$`) // markdown link [text](url) → text (used to strip link wrappers in id). reMdLink = regexp.MustCompile(`\[(.*?)\]\((.*?)\)`) // collapse multiple hyphens. reMultiHyphens = regexp.MustCompile(`-+`) ) // splitTableRow splits a markdown table line on pipes, while keeping escaped pipes. // parts[1] will be the first data cell for lines that start with '|'. func splitTableRow(line string) []string { var parts []string var b strings.Builder escaped := false for _, r := range line { if escaped { b.WriteRune(r) escaped = false continue } if r == '\\' { escaped = true b.WriteRune(r) continue } if r == '|' { parts = append(parts, b.String()) b.Reset() continue } b.WriteRune(r) } parts = append(parts, b.String()) return parts } func isTableRow(line string) bool { s := strings.TrimSpace(line) if !strings.HasPrefix(s, "|") { return false } parts := splitTableRow(line) return len(parts) >= 3 } func isSeparatorRow(line string) bool { if !isTableRow(line) { return false } parts := splitTableRow(line) // check all middle cells (skip first and last which are outside pipes) for i := 1; i < len(parts)-1; i++ { cell := strings.TrimSpace(parts[i]) if cell == "" { continue } if !reSepCell.MatchString(cell) { return false } } return true } // Create ID from cell text, preserving letter case, removing <br /> and markdown decorations. func makeID(text string) string { id := strings.TrimSpace(text) // remove BR tags (common in table cells) id = strings.ReplaceAll(id, "<br />", " ") id = strings.ReplaceAll(id, "<br/>", " ") id = strings.ReplaceAll(id, "<br>", " ") // remove the dots id = strings.ReplaceAll(id, ".", "-") // strip markdown link wrappers [text](url) -> text id = reMdLink.ReplaceAllString(id, "$1") // remove inline markdown characters id = strings.ReplaceAll(id, "`", "") id = strings.ReplaceAll(id, "*", "") id = strings.ReplaceAll(id, "~", "") // replace spaces/underscores with hyphen id = strings.ReplaceAll(id, " ", "-") id = strings.ReplaceAll(id, "_", "-") // keep only letters (both cases), digits and hyphens var clean []rune for _, r := range id { if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '.' { // keep dot as you requested (we won't replace it) clean = append(clean, r) } } id = string(clean) // collapse multiple hyphens and trim id = reMultiHyphens.ReplaceAllString(id, "-") id = strings.Trim(id, "-") if id == "" { id = "row" } return id } // Dedupe ID within a file: if id already seen, append -2, -3... // Use "opt-" prefix to avoid conflicts with section headings. func dedupeID(base string, seen map[string]int) string { if base == "" { base = "row" } // Add prefix to avoid conflicts with section headings. optID := "opt-" + base count, ok := seen[optID] if !ok { seen[optID] = 1 return optID } seen[optID] = count + 1 return fmt.Sprintf("%s-%d", optID, count+1) } // Clean existing anchors from cell content. func cleanExistingAnchors(text string) string { return reExistingAnchor.ReplaceAllStringFunc(text, func(match string) string { // Extract content between <a> tags. start := strings.Index(match, ">") end := strings.LastIndex(match, "</") if start >= 0 && end > start { return strings.TrimSpace(match[start+1 : end]) } return strings.TrimSpace(match) }) } // Inject clickable link that is also the target (id + href on same element). func injectClickableFirstCell(line string, seen map[string]int) string { parts := splitTableRow(line) // first data cell is index 1 firstCellRaw := parts[1] // Clean any existing anchors first. firstCellRaw = cleanExistingAnchors(firstCellRaw) firstTrimmed := strings.TrimSpace(firstCellRaw) id := makeID(firstTrimmed) if id == "" { return strings.Join(parts, "|") } id = dedupeID(id, seen) // wrap the visible cell content in a link that is also the target // keep the cell inner HTML/text (firstCellRaw) as-is inside the <a> parts[1] = fmt.Sprintf(" <a id=\"%s\" href=\"#%s\" title=\"#%s\">%s</a> ", id, id, id, strings.TrimSpace(firstCellRaw)) return strings.Join(parts, "|") } func processFile(path string) error { // read file f, err := os.Open(path) if err != nil { return err } var lines []string sc := bufio.NewScanner(f) for sc.Scan() { lines = append(lines, sc.Text()) } if err := sc.Err(); err != nil { _ = f.Close() return err } _ = f.Close() inFence := false seen := make(map[string]int) out := make([]string, len(lines)) for i, line := range lines { trim := strings.TrimSpace(line) // toggle code fence (``` or ~~~) if strings.HasPrefix(trim, "```") || strings.HasPrefix(trim, "~~~") { inFence = !inFence out[i] = line continue } if inFence { out[i] = line continue } // not a table row -> copy as-is if !isTableRow(line) { out[i] = line continue } // separator row -> copy as-is if isSeparatorRow(line) { out[i] = line continue } // detect header row (the row immediately before a separator) and skip it isHeader := false for j := i + 1; j < len(lines); j++ { if strings.TrimSpace(lines[j]) == "" { continue } if isSeparatorRow(lines[j]) { isHeader = true } break } if isHeader { out[i] = line continue } // otherwise inject clickable link in first cell out[i] = injectClickableFirstCell(line, seen) } // overwrite file in place wf, err := os.Create(path) if err != nil { return err } bw := bufio.NewWriter(wf) for _, l := range out { fmt.Fprintln(bw, l) } if err := bw.Flush(); err != nil { _ = wf.Close() return err } return wf.Close() } func genAnchors() { root := "./docs/content/reference/" err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() && strings.HasSuffix(strings.ToLower(info.Name()), ".md") { if perr := processFile(path); perr != nil { fmt.Printf("⚠️ Error processing %s: %v\n", path, perr) } else { fmt.Printf("✅ Processed %s\n", path) } } return nil }) if err != nil { log.Fatalf("walk error: %v", err) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/internal/release/release.go
internal/release/release.go
package main import ( "fmt" "log" "os" "path" "strings" "text/template" ) func main() { if len(os.Args) < 2 { log.Fatal("GOOS should be provided as a CLI argument") } goos := strings.TrimSpace(os.Args[1]) if goos == "" { log.Fatal("GOOS should be provided as a CLI argument") } tmpl := template.Must( template.New(".goreleaser.yml.tmpl"). Delims("[[", "]]"). ParseFiles("./.goreleaser.yml.tmpl"), ) goarch := "" outputFileName := fmt.Sprintf(".goreleaser_%s.yml", goos) if strings.Contains(goos, "-") { split := strings.Split(goos, "-") goos = split[0] goarch = split[1] } outputPath := path.Join(os.TempDir(), outputFileName) output, err := os.Create(outputPath) if err != nil { log.Fatal(err) } err = tmpl.Execute(output, map[string]string{"GOOS": goos, "GOARCH": goarch}) if err != nil { log.Fatal(err) } fmt.Print(outputPath) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/internal/testsci/genmatrix.go
internal/testsci/genmatrix.go
package main import ( "encoding/json" "fmt" "os" "strings" "github.com/rs/zerolog/log" "golang.org/x/tools/go/packages" ) const groupCount = 12 type group struct { Group string `json:"group"` } func main() { cfg := &packages.Config{ Mode: packages.NeedName, Dir: ".", } pkgs, err := packages.Load(cfg, "./cmd/...", "./pkg/...") if err != nil { log.Fatal().Err(err).Msg("Loading packages") } var packageNames []string for _, pkg := range pkgs { if pkg.PkgPath != "" { packageNames = append(packageNames, pkg.PkgPath) } } total := len(packageNames) perGroup := (total + groupCount - 1) / groupCount fmt.Fprintf(os.Stderr, "Total packages: %d\n", total) fmt.Fprintf(os.Stderr, "Packages per group: %d\n", perGroup) var matrix []group for i := range groupCount { start := i * perGroup end := start + perGroup if start >= total { break } if end > total { end = total } g := strings.Join(packageNames[start:end], " ") matrix = append(matrix, group{Group: g}) } jsonBytes, err := json.Marshal(matrix) if err != nil { log.Fatal().Err(err).Msg("Failed to marshal matrix") } // Output for GitHub Actions fmt.Printf("matrix=%s\n", string(jsonBytes)) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/webui/embed.go
webui/embed.go
package webui import ( "embed" "io/fs" ) // Files starting with . and _ are excluded by default // //go:embed static var assets embed.FS // FS contains the web UI assets. var FS, _ = fs.Sub(assets, "static")
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
schollz/croc
https://github.com/schollz/croc/blob/913c22f8ab0b399f87ac3a681091771b39dc763b/main.go
main.go
package main //go:generate go run src/install/updateversion.go //go:generate git commit -am "bump $VERSION" //go:generate git tag -af v$VERSION -m "v$VERSION" import ( "fmt" "os" "os/signal" "syscall" "github.com/schollz/croc/v10/src/cli" "github.com/schollz/croc/v10/src/utils" ) func main() { // "github.com/pkg/profile" // go func() { // for { // f, err := os.Create("croc.pprof") // if err != nil { // panic(err) // } // runtime.GC() // get up-to-date statistics // if err := pprof.WriteHeapProfile(f); err != nil { // panic(err) // } // f.Close() // time.Sleep(3 * time.Second) // fmt.Println("wrote profile") // } // }() // Create a channel to receive OS signals sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) go func() { if err := cli.Run(); err != nil { fmt.Println(err) os.Exit(1) } // Exit the program gracefully utils.RemoveMarkedFiles() os.Exit(0) }() // Wait for a termination signal <-sigs utils.RemoveMarkedFiles() // Exit the program gracefully os.Exit(0) }
go
MIT
913c22f8ab0b399f87ac3a681091771b39dc763b
2026-01-07T08:36:10.668174Z
false
schollz/croc
https://github.com/schollz/croc/blob/913c22f8ab0b399f87ac3a681091771b39dc763b/src/tcp/tcp.go
src/tcp/tcp.go
package tcp import ( "bytes" "fmt" "net" "strings" "sync" "time" log "github.com/schollz/logger" "github.com/schollz/pake/v3" "github.com/schollz/croc/v10/src/comm" "github.com/schollz/croc/v10/src/crypt" "github.com/schollz/croc/v10/src/models" ) type server struct { host string port string debugLevel string banner string password string rooms roomMap roomCleanupInterval time.Duration roomTTL time.Duration stopRoomCleanup chan struct{} } type roomInfo struct { first *comm.Comm second *comm.Comm opened time.Time full bool } type roomMap struct { rooms map[string]roomInfo sync.Mutex } const pingRoom = "pinglkasjdlfjsaldjf" // newDefaultServer initializes a new server, with some default configuration options func newDefaultServer() *server { s := new(server) s.roomCleanupInterval = DEFAULT_ROOM_CLEANUP_INTERVAL s.roomTTL = DEFAULT_ROOM_TTL s.debugLevel = DEFAULT_LOG_LEVEL s.stopRoomCleanup = make(chan struct{}) return s } // RunWithOptionsAsync asynchronously starts a TCP listener. func RunWithOptionsAsync(host, port, password string, opts ...serverOptsFunc) error { s := newDefaultServer() s.host = host s.port = port s.password = password for _, opt := range opts { err := opt(s) if err != nil { return fmt.Errorf("could not apply optional configurations: %w", err) } } return s.start() } // Run starts a tcp listener, run async func Run(debugLevel, host, port, password string, banner ...string) (err error) { return RunWithOptionsAsync(host, port, password, WithBanner(banner...), WithLogLevel(debugLevel)) } func (s *server) start() (err error) { log.SetLevel(s.debugLevel) // Mask our password in logs maskedPassword := "" if len(s.password) > 2 { maskedPassword = fmt.Sprintf("%c***%c", s.password[0], s.password[len(s.password)-1]) } else { maskedPassword = s.password } log.Debugf("starting with password '%s'", maskedPassword) s.rooms.Lock() s.rooms.rooms = make(map[string]roomInfo) s.rooms.Unlock() go s.deleteOldRooms() defer s.stopRoomDeletion() err = s.run() if err != nil { log.Error(err) } return } func (s *server) run() (err error) { network := "tcp" addr := net.JoinHostPort(s.host, s.port) if s.host != "" { ip := net.ParseIP(s.host) if ip == nil { var tcpIP *net.IPAddr tcpIP, err = net.ResolveIPAddr("ip", s.host) if err != nil { return err } ip = tcpIP.IP } addr = net.JoinHostPort(ip.String(), s.port) if ip.To4() != nil { network = "tcp4" } else { network = "tcp6" } } addr = strings.Replace(addr, "127.0.0.1", "0.0.0.0", 1) log.Infof("starting TCP server on %s", addr) server, err := net.Listen(network, addr) if err != nil { return fmt.Errorf("error listening on %s: %w", addr, err) } defer server.Close() // spawn a new goroutine whenever a client connects for { connection, err := server.Accept() if err != nil { return fmt.Errorf("problem accepting connection: %w", err) } log.Debugf("client %s connected", connection.RemoteAddr().String()) go func(connection net.Conn) { c := comm.New(connection) room, errCommunication := s.clientCommunication(c) log.Debugf("room: %+v", room) log.Debugf("err: %+v", errCommunication) if errCommunication != nil { log.Debugf("relay-%s: %s", connection.RemoteAddr().String(), errCommunication.Error()) connection.Close() return } if room == pingRoom { log.Debugf("got ping") connection.Close() return } for { // check connection log.Debugf("checking connection of room %s for %+v", room, c) deleteIt := false s.rooms.Lock() roomData, ok := s.rooms.rooms[room] if !ok { log.Debug("room is gone") s.rooms.Unlock() return } log.Debugf("room: %+v", roomData) if roomData.first != nil && roomData.second != nil { log.Debug("rooms ready") s.rooms.Unlock() break } if s.rooms.rooms[room].first != nil { errSend := s.rooms.rooms[room].first.Send([]byte{1}) if errSend != nil { log.Debug(errSend) deleteIt = true } } s.rooms.Unlock() if deleteIt { s.deleteRoom(room) break } time.Sleep(1 * time.Second) } }(connection) } } // deleteOldRooms checks for rooms at a regular interval and removes those that // have exceeded their allocated TTL. func (s *server) deleteOldRooms() { ticker := time.NewTicker(s.roomCleanupInterval) for { select { case <-ticker.C: var roomsToDelete []string s.rooms.Lock() for room := range s.rooms.rooms { if time.Since(s.rooms.rooms[room].opened) > s.roomTTL { roomsToDelete = append(roomsToDelete, room) } } s.rooms.Unlock() for _, room := range roomsToDelete { s.deleteRoom(room) log.Debugf("room cleaned up: %s", room) } case <-s.stopRoomCleanup: ticker.Stop() log.Debug("room cleanup stopped") return } } } func (s *server) stopRoomDeletion() { log.Debug("stop room cleanup fired") s.stopRoomCleanup <- struct{}{} } var weakKey = []byte{1, 2, 3} func (s *server) clientCommunication(c *comm.Comm) (room string, err error) { // establish secure password with PAKE for communication with relay B, err := pake.InitCurve(weakKey, 1, "siec") if err != nil { return } Abytes, err := c.Receive() if err != nil { return } log.Debugf("Abytes: %s", Abytes) if bytes.Equal(Abytes, []byte("ping")) { room = pingRoom log.Debug("sending back pong") c.Send([]byte("pong")) return } err = B.Update(Abytes) if err != nil { return } err = c.Send(B.Bytes()) if err != nil { return } strongKey, err := B.SessionKey() if err != nil { return } log.Debugf("strongkey: %x", strongKey) // receive salt salt, err := c.Receive() if err != nil { return } strongKeyForEncryption, _, err := crypt.New(strongKey, salt) if err != nil { return } log.Debugf("waiting for password") passwordBytesEnc, err := c.Receive() if err != nil { return } passwordBytes, err := crypt.Decrypt(passwordBytesEnc, strongKeyForEncryption) if err != nil { return } if strings.TrimSpace(string(passwordBytes)) != s.password { err = fmt.Errorf("bad password") enc, _ := crypt.Encrypt([]byte(err.Error()), strongKeyForEncryption) if err = c.Send(enc); err != nil { return "", fmt.Errorf("send error: %w", err) } return } // send ok to tell client they are connected banner := s.banner if len(banner) == 0 { banner = "ok" } log.Debugf("sending '%s'", banner) bSend, err := crypt.Encrypt([]byte(banner+"|||"+c.Connection().RemoteAddr().String()), strongKeyForEncryption) if err != nil { return } err = c.Send(bSend) if err != nil { return } // wait for client to tell me which room they want log.Debug("waiting for answer") enc, err := c.Receive() if err != nil { return } roomBytes, err := crypt.Decrypt(enc, strongKeyForEncryption) if err != nil { return } room = string(roomBytes) s.rooms.Lock() // create the room if it is new if _, ok := s.rooms.rooms[room]; !ok { s.rooms.rooms[room] = roomInfo{ first: c, opened: time.Now(), } s.rooms.Unlock() // tell the client that they got the room bSend, err = crypt.Encrypt([]byte("ok"), strongKeyForEncryption) if err != nil { return } err = c.Send(bSend) if err != nil { log.Error(err) s.deleteRoom(room) return } log.Debugf("room %s has 1", room) return } if s.rooms.rooms[room].full { s.rooms.Unlock() bSend, err = crypt.Encrypt([]byte("room full"), strongKeyForEncryption) if err != nil { return } err = c.Send(bSend) if err != nil { log.Error(err) return } return } log.Debugf("room %s has 2", room) s.rooms.rooms[room] = roomInfo{ first: s.rooms.rooms[room].first, second: c, opened: s.rooms.rooms[room].opened, full: true, } otherConnection := s.rooms.rooms[room].first s.rooms.Unlock() // second connection is the sender, time to staple connections var wg sync.WaitGroup wg.Add(1) // start piping go func(com1, com2 *comm.Comm, wg *sync.WaitGroup) { log.Debug("starting pipes") pipe(com1.Connection(), com2.Connection()) wg.Done() log.Debug("done piping") }(otherConnection, c, &wg) // tell the sender everything is ready bSend, err = crypt.Encrypt([]byte("ok"), strongKeyForEncryption) if err != nil { return } err = c.Send(bSend) if err != nil { s.deleteRoom(room) return } wg.Wait() // delete room s.deleteRoom(room) return } func (s *server) deleteRoom(room string) { s.rooms.Lock() defer s.rooms.Unlock() roomData, ok := s.rooms.rooms[room] if !ok { return } log.Debugf("deleting room: %s", room) if roomData.first != nil { roomData.first.Close() } if roomData.second != nil { roomData.second.Close() } delete(s.rooms.rooms, room) } // chanFromConn creates a channel from a Conn object, and sends everything it // // Read()s from the socket to the channel. func chanFromConn(conn net.Conn) chan []byte { c := make(chan []byte, 1) if err := conn.SetReadDeadline(time.Now().Add(3 * time.Hour)); err != nil { log.Warnf("can't set read deadline: %v", err) } go func() { b := make([]byte, models.TCP_BUFFER_SIZE) for { n, err := conn.Read(b) if n > 0 { res := make([]byte, n) // Copy the buffer so it doesn't get changed while read by the recipient. copy(res, b[:n]) c <- res } if err != nil { log.Debug(err) c <- nil break } } log.Debug("exiting") }() return c } // pipe creates a full-duplex pipe between the two sockets and // transfers data from one to the other. func pipe(conn1 net.Conn, conn2 net.Conn) { chan1 := chanFromConn(conn1) chan2 := chanFromConn(conn2) for { select { case b1 := <-chan1: if b1 == nil { return } if _, err := conn2.Write(b1); err != nil { log.Errorf("write error on channel 1: %v", err) } case b2 := <-chan2: if b2 == nil { return } if _, err := conn1.Write(b2); err != nil { log.Errorf("write error on channel 2: %v", err) } } } } func PingServer(address string) (err error) { log.Debugf("pinging %s", address) c, err := comm.NewConnection(address, 300*time.Millisecond) if err != nil { log.Debug(err) return } err = c.Send([]byte("ping")) if err != nil { log.Debug(err) return } b, err := c.Receive() if err != nil { log.Debug(err) return } if bytes.Equal(b, []byte("pong")) { return nil } return fmt.Errorf("no pong") } // ConnectToTCPServer will initiate a new connection // to the specified address, room with optional time limit func ConnectToTCPServer(address, password, room string, timelimit ...time.Duration) (c *comm.Comm, banner string, ipaddr string, err error) { if len(timelimit) > 0 { c, err = comm.NewConnection(address, timelimit[0]) } else { c, err = comm.NewConnection(address) } if err != nil { log.Debug(err) return } // get PAKE connection with server to establish strong key to transfer info A, err := pake.InitCurve(weakKey, 0, "siec") if err != nil { log.Debug(err) return } err = c.Send(A.Bytes()) if err != nil { log.Debug(err) return } Bbytes, err := c.Receive() if err != nil { log.Debug(err) return } err = A.Update(Bbytes) if err != nil { log.Debug(err) return } strongKey, err := A.SessionKey() if err != nil { log.Debug(err) return } log.Debugf("strong key: %x", strongKey) strongKeyForEncryption, salt, err := crypt.New(strongKey, nil) if err != nil { log.Debug(err) return } // send salt err = c.Send(salt) if err != nil { log.Debug(err) return } log.Debug("sending password") bSend, err := crypt.Encrypt([]byte(password), strongKeyForEncryption) if err != nil { log.Debug(err) return } err = c.Send(bSend) if err != nil { log.Debug(err) return } log.Debug("waiting for first ok") enc, err := c.Receive() if err != nil { log.Debug(err) return } data, err := crypt.Decrypt(enc, strongKeyForEncryption) if err != nil { log.Debug(err) return } if !strings.Contains(string(data), "|||") { err = fmt.Errorf("bad response: %s", string(data)) log.Debug(err) return } banner = strings.Split(string(data), "|||")[0] ipaddr = strings.Split(string(data), "|||")[1] log.Debugf("sending room; %s", room) bSend, err = crypt.Encrypt([]byte(room), strongKeyForEncryption) if err != nil { log.Debug(err) return } err = c.Send(bSend) if err != nil { log.Debug(err) return } log.Debug("waiting for room confirmation") enc, err = c.Receive() if err != nil { log.Debug(err) return } data, err = crypt.Decrypt(enc, strongKeyForEncryption) if err != nil { log.Debug(err) return } if !bytes.Equal(data, []byte("ok")) { err = fmt.Errorf("got bad response: %s", data) log.Debug(err) return } log.Debug("all set") return }
go
MIT
913c22f8ab0b399f87ac3a681091771b39dc763b
2026-01-07T08:36:10.668174Z
false
schollz/croc
https://github.com/schollz/croc/blob/913c22f8ab0b399f87ac3a681091771b39dc763b/src/tcp/defaults.go
src/tcp/defaults.go
package tcp import "time" const ( DEFAULT_LOG_LEVEL = "debug" DEFAULT_ROOM_CLEANUP_INTERVAL = 10 * time.Minute DEFAULT_ROOM_TTL = 3 * time.Hour )
go
MIT
913c22f8ab0b399f87ac3a681091771b39dc763b
2026-01-07T08:36:10.668174Z
false
schollz/croc
https://github.com/schollz/croc/blob/913c22f8ab0b399f87ac3a681091771b39dc763b/src/tcp/options.go
src/tcp/options.go
package tcp import ( "fmt" "time" ) // TODO: maybe export from logger library? var availableLogLevels = []string{"info", "error", "warn", "debug", "trace"} type serverOptsFunc func(s *server) error func WithBanner(banner ...string) serverOptsFunc { return func(s *server) error { if len(banner) > 0 { s.banner = banner[0] } return nil } } func WithLogLevel(level string) serverOptsFunc { return func(s *server) error { if !containsSlice(availableLogLevels, level) { return fmt.Errorf("invalid log level specified: %s", level) } s.debugLevel = level return nil } } func WithRoomCleanupInterval(interval time.Duration) serverOptsFunc { return func(s *server) error { s.roomCleanupInterval = interval return nil } } func WithRoomTTL(ttl time.Duration) serverOptsFunc { return func(s *server) error { s.roomTTL = ttl return nil } } func containsSlice(s []string, e string) bool { for _, ss := range s { if e == ss { return true } } return false }
go
MIT
913c22f8ab0b399f87ac3a681091771b39dc763b
2026-01-07T08:36:10.668174Z
false
schollz/croc
https://github.com/schollz/croc/blob/913c22f8ab0b399f87ac3a681091771b39dc763b/src/tcp/tcp_test.go
src/tcp/tcp_test.go
package tcp import ( "bytes" "fmt" "testing" "time" log "github.com/schollz/logger" "github.com/stretchr/testify/assert" ) func BenchmarkConnection(b *testing.B) { log.SetLevel("trace") go Run("debug", "127.0.0.1", "8283", "pass123", "8284") time.Sleep(100 * time.Millisecond) b.ResetTimer() for i := 0; i < b.N; i++ { c, _, _, _ := ConnectToTCPServer("127.0.0.1:8283", "pass123", fmt.Sprintf("testroom%d", i), 1*time.Minute) c.Close() } } func TestTCP(t *testing.T) { log.SetLevel("error") timeToRoomDeletion := 100 * time.Millisecond go RunWithOptionsAsync("127.0.0.1", "8381", "pass123", WithBanner("8382"), WithLogLevel("debug"), WithRoomTTL(timeToRoomDeletion)) time.Sleep(timeToRoomDeletion) err := PingServer("127.0.0.1:8381") assert.Nil(t, err) err = PingServer("127.0.0.1:8333") assert.NotNil(t, err) time.Sleep(timeToRoomDeletion) c1, banner, _, err := ConnectToTCPServer("127.0.0.1:8381", "pass123", "testRoom", 1*time.Minute) assert.Equal(t, banner, "8382") assert.Nil(t, err) c2, _, _, err := ConnectToTCPServer("127.0.0.1:8381", "pass123", "testRoom") assert.Nil(t, err) _, _, _, err = ConnectToTCPServer("127.0.0.1:8381", "pass123", "testRoom") assert.NotNil(t, err) _, _, _, err = ConnectToTCPServer("127.0.0.1:8381", "pass123", "testRoom", 1*time.Nanosecond) assert.NotNil(t, err) // try sending data assert.Nil(t, c1.Send([]byte("hello, c2"))) var data []byte for { data, err = c2.Receive() if bytes.Equal(data, []byte{1}) { continue } break } assert.Nil(t, err) assert.Equal(t, []byte("hello, c2"), data) assert.Nil(t, c2.Send([]byte("hello, c1"))) for { data, err = c1.Receive() if bytes.Equal(data, []byte{1}) { continue } break } assert.Nil(t, err) assert.Equal(t, []byte("hello, c1"), data) c1.Close() time.Sleep(300 * time.Millisecond) }
go
MIT
913c22f8ab0b399f87ac3a681091771b39dc763b
2026-01-07T08:36:10.668174Z
false
schollz/croc
https://github.com/schollz/croc/blob/913c22f8ab0b399f87ac3a681091771b39dc763b/src/comm/comm.go
src/comm/comm.go
package comm import ( "bytes" "encoding/binary" "fmt" "io" "net" "net/url" "strings" "time" "github.com/magisterquis/connectproxy" "github.com/schollz/croc/v10/src/utils" log "github.com/schollz/logger" "golang.org/x/net/proxy" ) var Socks5Proxy = "" var HttpProxy = "" var MAGIC_BYTES = []byte("croc") // Comm is some basic TCP communication type Comm struct { connection net.Conn } // NewConnection gets a new comm to a tcp address func NewConnection(address string, timelimit ...time.Duration) (c *Comm, err error) { tlimit := 30 * time.Second if len(timelimit) > 0 { tlimit = timelimit[0] } var connection net.Conn if Socks5Proxy != "" && !utils.IsLocalIP(address) { var dialer proxy.Dialer // prepend schema if no schema is given if !strings.Contains(Socks5Proxy, `://`) { Socks5Proxy = `socks5://` + Socks5Proxy } socks5ProxyURL, urlParseError := url.Parse(Socks5Proxy) if urlParseError != nil { err = fmt.Errorf("unable to parse socks proxy url: %s", urlParseError) log.Debug(err) return } dialer, err = proxy.FromURL(socks5ProxyURL, proxy.Direct) if err != nil { err = fmt.Errorf("proxy failed: %w", err) log.Debug(err) return } log.Debug("dialing with dialer.Dial") connection, err = dialer.Dial("tcp", address) } else if HttpProxy != "" && !utils.IsLocalIP(address) { var dialer proxy.Dialer // prepend schema if no schema is given if !strings.Contains(HttpProxy, `://`) { HttpProxy = `http://` + HttpProxy } HttpProxyURL, urlParseError := url.Parse(HttpProxy) if urlParseError != nil { err = fmt.Errorf("unable to parse http proxy url: %s", urlParseError) log.Debug(err) return } dialer, err = connectproxy.New(HttpProxyURL, proxy.Direct) if err != nil { err = fmt.Errorf("proxy failed: %w", err) log.Debug(err) return } log.Debug("dialing with dialer.Dial") connection, err = dialer.Dial("tcp", address) } else { log.Debugf("dialing to %s with timelimit %s", address, tlimit) connection, err = net.DialTimeout("tcp", address, tlimit) } if err != nil { err = fmt.Errorf("comm.NewConnection failed: %w", err) log.Debug(err) return } c = New(connection) log.Debugf("connected to '%s'", address) return } // New returns a new comm func New(c net.Conn) *Comm { if err := c.SetReadDeadline(time.Now().Add(3 * time.Hour)); err != nil { log.Warnf("error setting read deadline: %v", err) } if err := c.SetDeadline(time.Now().Add(3 * time.Hour)); err != nil { log.Warnf("error setting overall deadline: %v", err) } if err := c.SetWriteDeadline(time.Now().Add(3 * time.Hour)); err != nil { log.Errorf("error setting write deadline: %v", err) } comm := new(Comm) comm.connection = c return comm } // Connection returns the net.Conn connection func (c *Comm) Connection() net.Conn { return c.connection } // Close closes the connection func (c *Comm) Close() { if err := c.connection.Close(); err != nil { log.Warnf("error closing connection: %v", err) } } func (c *Comm) Write(b []byte) (n int, err error) { header := new(bytes.Buffer) err = binary.Write(header, binary.LittleEndian, uint32(len(b))) if err != nil { fmt.Println("binary.Write failed:", err) } tmpCopy := append(header.Bytes(), b...) tmpCopy = append(MAGIC_BYTES, tmpCopy...) n, err = c.connection.Write(tmpCopy) if err != nil { err = fmt.Errorf("connection.Write failed: %w", err) return } if n != len(tmpCopy) { err = fmt.Errorf("wanted to write %d but wrote %d", len(b), n) return } return } func (c *Comm) Read() (buf []byte, numBytes int, bs []byte, err error) { // long read deadline in case waiting for file if err = c.connection.SetReadDeadline(time.Now().Add(3 * time.Hour)); err != nil { log.Warnf("error setting read deadline: %v", err) } // must clear the timeout setting if err := c.connection.SetDeadline(time.Time{}); err != nil { log.Warnf("failed to clear deadline: %v", err) } // read until we get 4 bytes for the magic header := make([]byte, 4) _, err = io.ReadFull(c.connection, header) if err != nil { log.Debugf("initial read error: %v", err) return } if !bytes.Equal(header, MAGIC_BYTES) { err = fmt.Errorf("initial bytes are not magic: %x", header) return } // read until we get 4 bytes for the header header = make([]byte, 4) _, err = io.ReadFull(c.connection, header) if err != nil { log.Debugf("initial read error: %v", err) return } var numBytesUint32 uint32 rbuf := bytes.NewReader(header) err = binary.Read(rbuf, binary.LittleEndian, &numBytesUint32) if err != nil { err = fmt.Errorf("binary.Read failed: %w", err) log.Debug(err.Error()) return } numBytes = int(numBytesUint32) // shorten the reading deadline in case getting weird data if err = c.connection.SetReadDeadline(time.Now().Add(10 * time.Second)); err != nil { log.Warnf("error setting read deadline: %v", err) } buf = make([]byte, numBytes) _, err = io.ReadFull(c.connection, buf) if err != nil { log.Debugf("consecutive read error: %v", err) return } return } // Send a message func (c *Comm) Send(message []byte) (err error) { _, err = c.Write(message) return } // Receive a message func (c *Comm) Receive() (b []byte, err error) { b, _, _, err = c.Read() return }
go
MIT
913c22f8ab0b399f87ac3a681091771b39dc763b
2026-01-07T08:36:10.668174Z
false
schollz/croc
https://github.com/schollz/croc/blob/913c22f8ab0b399f87ac3a681091771b39dc763b/src/comm/comm_test.go
src/comm/comm_test.go
package comm import ( "crypto/rand" "net" "testing" "time" log "github.com/schollz/logger" "github.com/stretchr/testify/assert" ) func TestComm(t *testing.T) { token := make([]byte, 3000) if _, err := rand.Read(token); err != nil { t.Error(err) } // Use dynamic port allocation to avoid conflicts listener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } port := listener.Addr().(*net.TCPAddr).Port portStr := listener.Addr().String() listener.Close() // Close the listener so we can reopen it in the goroutine go func() { log.Debug("starting TCP server on " + portStr) server, err := net.Listen("tcp", portStr) if err != nil { log.Error(err) return } defer func() { if err := server.Close(); err != nil { log.Error(err) } }() // spawn a new goroutine whenever a client connects for { connection, err := server.Accept() if err != nil { log.Error(err) } log.Debugf("client %s connected", connection.RemoteAddr().String()) go func(_ int, connection net.Conn) { c := New(connection) err = c.Send([]byte("hello, world")) assert.Nil(t, err) data, err := c.Receive() assert.Nil(t, err) assert.Equal(t, []byte("hello, computer"), data) data, err = c.Receive() assert.Nil(t, err) assert.Equal(t, []byte{'\x00'}, data) data, err = c.Receive() assert.Nil(t, err) assert.Equal(t, token, data) }(port, connection) } }() time.Sleep(300 * time.Millisecond) a, err := NewConnection(portStr, 10*time.Minute) assert.Nil(t, err) data, err := a.Receive() assert.Equal(t, []byte("hello, world"), data) assert.Nil(t, err) assert.Nil(t, a.Send([]byte("hello, computer"))) assert.Nil(t, a.Send([]byte{'\x00'})) assert.Nil(t, a.Send(token)) _ = a.Connection() a.Close() assert.NotNil(t, a.Send(token)) _, err = a.Write(token) assert.NotNil(t, err) }
go
MIT
913c22f8ab0b399f87ac3a681091771b39dc763b
2026-01-07T08:36:10.668174Z
false
schollz/croc
https://github.com/schollz/croc/blob/913c22f8ab0b399f87ac3a681091771b39dc763b/src/models/constants.go
src/models/constants.go
package models import ( "context" "fmt" "net" "os" "path" "time" "github.com/schollz/croc/v10/src/utils" log "github.com/schollz/logger" ) // TCP_BUFFER_SIZE is the maximum packet size const TCP_BUFFER_SIZE = 1024 * 64 // DEFAULT_RELAY is the default relay used (can be set using --relay) var ( DEFAULT_RELAY = "croc.schollz.com" DEFAULT_RELAY6 = "croc6.schollz.com" DEFAULT_PORT = "9009" DEFAULT_PASSPHRASE = "pass123" INTERNAL_DNS = false ) // publicDNS are servers to be queried if a local lookup fails var publicDNS = []string{ "1.0.0.1", // Cloudflare "1.1.1.1", // Cloudflare "[2606:4700:4700::1111]", // Cloudflare "[2606:4700:4700::1001]", // Cloudflare "8.8.4.4", // Google "8.8.8.8", // Google "[2001:4860:4860::8844]", // Google "[2001:4860:4860::8888]", // Google "9.9.9.9", // Quad9 "149.112.112.112", // Quad9 "[2620:fe::fe]", // Quad9 "[2620:fe::fe:9]", // Quad9 "8.26.56.26", // Comodo "8.20.247.20", // Comodo "208.67.220.220", // Cisco OpenDNS "208.67.222.222", // Cisco OpenDNS "[2620:119:35::35]", // Cisco OpenDNS "[2620:119:53::53]", // Cisco OpenDNS } func getConfigFile(requireValidPath bool) (fname string, err error) { configFile, err := utils.GetConfigDir(requireValidPath) if err != nil { return } fname = path.Join(configFile, "internal-dns") return } func init() { log.SetLevel("info") log.SetOutput(os.Stderr) doRemember := false for _, flag := range os.Args { if flag == "--internal-dns" { INTERNAL_DNS = true break } if flag == "--remember" { doRemember = true } } if doRemember { // save in config file fname, err := getConfigFile(true) if err == nil { f, _ := os.Create(fname) f.Close() } } if !INTERNAL_DNS { fname, err := getConfigFile(false) if err == nil { INTERNAL_DNS = utils.Exists(fname) } } log.Trace("Using internal DNS: ", INTERNAL_DNS) var err error var addr string addr, err = lookup(DEFAULT_RELAY) if err == nil { DEFAULT_RELAY = net.JoinHostPort(addr, DEFAULT_PORT) } else { DEFAULT_RELAY = "" } log.Tracef("Default ipv4 relay: %s", addr) addr, err = lookup(DEFAULT_RELAY6) if err == nil { DEFAULT_RELAY6 = net.JoinHostPort(addr, DEFAULT_PORT) } else { DEFAULT_RELAY6 = "" } log.Tracef("Default ipv6 relay: %s", addr) } // Resolve a hostname to an IP address using DNS. func lookup(address string) (ipaddress string, err error) { if !INTERNAL_DNS { log.Tracef("Using local DNS to resolve %s", address) return localLookupIP(address) } type Result struct { s string err error } result := make(chan Result, len(publicDNS)) for _, dns := range publicDNS { go func(dns string) { var r Result r.s, r.err = remoteLookupIP(address, dns) log.Tracef("Resolved %s to %s using %s", address, r.s, dns) result <- r }(dns) } for i := 0; i < len(publicDNS); i++ { ipaddress = (<-result).s log.Tracef("Resolved %s to %s", address, ipaddress) if ipaddress != "" { return } } err = fmt.Errorf("failed to resolve %s: all DNS servers exhausted", address) return } // localLookupIP returns a host's IP address using the local DNS configuration. func localLookupIP(address string) (ipaddress string, err error) { // Create a context with a 500 millisecond timeout ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) defer cancel() r := &net.Resolver{} // Use the context with timeout in the LookupHost function ip, err := r.LookupHost(ctx, address) if err != nil { return } ipaddress = ip[0] return } // remoteLookupIP returns a host's IP address based on a remote DNS server. func remoteLookupIP(address, dns string) (ipaddress string, err error) { ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) defer cancel() r := &net.Resolver{ PreferGo: true, Dial: func(ctx context.Context, network, _ string) (net.Conn, error) { d := new(net.Dialer) return d.DialContext(ctx, network, dns+":53") }, } ip, err := r.LookupHost(ctx, address) if err != nil { return } ipaddress = ip[0] return }
go
MIT
913c22f8ab0b399f87ac3a681091771b39dc763b
2026-01-07T08:36:10.668174Z
false
schollz/croc
https://github.com/schollz/croc/blob/913c22f8ab0b399f87ac3a681091771b39dc763b/src/models/models_test.go
src/models/models_test.go
package models import ( "net" "strings" "testing" "time" ) func TestConstants(t *testing.T) { if TCP_BUFFER_SIZE != 1024*64 { t.Errorf("TCP_BUFFER_SIZE = %d, want %d", TCP_BUFFER_SIZE, 1024*64) } if DEFAULT_PORT != "9009" { t.Errorf("DEFAULT_PORT = %s, want %s", DEFAULT_PORT, "9009") } if DEFAULT_PASSPHRASE != "pass123" { t.Errorf("DEFAULT_PASSPHRASE = %s, want %s", DEFAULT_PASSPHRASE, "pass123") } } func TestPublicDNSServers(t *testing.T) { if len(publicDNS) == 0 { t.Error("publicDNS list should not be empty") } // Check that we have both IPv4 and IPv6 servers hasIPv4 := false hasIPv6 := false for _, dns := range publicDNS { if strings.Contains(dns, "[") { hasIPv6 = true } else { hasIPv4 = true } } if !hasIPv4 { t.Error("publicDNS should contain IPv4 servers") } if !hasIPv6 { t.Error("publicDNS should contain IPv6 servers") } // Verify known DNS servers are present expectedServers := []string{ "1.1.1.1", // Cloudflare "8.8.8.8", // Google "9.9.9.9", // Quad9 "208.67.220.220", // OpenDNS } for _, expected := range expectedServers { found := false for _, dns := range publicDNS { if dns == expected { found = true break } } if !found { t.Errorf("Expected DNS server %s not found in publicDNS", expected) } } } func TestLocalLookupIP(t *testing.T) { tests := []struct { name string address string wantErr bool }{ { name: "localhost", address: "localhost", wantErr: false, }, { name: "invalid hostname", address: "this-hostname-should-not-exist-12345", wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ip, err := localLookupIP(tt.address) if (err != nil) != tt.wantErr { t.Errorf("localLookupIP() error = %v, wantErr %v", err, tt.wantErr) return } if !tt.wantErr && ip == "" { t.Error("localLookupIP() returned empty IP for valid hostname") } if !tt.wantErr { // Verify it's a valid IP address if net.ParseIP(ip) == nil { t.Errorf("localLookupIP() returned invalid IP: %s", ip) } } }) } } func TestRemoteLookupIPTimeout(t *testing.T) { // Test with an invalid DNS server that should timeout start := time.Now() _, err := remoteLookupIP("example.com", "192.0.2.1") duration := time.Since(start) // Should timeout within reasonable time (we set 500ms timeout) if duration > time.Second { t.Errorf("remoteLookupIP took too long: %v", duration) } if err == nil { t.Error("remoteLookupIP should have failed with invalid DNS server") } } func TestLookupFunction(t *testing.T) { // Test the main lookup function tests := []struct { name string address string wantErr bool }{ { name: "localhost", address: "localhost", wantErr: false, }, { name: "invalid hostname", address: "this-hostname-should-definitely-not-exist-98765", wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ip, err := lookup(tt.address) if (err != nil) != tt.wantErr { t.Errorf("lookup() error = %v, wantErr %v", err, tt.wantErr) return } if !tt.wantErr && ip == "" { t.Error("lookup() returned empty IP for valid hostname") } if !tt.wantErr { // Verify it's a valid IP address if net.ParseIP(ip) == nil { t.Errorf("lookup() returned invalid IP: %s", ip) } } }) } } func TestGetConfigFile(t *testing.T) { fname, err := getConfigFile(false) if err != nil { t.Skip("Could not get config directory") } if !strings.HasSuffix(fname, "internal-dns") { t.Errorf("Expected config file to end with 'internal-dns', got %s", fname) } }
go
MIT
913c22f8ab0b399f87ac3a681091771b39dc763b
2026-01-07T08:36:10.668174Z
false
schollz/croc
https://github.com/schollz/croc/blob/913c22f8ab0b399f87ac3a681091771b39dc763b/src/utils/utils.go
src/utils/utils.go
package utils import ( "archive/zip" "bufio" "bytes" "compress/flate" "crypto/md5" "crypto/rand" "crypto/sha256" "encoding/hex" "fmt" "io" "math" "math/big" "net" "net/http" "os" "path" "path/filepath" "strings" "time" "unicode" "github.com/cespare/xxhash/v2" "github.com/kalafut/imohash" "github.com/minio/highwayhash" "github.com/schollz/croc/v10/src/mnemonicode" log "github.com/schollz/logger" "github.com/schollz/progressbar/v3" ) const NbPinNumbers = 4 const NbBytesWords = 4 // Get or create home directory func GetConfigDir(requireValidPath bool) (homedir string, err error) { if envHomedir, isSet := os.LookupEnv("CROC_CONFIG_DIR"); isSet { homedir = envHomedir } else if xdgConfigHome, isSet := os.LookupEnv("XDG_CONFIG_HOME"); isSet { homedir = path.Join(xdgConfigHome, "croc") } else { homedir, err = os.UserHomeDir() if err != nil { if !requireValidPath { err = nil homedir = "" } return } homedir = path.Join(homedir, ".config", "croc") } if requireValidPath { if _, err = os.Stat(homedir); os.IsNotExist(err) { err = os.MkdirAll(homedir, 0o700) } } return } // Exists reports whether the named file or directory exists. func Exists(name string) bool { if _, err := os.Stat(name); err != nil { if os.IsNotExist(err) { return false } } return true } // GetInput returns the input with a given prompt func GetInput(prompt string) string { reader := bufio.NewReader(os.Stdin) fmt.Fprintf(os.Stderr, "%s", prompt) text, _ := reader.ReadString('\n') return strings.TrimSpace(text) } // HashFile returns the hash of a file or, in case of a symlink, the // SHA256 hash of its target. Takes an argument to specify the algorithm to use. func HashFile(fname string, algorithm string, showProgress ...bool) (hash256 []byte, err error) { doShowProgress := false if len(showProgress) > 0 { doShowProgress = showProgress[0] } var fstats os.FileInfo fstats, err = os.Lstat(fname) if err != nil { return nil, err } if fstats.Mode()&os.ModeSymlink != 0 { var target string target, err = os.Readlink(fname) if err != nil { return nil, err } return []byte(SHA256(target)), nil } switch algorithm { case "imohash": return IMOHashFile(fname) case "md5": return MD5HashFile(fname, doShowProgress) case "xxhash": return XXHashFile(fname, doShowProgress) case "highway": return HighwayHashFile(fname, doShowProgress) } err = fmt.Errorf("unspecified algorithm") return } // HighwayHashFile returns highwayhash of a file func HighwayHashFile(fname string, doShowProgress bool) (hashHighway []byte, err error) { f, err := os.Open(fname) if err != nil { return } defer f.Close() key, err := hex.DecodeString("1553c5383fb0b86578c3310da665b4f6e0521acf22eb58a99532ffed02a6b115") if err != nil { return } h, err := highwayhash.New(key) if err != nil { err = fmt.Errorf("could not create highwayhash: %s", err.Error()) return } if doShowProgress { stat, _ := f.Stat() fnameShort := path.Base(fname) if len(fnameShort) > 20 { fnameShort = fnameShort[:20] + "..." } bar := progressbar.NewOptions64(stat.Size(), progressbar.OptionSetWriter(os.Stderr), progressbar.OptionShowBytes(true), progressbar.OptionSetDescription(fmt.Sprintf("Hashing %s", fnameShort)), progressbar.OptionClearOnFinish(), progressbar.OptionFullWidth(), ) if _, err = io.Copy(io.MultiWriter(h, bar), f); err != nil { return } } else { if _, err = io.Copy(h, f); err != nil { return } } hashHighway = h.Sum(nil) return } // MD5HashFile returns MD5 hash func MD5HashFile(fname string, doShowProgress bool) (hash256 []byte, err error) { f, err := os.Open(fname) if err != nil { return } defer f.Close() h := md5.New() if doShowProgress { stat, _ := f.Stat() fnameShort := path.Base(fname) if len(fnameShort) > 20 { fnameShort = fnameShort[:20] + "..." } bar := progressbar.NewOptions64(stat.Size(), progressbar.OptionSetWriter(os.Stderr), progressbar.OptionShowBytes(true), progressbar.OptionSetDescription(fmt.Sprintf("Hashing %s", fnameShort)), progressbar.OptionClearOnFinish(), progressbar.OptionFullWidth(), ) if _, err = io.Copy(io.MultiWriter(h, bar), f); err != nil { return } } else { if _, err = io.Copy(h, f); err != nil { return } } hash256 = h.Sum(nil) return } var imofull = imohash.NewCustom(0, 0) var imopartial = imohash.NewCustom(16*16*8*1024, 128*1024) // IMOHashFile returns imohash func IMOHashFile(fname string) (hash []byte, err error) { b, err := imopartial.SumFile(fname) hash = b[:] return } // IMOHashFileFull returns imohash of full file func IMOHashFileFull(fname string) (hash []byte, err error) { b, err := imofull.SumFile(fname) hash = b[:] return } // XXHashFile returns the xxhash of a file func XXHashFile(fname string, doShowProgress bool) (hash256 []byte, err error) { f, err := os.Open(fname) if err != nil { return } defer f.Close() h := xxhash.New() if doShowProgress { stat, _ := f.Stat() fnameShort := path.Base(fname) if len(fnameShort) > 20 { fnameShort = fnameShort[:20] + "..." } bar := progressbar.NewOptions64(stat.Size(), progressbar.OptionSetWriter(os.Stderr), progressbar.OptionShowBytes(true), progressbar.OptionSetDescription(fmt.Sprintf("Hashing %s", fnameShort)), progressbar.OptionClearOnFinish(), progressbar.OptionFullWidth(), ) if _, err = io.Copy(io.MultiWriter(h, bar), f); err != nil { return } } else { if _, err = io.Copy(h, f); err != nil { return } } hash256 = h.Sum(nil) return } // SHA256 returns sha256 sum func SHA256(s string) string { sha := sha256.New() sha.Write([]byte(s)) return hex.EncodeToString(sha.Sum(nil)) } // PublicIP returns public ip address func PublicIP() (ip string, err error) { // ask ipv4.icanhazip.com for the public ip // by making http request // if the request fails, return nothing resp, err := http.Get("http://ipv4.icanhazip.com") if err != nil { return } defer resp.Body.Close() // read the body of the response // and return the ip address buf := new(bytes.Buffer) buf.ReadFrom(resp.Body) ip = strings.TrimSpace(buf.String()) return } // LocalIP returns local ip address func LocalIP() string { conn, err := net.Dial("udp", "8.8.8.8:80") if err != nil { log.Error(err) return "" } defer conn.Close() localAddr := conn.LocalAddr().(*net.UDPAddr) return localAddr.IP.String() } // GenerateRandomPin returns a randomly generated pin with set length func GenerateRandomPin() string { s := "" max := new(big.Int) max.SetInt64(9) for range NbPinNumbers { v, err := rand.Int(rand.Reader, max) if err != nil { panic(err) } s += fmt.Sprintf("%d", v) } return s } // GetRandomName returns mnemonicoded random name func GetRandomName() string { var result []string bs := make([]byte, NbBytesWords) rand.Read(bs) result = mnemonicode.EncodeWordList(result, bs) return GenerateRandomPin() + "-" + strings.Join(result, "-") } // ByteCountDecimal converts bytes to human readable byte string func ByteCountDecimal(b int64) string { const unit = 1024 if b < unit { return fmt.Sprintf("%d B", b) } div, exp := int64(unit), 0 for n := b / unit; n >= unit; n /= unit { div *= unit exp++ } return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "kMGTPE"[exp]) } // MissingChunks returns the positions of missing chunks. // If file doesn't exist, it returns an empty chunk list (all chunks). // If the file size is not the same as requested, it returns an empty chunk list (all chunks). func MissingChunks(fname string, fsize int64, chunkSize int) (chunkRanges []int64) { f, err := os.Open(fname) if err != nil { return } defer f.Close() fstat, err := os.Stat(fname) if err != nil || fstat.Size() != fsize { return } // Show progress bar for large files (> 10MB) var bar *progressbar.ProgressBar showProgress := fsize > 10*1024*1024 if showProgress { fnameShort := path.Base(fname) if len(fnameShort) > 20 { fnameShort = fnameShort[:20] + "..." } bar = progressbar.NewOptions64(fsize, progressbar.OptionSetWriter(os.Stderr), progressbar.OptionShowBytes(true), progressbar.OptionSetDescription(fmt.Sprintf("Checking %s", fnameShort)), progressbar.OptionClearOnFinish(), progressbar.OptionFullWidth(), progressbar.OptionThrottle(100*time.Millisecond), ) } emptyBuffer := make([]byte, chunkSize) chunkNum := 0 chunks := make([]int64, int64(math.Ceil(float64(fsize)/float64(chunkSize)))) var currentLocation int64 for { buffer := make([]byte, chunkSize) bytesread, err := f.Read(buffer) if err != nil { break } if bytes.Equal(buffer[:bytesread], emptyBuffer[:bytesread]) { chunks[chunkNum] = currentLocation chunkNum++ } currentLocation += int64(bytesread) if showProgress && bar != nil { bar.Add(bytesread) } } if showProgress && bar != nil { bar.Finish() } if chunkNum == 0 { chunkRanges = []int64{} } else { chunks = chunks[:chunkNum] chunkRanges = []int64{int64(chunkSize), chunks[0]} curCount := 0 for i, chunk := range chunks { if i == 0 { continue } curCount++ if chunk-chunks[i-1] > int64(chunkSize) { chunkRanges = append(chunkRanges, int64(curCount)) chunkRanges = append(chunkRanges, chunk) curCount = 0 } } chunkRanges = append(chunkRanges, int64(curCount+1)) } return } // ChunkRangesToChunks converts chunk ranges to list func ChunkRangesToChunks(chunkRanges []int64) (chunks []int64) { if len(chunkRanges) == 0 { return } chunkSize := chunkRanges[0] chunks = []int64{} for i := 1; i < len(chunkRanges); i += 2 { for j := int64(0); j < (chunkRanges[i+1]); j++ { chunks = append(chunks, chunkRanges[i]+j*chunkSize) } } return } // GetLocalIPs returns all local ips func GetLocalIPs() (ips []string, err error) { addrs, err := net.InterfaceAddrs() if err != nil { return } ips = []string{} for _, address := range addrs { // check the address type and if it is not a loopback the display it if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipnet.IP.To4() != nil { ips = append(ips, ipnet.IP.String()) } } } return } func RandomFileName() (fname string, err error) { f, err := os.CreateTemp(".", "croc-stdin-") if err != nil { return } fname = f.Name() _ = f.Close() return } func FindOpenPorts(host string, portNumStart, numPorts int) (openPorts []int) { openPorts = []int{} for port := portNumStart; port-portNumStart < 200; port++ { timeout := 100 * time.Millisecond conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, fmt.Sprint(port)), timeout) if conn != nil { conn.Close() } else if err != nil { openPorts = append(openPorts, port) } if len(openPorts) >= numPorts { return } } return } // local ip determination // https://stackoverflow.com/questions/41240761/check-if-ip-address-is-in-private-network-space var privateIPBlocks []*net.IPNet func init() { for _, cidr := range []string{ "127.0.0.0/8", // IPv4 loopback "10.0.0.0/8", // RFC1918 "172.16.0.0/12", // RFC1918 "192.168.0.0/16", // RFC1918 "169.254.0.0/16", // RFC3927 link-local "::1/128", // IPv6 loopback "fe80::/10", // IPv6 link-local "fc00::/7", // IPv6 unique local addr } { _, block, err := net.ParseCIDR(cidr) if err != nil { panic(fmt.Errorf("parse error on %q: %v", cidr, err)) } privateIPBlocks = append(privateIPBlocks, block) } } func IsLocalIP(ipaddress string) bool { if strings.Contains(ipaddress, "127.0.0.1") { return true } host, _, _ := net.SplitHostPort(ipaddress) ip := net.ParseIP(host) if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() { return true } for _, block := range privateIPBlocks { if block.Contains(ip) { return true } } return false } func ZipDirectory(destination string, source string) (err error) { if _, err = os.Stat(destination); err == nil { log.Errorf("%s file already exists!\n", destination) return fmt.Errorf("file already exists: %s", destination) } // Check if source directory exists if _, err := os.Stat(source); os.IsNotExist(err) { log.Errorf("Source directory does not exist: %s", source) return fmt.Errorf("source directory does not exist: %s", source) } fmt.Fprintf(os.Stderr, "Zipping %s to %s\n", source, destination) file, err := os.Create(destination) if err != nil { log.Error(err) return fmt.Errorf("failed to create zip file: %w", err) } defer file.Close() writer := zip.NewWriter(file) // no compression because croc does its compression on the fly writer.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) { return flate.NewWriter(out, flate.NoCompression) }) defer writer.Close() // Get base name for zip structure baseName := strings.TrimSuffix(filepath.Base(destination), ".zip") // First pass: add the root directory with its modification time rootInfo, err := os.Stat(source) if err == nil && rootInfo.IsDir() { header, err := zip.FileInfoHeader(rootInfo) if err != nil { log.Error(err) } else { header.Name = baseName + "/" // Trailing slash indicates directory header.Method = zip.Store header.Modified = rootInfo.ModTime() _, err = writer.CreateHeader(header) if err != nil { log.Error(err) } else { fmt.Fprintf(os.Stderr, "\r\033[2K") fmt.Fprintf(os.Stderr, "\rAdding %s", baseName+"/") } } } // Second pass: add all other directories and files err = filepath.Walk(source, func(path string, info os.FileInfo, err error) error { if err != nil { log.Error(err) return nil } // Skip root directory (we already added it) if path == source { return nil } // Calculate relative path from source directory relPath, err := filepath.Rel(source, path) if err != nil { log.Error(err) return nil } // Create zip path with base name structure zipPath := filepath.Join(baseName, relPath) zipPath = filepath.ToSlash(zipPath) if info.IsDir() { // Add directory entry to zip with original modification time header, err := zip.FileInfoHeader(info) if err != nil { log.Error(err) return nil } header.Name = zipPath + "/" // Trailing slash indicates directory header.Method = zip.Store // Preserve the original modification time header.Modified = info.ModTime() _, err = writer.CreateHeader(header) if err != nil { log.Error(err) return nil } fmt.Fprintf(os.Stderr, "\r\033[2K") fmt.Fprintf(os.Stderr, "\rAdding %s", zipPath+"/") return nil } if info.Mode().IsRegular() { f1, err := os.Open(path) if err != nil { log.Error(err) return nil } defer f1.Close() // Create file header with modified time header, err := zip.FileInfoHeader(info) if err != nil { log.Error(err) return nil } header.Name = zipPath header.Method = zip.Deflate w1, err := writer.CreateHeader(header) if err != nil { log.Error(err) return nil } if _, err := io.Copy(w1, f1); err != nil { log.Error(err) return nil } fmt.Fprintf(os.Stderr, "\r\033[2K") fmt.Fprintf(os.Stderr, "\rAdding %s", zipPath) } return nil }) if err != nil { log.Error(err) return fmt.Errorf("error during directory walk: %w", err) } fmt.Fprintf(os.Stderr, "\n") return nil } func UnzipDirectory(destination string, source string) error { archive, err := zip.OpenReader(source) if err != nil { log.Error(err) return fmt.Errorf("failed to open zip file: %w", err) } defer archive.Close() // Store modification times for all files and directories modTimes := make(map[string]time.Time) // First pass: extract all files and directories, store modification times for _, f := range archive.File { filePath := filepath.Join(destination, f.Name) fmt.Fprintf(os.Stderr, "\r\033[2K") fmt.Fprintf(os.Stderr, "\rUnzipping file %s", filePath) // Issue #593 conceal path traversal vulnerability // make sure the filepath does not have ".." filePath = filepath.Clean(filePath) if strings.Contains(filePath, "..") { log.Errorf("Invalid file path %s\n", filePath) continue } // Store modification time for this entry (BOTH files and directories) modifiedTime := f.Modified if modifiedTime.IsZero() { modifiedTime = f.FileHeader.Modified } if !modifiedTime.IsZero() { modTimes[filePath] = modifiedTime } if f.FileInfo().IsDir() { if err := os.MkdirAll(filePath, os.ModePerm); err != nil { log.Error(err) } continue } if err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil { log.Error(err) continue } // check if file exists if _, err := os.Stat(filePath); err == nil { prompt := fmt.Sprintf("\nOverwrite '%s'? (y/N) ", filePath) choice := strings.ToLower(GetInput(prompt)) if choice != "y" && choice != "yes" { fmt.Fprintf(os.Stderr, "Skipping '%s'\n", filePath) continue } } dstFile, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) if err != nil { log.Error(err) continue } fileInArchive, err := f.Open() if err != nil { log.Error(err) dstFile.Close() continue } if _, err := io.Copy(dstFile, fileInArchive); err != nil { log.Error(err) } dstFile.Close() fileInArchive.Close() } // Second pass: restore modification times for ALL files and directories for path, modTime := range modTimes { if err := os.Chtimes(path, modTime, modTime); err != nil { log.Errorf("Failed to set modification time for %s: %v", path, err) } else { fi, err := os.Lstat(path) if err != nil || !modTime.UTC().Equal(fi.ModTime().UTC()) { log.Errorf("Failed to set modification time for %s: %v", path, err) fmt.Fprintf(os.Stderr, "Failed to set modification time %s %v: %v\n", path, modTime, err) } } } fmt.Fprintf(os.Stderr, "\n") return nil } // ValidFileName checks if a filename is valid // by making sure it has no invisible characters func ValidFileName(fname string) (err error) { // make sure it doesn't contain unicode or invisible characters for _, r := range fname { if !unicode.IsGraphic(r) { err = fmt.Errorf("non-graphical unicode: %x U+%d in '%x'", string(r), r, fname) return } if !unicode.IsPrint(r) { err = fmt.Errorf("non-printable unicode: %x U+%d in '%x'", string(r), r, fname) return } } // make sure basename does not include path separators _, basename := filepath.Split(fname) if strings.Contains(basename, string(os.PathSeparator)) { err = fmt.Errorf("basename cannot contain path separators: '%s'", basename) return } // make sure the filename is not an absolute path if filepath.IsAbs(fname) { err = fmt.Errorf("filename cannot be an absolute path: '%s'", fname) return } if !filepath.IsLocal(fname) { err = fmt.Errorf("filename must be a local path: '%s'", fname) return } return } const crocRemovalFile = "croc-marked-files.txt" func MarkFileForRemoval(fname string) { // append the fname to the list of files to remove f, err := os.OpenFile(crocRemovalFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) if err != nil { log.Debug(err) return } defer f.Close() _, err = f.WriteString(fname + "\n") } func RemoveMarkedFiles() (err error) { // read the file and remove all the files f, err := os.Open(crocRemovalFile) if err != nil { return } scanner := bufio.NewScanner(f) for scanner.Scan() { fname := scanner.Text() err = os.Remove(fname) if err == nil { log.Tracef("Removed %s", fname) } } f.Close() os.Remove(crocRemovalFile) return }
go
MIT
913c22f8ab0b399f87ac3a681091771b39dc763b
2026-01-07T08:36:10.668174Z
false