### Install Objx Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/stretchr/objx/README.md Use `go get` to install the Objx package. ```bash go get github.com/stretchr/objx ``` -------------------------------- ### Install go-redis/v9 Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/redis/go-redis/v9/README.md Install the go-redis/v9 library using the go get command. ```shell go get github.com/redis/go-redis/v9 ``` -------------------------------- ### Basic Redis Client Setup and Usage in Go Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/redis/go-redis/v9/README.md Demonstrates setting and getting a key, and handling a non-existent key with go-redis. ```go import ( "context" "fmt" "github.com/redis/go-redis/v9" ) var ctx = context.Background() func ExampleClient() { rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password set DB: 0, // use default DB }) err := rdb.Set(ctx, "key", "value", 0).Err() if err != nil { panic(err) } val, err := rdb.Get(ctx, "key").Result() if err != nil { panic(err) } fmt.Println("key", val) val2, err := rdb.Get(ctx, "key2").Result() if err == redis.Nil { fmt.Println("key2 does not exist") } else if err != nil { panic(err) } else { fmt.Println("key2", val2) } // Output: key value // key2 does not exist } ``` -------------------------------- ### Install Go YAML Package v3 Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/gopkg.in/yaml.v3/README.md Use 'go get' to install the yaml.v3 package. This command fetches and installs the specified package and its dependencies. ```bash go get gopkg.in/yaml.v3 ``` -------------------------------- ### Basic Configuration Example Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/CONFIGURATION.md A fundamental example demonstrating the essential parameters for setting up the Traefik OIDC middleware. ```APIDOC ## POST /api/users ### Description Creates a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. - **password** (string) - Required - The password for the new user. ### Request Example { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ### Response #### Success Response (201) - **userId** (string) - The unique identifier for the newly created user. - **message** (string) - A confirmation message. #### Response Example { "userId": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "message": "User created successfully." } ``` -------------------------------- ### Install GopherLua Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/yuin/gopher-lua/README.rst Use 'go get' to install the GopherLua package. Requires Go 1.9 or later. ```bash go get github.com/yuin/gopher-lua ``` -------------------------------- ### Install GopherLua Interpreter Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/yuin/gopher-lua/README.rst Use 'go get' to install the standalone GopherLua interpreter, 'glua'. This interpreter has the same options as the standard Lua interpreter. ```bash go get github.com/yuin/gopher-lua/cmd/glua ``` -------------------------------- ### Install Required Development Tools Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/DEVELOPMENT.md Installs essential Go development tools for linting, static analysis, and security scanning. Ensure Go 1.24+ is installed. ```bash go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest ``` ```bash go install honnef.co/go/tools/cmd/staticcheck@latest ``` ```bash go install github.com/securego/gosec/v2/cmd/gosec@latest ``` ```bash go install golang.org/x/vuln/cmd/govulncheck@latest ``` -------------------------------- ### Go and Lua Channel Communication Example Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/yuin/gopher-lua/README.rst This example shows how to set up Go channels and expose them to Lua as LChannel objects. It demonstrates receiving and sending data between Go and Lua, including handling channel closure and using select for non-blocking operations. ```go func receiver(ch, quit chan lua.LValue) { L := lua.NewState() defer L.Close() L.SetGlobal("ch", lua.LChannel(ch)) L.SetGlobal("quit", lua.LChannel(quit)) if err := L.DoString(` local exit = false while not exit do channel.select( {"|<-", ch, function(ok, v) if not ok then print("channel closed") exit = true else print("received:", v) end end}, {"|<-", quit, function(ok, v) print("quit") exit = true end} ) end `); err != nil { panic(err) } } ``` ```go func sender(ch, quit chan lua.LValue) { L := lua.NewState() defer L.Close() L.SetGlobal("ch", lua.LChannel(ch)) L.SetGlobal("quit", lua.LChannel(quit)) if err := L.DoString(` ch:send("1") ch:send("2") `); err != nil { panic(err) } ch <- lua.LString("3") quit <- lua.LTrue } ``` ```go func main() { ch := make(chan lua.LValue) quit := make(chan lua.LValue) go receiver(ch, quit) go sender(ch, quit) time.Sleep(3 * time.Second) } ``` -------------------------------- ### Initialize Redis Client with Maintenance Notifications Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/redis/go-redis/v9/maintnotifications/README.md Quick start example for initializing a Redis client with maintenance notifications enabled. Requires RESP3 protocol. Note: Cluster clients do not support this functionality. ```go client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Protocol: 3, // RESP3 required MaintNotificationsConfig: &maintnotifications.Config{ Mode: maintnotifications.ModeEnabled, }, }) ``` -------------------------------- ### Session Management - Multi-Subdomain Setup Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/CONFIGURATION.md Example configuration for managing session cookies across multiple subdomains. ```APIDOC ## POST /api/auth/login ### Description Authenticates a user and returns an access token. ### Method POST ### Endpoint /api/auth/login ### Parameters #### Request Body - **username** (string) - Required - The user's username. - **password** (string) - Required - The user's password. ### Response #### Success Response (200) - **accessToken** (string) - The JWT access token for authenticated requests. - **tokenType** (string) - The type of token (e.g., "Bearer"). - **expiresIn** (integer) - The token's expiration time in seconds. #### Response Example { "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "tokenType": "Bearer", "expiresIn": 3600 } ``` -------------------------------- ### Quick Start Testing Commands Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/DEVELOPMENT.md Provides commands for quick development testing, standard tests with race detection, and generating coverage reports. ```bash # Fast development testing (< 30 seconds) go test ./... -short ``` ```bash # Standard tests with race detector go test -race -timeout=15m ./... ``` ```bash # With coverage report go test -coverprofile=coverage.out ./... go tool cover -func=coverage.out ``` -------------------------------- ### Initialize Go Module Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/redis/go-redis/v9/README.md Before installing go-redis, initialize a Go module for your project. ```shell go mod init github.com/my/repo ``` -------------------------------- ### GitLab Provider URL Examples Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/PROVIDERS.md Provides example `providerURL` values for both GitLab.com and self-hosted GitLab instances. ```yaml # GitLab.com providerURL: "https://gitlab.com" # Self-hosted providerURL: "https://gitlab.your-company.com" ``` -------------------------------- ### Go Channel Operations Example Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/yuin/gopher-lua/README.rst Demonstrates how to use Go channels with GopherLua for inter-goroutine communication. ```APIDOC ## Go Channel Operations Example ### Description This example shows how to use Go channels with GopherLua for sending and receiving data between goroutines. It includes a sender and a receiver function, along with a main function to orchestrate their execution. ### Code ```go func receiver(ch, quit chan lua.LValue) { L := lua.NewState() defer L.Close() L.SetGlobal("ch", lua.LChannel(ch)) L.SetGlobal("quit", lua.LChannel(quit)) if err := L.DoString(` local exit = false while not exit do channel.select( {"|<-", ch, function(ok, v) if not ok then print("channel closed") exit = true else print("received:", v) end end}, {"|<-", quit, function(ok, v) print("quit") exit = true end} ) end `); err != nil { panic(err) } } func sender(ch, quit chan lua.LValue) { L := lua.NewState() defer L.Close() L.SetGlobal("ch", lua.LChannel(ch)) L.SetGlobal("quit", lua.LChannel(quit)) if err := L.DoString(` ch:send("1") ch:send("2") `); err != nil { panic(err) } ch <- lua.LString("3") quit <- lua.LTrue } func main() { ch := make(chan lua.LValue) quit := make(chan lua.LValue) go receiver(ch, quit) go sender(ch, quit) time.Sleep(3 * time.Second) } ``` ``` -------------------------------- ### Azure AD Provider URL Configuration (Multi-Tenant) Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/PROVIDERS.md Example provider URL for a multi-tenant Azure AD setup. ```yaml # Multi-tenant providerURL: "https://login.microsoftonline.com/common/v2.0" ``` -------------------------------- ### Azure AD Provider URL Configuration (Single Tenant) Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/PROVIDERS.md Example provider URL for a single-tenant Azure AD setup. ```yaml # Single tenant providerURL: "https://login.microsoftonline.com/{tenant-id}/v2.0" ``` -------------------------------- ### Recommended Auth0 Configuration for Default Setup Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/AUTH0_AUDIENCE_GUIDE.md For the default Auth0 setup where the audience defaults to the client ID, ensure strict audience validation is enabled. ```yaml # Don't set audience (defaults to client_id) strictAudienceValidation: true # Enforce proper configuration ``` -------------------------------- ### Redis Command Examples in Go Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/redis/go-redis/v9/README.md Demonstrates various Redis commands with go-redis, including SetNX, Sort, ZRangeByScoreWithScores, ZInterStore, Eval, and custom commands. Ensure proper context and arguments are provided for each command. ```go // SET key value EX 10 NX set, err := rdb.SetNX(ctx, "key", "value", 10*time.Second).Result() ``` ```go // SET key value keepttl NX set, err := rdb.SetNX(ctx, "key", "value", redis.KeepTTL).Result() ``` ```go // SORT list LIMIT 0 2 ASC vals, err := rdb.Sort(ctx, "list", &redis.Sort{Offset: 0, Count: 2, Order: "ASC"}).Result() ``` ```go // ZRANGEBYSCORE zset -inf +inf WITHSCORES LIMIT 0 2 vals, err := rdb.ZRangeByScoreWithScores(ctx, "zset", &redis.ZRangeBy{ Min: "-inf", Max: "+inf", Offset: 0, Count: 2, }).Result() ``` ```go // ZINTERSTORE out 2 zset1 zset2 WEIGHTS 2 3 AGGREGATE SUM vals, err := rdb.ZInterStore(ctx, "out", &redis.ZStore{ Keys: []string{"zset1", "zset2"}, Weights: []int64{2, 3} }).Result() ``` ```go // EVAL "return {KEYS[1],ARGV[1]}" 1 "key" "hello" vals, err := rdb.Eval(ctx, "return {KEYS[1],ARGV[1]}", []string{"key"}, "hello").Result() ``` ```go // custom command res, err := rdb.Do(ctx, "set", "key", "value").Result() ``` -------------------------------- ### Start Docker Development Environment Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/redis/go-redis/v9/CONTRIBUTING.md Use this command to clone and build the Docker containers for development. You can specify a Redis image using the CLIENT_LIBS_TEST_IMAGE environment variable. ```bash make docker.start ``` -------------------------------- ### Update Objx Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/stretchr/objx/README.md Use `go get -u` to update Objx to the latest version. ```bash go get -u github.com/stretchr/objx ``` -------------------------------- ### Scope Filtering Logging Examples Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/PROVIDERS.md Shows example log output indicating the scope filtering process. The `INFO` level message shows filtered scopes, while `DEBUG` shows the final set of scopes used. ```text INFO: ScopeFilter: Filtered unsupported scopes: [offline_access] DEBUG: ScopeFilter: Final filtered scopes: [openid profile email] ``` -------------------------------- ### Keycloak Provider URL Configuration Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/PROVIDERS.md Example of configuring the `providerURL` for Keycloak, including the realm name placeholder. ```yaml providerURL: "https://keycloak.your-domain.com/realms/{realm-name}" ``` -------------------------------- ### Run All Tests and Manage Docker Containers Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/redis/go-redis/v9/CONTRIBUTING.md This command starts all Docker containers, runs the tests, and then stops the containers. It's a comprehensive way to test your changes. ```bash make test ``` -------------------------------- ### Basic Traefik OIDC Middleware Configuration Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/CONFIGURATION.md This is a basic example of how to configure the Traefik OIDC middleware with essential parameters. ```yaml apiVersion: traefik.io/v1alpha1 kind: Middleware metadata: name: oidc-auth spec: plugin: traefikoidc: providerURL: https://accounts.google.com clientID: your-client-id.apps.googleusercontent.com clientSecret: your-client-secret sessionEncryptionKey: your-32-byte-encryption-key-here callbackURL: /oauth2/callback ``` -------------------------------- ### Lua Channel Select Example Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/yuin/gopher-lua/README.rst Demonstrates using the channel.select function in Lua to handle multiple channel operations, including receiving from channels and executing default actions. It shows how to specify handlers for each case. ```lua local idx, recv, ok = channel.select( {"|<-", ch1}, {"|<-", ch2} ) if not ok then print("closed") elseif idx == 1 then -- received from ch1 print(recv) elseif idx == 2 then -- received from ch2 print(recv) end ``` ```lua channel.select( {"|<-", ch1, function(ok, data) print(ok, data) end}, {"<-|", ch2, "value", function(data) print(data) end}, {"default", function() print("default action") end} ) ``` -------------------------------- ### Basic Test Suite Structure in Go Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/TESTING.md Defines the fundamental structure for a Go test suite using testify's suite package. Includes setup and teardown methods for test fixtures and the OIDC client. ```go type MyTestSuite struct { suite.Suite fixture *testutil.TokenFixture tOidc *TraefikOidc } func (s *MyTestSuite) SetupSuite() { var err error s.fixture, err = testutil.NewTokenFixture() s.Require().NoError(err) } func (s *MyTestSuite) SetupTest() { // Per-test setup s.tOidc = &TraefikOidc{ issuerURL: s.fixture.Issuer, // ... } } func (s *MyTestSuite) TearDownTest() { // Per-test cleanup } func (s *MyTestSuite) TestSomething() { token, err := s.fixture.ValidToken(nil) s.Require().NoError(err) err = s.tOidc.VerifyToken(token) s.NoError(err) } func TestMyTestSuite(t *testing.T) { suite.Run(t, new(MyTestSuite)) } ``` -------------------------------- ### Build and Run Unit Tests Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/DEVELOPMENT.md Commands to tidy Go modules, build the project, and run unit tests. Use the '-short' flag for a faster test loop. ```bash go mod tidy go build ./... go test ./... -short # fast loop, < 30 s ``` ```bash go test -race -timeout=15m ./... ``` -------------------------------- ### Enable Dynamic Client Registration (Basic) Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/CONFIGURATION.md Enable dynamic client registration for automatic client credential management. Specify optional `initialAccessToken` if required by the provider. ```yaml dynamicClientRegistration: enabled: true initialAccessToken: "your-token" # Optional, if provider requires it persistCredentials: true credentialsFile: "/tmp/oidc-credentials.json" clientMetadata: redirect_uris: - "https://your-app.com/oauth2/callback" client_name: "My Application" application_type: "web" grant_types: - "authorization_code" - "refresh_token" ``` -------------------------------- ### Access Data with Get Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/stretchr/objx/README.md Use the `Get` method to retrieve values from an `objx.Map`. Chain methods like `Str()` or `Int()` to get strongly typed values. A default value can be provided if the key is missing or the type is incorrect. ```go // Get the details name := m.Get("name").Str() age := m.Get("age").Int() // Get their nickname (or use their name if they don't have one) nickname := m.Get("nickname").Str(name) ``` -------------------------------- ### Mock OIDC Server - Default Configuration Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/TESTING.md Initializes a mock OIDC server with default configuration. Remember to close the server when done using defer. ```go server := testutil.NewOIDCServer(nil) def server.Close() ``` -------------------------------- ### Open Subset of Built-in Lua Modules Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/yuin/gopher-lua/README.rst Shows how to initialize the Lua state with only specific modules like 'package', 'base', and 'table', skipping others. This is useful for security or resource management. ```go func main() { L := lua.NewState(lua.Options{SkipOpenLibs: true}) defer L.Close() for _, pair := range []struct { n string f lua.LGFunction }{ {lua.LoadLibName, lua.OpenPackage}, // Must be first {lua.BaseLibName, lua.OpenBase}, {lua.TabLibName, lua.OpenTable}, } { if err := L.CallByParam(lua.P{ Fn: L.NewFunction(pair.f), NRet: 0, Protect: true, }, lua.LString(pair.n)); err != nil { panic(err) } } if err := L.DoFile("main.lua"); err != nil { panic(err) } } ``` -------------------------------- ### Mock OIDC Server - Custom Configuration Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/TESTING.md Sets up a mock OIDC server with custom configurations, including issuer URL and specific token errors. ```go config := testutil.DefaultServerConfig() config.Issuer = "https://custom-issuer.com" config.TokenError = &testutil.OIDCError{ Error: "invalid_grant", Description: "Authorization code expired", } server := testutil.NewOIDCServer(config) ``` -------------------------------- ### Run All Go Tests Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/TESTING.md Execute all tests within the project. Use this for a full test run. ```bash go test ./... ``` -------------------------------- ### Example of CA Certificate in PEM format Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/README.md Inline CA certificate in PEM format for TLS configuration. ```yaml caCertPEM: | -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- ``` -------------------------------- ### Basic MockJWKCache Usage Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/TESTING.md Demonstrates the initialization and usage of a basic state-based mock for JWKCache. This mock is suitable for simple test scenarios where direct state manipulation is sufficient. ```go mock := &MockJWKCache{ JWKS: &JWKSet{Keys: []JWK{jwk}}, Err: nil, } tOidc := &TraefikOidc{ jwkCache: mock, // ... } ``` -------------------------------- ### Check Lua Table Type in Go Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/yuin/gopher-lua/README.rst Use type assertion to check if a Lua value is a table and get its length. ```go lv := L.Get(-1) // get the value at the top of the stack if tbl, ok := lv.(*lua.LTable); ok { // lv is LTable fmt.Println(L.ObjLen(tbl)) } ``` -------------------------------- ### Configure Initial Registry Size and Growth Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/yuin/gopher-lua/README.rst Set initial, maximum, and step sizes for the Lua registry when creating a new LState. ```go L := lua.NewState(lua.Options{ RegistrySize: 1024 * 20, // this is the initial size of the registry RegistryMaxSize: 1024 * 80, // this is the maximum size that the registry can grow to. If set to `0` (the default) then the registry will not auto grow RegistryGrowStep: 32, // this is how much to step up the registry by each time it runs out of space. The default is `32`. }) defer L.Close() ``` -------------------------------- ### Token Fixture - Get JWKS Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/TESTING.md Retrieves the JSON Web Key Set (JWKS) from the token fixture for verification purposes. ```go jwks := fixture.GetJWKS() ``` -------------------------------- ### Generic OIDC Provider URL Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/PROVIDERS.md Example `providerURL` for a generic OIDC-compliant provider. Ensure your provider exposes the `.well-known/openid-configuration` endpoint. ```yaml providerURL: "https://oidc.your-provider.com" ``` -------------------------------- ### Redis Client Initialization (Before Migration) Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/redis/go-redis/v9/maintnotifications/FEATURES.md Initializes a standalone Redis client using RESP2 protocol before enabling maintenance notifications. ```go client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Protocol: 2, // RESP2 }) ``` -------------------------------- ### Okta Provider URL Configuration Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/PROVIDERS.md Examples of configuring the `providerURL` for Okta, including the default and custom authorization server URLs. ```yaml providerURL: "https://your-domain.okta.com" # Or with custom authorization server: providerURL: "https://your-domain.okta.com/oauth2/default" ``` -------------------------------- ### Create Kubernetes Secret for OIDC Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/CONFIGURATION.md Example command to create a Kubernetes generic secret containing OIDC provider credentials. ```bash kubectl create secret generic oidc-secret \ --from-literal=ISSUER=https://accounts.google.com \ --from-literal=CLIENT_ID=your-client-id \ --from-literal=SECRET=your-client-secret \ -n traefik ``` -------------------------------- ### Redis Client with Username and Password Fields in Go Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/redis/go-redis/v9/README.md Demonstrates the basic method of providing credentials directly via the Username and Password fields in the Redis client options. ```go rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Username: "user", Password: "pass", }) ``` -------------------------------- ### Run Benchmarks and Profiling Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/DEVELOPMENT.md Commands for running benchmarks, including quick and extended modes, and generating memory profiles for analysis. ```bash # Quick benchmarks go test -bench=. -short ``` ```bash # Extended benchmarks RUN_EXTENDED_TESTS=1 go test -bench=. ``` ```bash # Memory profiling go test -bench=. -memprofile=mem.prof go tool pprof mem.prof ``` -------------------------------- ### Get Redis Database Size Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/REDIS.md Returns the number of keys in the currently selected database. Useful for understanding the scale of cached data. ```bash redis-cli DBSIZE ``` -------------------------------- ### Keycloak OIDC Middleware Configuration Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/PROVIDERS.md Configuration for OIDC authentication with Keycloak. This example includes scopes for roles and groups, and enables PKCE. ```yaml apiVersion: traefik.io/v1alpha1 kind: Middleware metadata: name: oidc-keycloak spec: plugin: traefikoidc: providerURL: "https://keycloak.company.com/realms/your-realm" clientID: "your-keycloak-client-id" clientSecret: "your-keycloak-client-secret" callbackURL: "/oauth2/callback" sessionEncryptionKey: "your-32-char-encryption-key-here" scopes: - openid - profile - email - roles - groups - offline_access allowedRolesAndGroups: - admin - editor forceHttps: true enablePkce: true ``` -------------------------------- ### Redis Client Initialization (After Migration) Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/redis/go-redis/v9/maintnotifications/FEATURES.md Initializes a standalone Redis client with RESP3 protocol and automatic maintenance notification mode enabled. ```go client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Protocol: 3, // RESP3 required MaintNotificationsConfig: &maintnotifications.Config{ Mode: maintnotifications.ModeAuto, }, }) ``` -------------------------------- ### Monitor Redis Memory Usage Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/REDIS.md Get detailed memory usage statistics for Redis. Essential for capacity planning and identifying memory leaks. ```bash redis-cli INFO memory ``` -------------------------------- ### Initialize and Use Cookie Store Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/gorilla/sessions/README.md Initializes a cookie store with a secret key and demonstrates setting and saving session values within an HTTP handler. Ensure the session key is securely managed and not hardcoded. ```go import ( "net/http" "github.com/gorilla/sessions" ) // Note: Don't store your key in your source code. Pass it via an // environmental variable, or flag (or both), and don't accidentally commit it // alongside your code. Ensure your key is sufficiently random - i.e. use Go's // crypto/rand or securecookie.GenerateRandomKey(32) and persist the result. var store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY"))) func MyHandler(w http.ResponseWriter, r *http.Request) { // Get a session. We're ignoring the error resulted from decoding an // existing session: Get() always returns a session, even if empty. session, _ := store.Get(r, "session-name") // Set some session values. session.Values["foo"] = "bar" session.Values[42] = 43 // Save it before we write to the response/return from the handler. err := session.Save(r, w) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } ``` -------------------------------- ### Mock OIDC Server - Provider Configurations Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/TESTING.md Provides pre-configured settings for common OIDC providers like Google, Azure, Auth0, and Keycloak. ```go googleConfig := testutil.GoogleServerConfig() azureConfig := testutil.AzureServerConfig() auth0Config := testutil.Auth0ServerConfig() keycloakConfig := testutil.KeycloakServerConfig() ``` -------------------------------- ### Install Traefik OIDC Plugin Source: https://context7.com/lukaszraczylo/traefikoidc/llms.txt Enable the TraefikOIDC plugin in Traefik's static configuration. This makes the plugin available for use in middleware definitions. ```yaml # traefik.yml (static configuration) experimental: plugins: traefikoidc: moduleName: github.com/lukaszraczylo/traefikoidc version: v0.7.10 ``` -------------------------------- ### Testify Mock JWKCache Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/TESTING.md Example of using testify's .On().Return() pattern for mocking JWKCache interface. Ensure to call AssertExpectations after tests. ```go mock := &TestifyJWKCache{} mock.On("GetJWKS", mock.Anything, "https://example.com/jwks", mock.Anything). Return(&JWKSet{Keys: []JWK{jwk}}, nil) // After test mock.AssertExpectations(t) ``` -------------------------------- ### Performance Benchmarks Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/cespare/xxhash/v2/README.md Comparison of pure Go and assembly implementations for the Sum64 function. ```APIDOC ## Performance Benchmarks ### Description Benchmarks comparing the performance of the pure Go implementation versus assembly implementations for the `Sum64` function across different input sizes. ### Benchmark Table | input size | purego | asm | | ---------- | --------- | --------- | | 4 B | 1.3 GB/s | 1.2 GB/s | | 16 B | 2.9 GB/s | 3.5 GB/s | | 100 B | 6.9 GB/s | 8.1 GB/s | | 4 KB | 11.7 GB/s | 16.7 GB/s | | 10 MB | 12.0 GB/s | 17.3 GB/s | ### Benchmark Commands ```bash benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') ``` ``` -------------------------------- ### Connecting to Redis via URL in Go Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/redis/go-redis/v9/README.md Demonstrates parsing a Redis URL string to configure the Redis client options, supporting various connection parameters. ```go import ( "github.com/redis/go-redis/v9" ) func ExampleClient() *redis.Client { url := "redis://user:password@localhost:6379/0?protocol=3" opts, err := redis.ParseURL(url) if err != nil { panic(err) } return redis.NewClient(opts) } ``` -------------------------------- ### Configure AWS Cognito Provider Source: https://context7.com/lukaszraczylo/traefikoidc/llms.txt Configure AWS Cognito authentication using a user pool. This setup is suitable for identity management through AWS Cognito. ```yaml apiVersion: traefik.io/v1alpha1 kind: Middleware metadata: name: oidc-cognito spec: plugin: traefikoidc: providerURL: "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_ABCDEF123" clientID: "your-cognito-client-id" clientSecret: "your-cognito-client-secret" callbackURL: "/oauth2/callback" sessionEncryptionKey: "your-32-char-encryption-key-here" scopes: - openid - profile - email - aws.cognito.signin.user.admin allowedRolesAndGroups: - admin - users forceHTTPS: true ``` -------------------------------- ### Troubleshoot Linter Errors Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/DEVELOPMENT.md Run the linter with verbose output to get more details on errors, or use the --fix flag to attempt automatic resolution of some issues. ```bash golangci-lint run -v ``` ```bash golangci-lint run --fix ``` -------------------------------- ### Gradual Strict Audience Validation in Traefik Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/AUTH0_AUDIENCE_GUIDE.md Steps to enable strict audience validation. Start with `false` to monitor logs for warnings, then switch to `true` once confirmed. ```yaml strictAudienceValidation: false # Default ``` ```yaml strictAudienceValidation: true ``` -------------------------------- ### Enable Dynamic Client Registration (Multi-Replica with Redis) Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/CONFIGURATION.md Configure dynamic client registration for multi-replica deployments using Redis for shared credentials. This prevents registration race conditions. ```yaml dynamicClientRegistration: enabled: true persistCredentials: true storageBackend: "redis" # Share credentials via Redis redisKeyPrefix: "myapp:dcr:" # Optional custom prefix clientMetadata: redirect_uris: - "https://your-app.com/oauth2/callback" client_name: "My Application" redis: enabled: true address: "redis:6379" cacheMode: "redis" ``` -------------------------------- ### Run Lua Script from File Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/yuin/gopher-lua/README.rst Initialize a new Lua state, defer its closing, and execute a Lua script from a file using DoFile. Handles potential errors during script execution. ```go L := lua.NewState() def L.Close() if err := L.DoFile("hello.lua"); err != nil { panic(err) } ``` -------------------------------- ### Automatic Scope Filtering Example Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/PROVIDERS.md Demonstrates how the middleware automatically filters unsupported OAuth scopes, such as `offline_access` for self-hosted GitLab, by checking the provider's discovery document. ```yaml scopes: - openid - profile - email - offline_access # Will be automatically filtered out if unsupported ``` -------------------------------- ### Traefik OIDC Configuration Example Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/index.html Configure Traefik OIDC middleware with back-channel and front-channel logout enabled. Ensure your Identity Provider is configured with the full logout URLs. ```yaml http: middlewares: oidc-auth: plugin: traefikoidc: # ... other OIDC configuration ... # Back-Channel Logout (server-to-server) enableBackchannelLogout: true backchannelLogoutURL: "/backchannel-logout" # Front-Channel Logout (browser-based) enableFrontchannelLogout: true frontchannelLogoutURL: "/frontchannel-logout" ``` -------------------------------- ### Import Miniredis v2 Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/alicebob/miniredis/v2/README.md Import the Miniredis library version 2 for use in your Go projects. ```go import "github.com/alicebob/miniredis/v2" ``` -------------------------------- ### Initialize Keys for Rotation Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/gorilla/securecookie/README.md Set up multiple secure cookie instances for key rotation. Store keys in a map, considering that this in-memory storage is not persistent across restarts. Production applications should use persistent storage. ```go // keys stored in a map will not be persisted between restarts // a more persistent storage should be considered for production applications. var cookies = map[string]*securecookie.SecureCookie{ "previous": securecookie.New( securecookie.GenerateRandomKey(64), securecookie.GenerateRandomKey(32), ), "current": securecookie.New( securecookie.GenerateRandomKey(64), securecookie.GenerateRandomKey(32), ), } ``` -------------------------------- ### Specify Redis-Search Dialect Version in go-redis Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/redis/go-redis/v9/README.md Explicitly set the query dialect version for Redis-Search commands. The default is dialect 2. This example uses dialect 3. ```go res2, err := rdb.FTSearchWithArgs(ctx, "idx:bicycle", "@pickup_zone:[CONTAINS $bike]", &redis.FTSearchOptions{ Params: map[string]interface{}{ "bike": "POINT(-0.1278 51.5074)", }, DialectVersion: 3, }, ).Result() ``` -------------------------------- ### Configure Custom Buffer Sizes for go-redis Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/redis/go-redis/v9/README.md Adjust read and write buffer sizes for high-throughput applications or large pipelines. The default is 32KiB. Example shows 1MiB. ```go rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", ReadBufferSize: 1024 * 1024, // 1MiB read buffer WriteBufferSize: 1024 * 1024, // 1MiB write buffer }) ``` ```go rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", ReadBufferSize: 1024 * 1024, // 1MiB read buffer WriteBufferSize: 1024 * 1024, // 1MiB write buffer }) ``` -------------------------------- ### Create SecureCookie Instance Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/vendor/github.com/gorilla/securecookie/README.md Instantiate SecureCookie with hash and block keys. Hash keys authenticate, block keys encrypt. Use nil for blockKey to disable encryption. Keys should be of appropriate lengths for security. ```go // Hash keys should be at least 32 bytes long var hashKey = []byte("very-secret") // Block keys should be 16 bytes (AES-128) or 32 bytes (AES-256) long. // Shorter keys may weaken the encryption used. var blockKey = []byte("a-lot-secret") var s = securecookie.New(hashKey, blockKey) ``` -------------------------------- ### Run Go Tests with Coverage Source: https://github.com/lukaszraczylo/traefikoidc/blob/main/docs/TESTING.md Execute all tests and generate a code coverage report. Useful for assessing test completeness. ```bash go test -cover ./... ``` -------------------------------- ### Google Provider Configuration for Traefik OIDC Source: https://context7.com/lukaszraczylo/traefikoidc/llms.txt Configure the Traefik OIDC middleware for Google OAuth. This example includes automatic offline access handling and Workspace domain restrictions. ```yaml apiVersion: traefik.io/v1alpha1 kind: Middleware metadata: name: oidc-google spec: plugin: traefikoidc: providerURL: "https://accounts.google.com" clientID: "your-id.apps.googleusercontent.com" clientSecret: "your-client-secret" callbackURL: "/oauth2/callback" sessionEncryptionKey: "your-32-char-encryption-key-here" scopes: - openid - email - profile allowedUserDomains: - "your-gsuite-domain.com" forceHTTPS: true enablePKCE: true ```