From e7724f3a745ac36225305f3d17b59931b647dc6e Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Thu, 12 Feb 2026 21:18:45 +0100 Subject: [PATCH 01/53] ci: ensure release branches originate from the local repository and reduce residual risk of command injection (#3337) Signed-off-by: Jan Larwig --- .github/workflows/publish-release.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index d3a8115f..9f235fb6 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -14,7 +14,7 @@ permissions: jobs: publish: - if: github.event.pull_request.merged && startsWith(github.event.pull_request.head.ref, 'release/') + if: github.event.pull_request.merged && startsWith(github.event.pull_request.head.ref, 'release/') && github.event.pull_request.head.repo.full_name == github.repository runs-on: ubuntu-latest outputs: tag: ${{ steps.tag.outputs.version }} @@ -27,14 +27,15 @@ jobs: fetch-tags: true - name: Tag release + env: + BRANCH: ${{ github.event.pull_request.head.ref }} run: | # Set up github-actions[bot] user git config --local user.name "github-actions[bot]" git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com" # Get the version from the branch name - branch="${{ github.event.pull_request.head.ref }}" - version="${branch#release/}" + version="${BRANCH#release/}" echo ${version} # Tag and create release From 178532741fbe19ed72a30fcbf1e2cfb44acf81b6 Mon Sep 17 00:00:00 2001 From: Richard87 Date: Tue, 2 Sep 2025 13:00:16 +0200 Subject: [PATCH 02/53] fix: dont override parameters set in redis uri Signed-off-by: Richard Hagen --- pkg/sessions/redis/redis_store.go | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/pkg/sessions/redis/redis_store.go b/pkg/sessions/redis/redis_store.go index 4e846e9b..79f8f7d1 100644 --- a/pkg/sessions/redis/redis_store.go +++ b/pkg/sessions/redis/redis_store.go @@ -109,6 +109,9 @@ func buildSentinelClient(opts options.RedisStoreOptions) (Client, error) { if opts.Username != "" { opt.Username = opts.Username } + if opts.IdleTimeout > 0 { + opt.ConnMaxIdleTime = time.Duration(opts.IdleTimeout) * time.Second + } if err := setupTLSConfig(opts, opt); err != nil { return nil, err @@ -118,10 +121,10 @@ func buildSentinelClient(opts options.RedisStoreOptions) (Client, error) { MasterName: opts.SentinelMasterName, SentinelAddrs: addrs, SentinelPassword: opts.SentinelPassword, - Username: opts.Username, - Password: opts.Password, + Username: opt.Username, + Password: opt.Password, TLSConfig: opt.TLSConfig, - ConnMaxIdleTime: time.Duration(opts.IdleTimeout) * time.Second, + ConnMaxIdleTime: opt.ConnMaxIdleTime, }) return newClient(client), nil } @@ -139,6 +142,9 @@ func buildClusterClient(opts options.RedisStoreOptions) (Client, error) { if opts.Username != "" { opt.Username = opts.Username } + if opts.IdleTimeout > 0 { + opt.ConnMaxIdleTime = time.Duration(opts.IdleTimeout) * time.Second + } if err := setupTLSConfig(opts, opt); err != nil { return nil, err @@ -146,10 +152,10 @@ func buildClusterClient(opts options.RedisStoreOptions) (Client, error) { client := redis.NewClusterClient(&redis.ClusterOptions{ Addrs: addrs, - Username: opts.Username, - Password: opts.Password, + Username: opt.Username, + Password: opt.Password, TLSConfig: opt.TLSConfig, - ConnMaxIdleTime: time.Duration(opts.IdleTimeout) * time.Second, + ConnMaxIdleTime: opt.ConnMaxIdleTime, }) return newClusterClient(client), nil } @@ -168,13 +174,14 @@ func buildStandaloneClient(opts options.RedisStoreOptions) (Client, error) { if opts.Username != "" { opt.Username = opts.Username } + if opts.IdleTimeout > 0 { + opt.ConnMaxIdleTime = time.Duration(opts.IdleTimeout) * time.Second + } if err := setupTLSConfig(opts, opt); err != nil { return nil, err } - opt.ConnMaxIdleTime = time.Duration(opts.IdleTimeout) * time.Second - client := redis.NewClient(opt) return newClient(client), nil } From 7747a884049fca383f7c6ec1e804a4ad39f59c65 Mon Sep 17 00:00:00 2001 From: Richard Hagen Date: Thu, 19 Feb 2026 10:14:05 +0100 Subject: [PATCH 03/53] fix: add tests for configure options and URL overrides when empty Signed-off-by: Richard Hagen --- pkg/sessions/redis/redis_store_test.go | 50 ++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/pkg/sessions/redis/redis_store_test.go b/pkg/sessions/redis/redis_store_test.go index 1bff6855..18dbe934 100644 --- a/pkg/sessions/redis/redis_store_test.go +++ b/pkg/sessions/redis/redis_store_test.go @@ -1,6 +1,7 @@ package redis import ( + "fmt" "time" "github.com/Bose/minisentinel" @@ -246,6 +247,55 @@ var _ = Describe("Redis SessionStore Tests", func() { }) Describe("Redis URL Parsing", func() { + It("should prefer configured username password and timeout over URL parameters", func() { + configuredUsername := "configured-user" + configuredPassword := "configured-password" + configuredIdleTimeout := 90 + + urlUsername := "url-user" + urlPassword := "url-password" + urlIdleTimeout := 30 + + redisClient, err := buildStandaloneClient(options.RedisStoreOptions{ + ConnectionURL: fmt.Sprintf("redis://%s:%s@localhost:6379?conn_max_idle_time=%d", urlUsername, urlPassword, urlIdleTimeout), + Username: configuredUsername, + Password: configuredPassword, + IdleTimeout: configuredIdleTimeout, + }) + Expect(err).ToNot(HaveOccurred()) + + rc, ok := redisClient.(*client) + Expect(ok).To(BeTrue()) + Expect(rc.Close()).To(Succeed()) + + redisOptions := rc.Options() + Expect(redisOptions.Username).To(Equal(configuredUsername)) + Expect(redisOptions.Password).To(Equal(configuredPassword)) + Expect(redisOptions.ConnMaxIdleTime).To(Equal(time.Duration(configuredIdleTimeout) * time.Second)) + }) + It("should prefer URL username password and timeout when configured values are empty", func() { + urlUsername := "url-user" + urlPassword := "url-password" + urlIdleTimeout := 30 + + redisClient, err := buildStandaloneClient(options.RedisStoreOptions{ + ConnectionURL: fmt.Sprintf("redis://%s:%s@localhost:6379?conn_max_idle_time=%d", urlUsername, urlPassword, urlIdleTimeout), + Username: "", + Password: "", + IdleTimeout: 0, + }) + Expect(err).ToNot(HaveOccurred()) + + rc, ok := redisClient.(*client) + Expect(ok).To(BeTrue()) + Expect(rc.Close()).To(Succeed()) + + redisOptions := rc.Options() + Expect(redisOptions.Username).To(Equal(urlUsername)) + Expect(redisOptions.Password).To(Equal(urlPassword)) + Expect(redisOptions.ConnMaxIdleTime).To(Equal(time.Duration(urlIdleTimeout) * time.Second)) + }) + It("should parse valid redis URL", func() { addrs, opts, err := parseRedisURLs([]string{"redis://localhost:6379"}) Expect(err).ToNot(HaveOccurred()) From 7822698ab1788fd53226ef0e4e3772afcbcb5eb8 Mon Sep 17 00:00:00 2001 From: Richard Hagen Date: Thu, 19 Feb 2026 10:20:26 +0100 Subject: [PATCH 04/53] fix: update CHANGELOG to include new fix for URL parameters configuration Signed-off-by: Richard Hagen --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed40d056..76c506ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ ## Changes since v7.14.2 +- [#3183](https://github.com/oauth2-proxy/oauth2-proxy/pull/3183) fix: allow URL parameters to configure username, password and max idle connection timeout if the matching configuration is empty. + # V7.14.2 ## Release Highlights From 06f1234b69676c63dae998a3539992c17700c9cc Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Thu, 26 Feb 2026 14:43:52 +0100 Subject: [PATCH 05/53] ci: ensure we always use the latest patch version of golang (#3349) Signed-off-by: Jan Larwig --- .github/workflows/ci.yml | 10 ++++++++-- .github/workflows/publish-release.yml | 13 ++++++++++--- go.mod | 2 +- 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cd9b6dbe..4c9b969e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,11 +20,17 @@ jobs: - name: Check out code uses: actions/checkout@v6 + - name: Get Go version + run: | + version=$(grep "^go " go.mod | cut -d' ' -f2) + echo "version=${version}" >> "$GITHUB_OUTPUT" + id: go-version + - name: Set up Go uses: actions/setup-go@v6 with: - go-version-file: go.mod - id: go + go-version: ${{ steps.go-version.outputs.version }} + check-latest: true - name: Install golangci-lint env: diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 9f235fb6..c71266c9 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -42,11 +42,18 @@ jobs: git tag -a "${version}" -m "Release ${version}" echo "version=${version}" >> $GITHUB_OUTPUT id: tag - - - name: Set up go + + - name: Get Go version + run: | + version=$(grep "^go " go.mod | cut -d' ' -f2) + echo "version=${version}" >> "$GITHUB_OUTPUT" + id: go-version + + - name: Set up Go uses: actions/setup-go@v6 with: - go-version-file: go.mod + go-version: ${{ steps.go-version.outputs.version }} + check-latest: true - name: Get dependencies env: diff --git a/go.mod b/go.mod index c998b25f..4f54660f 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/oauth2-proxy/oauth2-proxy/v7 -go 1.25.6 +go 1.25.0 require ( cloud.google.com/go/compute/metadata v0.9.0 From 788f3d0e1df540d945a3ffe0e95d432baf1387c3 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Thu, 26 Feb 2026 14:48:35 +0100 Subject: [PATCH 06/53] ci: ensure we always use the latest patch version of golang (#3350) Signed-off-by: Jan Larwig --- .github/workflows/ci.yml | 2 +- .github/workflows/publish-release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4c9b969e..5c3a18c5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,7 +22,7 @@ jobs: - name: Get Go version run: | - version=$(grep "^go " go.mod | cut -d' ' -f2) + version=$(grep "^go " go.mod | cut -d' ' -f2 | cut -d. -f1,2) echo "version=${version}" >> "$GITHUB_OUTPUT" id: go-version diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index c71266c9..f853d8de 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -45,7 +45,7 @@ jobs: - name: Get Go version run: | - version=$(grep "^go " go.mod | cut -d' ' -f2) + version=$(grep "^go " go.mod | cut -d' ' -f2 | cut -d. -f1,2) echo "version=${version}" >> "$GITHUB_OUTPUT" id: go-version From b5c8df79886c3d4601adc0ec9fda1d17290f45b1 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 26 Feb 2026 15:03:07 +0100 Subject: [PATCH 07/53] release v7.14.3 (#3351) * update to release version v7.14.3 * doc: release note v7.14.3 Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Jan Larwig --- CHANGELOG.md | 18 ++++++++++++++++++ .../docker-compose-alpha-config.yaml | 2 +- .../docker-compose-gitea.yaml | 2 +- .../docker-compose-keycloak.yaml | 2 +- .../docker-compose-nginx.yaml | 2 +- .../docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/installation.md | 2 +- .../version-7.14.x/installation.md | 2 +- 9 files changed, 26 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 76c506ba..4542945f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,24 @@ ## Important Notes +## Breaking Changes + +## Changes since v7.14.3 + +# V7.14.3 + +## Release Highlights + +- 🔵 Go1.25.7 and upgrade of dependencies to latest versions + - Fixes [CVE-2025-68121](https://nvd.nist.gov/vuln/detail/cve-2025-68121) +- 🐛 Bug fixes + - Allow Redis URL parameters to configure username, password and max idle connection timeout if the matching configuration is empty. + +## Important Notes + +We improved our supply chain security by added additional checks to prevent potential command injection in the publish release workflow and to ensure that it can only be triggered from branches originating in the local repository. This potential issue was reported by automated systems as well as a couple of security researchers, and we want to thank everyone for their diligence in looking out for the security of the project. Especially Aastha Aggarwal for her detailed report and follow-up. @Aastha2602 + + ## Breaking Changes ## Changes since v7.14.2 diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index 595ce4e4..6854ef95 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -14,7 +14,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.3 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 65968fe8..bb17c752 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.3 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index cc56f4ae..ea86ea82 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.3 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 771815b1..113616d6 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,7 +22,7 @@ version: "3.0" services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.3 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index b5d25e2f..e4490b3a 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.3 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 12ddeb68..1eaba82a 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.3 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/installation.md b/docs/docs/installation.md index 4bb94f4f..75603801 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.2`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.3`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.14.x/installation.md b/docs/versioned_docs/version-7.14.x/installation.md index 4bb94f4f..75603801 100644 --- a/docs/versioned_docs/version-7.14.x/installation.md +++ b/docs/versioned_docs/version-7.14.x/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.2`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.3`) b. Using Go to install the latest release ```bash From 88075737a6c349508700cab0e342c8591af8c6d0 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 27 Feb 2026 15:00:04 +0100 Subject: [PATCH 08/53] chore(deps): update alpine docker tag to v3.23.3 (#3329) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 73507560..ed9d2186 100644 --- a/Makefile +++ b/Makefile @@ -66,7 +66,7 @@ DOCKER_BUILDX_PUSH := $(DOCKER_BUILDX) --push DOCKER_BUILDX_PUSH_X_PLATFORM := $(DOCKER_BUILDX_PUSH) --platform ${DOCKER_BUILD_PLATFORM} DOCKER_BUILD_PLATFORM_ALPINE ?= linux/amd64,linux/arm64,linux/ppc64le,linux/arm/v6,linux/arm/v7,linux/s390x -DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.23.2 +DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.23.3 DOCKER_BUILDX_ARGS_ALPINE ?= --build-arg RUNTIME_IMAGE=${DOCKER_BUILD_RUNTIME_IMAGE_ALPINE} ${DOCKER_BUILDX_COMMON_ARGS} DOCKER_BUILDX_X_PLATFORM_ALPINE := docker buildx build ${DOCKER_BUILDX_ARGS_ALPINE} --platform ${DOCKER_BUILD_PLATFORM_ALPINE} DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE := $(DOCKER_BUILDX_X_PLATFORM_ALPINE) --push From 75ff537915b84e1113446b3e5bacbc8b3ee5a741 Mon Sep 17 00:00:00 2001 From: Vivek S Sejpal Date: Fri, 13 Mar 2026 19:05:57 -0700 Subject: [PATCH 09/53] fix: backend logout URL call on sign out (#3172) (#3352) * Fix backend logout URL call on sign out (#3172) Signed-off-by: Vivek Sejpal * doc: changelog entry for #3352 Signed-off-by: Jan Larwig --------- Signed-off-by: Vivek Sejpal Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 2 ++ oauthproxy.go | 6 ++++-- oauthproxy_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4542945f..6a284fa6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ ## Changes since v7.14.3 +- [#3352](https://github.com/oauth2-proxy/oauth2-proxy/pull/3352) fix: backend logout URL call on sign out (#3172)(@vsejpal) + # V7.14.3 ## Release Highlights diff --git a/oauthproxy.go b/oauthproxy.go index 508084c8..d140f6a7 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -746,6 +746,10 @@ func (p *OAuthProxy) SignOut(rw http.ResponseWriter, req *http.Request) { p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error()) return } + // Call backend logout before clearing the session so we still have the session + // (and id_token) available to invoke the provider's logout endpoint + p.backendLogout(rw, req) + err = p.ClearSessionCookie(rw, req) if err != nil { logger.Errorf("Error clearing session cookie: %v", err) @@ -753,8 +757,6 @@ func (p *OAuthProxy) SignOut(rw http.ResponseWriter, req *http.Request) { return } - p.backendLogout(rw, req) - http.Redirect(rw, req, redirect, http.StatusFound) } diff --git a/oauthproxy_test.go b/oauthproxy_test.go index ccabdbbd..b33bdfe5 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -2028,6 +2028,44 @@ func Test_noCacheHeaders(t *testing.T) { }) } +func TestSignOutCallsBackendLogoutURL(t *testing.T) { + const testIDToken = "test-id-token-12345" + var receivedURL string + backendLogoutServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + receivedURL = req.URL.String() + rw.WriteHeader(http.StatusOK) + })) + defer backendLogoutServer.Close() + + opts := baseTestOptions() + opts.Providers[0].BackendLogoutURL = backendLogoutServer.URL + "/logout?id_token_hint={id_token}" + err := validation.Validate(opts) + require.NoError(t, err) + + proxy, err := NewOAuthProxy(opts, func(string) bool { return true }) + require.NoError(t, err) + + // Save a session with IDToken so backend logout can use it + rw := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/", nil) + err = proxy.sessionStore.Save(rw, req, &sessions.SessionState{ + Email: "user@example.com", + IDToken: testIDToken, + }) + require.NoError(t, err) + cookie := rw.Header().Values("Set-Cookie")[0] + + // Hit sign_out with the session cookie; backend logout should be called before session is cleared + signOutReq := httptest.NewRequest(http.MethodGet, "/oauth2/sign_out", nil) + signOutReq.Header.Set("Cookie", cookie) + rec := httptest.NewRecorder() + proxy.ServeHTTP(rec, signOutReq) + + assert.Equal(t, http.StatusFound, rec.Code, "sign_out should redirect") + assert.Contains(t, receivedURL, "id_token_hint="+testIDToken, + "backend logout URL should have been called with id_token from session") +} + func baseTestOptions() *options.Options { opts := options.NewOptions() opts.Cookie.Secret = rawCookieSecret From 5f446c3e00674f032e2e13491dd7020466701a25 Mon Sep 17 00:00:00 2001 From: Br1an <932039080@qq.com> Date: Sat, 14 Mar 2026 10:08:19 +0800 Subject: [PATCH 10/53] fix(devcontainer): bump Go version to 1.25 in devcontainer base image (#3366) The devcontainer was using Go 1.23 but go.mod requires Go 1.25.0. This caused 'go mod tidy' to fail in the devcontainer environment. Signed-off-by: Jan Larwig --- .devcontainer/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 89d97f30..7b6d5bba 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/vscode/devcontainers/go:1-1.23 +FROM mcr.microsoft.com/vscode/devcontainers/go:1-1.25 SHELL ["/bin/bash", "-o", "pipefail", "-c"] From 566b3aac9ff253f002cfe801664bdfdee7c4a27d Mon Sep 17 00:00:00 2001 From: Francois Botha Date: Sat, 14 Mar 2026 04:36:24 +0200 Subject: [PATCH 11/53] ci: distribute windows binary with .exe extension (#3332) * Ensure Windows binary has .exe extension Signed-off-by: Jan Larwig * doc: add changelog for #3332 Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + dist.sh | 13 ++++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a284fa6..db0be632 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ## Changes since v7.14.3 - [#3352](https://github.com/oauth2-proxy/oauth2-proxy/pull/3352) fix: backend logout URL call on sign out (#3172)(@vsejpal) +- [#3332](https://github.com/oauth2-proxy/oauth2-proxy/pull/3332) ci: distribute windows binary with .exe extension (@igitur) # V7.14.3 diff --git a/dist.sh b/dist.sh index 0990fff2..bcbd2292 100755 --- a/dist.sh +++ b/dist.sh @@ -30,16 +30,23 @@ for ARCH in "${ARCHS[@]}"; do GO_OS=$(echo $ARCH | awk -F- '{print $1}') GO_ARCH=$(echo $ARCH | awk -F- '{print $2}') + # Determine binary name based on OS + if [[ "${GO_OS}" == "windows" ]]; then + BINARY_NAME="${BINARY}.exe" + else + BINARY_NAME="${BINARY}" + fi + # Create architecture specific binaries if [[ ${GO_ARCH} == armv* ]]; then GO_ARM=$(echo $GO_ARCH | awk -Fv '{print $2}') GO111MODULE=on GOOS=${GO_OS} GOARCH=arm GOARM=${GO_ARM} CGO_ENABLED=0 go build \ -ldflags="-X github.com/oauth2-proxy/oauth2-proxy/v7/pkg/version.VERSION=${VERSION}" \ - -o release/${BINARY}-${VERSION}.${ARCH}/${BINARY} . + -o release/${BINARY}-${VERSION}.${ARCH}/${BINARY_NAME} . else GO111MODULE=on GOOS=${GO_OS} GOARCH=${GO_ARCH} CGO_ENABLED=0 go build \ -ldflags="-X github.com/oauth2-proxy/oauth2-proxy/v7/pkg/version.VERSION=${VERSION}" \ - -o release/${BINARY}-${VERSION}.${ARCH}/${BINARY} . + -o release/${BINARY}-${VERSION}.${ARCH}/${BINARY_NAME} . fi cd release @@ -51,7 +58,7 @@ for ARCH in "${ARCHS[@]}"; do sha256sum ${BINARY}-${VERSION}.${ARCH}.tar.gz > ${BINARY}-${VERSION}.${ARCH}.tar.gz-sha256sum.txt # Create sha256sum for architecture specific binary - sha256sum ${BINARY}-${VERSION}.${ARCH}/${BINARY} > ${BINARY}-${VERSION}.${ARCH}-sha256sum.txt + sha256sum ${BINARY}-${VERSION}.${ARCH}/${BINARY_NAME} > ${BINARY}-${VERSION}.${ARCH}-sha256sum.txt cd .. done From 6d272214e1d17e1af79b97195e76e7b4c4e158d2 Mon Sep 17 00:00:00 2001 From: Mridul <111583945+YMridul18@users.noreply.github.com> Date: Sat, 14 Mar 2026 08:28:26 +0530 Subject: [PATCH 12/53] docs: fix plural typo in gitlab provider flag (#3363) * doc: fix plural typo in gitlab provider flag Signed-off-by: Mridul Yadav * doc: fix plural typo in gitlab provider flag in versioned docs Signed-off-by: Jan Larwig --------- Signed-off-by: Mridul Yadav Signed-off-by: Jan Larwig Co-authored-by: Mridul Yadav Co-authored-by: Jan Larwig --- docs/docs/configuration/providers/gitlab.md | 2 +- .../version-7.10.x/configuration/providers/gitlab.md | 2 +- .../version-7.11.x/configuration/providers/gitlab.md | 2 +- .../version-7.12.x/configuration/providers/gitlab.md | 2 +- .../version-7.13.x/configuration/providers/gitlab.md | 2 +- .../version-7.14.x/configuration/providers/gitlab.md | 2 +- .../version-7.6.x/configuration/providers/gitlab.md | 2 +- .../version-7.7.x/configuration/providers/gitlab.md | 2 +- .../version-7.8.x/configuration/providers/gitlab.md | 2 +- .../version-7.9.x/configuration/providers/gitlab.md | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/docs/configuration/providers/gitlab.md b/docs/docs/configuration/providers/gitlab.md index 4cdbbbe1..fe259ab2 100644 --- a/docs/docs/configuration/providers/gitlab.md +++ b/docs/docs/configuration/providers/gitlab.md @@ -8,7 +8,7 @@ title: GitLab | Flag | Toml Field | Type | Description | Default | | ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | -| `--gitlab-projects` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | +| `--gitlab-project` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | ## Usage diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.10.x/configuration/providers/gitlab.md index 4cdbbbe1..fe259ab2 100644 --- a/docs/versioned_docs/version-7.10.x/configuration/providers/gitlab.md +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/gitlab.md @@ -8,7 +8,7 @@ title: GitLab | Flag | Toml Field | Type | Description | Default | | ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | -| `--gitlab-projects` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | +| `--gitlab-project` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | ## Usage diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.11.x/configuration/providers/gitlab.md index 4cdbbbe1..fe259ab2 100644 --- a/docs/versioned_docs/version-7.11.x/configuration/providers/gitlab.md +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/gitlab.md @@ -8,7 +8,7 @@ title: GitLab | Flag | Toml Field | Type | Description | Default | | ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | -| `--gitlab-projects` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | +| `--gitlab-project` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | ## Usage diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.12.x/configuration/providers/gitlab.md index 4cdbbbe1..fe259ab2 100644 --- a/docs/versioned_docs/version-7.12.x/configuration/providers/gitlab.md +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/gitlab.md @@ -8,7 +8,7 @@ title: GitLab | Flag | Toml Field | Type | Description | Default | | ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | -| `--gitlab-projects` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | +| `--gitlab-project` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | ## Usage diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.13.x/configuration/providers/gitlab.md index 4cdbbbe1..fe259ab2 100644 --- a/docs/versioned_docs/version-7.13.x/configuration/providers/gitlab.md +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/gitlab.md @@ -8,7 +8,7 @@ title: GitLab | Flag | Toml Field | Type | Description | Default | | ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | -| `--gitlab-projects` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | +| `--gitlab-project` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | ## Usage diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.14.x/configuration/providers/gitlab.md index 4cdbbbe1..fe259ab2 100644 --- a/docs/versioned_docs/version-7.14.x/configuration/providers/gitlab.md +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/gitlab.md @@ -8,7 +8,7 @@ title: GitLab | Flag | Toml Field | Type | Description | Default | | ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | -| `--gitlab-projects` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | +| `--gitlab-project` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | ## Usage diff --git a/docs/versioned_docs/version-7.6.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.6.x/configuration/providers/gitlab.md index 4cdbbbe1..fe259ab2 100644 --- a/docs/versioned_docs/version-7.6.x/configuration/providers/gitlab.md +++ b/docs/versioned_docs/version-7.6.x/configuration/providers/gitlab.md @@ -8,7 +8,7 @@ title: GitLab | Flag | Toml Field | Type | Description | Default | | ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | -| `--gitlab-projects` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | +| `--gitlab-project` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | ## Usage diff --git a/docs/versioned_docs/version-7.7.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.7.x/configuration/providers/gitlab.md index 4cdbbbe1..fe259ab2 100644 --- a/docs/versioned_docs/version-7.7.x/configuration/providers/gitlab.md +++ b/docs/versioned_docs/version-7.7.x/configuration/providers/gitlab.md @@ -8,7 +8,7 @@ title: GitLab | Flag | Toml Field | Type | Description | Default | | ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | -| `--gitlab-projects` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | +| `--gitlab-project` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | ## Usage diff --git a/docs/versioned_docs/version-7.8.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.8.x/configuration/providers/gitlab.md index 4cdbbbe1..fe259ab2 100644 --- a/docs/versioned_docs/version-7.8.x/configuration/providers/gitlab.md +++ b/docs/versioned_docs/version-7.8.x/configuration/providers/gitlab.md @@ -8,7 +8,7 @@ title: GitLab | Flag | Toml Field | Type | Description | Default | | ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | -| `--gitlab-projects` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | +| `--gitlab-project` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | ## Usage diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.9.x/configuration/providers/gitlab.md index 4cdbbbe1..fe259ab2 100644 --- a/docs/versioned_docs/version-7.9.x/configuration/providers/gitlab.md +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/gitlab.md @@ -8,7 +8,7 @@ title: GitLab | Flag | Toml Field | Type | Description | Default | | ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | -| `--gitlab-projects` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | +| `--gitlab-project` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | ## Usage From c6355ee402ac906aca383f21b8794911a1122d64 Mon Sep 17 00:00:00 2001 From: Nick Nikolakakis Date: Sat, 14 Mar 2026 05:09:25 +0200 Subject: [PATCH 13/53] docs: add statusRewrites to Traefik Errors middleware example (#3360) Add statusRewrites (401 -> 302) to the ForwardAuth with Errors middleware configuration and a troubleshooting note explaining that without it, browsers may show a "Found." link instead of auto-redirecting to the identity provider. Fixes #3359 Signed-off-by: Nick Nikolakakis Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- docs/docs/configuration/integrations/traefik.md | 8 ++++++++ .../version-7.10.x/configuration/integration.md | 8 ++++++++ .../version-7.11.x/configuration/integration.md | 8 ++++++++ .../version-7.12.x/configuration/integration.md | 8 ++++++++ .../version-7.13.x/configuration/integrations/traefik.md | 8 ++++++++ .../version-7.14.x/configuration/integrations/traefik.md | 8 ++++++++ 6 files changed, 48 insertions(+) diff --git a/docs/docs/configuration/integrations/traefik.md b/docs/docs/configuration/integrations/traefik.md index e4b64b94..43830d43 100644 --- a/docs/docs/configuration/integrations/traefik.md +++ b/docs/docs/configuration/integrations/traefik.md @@ -79,8 +79,16 @@ http: - "401-403" service: oauth-backend query: "/oauth2/sign_in?rd={url}" + statusRewrites: + "401": 302 ``` +:::caution Troubleshooting: Browser shows "Found." instead of redirecting +When using the Errors middleware without `statusRewrites`, the redirect response from oauth2-proxy can be served within the original 401/403 status context. This causes some browsers to display a "Found." link instead of automatically following the redirect to the identity provider. + +Adding `statusRewrites` to rewrite `401 -> 302` ensures the browser treats the response as a proper redirect and follows it automatically. +::: + ### ForwardAuth with static upstreams configuration Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint diff --git a/docs/versioned_docs/version-7.10.x/configuration/integration.md b/docs/versioned_docs/version-7.10.x/configuration/integration.md index a5afeda4..181cdbf9 100644 --- a/docs/versioned_docs/version-7.10.x/configuration/integration.md +++ b/docs/versioned_docs/version-7.10.x/configuration/integration.md @@ -225,8 +225,16 @@ http: - "401-403" service: oauth-backend query: "/oauth2/sign_in?rd={url}" + statusRewrites: + "401": 302 ``` +:::info Troubleshooting: Browser shows "Found." instead of redirecting +When using the Errors middleware without `statusRewrites`, the redirect response from oauth2-proxy can be served within the original 401/403 status context. This causes some browsers to display a "Found." link instead of automatically following the redirect to the identity provider. + +Adding `statusRewrites` to rewrite `401 -> 302` ensures the browser treats the response as a proper redirect and follows it automatically. +::: + ### ForwardAuth with static upstreams configuration Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint diff --git a/docs/versioned_docs/version-7.11.x/configuration/integration.md b/docs/versioned_docs/version-7.11.x/configuration/integration.md index a5afeda4..181cdbf9 100644 --- a/docs/versioned_docs/version-7.11.x/configuration/integration.md +++ b/docs/versioned_docs/version-7.11.x/configuration/integration.md @@ -225,8 +225,16 @@ http: - "401-403" service: oauth-backend query: "/oauth2/sign_in?rd={url}" + statusRewrites: + "401": 302 ``` +:::info Troubleshooting: Browser shows "Found." instead of redirecting +When using the Errors middleware without `statusRewrites`, the redirect response from oauth2-proxy can be served within the original 401/403 status context. This causes some browsers to display a "Found." link instead of automatically following the redirect to the identity provider. + +Adding `statusRewrites` to rewrite `401 -> 302` ensures the browser treats the response as a proper redirect and follows it automatically. +::: + ### ForwardAuth with static upstreams configuration Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint diff --git a/docs/versioned_docs/version-7.12.x/configuration/integration.md b/docs/versioned_docs/version-7.12.x/configuration/integration.md index a5afeda4..181cdbf9 100644 --- a/docs/versioned_docs/version-7.12.x/configuration/integration.md +++ b/docs/versioned_docs/version-7.12.x/configuration/integration.md @@ -225,8 +225,16 @@ http: - "401-403" service: oauth-backend query: "/oauth2/sign_in?rd={url}" + statusRewrites: + "401": 302 ``` +:::info Troubleshooting: Browser shows "Found." instead of redirecting +When using the Errors middleware without `statusRewrites`, the redirect response from oauth2-proxy can be served within the original 401/403 status context. This causes some browsers to display a "Found." link instead of automatically following the redirect to the identity provider. + +Adding `statusRewrites` to rewrite `401 -> 302` ensures the browser treats the response as a proper redirect and follows it automatically. +::: + ### ForwardAuth with static upstreams configuration Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint diff --git a/docs/versioned_docs/version-7.13.x/configuration/integrations/traefik.md b/docs/versioned_docs/version-7.13.x/configuration/integrations/traefik.md index e4b64b94..f6ea35f8 100644 --- a/docs/versioned_docs/version-7.13.x/configuration/integrations/traefik.md +++ b/docs/versioned_docs/version-7.13.x/configuration/integrations/traefik.md @@ -79,8 +79,16 @@ http: - "401-403" service: oauth-backend query: "/oauth2/sign_in?rd={url}" + statusRewrites: + "401": 302 ``` +:::info Troubleshooting: Browser shows "Found." instead of redirecting +When using the Errors middleware without `statusRewrites`, the redirect response from oauth2-proxy can be served within the original 401/403 status context. This causes some browsers to display a "Found." link instead of automatically following the redirect to the identity provider. + +Adding `statusRewrites` to rewrite `401 -> 302` ensures the browser treats the response as a proper redirect and follows it automatically. +::: + ### ForwardAuth with static upstreams configuration Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint diff --git a/docs/versioned_docs/version-7.14.x/configuration/integrations/traefik.md b/docs/versioned_docs/version-7.14.x/configuration/integrations/traefik.md index e4b64b94..f6ea35f8 100644 --- a/docs/versioned_docs/version-7.14.x/configuration/integrations/traefik.md +++ b/docs/versioned_docs/version-7.14.x/configuration/integrations/traefik.md @@ -79,8 +79,16 @@ http: - "401-403" service: oauth-backend query: "/oauth2/sign_in?rd={url}" + statusRewrites: + "401": 302 ``` +:::info Troubleshooting: Browser shows "Found." instead of redirecting +When using the Errors middleware without `statusRewrites`, the redirect response from oauth2-proxy can be served within the original 401/403 status context. This causes some browsers to display a "Found." link instead of automatically following the redirect to the identity provider. + +Adding `statusRewrites` to rewrite `401 -> 302` ensures the browser treats the response as a proper redirect and follows it automatically. +::: + ### ForwardAuth with static upstreams configuration Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint From e59f7c1549aeee85e96f771694ac55cf8a594edb Mon Sep 17 00:00:00 2001 From: af su Date: Sat, 14 Mar 2026 12:04:33 +0800 Subject: [PATCH 14/53] feat: allow arbitrary claims from the IDToken and IdentityProvider UserInfo endpoint to be added to the session state (#2685) * feat: support additional claims Signed-off-by: afsu Signed-off-by: af su * docs: clarify that AdditionalClaims may come from id_token or userinfo endpoint Signed-off-by: afsu Signed-off-by: af su * feat: include AdditionalClaims in /oauth2/userinfo response (#834) Signed-off-by: afsu Signed-off-by: af su * refactor: extract coerceClaim logic into util Signed-off-by: afsu Signed-off-by: af su * doc: add changelog entry for #2685 Signed-off-by: Jan Larwig * refactor: added more verbose comments to some struct fields and minor code cleanup Signed-off-by: Jan Larwig --------- Signed-off-by: afsu Signed-off-by: af su Signed-off-by: Jan Larwig Co-authored-by: af su Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + docs/docs/configuration/alpha_config.md | 1 + oauthproxy.go | 10 +-- oauthproxy_test.go | 14 ++++ pkg/apis/options/providers.go | 3 + pkg/apis/sessions/session_state.go | 16 ++++- pkg/apis/sessions/session_state_test.go | 64 +++++++++++++++++ pkg/providers/util/claim_extractor.go | 84 +++------------------- pkg/providers/util/claim_extractor_test.go | 55 +------------- pkg/util/util.go | 64 +++++++++++++++++ pkg/util/util_test.go | 70 ++++++++++++++++++ providers/provider_data.go | 45 ++++++++++-- providers/provider_data_test.go | 23 ++++++ providers/providers.go | 1 + 14 files changed, 314 insertions(+), 137 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index db0be632..0470479c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - [#3352](https://github.com/oauth2-proxy/oauth2-proxy/pull/3352) fix: backend logout URL call on sign out (#3172)(@vsejpal) - [#3332](https://github.com/oauth2-proxy/oauth2-proxy/pull/3332) ci: distribute windows binary with .exe extension (@igitur) +- [#2685](https://github.com/oauth2-proxy/oauth2-proxy/pull/2685) feat: allow arbitrary claims from the IDToken and IdentityProvider UserInfo endpoint to be added to the session state (@vegetablest) # V7.14.3 diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index b4a75582..b92b42f1 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -526,6 +526,7 @@ Provider holds all configuration for a single provider | `scope` | _string_ | Scope is the OAuth scope specification | | `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | | `code_challenge_method` | _string_ | The code challenge method | +| `additionalClaims` | _[]string_ | Additional claims to be obtained from the upstream IDP, either from the id_token or from the userinfo endpoint if configured. | | `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | ### ProviderType diff --git a/oauthproxy.go b/oauthproxy.go index d140f6a7..895f61a2 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -721,15 +721,17 @@ func (p *OAuthProxy) UserInfo(rw http.ResponseWriter, req *http.Request) { } userInfo := struct { - User string `json:"user"` - Email string `json:"email"` - Groups []string `json:"groups,omitempty"` - PreferredUsername string `json:"preferredUsername,omitempty"` + User string `json:"user"` + Email string `json:"email"` + Groups []string `json:"groups,omitempty"` + PreferredUsername string `json:"preferredUsername,omitempty"` + AdditionalClaims map[string]interface{} `json:"additionalClaims,omitempty"` }{ User: session.User, Email: session.Email, Groups: session.Groups, PreferredUsername: session.PreferredUsername, + AdditionalClaims: session.AdditionalClaims, } if err := json.NewEncoder(rw).Encode(userInfo); err != nil { diff --git a/oauthproxy_test.go b/oauthproxy_test.go index b33bdfe5..69951375 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -1032,6 +1032,20 @@ func TestUserInfoEndpointAccepted(t *testing.T) { }, expectedResponse: "{\"user\":\"john.doe\",\"email\":\"john.doe@example.com\",\"groups\":[\"example\",\"groups\"],\"preferredUsername\":\"john\"}\n", }, + { + name: "With Additional Claim", + session: &sessions.SessionState{ + User: "john.doe", + PreferredUsername: "john", + Email: "john.doe@example.com", + Groups: []string{"example", "groups"}, + AccessToken: "my_access_token", + AdditionalClaims: map[string]interface{}{ + "foo": "bar", + }, + }, + expectedResponse: "{\"user\":\"john.doe\",\"email\":\"john.doe@example.com\",\"groups\":[\"example\",\"groups\"],\"preferredUsername\":\"john\",\"additionalClaims\":{\"foo\":\"bar\"}}\n", + }, } for _, tc := range testCases { diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 94bdb592..55965ed9 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -134,6 +134,9 @@ type Provider struct { // The code challenge method CodeChallengeMethod string `yaml:"code_challenge_method,omitempty"` + // Additional claims to be obtained from the upstream IDP, either from the id_token or from the userinfo endpoint if configured. + AdditionalClaims []string `yaml:"additionalClaims,omitempty"` + // URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session BackendLogoutURL string `yaml:"backendLogoutURL"` } diff --git a/pkg/apis/sessions/session_state.go b/pkg/apis/sessions/session_state.go index a1f807ab..fef20aab 100644 --- a/pkg/apis/sessions/session_state.go +++ b/pkg/apis/sessions/session_state.go @@ -8,6 +8,7 @@ import ( "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util" "github.com/pierrec/lz4/v4" "github.com/vmihailenco/msgpack/v5" ) @@ -28,6 +29,9 @@ type SessionState struct { Groups []string `msgpack:"g,omitempty"` PreferredUsername string `msgpack:"pu,omitempty"` + // Additional claims + AdditionalClaims map[string]interface{} `msgpack:"ac,omitempty"` + // Internal helpers, not serialized Clock func() time.Time `msgpack:"-"` // override for time.Now, for testing Lock Lock `msgpack:"-"` @@ -156,10 +160,20 @@ func (s *SessionState) GetClaim(claim string) []string { case "preferred_username": return []string{s.PreferredUsername} default: - return []string{} + return s.getAdditionalClaim(claim) } } +func (s *SessionState) getAdditionalClaim(claim string) []string { + if value, ok := s.AdditionalClaims[claim]; ok { + var result []string + if err := util.CoerceClaim(value, &result); err == nil { + return result + } + } + return []string{} +} + // CheckNonce compares the Nonce against a potential hash of it func (s *SessionState) CheckNonce(hashed string) bool { return encryption.CheckNonce(s.Nonce, hashed) diff --git a/pkg/apis/sessions/session_state_test.go b/pkg/apis/sessions/session_state_test.go index 87b97614..1dc6d3ad 100644 --- a/pkg/apis/sessions/session_state_test.go +++ b/pkg/apis/sessions/session_state_test.go @@ -222,6 +222,23 @@ func TestEncodeAndDecodeSessionState(t *testing.T) { Nonce: []byte("abcdef1234567890abcdef1234567890"), Groups: []string{"group-a", "group-b"}, }, + "With additional claims": { + Email: "username@example.com", + User: "username", + PreferredUsername: "preferred.username", + AccessToken: "AccessToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7", + IDToken: "IDToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7", + CreatedAt: &created, + ExpiresOn: &expires, + RefreshToken: "RefreshToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7", + Nonce: []byte("abcdef1234567890abcdef1234567890"), + Groups: []string{"group-a", "group-b"}, + AdditionalClaims: map[string]interface{}{ + "custom_claim_1": "value1", + "custom_claim_2": true, + "custom_claim_3": []interface{}{"item1", "item2"}, + }, + }, } for _, secretSize := range []int{16, 24, 32} { @@ -289,3 +306,50 @@ func compareSessionStates(t *testing.T, expected *SessionState, actual *SessionS act.ExpiresOn = nil assert.Equal(t, exp, act) } + +func TestGetClaim(t *testing.T) { + createdAt := time.Now() + expiresOn := createdAt.Add(1 * time.Hour) + + ss := &SessionState{ + CreatedAt: &createdAt, + ExpiresOn: &expiresOn, + AccessToken: "AccessToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7", + IDToken: "IDToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7", + RefreshToken: "RefreshToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7", + Email: "user@example.com", + User: "user123", + Groups: []string{"group1", "group2"}, + PreferredUsername: "preferred_user", + AdditionalClaims: map[string]interface{}{ + "custom_claim_1": "value1", + "custom_claim_2": true, + "custom_claim_3": []string{"item1", "item2"}, + }, + } + + tests := []struct { + claim string + want []string + }{ + {"access_token", []string{"AccessToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7"}}, + {"id_token", []string{"IDToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7"}}, + {"refresh_token", []string{"RefreshToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7"}}, + {"created_at", []string{createdAt.String()}}, + {"expires_on", []string{expiresOn.String()}}, + {"email", []string{"user@example.com"}}, + {"user", []string{"user123"}}, + {"groups", []string{"group1", "group2"}}, + {"preferred_username", []string{"preferred_user"}}, + {"custom_claim_1", []string{"value1"}}, + {"custom_claim_2", []string{"true"}}, + {"custom_claim_3", []string{"[\"item1\",\"item2\"]"}}, + } + + for _, tt := range tests { + t.Run(tt.claim, func(t *testing.T) { + gs := NewWithT(t) + gs.Expect(ss.GetClaim(tt.claim)).To(Equal(tt.want)) + }) + } +} diff --git a/pkg/providers/util/claim_extractor.go b/pkg/providers/util/claim_extractor.go index 9ab7a8c8..469a4f54 100644 --- a/pkg/providers/util/claim_extractor.go +++ b/pkg/providers/util/claim_extractor.go @@ -3,7 +3,6 @@ package util import ( "context" "encoding/base64" - "encoding/json" "fmt" "mime" "net/http" @@ -12,17 +11,17 @@ import ( "github.com/bitly/go-simplejson" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" - "github.com/spf13/cast" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util" ) // ClaimExtractor is used to extract claim values from an ID Token, or, if not // present, from the profile URL. type ClaimExtractor interface { // GetClaim fetches a named claim and returns the value. - GetClaim(claim string) (interface{}, bool, error) + GetClaim(claim string) (any, bool, error) // GetClaimInto fetches a named claim and puts the value into the destination. - GetClaimInto(claim string, dst interface{}) (bool, error) + GetClaimInto(claim string, dst any) (bool, error) } // NewClaimExtractor constructs a new ClaimExtractor from the raw ID Token. @@ -31,12 +30,12 @@ type ClaimExtractor interface { func NewClaimExtractor(ctx context.Context, idToken string, profileURL *url.URL, profileRequestHeaders http.Header) (ClaimExtractor, error) { payload, err := parseJWT(idToken) if err != nil { - return nil, fmt.Errorf("failed to parse ID Token: %v", err) + return nil, fmt.Errorf("failed to parse ID Token: %w", err) } tokenClaims, err := simplejson.NewJson(payload) if err != nil { - return nil, fmt.Errorf("failed to parse ID Token payload: %v", err) + return nil, fmt.Errorf("failed to parse ID Token payload: %w", err) } return &claimExtractor{ @@ -59,7 +58,7 @@ type claimExtractor struct { // GetClaim will return the value claim if it exists. // It will only return an error if the profile URL needs to be fetched due to // the claim not being present in the ID Token. -func (c *claimExtractor) GetClaim(claim string) (interface{}, bool, error) { +func (c *claimExtractor) GetClaim(claim string) (any, bool, error) { if claim == "" { return nil, false, nil } @@ -124,7 +123,7 @@ func (c *claimExtractor) loadProfileClaims() (*simplejson.Json, error) { // GetClaimInto loads a claim and places it into the destination interface. // This will attempt to coerce the claim into the specified type. // If it cannot be coerced, an error may be returned. -func (c *claimExtractor) GetClaimInto(claim string, dst interface{}) (bool, error) { +func (c *claimExtractor) GetClaimInto(claim string, dst any) (bool, error) { value, exists, err := c.GetClaim(claim) if err != nil { return false, fmt.Errorf("could not get claim %q: %v", claim, err) @@ -132,8 +131,8 @@ func (c *claimExtractor) GetClaimInto(claim string, dst interface{}) (bool, erro if !exists { return false, nil } - if err := coerceClaim(value, dst); err != nil { - return false, fmt.Errorf("could no coerce claim: %v", err) + if err := util.CoerceClaim(value, dst); err != nil { + return false, fmt.Errorf("could not coerce claim: %v", err) } return true, nil @@ -156,73 +155,10 @@ func parseJWT(p string) ([]byte, error) { // getClaimFrom gets a claim from a Json object. // It can accept either a single claim name or a json path. The claim is always evaluated first as a single claim name. // Paths with indexes are not supported. -func getClaimFrom(claim string, src *simplejson.Json) interface{} { +func getClaimFrom(claim string, src *simplejson.Json) any { if value, ok := src.CheckGet(claim); ok { return value.Interface() } claimParts := strings.Split(claim, ".") return src.GetPath(claimParts...).Interface() } - -// coerceClaim tries to convert the value into the destination interface type. -// If it can convert the value, it will then store the value in the destination -// interface. -func coerceClaim(value, dst interface{}) error { - switch d := dst.(type) { - case *string: - str, err := toString(value) - if err != nil { - return fmt.Errorf("could not convert value to string: %v", err) - } - *d = str - case *[]string: - strSlice, err := toStringSlice(value) - if err != nil { - return fmt.Errorf("could not convert value to string slice: %v", err) - } - *d = strSlice - case *bool: - *d = cast.ToBool(value) - default: - return fmt.Errorf("unknown type for destination: %T", dst) - } - return nil -} - -// toStringSlice converts an interface (either a slice or single value) into -// a slice of strings. -func toStringSlice(value interface{}) ([]string, error) { - var sliceValues []interface{} - switch v := value.(type) { - case []interface{}: - sliceValues = v - case interface{}: - sliceValues = []interface{}{v} - default: - sliceValues = cast.ToSlice(value) - } - - out := []string{} - for _, v := range sliceValues { - str, err := toString(v) - if err != nil { - return nil, fmt.Errorf("could not convert slice entry to string %v: %v", v, err) - } - out = append(out, str) - } - return out, nil -} - -// toString coerces a value into a string. -// If it is non-string, marshal it into JSON. -func toString(value interface{}) (string, error) { - if str, err := cast.ToStringE(value); err == nil { - return str, nil - } - - jsonStr, err := json.Marshal(value) - if err != nil { - return "", err - } - return string(jsonStr), nil -} diff --git a/pkg/providers/util/claim_extractor_test.go b/pkg/providers/util/claim_extractor_test.go index 4ce4606f..57e2e1dc 100644 --- a/pkg/providers/util/claim_extractor_test.go +++ b/pkg/providers/util/claim_extractor_test.go @@ -76,7 +76,7 @@ var _ = Describe("Claim Extractor Suite", func() { func(in newClaimExtractorTableInput) { _, err := NewClaimExtractor(context.Background(), in.idToken, nil, nil) if in.expectedError != nil { - Expect(err).To(MatchError(in.expectedError)) + Expect(err).To(MatchError(in.expectedError.Error())) } else { Expect(err).ToNot(HaveOccurred()) } @@ -405,7 +405,7 @@ var _ = Describe("Claim Extractor Suite", func() { into: "", expectExists: false, expectedValue: "", - expectedError: errors.New("could no coerce claim: unknown type for destination: string"), + expectedError: errors.New("could not coerce claim: unknown type for destination: string"), }), Entry("flattens a complex claim value into a JSON string", getClaimIntoTableInput{ testClaimExtractorOpts: testClaimExtractorOpts{ @@ -451,53 +451,6 @@ var _ = Describe("Claim Extractor Suite", func() { }), ) - type coerceClaimTableInput struct { - value interface{} - dst interface{} - expectedDst interface{} - expectedError error - } - - DescribeTable("coerceClaim", - func(in coerceClaimTableInput) { - err := coerceClaim(in.value, in.dst) - if in.expectedError != nil { - Expect(err).To(MatchError(in.expectedError)) - return - } - - Expect(err).ToNot(HaveOccurred()) - Expect(in.dst).To(Equal(in.expectedDst)) - }, - Entry("coerces a string to a string", coerceClaimTableInput{ - value: "some_string", - dst: stringPointer(""), - expectedDst: stringPointer("some_string"), - }), - Entry("coerces a slice to a string slice", coerceClaimTableInput{ - value: []interface{}{"a", "b"}, - dst: stringSlicePointer([]string{}), - expectedDst: stringSlicePointer([]string{"a", "b"}), - }), - Entry("coerces a bool to a bool", coerceClaimTableInput{ - value: true, - dst: boolPointer(false), - expectedDst: boolPointer(true), - }), - Entry("coerces a string to a bool", coerceClaimTableInput{ - value: "true", - dst: boolPointer(false), - expectedDst: boolPointer(true), - }), - Entry("coerces a map to a string", coerceClaimTableInput{ - value: map[string]interface{}{ - "foo": []interface{}{"bar", "baz"}, - }, - dst: stringPointer(""), - expectedDst: stringPointer("{\"foo\":[\"bar\",\"baz\"]}"), - }), - ) - It("should extract claims from a JWT response", func() { jwtResponsePayload := `{ "user": "jwtUser", @@ -605,10 +558,6 @@ func stringSlicePointer(in []string) *[]string { return &in } -func boolPointer(in bool) *bool { - return &in -} - // ****************************** // Different profile URL handlers // ****************************** diff --git a/pkg/util/util.go b/pkg/util/util.go index 0f3d70ad..207316e7 100644 --- a/pkg/util/util.go +++ b/pkg/util/util.go @@ -5,6 +5,7 @@ import ( "crypto/rsa" "crypto/x509" "crypto/x509/pkix" + "encoding/json" "fmt" "math/big" "net" @@ -12,6 +13,8 @@ import ( "os" "strings" "time" + + "github.com/spf13/cast" ) func GetCertPool(paths []string, useSystemPool bool) (*x509.CertPool, error) { @@ -191,3 +194,64 @@ func RemoveDuplicateStr(strSlice []string) []string { } return list } + +// CoerceClaim tries to convert the value into the destination interface type. +// If it can convert the value, it will then store the value in the destination +// interface. +func CoerceClaim(value, dst any) error { + switch d := dst.(type) { + case *string: + str, err := toString(value) + if err != nil { + return fmt.Errorf("could not convert value to string: %v", err) + } + *d = str + case *[]string: + strSlice, err := toStringSlice(value) + if err != nil { + return fmt.Errorf("could not convert value to string slice: %v", err) + } + *d = strSlice + case *bool: + *d = cast.ToBool(value) + default: + return fmt.Errorf("unknown type for destination: %T", dst) + } + return nil +} + +// toStringSlice converts an interface (either a slice or single value) into +// a slice of strings. +func toStringSlice(value any) ([]string, error) { + var sliceValues []any + switch v := value.(type) { + case []any: + sliceValues = v + default: + sliceValues = []any{v} + } + + out := []string{} + for _, v := range sliceValues { + str, err := toString(v) + if err != nil { + return nil, fmt.Errorf("could not convert slice entry to string %v: %v", v, err) + } + out = append(out, str) + } + return out, nil +} + +// toString coerces a value into a string. +// If it is non-string, marshal it into JSON. +func toString(value any) (string, error) { + if str, err := cast.ToStringE(value); err == nil { + return str, nil + } + + jsonStr, err := json.Marshal(value) + if err != nil { + return "", err + } + return string(jsonStr), nil +} diff --git a/pkg/util/util_test.go b/pkg/util/util_test.go index 167c3e59..d2a2eeca 100644 --- a/pkg/util/util_test.go +++ b/pkg/util/util_test.go @@ -2,10 +2,13 @@ package util import ( "crypto/x509" + "encoding/json" "encoding/pem" "os" + "reflect" "testing" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" "github.com/stretchr/testify/assert" ) @@ -253,3 +256,70 @@ func TestGetCertPool(t *testing.T) { assert.Error(t, err3) } } + +type coerceClaimTableInput struct { + name string + value any + dst any + expectedDst any + expectedError error +} + +func TestCoerceClaim(t *testing.T) { + tests := []coerceClaimTableInput{ + { + name: "coerces a string to a string", + value: "some_string", + dst: ptr.To(""), + expectedDst: ptr.To("some_string"), + }, + { + name: "coerces a slice to a string slice", + value: []any{"a", "b"}, + dst: ptr.To([]string{}), + expectedDst: ptr.To([]string{"a", "b"}), + }, + { + name: "coerces a bool to a bool", + value: true, + dst: ptr.To(false), + expectedDst: ptr.To(true), + }, + { + name: "coerces a string to a bool", + value: "true", + dst: ptr.To(false), + expectedDst: ptr.To(true), + }, + { + name: "coerces a map to a string", + value: map[string]any{ + "foo": []any{"bar", "baz"}, + }, + dst: ptr.To(""), + expectedDst: ptr.To("{\"foo\":[\"bar\",\"baz\"]}"), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := CoerceClaim(tt.value, tt.dst) + if tt.expectedError != nil { + if err == nil || err.Error() != tt.expectedError.Error() { + t.Errorf("expected error %v, got %v", tt.expectedError, err) + } + return + } + + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if !reflect.DeepEqual(tt.dst, tt.expectedDst) { + gotJSON, _ := json.Marshal(tt.dst) + wantJSON, _ := json.Marshal(tt.expectedDst) + t.Errorf("expected dst to be %+v, got %+v", string(wantJSON), string(gotJSON)) + } + }) + } +} diff --git a/providers/provider_data.go b/providers/provider_data.go index 95de5c50..8f9d1e36 100644 --- a/providers/provider_data.go +++ b/providers/provider_data.go @@ -45,11 +45,26 @@ type ProviderData struct { SupportedCodeChallengeMethods []string `json:"code_challenge_methods_supported,omitempty"` // Common OIDC options for any OIDC-based providers to consume - AllowUnverifiedEmail bool - UserClaim string - EmailClaim string - GroupsClaim string - Verifier internaloidc.IDTokenVerifier + AllowUnverifiedEmail bool + + // UserClaim is the claim to use for populating the SessionState.User field. Defaults to "sub" if not set. + UserClaim string + + // EmailClaim is the claim to use for populating the SessionState.Email field. + EmailClaim string + + // GroupsClaim is the claim to use for populating the SessionState.Groups field. + // If not set, groups will not be extracted from the ID Token or userinfo response. + GroupsClaim string + + // Verifier is the OIDC ID Token Verifier to be used by any OIDC-based providers to verify ID Tokens returned by the provider. + // It must be set up by the provider implementation and is not expected to be configured directly by users. + Verifier internaloidc.IDTokenVerifier + + // Additional claims to be obtained from the upstream IDP, either from the id_token or from the userinfo endpoint if configured. + AdditionalClaims []string `json:"additionalClaims,omitempty"` + + // SkipClaimsFromProfileURL indicates that claims should not be fetched from the ProfileURL, even if it is set. SkipClaimsFromProfileURL bool // Universal Group authorization data structure @@ -268,6 +283,10 @@ func (p *ProviderData) buildSessionFromClaims(rawIDToken, accessToken string) (* } } + if p.AdditionalClaims != nil { + p.extractAdditionalClaims(extractor, ss) + } + // `email_verified` must be present and explicitly set to `false` to be // considered unverified. verifyEmail := (p.EmailClaim == options.OIDCEmailClaim) && !p.AllowUnverifiedEmail @@ -301,6 +320,22 @@ func (p *ProviderData) getClaimExtractor(rawIDToken, accessToken string) (util.C return extractor, nil } +func (p *ProviderData) extractAdditionalClaims(extractor util.ClaimExtractor, ss *sessions.SessionState) { + if ss.AdditionalClaims == nil { + ss.AdditionalClaims = make(map[string]any) + } + for _, claim := range p.AdditionalClaims { + value, exists, err := extractor.GetClaim(claim) + if err != nil { + logger.Printf("error extracting additional claim %q: %v", claim, err) + continue + } + if exists { + ss.AdditionalClaims[claim] = value + } + } +} + // checkNonce compares the session's nonce with the IDToken's nonce claim func (p *ProviderData) checkNonce(s *sessions.SessionState) error { extractor, err := p.getClaimExtractor(s.IDToken, "") diff --git a/providers/provider_data_test.go b/providers/provider_data_test.go index 044a77b1..9801d20c 100644 --- a/providers/provider_data_test.go +++ b/providers/provider_data_test.go @@ -237,6 +237,7 @@ func TestProviderData_buildSessionFromClaims(t *testing.T) { ExpectedError error ExpectedSession *sessions.SessionState ExpectProfileURLCalled bool + AdditionalClaims []string }{ "Standard": { IDToken: defaultIDToken, @@ -417,6 +418,27 @@ func TestProviderData_buildSessionFromClaims(t *testing.T) { SkipClaimsFromProfileURL: true, ExpectedSession: &sessions.SessionState{}, }, + "Additional claims": { + IDToken: defaultIDToken, + AdditionalClaims: []string{"phone_number", "picture"}, + ExpectedSession: &sessions.SessionState{ + PreferredUsername: "Jane Dobbs", + AdditionalClaims: map[string]interface{}{ + "phone_number": "+4798765432", + "picture": "http://mugbook.com/janed/me.jpg", + }, + }, + }, + "Additional claims with missing claim": { + IDToken: defaultIDToken, + AdditionalClaims: []string{"phone_number", "picture1"}, + ExpectedSession: &sessions.SessionState{ + PreferredUsername: "Jane Dobbs", + AdditionalClaims: map[string]interface{}{ + "phone_number": "+4798765432", + }, + }, + }, } for testName, tc := range testCases { t.Run(testName, func(t *testing.T) { @@ -453,6 +475,7 @@ func TestProviderData_buildSessionFromClaims(t *testing.T) { provider.EmailClaim = tc.EmailClaim provider.GroupsClaim = tc.GroupsClaim provider.SkipClaimsFromProfileURL = tc.SkipClaimsFromProfileURL + provider.AdditionalClaims = tc.AdditionalClaims rawIDToken, err := newSignedTestIDToken(tc.IDToken) g.Expect(err).ToNot(HaveOccurred()) diff --git a/providers/providers.go b/providers/providers.go index 6af51ecf..85c45ac5 100644 --- a/providers/providers.go +++ b/providers/providers.go @@ -84,6 +84,7 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData, ClientSecret: providerConfig.ClientSecret, ClientSecretFile: providerConfig.ClientSecretFile, AuthRequestResponseMode: providerConfig.AuthRequestResponseMode, + AdditionalClaims: providerConfig.AdditionalClaims, } needsVerifier, err := providerRequiresOIDCProviderVerifier(providerConfig.Type) From 274d7dec4680b74be18ed9c902d5a738a7fb3c83 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Tue, 17 Mar 2026 21:07:53 +0800 Subject: [PATCH 15/53] ci: harden workflows; add trivy scanning; (#3372) Signed-off-by: Jan Larwig --- .github/workflows/ci.yml | 39 +++++++++++++++++++++------ .github/workflows/publish-release.yml | 14 +++++----- 2 files changed, 38 insertions(+), 15 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5c3a18c5..47ca7f93 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,18 +7,21 @@ on: pull_request: branches: - '**' + workflow_dispatch: + permissions: contents: read id-token: write + security-events: write jobs: build: runs-on: ubuntu-latest - env: - COVER: true steps: - name: Check out code uses: actions/checkout@v6 + with: + fetch-depth: 0 - name: Get Go version run: | @@ -33,11 +36,10 @@ jobs: check-latest: true - name: Install golangci-lint - env: - # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.8.0 - run: | - curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} + uses: golangci/golangci-lint-action@v9 + with: + install-only: true + version: v2.8.0 # renovate: datasource=github-tags depName=golangci/golangci-lint - name: Verify Code Generation run: | @@ -59,13 +61,15 @@ jobs: make release - name: Test + env: + COVER: true run: | make test - name: Generate Coverage Report if: github.event_name == 'push' run: | - go install github.com/jandelgado/gcov2lcov@latest + go install github.com/jandelgado/gcov2lcov@25681830fb515e3d4c117e136b4f049e21efb4d0 gcov2lcov -infile=c.out -outfile=lcov.info - name: Upload Coverage Report @@ -75,11 +79,30 @@ jobs: oidc: true files: lcov.info + - name: Run Trivy vulnerability scanner + if: (!startsWith(github.head_ref, 'release')) + uses: aquasecurity/trivy-action@0.35.0 + with: + scan-type: 'rootfs' + scan-ref: './oauth2-proxy' + severity: 'CRITICAL,HIGH' + hide-progress: true + format: 'sarif' + output: 'trivy-results.sarif' + exit-code: '0' + + - name: Upload Trivy scan results + uses: github/codeql-action/upload-sarif@v4 + with: + sarif_file: 'trivy-results.sarif' + docker: runs-on: ubuntu-latest steps: - name: Check out code uses: actions/checkout@v6 + with: + fetch-depth: 0 - name: Set up QEMU uses: docker/setup-qemu-action@v3 diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index f853d8de..4a1f2696 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -55,14 +55,14 @@ jobs: go-version: ${{ steps.go-version.outputs.version }} check-latest: true - - name: Get dependencies - env: - # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.8.0 - run: | - curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} + - name: Install golangci-lint + uses: golangci/golangci-lint-action@v9 + with: + install-only: true + version: v2.8.0 # renovate: datasource=github-tags depName=golangci/golangci-lint - # Install go dependencies + - name: Get go dependencies + run: | go mod download - name: Build Artifacts From 7e225eed2cb72786292b2cc76b846c61b19b2af3 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 17 Mar 2026 21:09:14 +0800 Subject: [PATCH 16/53] chore(deps): update dependency @easyops-cn/docusaurus-search-local to ^0.55.0 (#3356) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- docs/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/package.json b/docs/package.json index bfedb21e..a288a213 100644 --- a/docs/package.json +++ b/docs/package.json @@ -17,7 +17,7 @@ "@docusaurus/core": "^3.3.2", "@docusaurus/preset-classic": "^3.3.2", "@docusaurus/theme-mermaid": "^3.3.2", - "@easyops-cn/docusaurus-search-local": "^0.52.0", + "@easyops-cn/docusaurus-search-local": "^0.55.0", "@mdx-js/react": "^3.0.0", "clsx": "^2.0.0", "prism-react-renderer": "^2.3.0", From 8cb06b7ada3e46bce7c416a72caf611a49912c17 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 17 Mar 2026 21:10:44 +0800 Subject: [PATCH 17/53] chore(deps): update docker-compose (#3320) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/docker-compose-alpha-config.yaml | 4 ++-- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 4 ++-- contrib/local-environment/docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index 6854ef95..4f245f65 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -31,7 +31,7 @@ services: - httpbin dex: container_name: dex - image: ghcr.io/dexidp/dex:v2.44.0 + image: ghcr.io/dexidp/dex:v2.45.1 command: dex serve /dex.yaml hostname: dex volumes: @@ -54,7 +54,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.7 + image: gcr.io/etcd-development/etcd:v3.6.8 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index bb17c752..8190d4ea 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -39,7 +39,7 @@ services: httpbin: {} gitea: - image: gitea/gitea:1.25.3 + image: gitea/gitea:1.25.5 container_name: gitea environment: - USER_UID=1000 diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 113616d6..45758e88 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -55,7 +55,7 @@ services: httpbin: {} dex: container_name: dex - image: ghcr.io/dexidp/dex:v2.44.0 + image: ghcr.io/dexidp/dex:v2.45.1 command: dex serve /dex.yaml hostname: dex volumes: @@ -78,7 +78,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.7 + image: gcr.io/etcd-development/etcd:v3.6.8 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index e4490b3a..73107b7d 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -34,7 +34,7 @@ services: # Reverse proxy gateway: container_name: traefik - image: traefik:v2.11.35 + image: traefik:v2.11.40 volumes: - "./traefik:/etc/traefik" ports: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 1eaba82a..a213544d 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -29,7 +29,7 @@ services: - httpbin dex: container_name: dex - image: ghcr.io/dexidp/dex:v2.44.0 + image: ghcr.io/dexidp/dex:v2.45.1 command: dex serve /dex.yaml hostname: dex volumes: @@ -52,7 +52,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.7 + image: gcr.io/etcd-development/etcd:v3.6.8 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 From 30853098c71dd4088bff9eb4069e7c6e7cee9ef8 Mon Sep 17 00:00:00 2001 From: Alban Fonrouge Date: Wed, 18 Mar 2026 13:19:10 +0100 Subject: [PATCH 18/53] feat: possibility to inject id_token in redirect url during sign out (#3278) * feat: possibility to inject id_token in redirect url during sign out Signed-off-by: Alban Fonrouge * doc: changelog for #3278 Signed-off-by: Jan Larwig * test: fix assertion for TestIdTokenPlaceholderInSignOut Signed-off-by: Jan Larwig --------- Signed-off-by: Alban Fonrouge Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + docs/docs/features/endpoints.md | 14 ++++++++++ oauthproxy.go | 14 +++++++++- oauthproxy_test.go | 47 +++++++++++++++++++++++++++++++++ 4 files changed, 75 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0470479c..d3225c3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - [#3352](https://github.com/oauth2-proxy/oauth2-proxy/pull/3352) fix: backend logout URL call on sign out (#3172)(@vsejpal) - [#3332](https://github.com/oauth2-proxy/oauth2-proxy/pull/3332) ci: distribute windows binary with .exe extension (@igitur) - [#2685](https://github.com/oauth2-proxy/oauth2-proxy/pull/2685) feat: allow arbitrary claims from the IDToken and IdentityProvider UserInfo endpoint to be added to the session state (@vegetablest) +- [#3278](https://github.com/oauth2-proxy/oauth2-proxy/pull/3278) feat: possibility to inject id_token in redirect url during sign out (@albanf) # V7.14.3 diff --git a/docs/docs/features/endpoints.md b/docs/docs/features/endpoints.md index 5befce18..f310e48a 100644 --- a/docs/docs/features/endpoints.md +++ b/docs/docs/features/endpoints.md @@ -38,6 +38,20 @@ X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page BEWARE that the domain you want to redirect to (`my-oidc-provider.example.com` in the example) must be added to the [`--whitelist-domain`](../configuration/overview) configuration option otherwise the redirect will be ignored. Make sure to include the actual domain and port (if needed) and not the URL (e.g "localhost:8081" instead of "http://localhost:8081"). +ID Token can be injected in the redirect url by using `{id_token}` placeholder. For example to redirect to `https://my-oidc-provider.example.com/sign_out_page?id_token_hint={id_token}&post_logout_redirect_uri=https://my-app.example.com`; + +``` +/oauth2/sign_out?rd=https%3A%2F%2Fmy-oidc-provider.example.com%2Fsign_out_page%3Fid_token_hint%3D%7Bid_token%7D%26post_logout_redirect_uri%3Dhttps%3A%2F%2Fmy-app.example.com +``` + +or alternatively in the header: + +``` +GET /oauth2/sign_out HTTP/1.1 +X-Auth-Request-Redirect: https://my-oidc-provider.example.com/sign_out_page?id_token_hint={id_token}&post_logout_redirect_uri=https://my-app.example.com +... +``` + ### Auth This endpoint returns 202 Accepted response or a 401 Unauthorized response. diff --git a/oauthproxy.go b/oauthproxy.go index 895f61a2..1610507b 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -54,6 +54,8 @@ const ( authOnlyPath = "/auth" userInfoPath = "/userinfo" staticPathPrefix = "/static/" + + idTokenPlaceholder = "{id_token}" ) var ( @@ -748,6 +750,16 @@ func (p *OAuthProxy) SignOut(rw http.ResponseWriter, req *http.Request) { p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error()) return } + + if strings.Contains(redirect, idTokenPlaceholder) { + session, err := p.getAuthenticatedSession(rw, req) + if err != nil { + logger.Errorf("error getting authenticated session during SignOut, won't replace id_token placeholder in redirect URL: %v", err) + } else { + redirect = strings.ReplaceAll(redirect, idTokenPlaceholder, session.IDToken) + } + } + // Call backend logout before clearing the session so we still have the session // (and id_token) available to invoke the provider's logout endpoint p.backendLogout(rw, req) @@ -778,7 +790,7 @@ func (p *OAuthProxy) backendLogout(rw http.ResponseWriter, req *http.Request) { return } - backendLogoutURL := strings.ReplaceAll(providerData.BackendLogoutURL, "{id_token}", session.IDToken) + backendLogoutURL := strings.ReplaceAll(providerData.BackendLogoutURL, idTokenPlaceholder, session.IDToken) // security exception because URL is dynamic ({id_token} replacement) but // base is not end-user provided but comes from configuration somewhat secure resp, err := http.Get(backendLogoutURL) // #nosec G107 diff --git a/oauthproxy_test.go b/oauthproxy_test.go index 69951375..38cdccab 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -15,6 +15,7 @@ import ( "time" "github.com/coreos/go-oidc/v3/oidc" + middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/hmacauth" @@ -3583,3 +3584,49 @@ func TestGetOAuthRedirectURI(t *testing.T) { }) } } + +func TestIdTokenPlaceholderInSignOut(t *testing.T) { + opts := baseTestOptions() + opts.WhitelistDomains = []string{"my-oidc-provider.example.com"} + + err := validation.Validate(opts) + assert.NoError(t, err) + + const emailAddress = "john.doe@example.com" + const userName = "9fcab5c9b889a557" + created := time.Now() + + session := &sessions.SessionState{ + User: userName, + Groups: []string{"a", "b"}, + Email: emailAddress, + IDToken: "eYjjjjjj.vvvv.ddd", + AccessToken: "oauth_token", + CreatedAt: &created, + } + + proxy, err := NewOAuthProxy(opts, func(email string) bool { + return true + }) + assert.NoError(t, err) + + // Save the required session + rw := httptest.NewRecorder() + req, _ := http.NewRequest("GET", "/", nil) + err = proxy.sessionStore.Save(rw, req, session) + assert.NoError(t, err) + + rw = httptest.NewRecorder() + + rdUrl := url.QueryEscape("https://my-oidc-provider.example.com/sign_out_page?id_token_hint={id_token}&post_logout_redirect_uri=https://my-app.example.com/") + req, _ = http.NewRequest("GET", "/oauth2/sign_out?rd="+rdUrl, nil) + req = middlewareapi.AddRequestScope(req, &middlewareapi.RequestScope{ + RequestID: "11111111-2222-4333-8444-555555555555", + Session: session, + }) + + proxy.SignOut(rw, req) + newLocation := rw.Header().Values("Location")[0] + + assert.Equal(t, "https://my-oidc-provider.example.com/sign_out_page?id_token_hint=eYjjjjjj.vvvv.ddd&post_logout_redirect_uri=https://my-app.example.com/", newLocation) +} From 7c96234233d7aa192939e90700313cc9c82e7516 Mon Sep 17 00:00:00 2001 From: andoks Date: Wed, 18 Mar 2026 15:24:27 +0100 Subject: [PATCH 19/53] feat: add support for specifying allowed OIDC JWT signing algorithms (#2753) (#2851) * feat: add support for specifying allowed OIDC JWT signing algorithms (#2753) TODO: - [X] update docs - [X] add support in yaml (modern) config - [X] add more test(s)? Add (legacy for now) configuration flag "oidc-enabled-signing-alg" (cfg: oidc_enabled_signing_algs) that allows setting what signing algorithms are specified by provider in JWT header ("alg" header claim). In particular useful when skip_oidc_discovery = true, as verifier defaults to only accept "RS256" in alg field in such circumstances. Signed-off-by: Jan Larwig * doc: update changelog and alpha config Signed-off-by: Jan Larwig * feat: add signing algorithm intersection handling with oidc discovery and additional tests Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + docs/docs/configuration/alpha_config.md | 1 + docs/docs/configuration/overview.md | 3 +- main_test.go | 1 + pkg/apis/options/legacy_options.go | 22 +++-- pkg/apis/options/legacy_options_test.go | 2 + pkg/apis/options/providers.go | 5 ++ pkg/providers/oidc/provider_verifier.go | 37 +++++++- pkg/providers/oidc/provider_verifier_test.go | 92 ++++++++++++++++++++ pkg/validation/providers.go | 33 +++++++ pkg/validation/providers_test.go | 53 +++++++++++ providers/providers.go | 1 + providers/providers_test.go | 90 +++++++++++++++++++ providers/util_test.go | 33 +++++++ 14 files changed, 363 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d3225c3f..9d964685 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - [#3332](https://github.com/oauth2-proxy/oauth2-proxy/pull/3332) ci: distribute windows binary with .exe extension (@igitur) - [#2685](https://github.com/oauth2-proxy/oauth2-proxy/pull/2685) feat: allow arbitrary claims from the IDToken and IdentityProvider UserInfo endpoint to be added to the session state (@vegetablest) - [#3278](https://github.com/oauth2-proxy/oauth2-proxy/pull/3278) feat: possibility to inject id_token in redirect url during sign out (@albanf) +- [#2851](https://github.com/oauth2-proxy/oauth2-proxy/pull/2851) feat: add support for specifying allowed OIDC JWT signing algorithms (#2753) (@andoks / @tuunit) # V7.14.3 diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index b92b42f1..385a9f85 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -488,6 +488,7 @@ character. | `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | | `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | | `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | +| `enabledSigningAlgs` | _[]string_ | EnabledSigningAlgs is a list of allowed JWT signing algorithms.
When discovery is enabled, the effective set is the intersection
between this list and the provider's discovered supported algorithms.
By default `RS256` is used if nothing has been discovered or specified. | ### Provider diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index 7bd7bf07..54ca3776 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -99,7 +99,8 @@ Provider specific options can be found on their respective subpages. | flag: `--oidc-groups-claim`
toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` | | flag: `--oidc-issuer-url`
toml: `oidc_issuer_url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | | | flag: `--oidc-jwks-url`
toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled and public key files are not provided | | -| flag: `--oidc-public-key-file`
toml: `oidc_public_key_files` | string | Path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times). Required if OIDC discovery is disabled na JWKS URL isn't provided | string \| list | +| flag: `--oidc-public-key-file`
toml: `oidc_public_key_files` | string | Path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times). Required if OIDC discovery is disabled na JWKS URL isn't provided | | +| flag: `--oidc-enabled-signing-alg`
toml: `oidc_enabled_signing_algs` | string \| list | List of allowed JWT signing algorithms. When oidc discovery is enabled, the effective set is the intersection between this list and the provider's discovered supported algorithms. | | | flag: `--profile-url`
toml: `profile_url` | string | Profile access endpoint | | | flag: `--prompt`
toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` | | flag: `--provider-ca-file`
toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. | diff --git a/main_test.go b/main_test.go index cbe79683..a90f1a38 100644 --- a/main_test.go +++ b/main_test.go @@ -186,6 +186,7 @@ redirect_url="http://localhost:4180/oauth2/callback" InsecureAllowUnverifiedEmail: ptr.To(false), InsecureSkipIssuerVerification: ptr.To(false), SkipDiscovery: ptr.To(false), + EnabledSigningAlgs: []string{}, }, MicrosoftEntraIDConfig: options.MicrosoftEntraIDOptions{ FederatedTokenAuth: ptr.To(false), diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index b4f37aaf..99e3679f 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -51,15 +51,16 @@ func NewLegacyOptions() *LegacyOptions { }, LegacyProvider: LegacyProvider{ - ProviderType: "google", - AzureTenant: "common", - ApprovalPrompt: "force", - UserIDClaim: "email", - OIDCEmailClaim: "email", - OIDCGroupsClaim: "groups", - OIDCAudienceClaims: []string{"aud"}, - OIDCExtraAudiences: []string{}, - InsecureOIDCSkipNonce: true, + ProviderType: "google", + AzureTenant: "common", + ApprovalPrompt: "force", + UserIDClaim: "email", + OIDCEmailClaim: "email", + OIDCGroupsClaim: "groups", + OIDCAudienceClaims: []string{"aud"}, + OIDCExtraAudiences: []string{}, + OIDCEnabledSigningAlgs: []string{}, + InsecureOIDCSkipNonce: true, }, Options: *NewOptions(), @@ -545,6 +546,7 @@ type LegacyProvider struct { OIDCAudienceClaims []string `flag:"oidc-audience-claim" cfg:"oidc_audience_claims"` OIDCExtraAudiences []string `flag:"oidc-extra-audience" cfg:"oidc_extra_audiences"` OIDCPublicKeyFiles []string `flag:"oidc-public-key-file" cfg:"oidc_public_key_files"` + OIDCEnabledSigningAlgs []string `flag:"oidc-enabled-signing-alg" cfg:"oidc_enabled_signing_algs"` LoginURL string `flag:"login-url" cfg:"login_url"` AuthRequestResponseMode string `flag:"auth-request-response-mode" cfg:"auth_request_response_mode"` RedeemURL string `flag:"redeem-url" cfg:"redeem_url"` @@ -606,6 +608,7 @@ func legacyProviderFlagSet() *pflag.FlagSet { flagSet.StringSlice("oidc-audience-claim", OIDCAudienceClaims, "which OIDC claims are used as audience to verify against client id") flagSet.StringSlice("oidc-extra-audience", []string{}, "additional audiences allowed to pass audience verification") flagSet.StringSlice("oidc-public-key-file", []string{}, "path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times)") + flagSet.StringSlice("oidc-enabled-signing-alg", []string{}, "accepted signing algorithms for provider to use") flagSet.String("login-url", "", "Authentication endpoint") flagSet.String("redeem-url", "", "Token redemption endpoint") flagSet.String("profile-url", "", "Profile access endpoint") @@ -727,6 +730,7 @@ func (l *LegacyProvider) convert() (Providers, error) { AudienceClaims: l.OIDCAudienceClaims, ExtraAudiences: l.OIDCExtraAudiences, PublicKeyFiles: l.OIDCPublicKeyFiles, + EnabledSigningAlgs: l.OIDCEnabledSigningAlgs, } // Support for legacy configuration option diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index d8d14bb0..f6cbfb7c 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -27,6 +27,7 @@ var _ = Describe("Legacy Options", func() { legacyOpts.LegacyUpstreams.Upstreams = []string{"http://foo.bar/baz", "file:///var/lib/website#/bar", "static://204"} legacyOpts.LegacyProvider.ClientID = "oauth-proxy" legacyOpts.LegacyUpstreams.DisableKeepAlives = false + legacyOpts.LegacyProvider.OIDCEnabledSigningAlgs = []string{"RS256", "EdDSA"} staticCode := 204 opts.UpstreamServers = UpstreamConfig{ @@ -128,6 +129,7 @@ var _ = Describe("Legacy Options", func() { opts.Providers[0].OIDCConfig.ExtraAudiences = []string{} opts.Providers[0].OIDCConfig.InsecureSkipNonce = ptr.To(true) opts.Providers[0].OIDCConfig.InsecureSkipIssuerVerification = ptr.To(false) + opts.Providers[0].OIDCConfig.EnabledSigningAlgs = []string{"RS256", "EdDSA"} opts.Providers[0].LoginURLParameters = []LoginURLParameter{ {Name: "approval_prompt", Default: []string{"force"}}, } diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 55965ed9..6f115f8a 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -321,6 +321,11 @@ type OIDCOptions struct { // ExtraAudiences is a list of additional audiences that are allowed // to pass verification in addition to the client id. ExtraAudiences []string `yaml:"extraAudiences,omitempty"` + // EnabledSigningAlgs is a list of allowed JWT signing algorithms. + // When discovery is enabled, the effective set is the intersection + // between this list and the provider's discovered supported algorithms. + // By default `RS256` is used if nothing has been discovered or specified. + EnabledSigningAlgs []string `yaml:"enabledSigningAlgs,omitempty"` } type LoginGovOptions struct { diff --git a/pkg/providers/oidc/provider_verifier.go b/pkg/providers/oidc/provider_verifier.go index eac80a8c..0457a9dc 100644 --- a/pkg/providers/oidc/provider_verifier.go +++ b/pkg/providers/oidc/provider_verifier.go @@ -155,13 +155,48 @@ func getVerifierBuilder(ctx context.Context, opts ProviderVerifierOptions) (veri return nil, nil, fmt.Errorf("error while discovery OIDC configuration: %w", err) } + supportedSigningAlgs, err := intersectSigningAlgs(provider.SupportedSigningAlgs(), opts.SupportedSigningAlgs) + if err != nil { + return nil, nil, fmt.Errorf("error while determining supported signing algorithms: %w", err) + } + return newVerifierBuilder( opts.IssuerURL, oidc.NewRemoteKeySet(ctx, provider.Endpoints().JWKsURL), - provider.SupportedSigningAlgs(), + supportedSigningAlgs, ), provider, nil } +// intersectSigningAlgs returns the intersecting list of signing algorithms from the oidc discovery +// and the signing algorithms provided through the options. +func intersectSigningAlgs(discoveredSigningAlgs, configuredSigningAlgs []string) ([]string, error) { + if len(configuredSigningAlgs) == 0 { + return discoveredSigningAlgs, nil + } + + if len(discoveredSigningAlgs) == 0 { + return configuredSigningAlgs, nil + } + + discovered := make(map[string]struct{}, len(discoveredSigningAlgs)) + for _, signingAlg := range discoveredSigningAlgs { + discovered[signingAlg] = struct{}{} + } + + intersection := make([]string, 0, len(configuredSigningAlgs)) + for _, signingAlg := range configuredSigningAlgs { + if _, ok := discovered[signingAlg]; ok { + intersection = append(intersection, signingAlg) + } + } + + if len(intersection) == 0 { + return nil, fmt.Errorf("no supported signing algorithms in common between provider and configuration: discovered=%v, configured=%v", discoveredSigningAlgs, configuredSigningAlgs) + } + + return intersection, nil +} + // GetPublicKeyFromBytes parses a PEM-encoded public key from a byte array // and returns a crypto.PublicKey object. func getPublicKeyFromBytes(bytes []byte) (crypto.PublicKey, error) { diff --git a/pkg/providers/oidc/provider_verifier_test.go b/pkg/providers/oidc/provider_verifier_test.go index ff91e016..b575a64a 100644 --- a/pkg/providers/oidc/provider_verifier_test.go +++ b/pkg/providers/oidc/provider_verifier_test.go @@ -2,6 +2,9 @@ package oidc import ( "context" + "encoding/json" + "net" + "net/http" "os" "path/filepath" "time" @@ -195,6 +198,21 @@ var _ = Describe("ProviderVerifier", func() { Expect(idToken.Subject).To(Equal(claims.Subject)) }, Entry("with the default opts and claims", &verifierTableInput{}), + Entry("with skip discovery and an allowed signing algorithm", &verifierTableInput{ + modifyOpts: func(p *ProviderVerifierOptions) { + p.SkipDiscovery = true + p.JWKsURL = m.JWKSEndpoint() + p.SupportedSigningAlgs = []string{"RS256"} + }, + }), + Entry("with skip discovery and a disallowed signing algorithm", &verifierTableInput{ + modifyOpts: func(p *ProviderVerifierOptions) { + p.SkipDiscovery = true + p.JWKsURL = m.JWKSEndpoint() + p.SupportedSigningAlgs = []string{"HS256"} + }, + expectedError: "failed to verify token: oidc: malformed jwt: unexpected signature algorithm \"RS256\"; expected [\"HS256\"]", + }), Entry("when the audience is mismatched", &verifierTableInput{ modifyClaims: func(j *jwt.RegisteredClaims) { j.Audience = jwt.ClaimStrings{"OtherClient"} @@ -230,4 +248,78 @@ var _ = Describe("ProviderVerifier", func() { expectedError: "failed to verify token: oidc: token is expired", }), ) + + Describe("intersectSigningAlgs", func() { + DescribeTable("when determining allowed signing algorithms", func(discoveredSigningAlgs, configuredSigningAlgs, expected []string, expectedError string) { + actual, err := intersectSigningAlgs(discoveredSigningAlgs, configuredSigningAlgs) + Expect(actual).To(Equal(expected)) + if len(expectedError) > 0 { + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(Equal(expectedError)) + } + }, + Entry("returns discovered values when no configured values are provided", []string{"RS256", "HS256"}, []string(nil), []string{"RS256", "HS256"}, ""), + Entry("returns configured values when no discovered values are provided", []string(nil), []string{"RS256"}, []string{"RS256"}, ""), + Entry("returns the configured order of the intersection", []string{"RS256", "HS256", "EdDSA"}, []string{"EdDSA", "RS256"}, []string{"EdDSA", "RS256"}, ""), + Entry("returns an error when there is no intersection", []string{"RS256", "HS256"}, []string{"EdDSA"}, nil, "no supported signing algorithms in common between provider and configuration: discovered=[RS256 HS256], configured=[EdDSA]"), + ) + }) + + It("uses the intersection between discovered and configured signing algorithms", func() { + customServer, err := mockoidc.NewServer(nil) + Expect(err).ToNot(HaveOccurred()) + customServer.AddMiddleware(newConfiguredSigningAlgsIssuerMiddleware(customServer, []string{"RS256", "HS256"})) + + listener, err := net.Listen("tcp", "127.0.0.1:0") + Expect(err).ToNot(HaveOccurred()) + + Expect(customServer.Start(listener, nil)).To(Succeed()) + defer func() { + Expect(customServer.Shutdown()).To(Succeed()) + }() + + pv, err := NewProviderVerifier(context.Background(), ProviderVerifierOptions{ + AudienceClaims: []string{"aud"}, + ClientID: customServer.Config().ClientID, + ExtraAudiences: []string{}, + IssuerURL: customServer.Issuer(), + SupportedSigningAlgs: []string{"HS256"}, + }) + Expect(err).ToNot(HaveOccurred()) + + rawIDToken, err := customServer.Keypair.SignJWT(jwt.RegisteredClaims{ + Audience: jwt.ClaimStrings{customServer.Config().ClientID}, + Issuer: customServer.Issuer(), + ExpiresAt: jwt.NewNumericDate(time.Now().Add(1 * time.Hour)), + IssuedAt: jwt.NewNumericDate(time.Now()), + Subject: "user", + }) + Expect(err).ToNot(HaveOccurred()) + + _, err = pv.Verifier().Verify(context.Background(), rawIDToken) + Expect(err).To(MatchError(HavePrefix("failed to verify token: oidc: malformed jwt: unexpected signature algorithm \"RS256\"; expected [\"HS256\"]"))) + }) }) + +func newConfiguredSigningAlgsIssuerMiddleware(m *mockoidc.MockOIDC, supportedSigningAlgs []string) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + provider := providerJSON{ + Issuer: m.Issuer(), + AuthURL: m.AuthorizationEndpoint(), + TokenURL: m.TokenEndpoint(), + JWKsURL: m.JWKSEndpoint(), + UserInfoURL: m.UserinfoEndpoint(), + SupportedSigningAlgs: supportedSigningAlgs, + } + + data, err := json.Marshal(provider) + if err != nil { + rw.WriteHeader(http.StatusInternalServerError) + return + } + + _, _ = rw.Write(data) + }) + } +} diff --git a/pkg/validation/providers.go b/pkg/validation/providers.go index 9e62e98a..ecc3277a 100644 --- a/pkg/validation/providers.go +++ b/pkg/validation/providers.go @@ -4,10 +4,27 @@ import ( "fmt" "os" + jose "github.com/go-jose/go-jose/v4" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) +var supportedOIDCSigningAlgorithms = map[jose.SignatureAlgorithm]struct{}{ + jose.EdDSA: {}, + jose.HS256: {}, + jose.HS384: {}, + jose.HS512: {}, + jose.RS256: {}, + jose.RS384: {}, + jose.RS512: {}, + jose.ES256: {}, + jose.ES384: {}, + jose.ES512: {}, + jose.PS256: {}, + jose.PS384: {}, + jose.PS512: {}, +} + // validateProviders is the initial validation migration for multiple providrers // It currently includes only logic that can verify the providers one by one and does not break the valdation pipe func validateProviders(o *options.Options) []string { @@ -59,6 +76,22 @@ func validateProvider(provider options.Provider, providerIDs map[string]struct{} msgs = append(msgs, validateEntraConfig(provider)...) } + msgs = append(msgs, validateOIDCSigningAlgorithms(provider)...) + + return msgs +} + +func validateOIDCSigningAlgorithms(provider options.Provider) []string { + msgs := []string{} + + for _, algorithm := range provider.OIDCConfig.EnabledSigningAlgs { + if _, ok := supportedOIDCSigningAlgorithms[jose.SignatureAlgorithm(algorithm)]; ok { + continue + } + + msgs = append(msgs, fmt.Sprintf("provider %s has invalid EnabledSigningAlgs entry %q", provider.ID, algorithm)) + } + return msgs } diff --git a/pkg/validation/providers_test.go b/pkg/validation/providers_test.go index 065eb305..3c3531d7 100644 --- a/pkg/validation/providers_test.go +++ b/pkg/validation/providers_test.go @@ -18,6 +18,33 @@ var _ = Describe("Providers", func() { ClientSecret: "ClientSecret", } + validOIDCSigningAlgorithmsProvider := options.Provider{ + ID: "ProviderIDOIDCSigningAlgorithms", + ClientID: "ClientID", + ClientSecret: "ClientSecret", + OIDCConfig: options.OIDCOptions{ + EnabledSigningAlgs: []string{"RS256", "EdDSA"}, + }, + } + + invalidOIDCSigningAlgorithmsProvider := options.Provider{ + ID: "ProviderIDInvalidOIDCSigningAlgorithms", + ClientID: "ClientID", + ClientSecret: "ClientSecret", + OIDCConfig: options.OIDCOptions{ + EnabledSigningAlgs: []string{"RS256", "invalid"}, + }, + } + + invalidOIDCSigningAlgorithmCaseProvider := options.Provider{ + ID: "ProviderIDInvalidOIDCSigningAlgorithmCase", + ClientID: "ClientID", + ClientSecret: "ClientSecret", + OIDCConfig: options.OIDCOptions{ + EnabledSigningAlgs: []string{"rs256"}, + }, + } + validLoginGovProvider := options.Provider{ Type: "login.gov", ID: "ProviderIDLoginGov", @@ -34,6 +61,8 @@ var _ = Describe("Providers", func() { emptyIDMsg := "provider has empty id: ids are required for all providers" duplicateProviderIDMsg := "multiple providers found with id ProviderID: provider ids must be unique" skipButtonAndMultipleProvidersMsg := "SkipProviderButton and multiple providers are mutually exclusive" + invalidOIDCSigningAlgorithmMsg := "provider ProviderIDInvalidOIDCSigningAlgorithms has invalid EnabledSigningAlgs entry \"invalid\"" + invalidOIDCSigningAlgorithmCaseMsg := "provider ProviderIDInvalidOIDCSigningAlgorithmCase has invalid EnabledSigningAlgs entry \"rs256\"" DescribeTable("validateProviders", func(o *validateProvidersTableInput) { @@ -79,5 +108,29 @@ var _ = Describe("Providers", func() { }, errStrings: []string{skipButtonAndMultipleProvidersMsg}, }), + Entry("with valid OIDC signing algorithms", &validateProvidersTableInput{ + options: &options.Options{ + Providers: options.Providers{ + validOIDCSigningAlgorithmsProvider, + }, + }, + errStrings: []string{}, + }), + Entry("with an invalid OIDC signing algorithm", &validateProvidersTableInput{ + options: &options.Options{ + Providers: options.Providers{ + invalidOIDCSigningAlgorithmsProvider, + }, + }, + errStrings: []string{invalidOIDCSigningAlgorithmMsg}, + }), + Entry("with an OIDC signing algorithm using invalid casing", &validateProvidersTableInput{ + options: &options.Options{ + Providers: options.Providers{ + invalidOIDCSigningAlgorithmCaseProvider, + }, + }, + errStrings: []string{invalidOIDCSigningAlgorithmCaseMsg}, + }), ) }) diff --git a/providers/providers.go b/providers/providers.go index 85c45ac5..f87d26a2 100644 --- a/providers/providers.go +++ b/providers/providers.go @@ -100,6 +100,7 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData, IssuerURL: providerConfig.OIDCConfig.IssuerURL, JWKsURL: providerConfig.OIDCConfig.JwksURL, PublicKeyFiles: providerConfig.OIDCConfig.PublicKeyFiles, + SupportedSigningAlgs: providerConfig.OIDCConfig.EnabledSigningAlgs, SkipDiscovery: ptr.Deref(providerConfig.OIDCConfig.SkipDiscovery, options.DefaultSkipDiscovery), SkipIssuerVerification: ptr.Deref(providerConfig.OIDCConfig.InsecureSkipIssuerVerification, options.DefaultInsecureSkipIssuerVerification), }) diff --git a/providers/providers_test.go b/providers/providers_test.go index 8e3b8d77..a0e7fd7e 100644 --- a/providers/providers_test.go +++ b/providers/providers_test.go @@ -1,9 +1,14 @@ package providers import ( + "context" + "net" "os" "testing" + "time" + "github.com/golang-jwt/jwt/v5" + "github.com/oauth2-proxy/mockoidc" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/gomega" @@ -121,6 +126,91 @@ func TestURLsCorrectlyParsed(t *testing.T) { g.Expect(pd.RedeemURL.String()).To(Equal(msTokenURL)) } +func TestEnabledSigningAlgsAreAppliedToProviderVerifier(t *testing.T) { + g := NewWithT(t) + + m, err := mockoidc.NewServer(nil) + g.Expect(err).ToNot(HaveOccurred()) + m.AddMiddleware(newSigningAlgsIssuerMiddleware(m, []string{"RS256", "HS256"})) + + listener, err := net.Listen("tcp", "127.0.0.1:0") + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(m.Start(listener, nil)).To(Succeed()) + defer func() { + g.Expect(m.Shutdown()).To(Succeed()) + }() + + providerConfig := options.Provider{ + ID: providerID, + Type: "oidc", + ClientID: m.Config().ClientID, + ClientSecretFile: clientSecret, + OIDCConfig: options.OIDCOptions{ + IssuerURL: m.Issuer(), + AudienceClaims: []string{"aud"}, + EnabledSigningAlgs: []string{"HS256"}, + }, + } + + pd, err := newProviderDataFromConfig(providerConfig) + g.Expect(err).ToNot(HaveOccurred()) + + rawIDToken, err := m.Keypair.SignJWT(jwt.RegisteredClaims{ + Audience: jwt.ClaimStrings{m.Config().ClientID}, + Issuer: m.Issuer(), + ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)), + IssuedAt: jwt.NewNumericDate(time.Now()), + Subject: "user", + }) + g.Expect(err).ToNot(HaveOccurred()) + + _, err = pd.Verifier.Verify(context.Background(), rawIDToken) + g.Expect(err).To(HaveOccurred()) + g.Expect(err.Error()).To(ContainSubstring("unexpected signature algorithm")) +} + +func TestEnabledSigningAlgsRejectUnsupportedTokens(t *testing.T) { + g := NewWithT(t) + + m, err := mockoidc.Run() + g.Expect(err).ToNot(HaveOccurred()) + defer func() { + g.Expect(m.Shutdown()).To(Succeed()) + }() + + providerConfig := options.Provider{ + ID: providerID, + Type: "oidc", + ClientID: m.Config().ClientID, + ClientSecretFile: clientSecret, + LoginURL: m.AuthorizationEndpoint(), + RedeemURL: m.TokenEndpoint(), + OIDCConfig: options.OIDCOptions{ + IssuerURL: m.Issuer(), + SkipDiscovery: ptr.To(true), + JwksURL: m.JWKSEndpoint(), + AudienceClaims: []string{"aud"}, + EnabledSigningAlgs: []string{"HS256"}, + }, + } + + pd, err := newProviderDataFromConfig(providerConfig) + g.Expect(err).ToNot(HaveOccurred()) + + rawIDToken, err := m.Keypair.SignJWT(jwt.RegisteredClaims{ + Audience: jwt.ClaimStrings{m.Config().ClientID}, + Issuer: m.Issuer(), + ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)), + IssuedAt: jwt.NewNumericDate(time.Now()), + Subject: "user", + }) + g.Expect(err).ToNot(HaveOccurred()) + + _, err = pd.Verifier.Verify(context.Background(), rawIDToken) + g.Expect(err).To(HaveOccurred()) + g.Expect(err.Error()).To(ContainSubstring("unexpected signature algorithm")) +} + func TestScope(t *testing.T) { g := NewWithT(t) diff --git a/providers/util_test.go b/providers/util_test.go index e14ff061..5e5ccbf2 100644 --- a/providers/util_test.go +++ b/providers/util_test.go @@ -1,9 +1,12 @@ package providers import ( + "encoding/json" "fmt" + "net/http" "testing" + "github.com/oauth2-proxy/mockoidc" . "github.com/onsi/gomega" "golang.org/x/oauth2" ) @@ -111,3 +114,33 @@ func Test_formatGroup(t *testing.T) { }) } } + +func newSigningAlgsIssuerMiddleware(m *mockoidc.MockOIDC, supportedSigningAlgs []string) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + provider := struct { + Issuer string `json:"issuer"` + AuthURL string `json:"authorization_endpoint"` + TokenURL string `json:"token_endpoint"` + JWKsURL string `json:"jwks_uri"` + UserInfoURL string `json:"userinfo_endpoint"` + SupportedSigningAlgs []string `json:"id_token_signing_alg_values_supported"` + }{ + Issuer: m.Issuer(), + AuthURL: m.AuthorizationEndpoint(), + TokenURL: m.TokenEndpoint(), + JWKsURL: m.JWKSEndpoint(), + UserInfoURL: m.UserinfoEndpoint(), + SupportedSigningAlgs: supportedSigningAlgs, + } + + data, err := json.Marshal(provider) + if err != nil { + rw.WriteHeader(http.StatusInternalServerError) + return + } + + _, _ = rw.Write(data) + }) + } +} From ff357daa045a5a4622f5ac73cb9a45d15bf8accc Mon Sep 17 00:00:00 2001 From: Br1an <932039080@qq.com> Date: Wed, 18 Mar 2026 22:30:07 +0800 Subject: [PATCH 20/53] fix: use CSRFExpire instead of Expire for CSRF cookie validation (#3369) * fix: use CSRFExpire instead of Expire for CSRF cookie validation Signed-off-by: Br1an67 <932039080@qq.com> * doc: add changelog entry for #3369 Signed-off-by: Jan Larwig --------- Signed-off-by: Br1an67 <932039080@qq.com> Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + pkg/cookies/csrf.go | 2 +- pkg/cookies/csrf_test.go | 26 +++++++++++++++++++++++++- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d964685..1477c99d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ - [#2685](https://github.com/oauth2-proxy/oauth2-proxy/pull/2685) feat: allow arbitrary claims from the IDToken and IdentityProvider UserInfo endpoint to be added to the session state (@vegetablest) - [#3278](https://github.com/oauth2-proxy/oauth2-proxy/pull/3278) feat: possibility to inject id_token in redirect url during sign out (@albanf) - [#2851](https://github.com/oauth2-proxy/oauth2-proxy/pull/2851) feat: add support for specifying allowed OIDC JWT signing algorithms (#2753) (@andoks / @tuunit) +- [#3369](https://github.com/oauth2-proxy/oauth2-proxy/pull/3369) fix: use CSRFExpire instead of Expire for CSRF cookie validation (@Br1an67) # V7.14.3 diff --git a/pkg/cookies/csrf.go b/pkg/cookies/csrf.go index 939578a2..6fc55716 100644 --- a/pkg/cookies/csrf.go +++ b/pkg/cookies/csrf.go @@ -234,7 +234,7 @@ func decodeCSRFCookie(cookie *http.Cookie, opts *options.Cookie) (*csrf, error) return nil, fmt.Errorf("error getting cookie secret: %v", err) } - val, t, ok := encryption.Validate(cookie, secret, opts.Expire) + val, t, ok := encryption.Validate(cookie, secret, opts.CSRFExpire) if !ok { return nil, errors.New("CSRF cookie failed validation") } diff --git a/pkg/cookies/csrf_test.go b/pkg/cookies/csrf_test.go index 085b91df..f791045d 100644 --- a/pkg/cookies/csrf_test.go +++ b/pkg/cookies/csrf_test.go @@ -119,9 +119,33 @@ var _ = Describe("CSRF Cookie Tests", func() { Value: encoded, } - _, _, valid := encryption.Validate(cookie, cookieOpts.Secret, cookieOpts.Expire) + _, _, valid := encryption.Validate(cookie, cookieOpts.Secret, cookieOpts.CSRFExpire) Expect(valid).To(BeTrue()) }) + + It("validates CSRF token using CSRFExpire when Expire is lower", func() { + // Set Expire to be much lower than CSRFExpire + cookieOpts.Expire = time.Second + cookieOpts.CSRFExpire = time.Hour + + privateCSRF.OAuthState = []byte(csrfState) + privateCSRF.OIDCNonce = []byte(csrfNonce) + + encoded, err := privateCSRF.encodeCookie() + Expect(err).ToNot(HaveOccurred()) + + cookie := &http.Cookie{ + Name: privateCSRF.cookieName(), + Value: encoded, + } + + // The cookie should still be valid even though Expire is only 1 second + decoded, err := decodeCSRFCookie(cookie, cookieOpts) + Expect(err).ToNot(HaveOccurred()) + Expect(decoded).ToNot(BeNil()) + Expect(decoded.OAuthState).To(Equal([]byte(csrfState))) + Expect(decoded.OIDCNonce).To(Equal([]byte(csrfNonce))) + }) }) Context("Cookie Management", func() { From 779cc5f350951b67169aec9836b3495f4faf80df Mon Sep 17 00:00:00 2001 From: Br1an <932039080@qq.com> Date: Wed, 18 Mar 2026 22:44:11 +0800 Subject: [PATCH 21/53] fix: filter empty strings from allowed groups (#3365) * fix: filter empty strings from allowed groups When parsing allowed groups from configuration (e.g., via environment variable OAUTH2_PROXY_ALLOWED_GROUPS), viper may include empty strings in the parsed slice when trailing commas are present (e.g., "group2," becomes ["group2", ""]). The setAllowedGroups function now filters out empty strings before adding them to the AllowedGroups map, ensuring that only valid group names are checked during authorization. Fixes #3123 Signed-off-by: Br1an67 <932039080@qq.com> * refactor: minor change Signed-off-by: Jan Larwig * doc: add changelog entry for 3365 Signed-off-by: Jan Larwig --------- Signed-off-by: Br1an67 <932039080@qq.com> Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + providers/provider_data.go | 4 ++++ providers/provider_default_test.go | 12 ++++++++++++ 3 files changed, 17 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1477c99d..967455db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ - [#3278](https://github.com/oauth2-proxy/oauth2-proxy/pull/3278) feat: possibility to inject id_token in redirect url during sign out (@albanf) - [#2851](https://github.com/oauth2-proxy/oauth2-proxy/pull/2851) feat: add support for specifying allowed OIDC JWT signing algorithms (#2753) (@andoks / @tuunit) - [#3369](https://github.com/oauth2-proxy/oauth2-proxy/pull/3369) fix: use CSRFExpire instead of Expire for CSRF cookie validation (@Br1an67) +- [#3365](https://github.com/oauth2-proxy/oauth2-proxy/pull/3365) fix: filter empty strings from allowed groups (@Br1an67) # V7.14.3 diff --git a/providers/provider_data.go b/providers/provider_data.go index 8f9d1e36..80bd77ae 100644 --- a/providers/provider_data.go +++ b/providers/provider_data.go @@ -194,6 +194,10 @@ func regexpForRule(rule options.URLParameterRule) string { func (p *ProviderData) setAllowedGroups(groups []string) { p.AllowedGroups = make(map[string]struct{}, len(groups)) for _, group := range groups { + if len(group) == 0 { + continue + } + p.AllowedGroups[group] = struct{}{} } } diff --git a/providers/provider_default_test.go b/providers/provider_default_test.go index 0fbe7abd..9370cdca 100644 --- a/providers/provider_default_test.go +++ b/providers/provider_default_test.go @@ -102,6 +102,18 @@ func TestProviderDataAuthorize(t *testing.T) { groups: []string{"baz", "foo"}, expectedAuthZ: false, }, + { + name: "AllowedGroupsWithEmptyString", + allowedGroups: []string{"group2", ""}, + groups: []string{"group1", "group2"}, + expectedAuthZ: true, + }, + { + name: "AllowedGroupsOnlyEmptyString", + allowedGroups: []string{""}, + groups: []string{"group1", "group2"}, + expectedAuthZ: true, + }, } for _, tc := range testCases { From fe5c6becec9291ee95aee9306880b8ecd186e12b Mon Sep 17 00:00:00 2001 From: Ganesh Jagadeesan Date: Wed, 18 Mar 2026 10:46:31 -0400 Subject: [PATCH 22/53] doc: add missing redis-ca-path documentation (#3341) Signed-off-by: Ganesh Jagadeesan Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- docs/docs/configuration/overview.md | 1 + docs/versioned_docs/version-7.10.x/configuration/overview.md | 1 + docs/versioned_docs/version-7.11.x/configuration/overview.md | 1 + docs/versioned_docs/version-7.12.x/configuration/overview.md | 1 + docs/versioned_docs/version-7.13.x/configuration/overview.md | 1 + docs/versioned_docs/version-7.14.x/configuration/overview.md | 1 + docs/versioned_docs/version-7.6.x/configuration/overview.md | 1 + docs/versioned_docs/version-7.7.x/configuration/overview.md | 1 + docs/versioned_docs/version-7.8.x/configuration/overview.md | 1 + docs/versioned_docs/version-7.9.x/configuration/overview.md | 1 + 10 files changed, 10 insertions(+) diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index 54ca3776..b4786cf7 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -245,6 +245,7 @@ Provider specific options can be found on their respective subpages. | flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | | flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | | flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-ca-path`
toml: `redis_ca_path` | string | Path to a CA certificates file that should be used when connecting to redis. If not specified, the system cert pool is used instead. | | | flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | | flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | | flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | diff --git a/docs/versioned_docs/version-7.10.x/configuration/overview.md b/docs/versioned_docs/version-7.10.x/configuration/overview.md index bea70617..e29fbf04 100644 --- a/docs/versioned_docs/version-7.10.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.10.x/configuration/overview.md @@ -241,6 +241,7 @@ Provider specific options can be found on their respective subpages. | flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | | flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | | flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-ca-path`
toml: `redis_ca_path` | string | Path to a CA certificates file that should be used when connecting to redis. If not specified, the system cert pool is used instead. | | flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | | flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | | flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | diff --git a/docs/versioned_docs/version-7.11.x/configuration/overview.md b/docs/versioned_docs/version-7.11.x/configuration/overview.md index 7c216dfb..83aaf2f5 100644 --- a/docs/versioned_docs/version-7.11.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.11.x/configuration/overview.md @@ -244,6 +244,7 @@ Provider specific options can be found on their respective subpages. | flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | | flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | | flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-ca-path`
toml: `redis_ca_path` | string | Path to a CA certificates file that should be used when connecting to redis. If not specified, the system cert pool is used instead. | | flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | | flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | | flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | diff --git a/docs/versioned_docs/version-7.12.x/configuration/overview.md b/docs/versioned_docs/version-7.12.x/configuration/overview.md index 7bd7bf07..73a58819 100644 --- a/docs/versioned_docs/version-7.12.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.12.x/configuration/overview.md @@ -244,6 +244,7 @@ Provider specific options can be found on their respective subpages. | flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | | flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | | flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-ca-path`
toml: `redis_ca_path` | string | Path to a CA certificates file that should be used when connecting to redis. If not specified, the system cert pool is used instead. | | flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | | flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | | flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | diff --git a/docs/versioned_docs/version-7.13.x/configuration/overview.md b/docs/versioned_docs/version-7.13.x/configuration/overview.md index 7bd7bf07..73a58819 100644 --- a/docs/versioned_docs/version-7.13.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.13.x/configuration/overview.md @@ -244,6 +244,7 @@ Provider specific options can be found on their respective subpages. | flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | | flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | | flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-ca-path`
toml: `redis_ca_path` | string | Path to a CA certificates file that should be used when connecting to redis. If not specified, the system cert pool is used instead. | | flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | | flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | | flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | diff --git a/docs/versioned_docs/version-7.14.x/configuration/overview.md b/docs/versioned_docs/version-7.14.x/configuration/overview.md index 7bd7bf07..73a58819 100644 --- a/docs/versioned_docs/version-7.14.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.14.x/configuration/overview.md @@ -244,6 +244,7 @@ Provider specific options can be found on their respective subpages. | flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | | flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | | flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-ca-path`
toml: `redis_ca_path` | string | Path to a CA certificates file that should be used when connecting to redis. If not specified, the system cert pool is used instead. | | flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | | flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | | flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | diff --git a/docs/versioned_docs/version-7.6.x/configuration/overview.md b/docs/versioned_docs/version-7.6.x/configuration/overview.md index b7891156..872ae908 100644 --- a/docs/versioned_docs/version-7.6.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.6.x/configuration/overview.md @@ -237,6 +237,7 @@ Provider specific options can be found on their respective subpages. | flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | | flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | | flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-ca-path`
toml: `redis_ca_path` | string | Path to a CA certificates file that should be used when connecting to redis. If not specified, the system cert pool is used instead. | | flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | | flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | | flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | diff --git a/docs/versioned_docs/version-7.7.x/configuration/overview.md b/docs/versioned_docs/version-7.7.x/configuration/overview.md index 7c7b396f..5340cac2 100644 --- a/docs/versioned_docs/version-7.7.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.7.x/configuration/overview.md @@ -237,6 +237,7 @@ Provider specific options can be found on their respective subpages. | flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | | flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | | flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-ca-path`
toml: `redis_ca_path` | string | Path to a CA certificates file that should be used when connecting to redis. If not specified, the system cert pool is used instead. | | flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | | flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | | flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | diff --git a/docs/versioned_docs/version-7.8.x/configuration/overview.md b/docs/versioned_docs/version-7.8.x/configuration/overview.md index 97b166df..b940013c 100644 --- a/docs/versioned_docs/version-7.8.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.8.x/configuration/overview.md @@ -239,6 +239,7 @@ Provider specific options can be found on their respective subpages. | flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | | flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | | flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-ca-path`
toml: `redis_ca_path` | string | Path to a CA certificates file that should be used when connecting to redis. If not specified, the system cert pool is used instead. | | flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | | flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | | flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | diff --git a/docs/versioned_docs/version-7.9.x/configuration/overview.md b/docs/versioned_docs/version-7.9.x/configuration/overview.md index bea70617..e29fbf04 100644 --- a/docs/versioned_docs/version-7.9.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.9.x/configuration/overview.md @@ -241,6 +241,7 @@ Provider specific options can be found on their respective subpages. | flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | | flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | | flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-ca-path`
toml: `redis_ca_path` | string | Path to a CA certificates file that should be used when connecting to redis. If not specified, the system cert pool is used instead. | | flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | | flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | | flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | From 51ecc50372c42299749dafb225dee42df3520755 Mon Sep 17 00:00:00 2001 From: Mayowa Fajobi <127399119+MayorFaj@users.noreply.github.com> Date: Wed, 18 Mar 2026 15:00:07 +0000 Subject: [PATCH 23/53] feat: add --config-test flag for validating configuration (#3338) * feat: add --config-test flag for validating configuration without starting the proxy Signed-off-by: MayorFaj * doc: fix alpha config and add changelog entry for #3338 Signed-off-by: Jan Larwig --------- Signed-off-by: MayorFaj Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- .golangci.yml | 5 ++ CHANGELOG.md | 1 + docs/docs/configuration/alpha_config.md | 11 +++ docs/docs/configuration/alpha_config.md.tmpl | 11 +++ docs/docs/configuration/overview.md | 45 ++++++++++-- main.go | 14 ++++ main_test.go | 75 ++++++++++++++++++++ 7 files changed, 158 insertions(+), 4 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 31f4b033..2f4ee6ea 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -53,6 +53,11 @@ linters: - revive path: util/.*\.go$ text: "var-naming: avoid meaningless package names" + # pkg/version conflicts with go/version (added in Go 1.22) + - linters: + - revive + path: pkg/version/.*\.go$ + text: "var-naming: avoid package names that conflict with" - linters: - prealloc path: _test\.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 967455db..c3a95f7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ - [#2851](https://github.com/oauth2-proxy/oauth2-proxy/pull/2851) feat: add support for specifying allowed OIDC JWT signing algorithms (#2753) (@andoks / @tuunit) - [#3369](https://github.com/oauth2-proxy/oauth2-proxy/pull/3369) fix: use CSRFExpire instead of Expire for CSRF cookie validation (@Br1an67) - [#3365](https://github.com/oauth2-proxy/oauth2-proxy/pull/3365) fix: filter empty strings from allowed groups (@Br1an67) +- [#3338](https://github.com/oauth2-proxy/oauth2-proxy/pull/3338) feat: add --config-test flag for validating configuration (@MayorFaj) # V7.14.3 diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index 385a9f85..d8cce916 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -106,6 +106,17 @@ the new config. oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg ``` +### Validating Alpha Configuration + +Use `--config-test` to validate your alpha configuration without starting the proxy: + +```bash +oauth2-proxy --config core.cfg --alpha-config alpha.yaml --config-test +``` + +This is useful for CI/CD pipelines to catch configuration errors before deployment. +See the [Configuration Validation](./overview.md#configuration-validation) section for more details. + ### How to use environment variables The alpha package supports the use of environment variables in place of yaml values, allowing sensitive data to be pulled from somewhere other than the yaml file. diff --git a/docs/docs/configuration/alpha_config.md.tmpl b/docs/docs/configuration/alpha_config.md.tmpl index 081657c4..2a9684da 100644 --- a/docs/docs/configuration/alpha_config.md.tmpl +++ b/docs/docs/configuration/alpha_config.md.tmpl @@ -106,6 +106,17 @@ the new config. oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg ``` +### Validating Alpha Configuration + +Use `--config-test` to validate your alpha configuration without starting the proxy: + +```bash +oauth2-proxy --config core.cfg --alpha-config alpha.yaml --config-test +``` + +This is useful for CI/CD pipelines to catch configuration errors before deployment. +See the [Configuration Validation](./overview.md#configuration-validation) section for more details. + ### How to use environment variables The alpha package supports the use of environment variables in place of yaml values, allowing sensitive data to be pulled from somewhere other than the yaml file. diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index b4786cf7..7d8a1c09 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -66,11 +66,48 @@ An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/ ### Command Line Options -| Flag | Description | -| ----------- | -------------------- | -| `--config` | path to config file | -| `--version` | print version string | +| Flag | Description | +| ---------------- | ------------------------------------------------------- | +| `--config` | path to config file | +| `--config-test` | test configuration and exit (for CI/CD validation) | +| `--version` | print version string | +## Configuration Validation + +The `--config-test` flag validates your configuration file without starting the proxy server. This is useful for: +- **CI/CD pipelines**: Pre-deployment validation +- **Configuration management**: Testing before applying changes +- **Debugging**: Verifying syntax and required fields + +### Usage + +```bash +# Test legacy config +oauth2-proxy --config /etc/oauth2-proxy.cfg --config-test + +# Test alpha config +oauth2-proxy --config /etc/core.cfg --alpha-config /etc/alpha.yaml --config-test + +# CI/CD pre-deployment check +# Returns with exit code 1 if any validation errors occur +oauth2-proxy --config new-config.cfg --config-test +``` + +### Exit Codes + +- **0**: Configuration is valid ✅ +- **1**: Configuration is invalid (errors printed to stderr) ❌ + +### Validation Coverage + +The `--config-test` flag performs the **same comprehensive validation** as normal startup, including: +- Required fields (client ID, client secret, cookie secret, etc.) +- Syntax validation (TOML/YAML parsing) +- Provider configuration +- Upstream server definitions +- Session store connectivity (e.g., Redis network checks if configured) + +**Note**: Cannot be combined with `--convert-config-to-alpha`. ### General Provider Options diff --git a/main.go b/main.go index 42e8bab0..ba970679 100644 --- a/main.go +++ b/main.go @@ -26,6 +26,7 @@ func main() { alphaConfig := configFlagSet.String("alpha-config", "", "path to alpha config file (use at your own risk - the structure in this config file may change between minor releases)") convertConfig := configFlagSet.Bool("convert-config-to-alpha", false, "if true, the proxy will load configuration as normal and convert existing configuration to the alpha config structure, and print it to stdout") showVersion := configFlagSet.Bool("version", false, "print version string") + configTest := configFlagSet.Bool("config-test", false, "test the configuration and exit") configFlagSet.Parse(os.Args[1:]) if *showVersion { @@ -37,11 +38,24 @@ func main() { logger.Fatal("cannot use alpha-config and convert-config-to-alpha together") } + if *configTest && *convertConfig { + logger.Fatal("cannot use config-test and convert-config-to-alpha together") + } + opts, err := loadConfiguration(*config, *alphaConfig, configFlagSet, os.Args[1:]) if err != nil { logger.Fatalf("ERROR: %v", err) } + if *configTest { + if err = validation.Validate(opts); err != nil { + logger.Errorf("%s", err) + os.Exit(1) + } + fmt.Println("configuration is valid") + return + } + if *convertConfig { if err := printConvertedConfig(opts); err != nil { logger.Fatalf("ERROR: could not convert config: %v", err) diff --git a/main_test.go b/main_test.go index a90f1a38..c7c7057d 100644 --- a/main_test.go +++ b/main_test.go @@ -7,6 +7,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" . "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options/testutil" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/validation" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/format" @@ -292,4 +293,78 @@ redirect_url="http://localhost:4180/oauth2/callback" expectedErr: errors.New("failed to load legacy options: failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"), }), ) + + Describe("Config Test Mode", func() { + const validConfig = ` +http_address="127.0.0.1:4180" +upstreams="http://httpbin" +client_id="oauth2-proxy" +client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK" +cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w=" +email_domains="example.com" +cookie_secure="false" +redirect_url="http://localhost:4180/oauth2/callback" +` + + const invalidConfig = ` +http_address="127.0.0.1:4180" +upstreams="http://httpbin" +email_domains="example.com" +cookie_secure="false" +redirect_url="http://localhost:4180/oauth2/callback" +` + + writeTempConfig := func(content string) string { + file, err := os.CreateTemp("", "oauth2-proxy-test-config-XXXX.cfg") + Expect(err).ToNot(HaveOccurred()) + defer file.Close() + + _, err = file.WriteString(content) + Expect(err).ToNot(HaveOccurred()) + return file.Name() + } + + It("should pass validation with a valid configuration", func() { + configFile := writeTempConfig(validConfig) + defer os.Remove(configFile) + + flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError) + opts, err := loadConfiguration(configFile, "", flagSet, []string{}) + Expect(err).ToNot(HaveOccurred()) + + err = validation.Validate(opts) + Expect(err).ToNot(HaveOccurred()) + }) + + It("should fail validation with an invalid configuration (missing required fields)", func() { + configFile := writeTempConfig(invalidConfig) + defer os.Remove(configFile) + + flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError) + opts, err := loadConfiguration(configFile, "", flagSet, []string{}) + Expect(err).ToNot(HaveOccurred()) + + err = validation.Validate(opts) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("invalid configuration")) + }) + + It("should fail to load a configuration file with syntax errors", func() { + configFile := writeTempConfig("this is not valid toml ===") + defer os.Remove(configFile) + + flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError) + _, err := loadConfiguration(configFile, "", flagSet, []string{}) + Expect(err).To(HaveOccurred()) + }) + + It("should register the config-test flag", func() { + flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError) + flagSet.ParseErrorsAllowlist.UnknownFlags = true + configTest := flagSet.Bool("config-test", false, "test the configuration and exit") + err := flagSet.Parse([]string{"--config-test"}) + Expect(err).ToNot(HaveOccurred()) + Expect(*configTest).To(BeTrue()) + }) + }) }) From cdbdb1128dc09cae34670b7958cff56378137817 Mon Sep 17 00:00:00 2001 From: Joost <439100+jvnoije@users.noreply.github.com> Date: Wed, 18 Mar 2026 16:14:36 +0100 Subject: [PATCH 24/53] feat: add same site option for csrf cookies (#3347) * the attribute version is obsolete, it will be ignored, please remove it to avoid potential confusion Signed-off-by: Joost <439100+jvnoije@users.noreply.github.com> * Add cookie-csrf-samesite option Most of the code is copied form pull request #1947 Signed-off-by: Joost <439100+jvnoije@users.noreply.github.com> * Update CHANGELOG.md Signed-off-by: Joost <439100+jvnoije@users.noreply.github.com> * Removed release information (review comment) Signed-off-by: Joost <439100+jvnoije@users.noreply.github.com> * All cookie variables in a struct Signed-off-by: Joost <439100+jvnoije@users.noreply.github.com> * doc: add changelog entry for #3347 Signed-off-by: Jan Larwig * revert: unnecessary removal of docker compose version Signed-off-by: Jan Larwig * doc: sort csrf flags Signed-off-by: Jan Larwig --------- Signed-off-by: Joost <439100+jvnoije@users.noreply.github.com> Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + docs/docs/configuration/overview.md | 9 +- pkg/apis/options/cookie.go | 3 + pkg/cookies/cookies.go | 26 ++- pkg/cookies/cookies_suite_test.go | 4 + pkg/cookies/cookies_test.go | 82 +++---- pkg/cookies/csrf.go | 47 ++-- pkg/cookies/csrf_per_request_test.go | 19 +- pkg/cookies/csrf_test.go | 259 ++++++++++++++++++++++ pkg/sessions/cookie/session_store.go | 36 +-- pkg/sessions/persistence/ticket.go | 37 ++-- pkg/sessions/tests/session_store_tests.go | 12 +- 12 files changed, 424 insertions(+), 111 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c3a95f7e..0e0a4b23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ - [#3369](https://github.com/oauth2-proxy/oauth2-proxy/pull/3369) fix: use CSRFExpire instead of Expire for CSRF cookie validation (@Br1an67) - [#3365](https://github.com/oauth2-proxy/oauth2-proxy/pull/3365) fix: filter empty strings from allowed groups (@Br1an67) - [#3338](https://github.com/oauth2-proxy/oauth2-proxy/pull/3338) feat: add --config-test flag for validating configuration (@MayorFaj) +- [#3347](https://github.com/oauth2-proxy/oauth2-proxy/pull/3347) feat: add same site option for csrf cookies (@jvnoije) # V7.14.3 diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index 7d8a1c09..c225228e 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -120,7 +120,7 @@ Provider specific options can be found on their respective subpages. | flag: `--approval-prompt`
toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` | | flag: `--backend-logout-url`
toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | | | flag: `--client-id`
toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | | -| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret. The file must contain the secret only, with no trailing newline | | +| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret. The file must contain the secret only, with no trailing newline | | | flag: `--client-secret`
toml: `client_secret` | string | the OAuth Client Secret | | | flag: `--code-challenge-method`
toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | | | flag: `--insecure-oidc-allow-unverified-email`
toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false | @@ -140,7 +140,7 @@ Provider specific options can be found on their respective subpages. | flag: `--oidc-enabled-signing-alg`
toml: `oidc_enabled_signing_algs` | string \| list | List of allowed JWT signing algorithms. When oidc discovery is enabled, the effective set is the intersection between this list and the provider's discovered supported algorithms. | | | flag: `--profile-url`
toml: `profile_url` | string | Profile access endpoint | | | flag: `--prompt`
toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` | -| flag: `--provider-ca-file`
toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. | +| flag: `--provider-ca-file`
toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. | | | flag: `--provider-display-name`
toml: `provider_display_name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) | | flag: `--provider`
toml: `provider` | string | OAuth provider | google | | flag: `--pubjwk-url`
toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | | @@ -158,6 +158,7 @@ Provider specific options can be found on their respective subpages. | flag: `--cookie-csrf-expire`
toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m | | flag: `--cookie-csrf-per-request`
toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false | | flag: `--cookie-csrf-per-request-limit`
toml: `cookie_csrf_per_request_limit` | int | Sets a limit on the number of CSRF requests cookies that oauth2-proxy will create. The oldest cookie will be removed. Useful if users end up with 431 Request headers too large status codes. Only effective if --cookie-csrf-per-request is true | "infinite" | +| flag: `--cookie-csrf-samesite`
toml: `cookie_csrf_samesite` | string | set SameSite CSRF cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). When using the default setting, the CSRF cookie samesite value is taken from the session cookie configuration. | `""` | | flag: `--cookie-domain`
toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | | | flag: `--cookie-expire`
toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s | | flag: `--cookie-httponly`
toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true | @@ -166,7 +167,7 @@ Provider specific options can be found on their respective subpages. | flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | | flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | | flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | -| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | File containing the cookie secret (must be raw binary, exactly 16, 24, or 32 bytes). Use dd if=/dev/urandom bs=32 count=1 > cookie.secret to generate | | +| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | File containing the cookie secret (must be raw binary, exactly 16, 24, or 32 bytes). Use dd if=/dev/urandom bs=32 count=1 > cookie.secret to generate | | | flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | [^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) @@ -212,7 +213,7 @@ Provider specific options can be found on their respective subpages. | Flag / Config Field | Type | Description | Default | | ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- | | flag: `--banner`
toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | | -| flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | +| flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | | | flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | | flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | | flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | | diff --git a/pkg/apis/options/cookie.go b/pkg/apis/options/cookie.go index 3653b7d0..3dee9505 100644 --- a/pkg/apis/options/cookie.go +++ b/pkg/apis/options/cookie.go @@ -24,6 +24,7 @@ type Cookie struct { CSRFPerRequest bool `flag:"cookie-csrf-per-request" cfg:"cookie_csrf_per_request"` CSRFPerRequestLimit int `flag:"cookie-csrf-per-request-limit" cfg:"cookie_csrf_per_request_limit"` CSRFExpire time.Duration `flag:"cookie-csrf-expire" cfg:"cookie_csrf_expire"` + CSRFSameSite string `flag:"cookie-csrf-samesite" cfg:"cookie_csrf_samesite"` } func cookieFlagSet() *pflag.FlagSet { @@ -42,6 +43,7 @@ func cookieFlagSet() *pflag.FlagSet { flagSet.Bool("cookie-csrf-per-request", false, "When this property is set to true, then the CSRF cookie name is built based on the state and varies per request. If property is set to false, then CSRF cookie has the same name for all requests.") flagSet.Int("cookie-csrf-per-request-limit", 0, "Sets a limit on the number of CSRF requests cookies that oauth2-proxy will create. The oldest cookies will be removed. Useful if users end up with 431 Request headers too large status codes.") flagSet.Duration("cookie-csrf-expire", time.Duration(15)*time.Minute, "expire timeframe for CSRF cookie") + flagSet.String("cookie-csrf-samesite", "", "set SameSite CSRF cookie attribute (ie: \"lax\", \"strict\", \"none\", or \"\"). When using the default setting, the CSRF cookie samesite value is taken from the session cookie configuration.") return flagSet } @@ -61,6 +63,7 @@ func cookieDefaults() Cookie { CSRFPerRequest: false, CSRFPerRequestLimit: 0, CSRFExpire: time.Duration(15) * time.Minute, + CSRFSameSite: "", } } diff --git a/pkg/cookies/cookies.go b/pkg/cookies/cookies.go index 24ae2841..be5ee451 100644 --- a/pkg/cookies/cookies.go +++ b/pkg/cookies/cookies.go @@ -7,14 +7,24 @@ import ( "strings" "time" - "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" requestutil "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests/util" ) +type CookieOptions struct { + Name string + Value string + Domains []string + Expiration time.Duration + SameSite string + Path string + HTTPOnly bool + Secure bool +} + // MakeCookieFromOptions constructs a cookie based on the given *options.CookieOptions, // value and creation time -func MakeCookieFromOptions(req *http.Request, name string, value string, opts *options.Cookie, expiration time.Duration) *http.Cookie { +func MakeCookieFromOptions(req *http.Request, opts *CookieOptions) *http.Cookie { domain := GetCookieDomain(req, opts.Domains) // If nothing matches, create the cookie with the shortest domain if domain == "" && len(opts.Domains) > 0 { @@ -26,8 +36,8 @@ func MakeCookieFromOptions(req *http.Request, name string, value string, opts *o } c := &http.Cookie{ - Name: name, - Value: value, + Name: opts.Name, + Value: opts.Value, Path: opts.Path, Domain: domain, HttpOnly: opts.HTTPOnly, @@ -35,9 +45,9 @@ func MakeCookieFromOptions(req *http.Request, name string, value string, opts *o SameSite: ParseSameSite(opts.SameSite), } - if expiration > time.Duration(0) { - c.MaxAge = int(expiration.Seconds()) - } else if expiration < time.Duration(0) { + if opts.Expiration > time.Duration(0) { + c.MaxAge = int(opts.Expiration.Seconds()) + } else if opts.Expiration < time.Duration(0) { c.MaxAge = -1 } @@ -58,7 +68,7 @@ func GetCookieDomain(req *http.Request, cookieDomains []string) string { return "" } -// Parse a valid http.SameSite value from a user supplied string for use of making cookies. +// ParseSameSite a valid http.SameSite value from a user supplied string for use of making cookies. func ParseSameSite(v string) http.SameSite { switch v { case "lax": diff --git a/pkg/cookies/cookies_suite_test.go b/pkg/cookies/cookies_suite_test.go index f4893cbd..a11dd798 100644 --- a/pkg/cookies/cookies_suite_test.go +++ b/pkg/cookies/cookies_suite_test.go @@ -17,6 +17,10 @@ const ( cookieDomain = "o2p.cookies.test" cookiePath = "/cookie-tests" + sameSiteLax = "lax" + sameSiteStrict = "strict" + sameSiteNone = "none" + nowEpoch = 1609366421 ) diff --git a/pkg/cookies/cookies_test.go b/pkg/cookies/cookies_test.go index ef0fbd4f..b67f8a69 100644 --- a/pkg/cookies/cookies_test.go +++ b/pkg/cookies/cookies_test.go @@ -5,8 +5,6 @@ import ( "net/http" "time" - "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" - middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -82,16 +80,12 @@ var _ = Describe("Cookie Tests", func() { Context("MakeCookieFromOptions", func() { type makeCookieFromOptionsTableInput struct { host string - name string - value string - opts options.Cookie - expiration time.Duration + opts CookieOptions now time.Time expectedOutput int } validName := "_oauth2_proxy" - validSecret := "secretthirtytwobytes+abcdefghijk" domains := []string{"www.cookies.test"} now := time.Now() @@ -106,62 +100,50 @@ var _ = Describe("Cookie Tests", func() { ) Expect(err).ToNot(HaveOccurred()) - Expect(MakeCookieFromOptions(req, in.name, in.value, &in.opts, in.expiration).MaxAge).To(Equal(in.expectedOutput)) + Expect(MakeCookieFromOptions(req, &in.opts).MaxAge).To(Equal(in.expectedOutput)) }, Entry("persistent cookie", makeCookieFromOptionsTableInput{ - host: "www.cookies.test", - name: validName, - value: "1", - opts: options.Cookie{ - Name: validName, - Secret: validSecret, - Domains: domains, - Path: "", - Expire: time.Hour, - Refresh: 15 * time.Minute, - Secure: true, - HTTPOnly: false, - SameSite: "", + host: "www.cookies.test", + opts: CookieOptions{ + Name: validName, + Value: "1", + Domains: domains, + Expiration: 15 * time.Minute, + SameSite: "", + Path: "", + HTTPOnly: false, + Secure: true, }, - expiration: 15 * time.Minute, now: now, expectedOutput: int((15 * time.Minute).Seconds()), }), Entry("persistent cookie to be cleared", makeCookieFromOptionsTableInput{ - host: "www.cookies.test", - name: validName, - value: "1", - opts: options.Cookie{ - Name: validName, - Secret: validSecret, - Domains: domains, - Path: "", - Expire: time.Hour * -1, - Refresh: 15 * time.Minute, - Secure: true, - HTTPOnly: false, - SameSite: "", + host: "www.cookies.test", + opts: CookieOptions{ + Name: validName, + Value: "1", + Domains: domains, + Expiration: time.Hour * -1, + SameSite: "", + Path: "", + HTTPOnly: false, + Secure: true, }, - expiration: time.Hour * -1, now: now, expectedOutput: -1, }), Entry("session cookie", makeCookieFromOptionsTableInput{ - host: "www.cookies.test", - name: validName, - value: "1", - opts: options.Cookie{ - Name: validName, - Secret: validSecret, - Domains: domains, - Path: "", - Expire: 0, - Refresh: 15 * time.Minute, - Secure: true, - HTTPOnly: false, - SameSite: "", + host: "www.cookies.test", + opts: CookieOptions{ + Name: validName, + Value: "1", + Domains: domains, + Expiration: 0, + SameSite: "", + Path: "", + HTTPOnly: false, + Secure: true, }, - expiration: 0, now: now, expectedOutput: expectedMaxAge, }), diff --git a/pkg/cookies/csrf.go b/pkg/cookies/csrf.go index 6fc55716..2614f378 100644 --- a/pkg/cookies/csrf.go +++ b/pkg/cookies/csrf.go @@ -134,6 +134,15 @@ func (c *csrf) SetSessionNonce(s *sessions.SessionState) { s.Nonce = c.OIDCNonce } +// getCSRFSameSite get the CSRF same site +func getCSRFSameSite(opts *options.Cookie) string { + sameSite := opts.CSRFSameSite + if sameSite == "" { + sameSite = opts.SameSite + } + return sameSite +} + // SetCookie encodes the CSRF to a signed cookie and sets it on the ResponseWriter func (c *csrf) SetCookie(rw http.ResponseWriter, req *http.Request) (*http.Cookie, error) { encoded, err := c.encodeCookie() @@ -141,13 +150,18 @@ func (c *csrf) SetCookie(rw http.ResponseWriter, req *http.Request) (*http.Cooki return nil, err } - cookie := MakeCookieFromOptions( - req, - c.cookieName(), - encoded, - c.cookieOpts, - c.cookieOpts.CSRFExpire, - ) + csrfCookieOptions := &CookieOptions{ + Name: c.cookieName(), + Value: encoded, + Domains: c.cookieOpts.Domains, + Expiration: c.cookieOpts.CSRFExpire, + SameSite: getCSRFSameSite(c.cookieOpts), + Path: c.cookieOpts.Path, + HTTPOnly: c.cookieOpts.HTTPOnly, + Secure: c.cookieOpts.Secure, + } + + cookie := MakeCookieFromOptions(req, csrfCookieOptions) http.SetCookie(rw, cookie) return cookie, nil @@ -197,13 +211,18 @@ func ClearExtraCsrfCookies(opts *options.Cookie, rw http.ResponseWriter, req *ht // ClearCookie removes the CSRF cookie func (c *csrf) ClearCookie(rw http.ResponseWriter, req *http.Request) { - http.SetCookie(rw, MakeCookieFromOptions( - req, - c.cookieName(), - "", - c.cookieOpts, - time.Hour*-1, - )) + csrfCookieOptions := &CookieOptions{ + Name: c.cookieName(), + Value: "", + Domains: c.cookieOpts.Domains, + Expiration: time.Hour * -1, + SameSite: getCSRFSameSite(c.cookieOpts), + Path: c.cookieOpts.Path, + HTTPOnly: c.cookieOpts.HTTPOnly, + Secure: c.cookieOpts.Secure, + } + + http.SetCookie(rw, MakeCookieFromOptions(req, csrfCookieOptions)) } // encodeCookie MessagePack encodes and encrypts the CSRF and then creates a diff --git a/pkg/cookies/csrf_per_request_test.go b/pkg/cookies/csrf_per_request_test.go index 6a17013b..59ff0a8a 100644 --- a/pkg/cookies/csrf_per_request_test.go +++ b/pkg/cookies/csrf_per_request_test.go @@ -216,13 +216,18 @@ var _ = Describe("CSRF Cookie with non-fixed name Tests", func() { for _, csrf := range []*csrf{privateCSRF1, privateCSRF2, privateCSRF3} { encoded, err := csrf.encodeCookie() Expect(err).ToNot(HaveOccurred()) - cookie := MakeCookieFromOptions( - req, - csrf.cookieName(), - encoded, - csrf.cookieOpts, - csrf.cookieOpts.CSRFExpire, - ) + csrfCookieOptions := &CookieOptions{ + Name: csrf.cookieName(), + Value: encoded, + Domains: csrf.cookieOpts.Domains, + Expiration: csrf.cookieOpts.CSRFExpire, + SameSite: getCSRFSameSite(csrf.cookieOpts), + Path: csrf.cookieOpts.Path, + HTTPOnly: csrf.cookieOpts.HTTPOnly, + Secure: csrf.cookieOpts.Secure, + } + + cookie := MakeCookieFromOptions(req, csrfCookieOptions) cookies = append(cookies, fmt.Sprintf("%v=%v", cookie.Name, cookie.Value)) } diff --git a/pkg/cookies/csrf_test.go b/pkg/cookies/csrf_test.go index f791045d..3182f663 100644 --- a/pkg/cookies/csrf_test.go +++ b/pkg/cookies/csrf_test.go @@ -278,4 +278,263 @@ var _ = Describe("CSRF Cookie Tests", func() { }) }) }) + + Context("Test Cookie SameSite", func() { + var req *http.Request + var cookieOpts *options.Cookie + + testNow := time.Unix(nowEpoch, 0) + + BeforeEach(func() { + // we need to reset the time to ensure the cookie is valid + privateCSRF.clock = time.Now + + req = &http.Request{ + Method: http.MethodGet, + Proto: "HTTP/1.1", + Host: cookieDomain, + + URL: &url.URL{ + Scheme: "https", + Host: cookieDomain, + Path: cookiePath, + }, + } + + cookieOpts = &options.Cookie{ + Name: cookieName, + Secret: cookieSecret, + Domains: []string{cookieDomain}, + Path: cookiePath, + Expire: time.Hour, + Secure: true, + HTTPOnly: true, + CSRFPerRequest: false, + CSRFExpire: time.Hour, + } + }) + + It("Call SetCookie when CSRF SameSite is not defined. Expected result: CSRF cookie SameSite is the same as session cookie.", func() { + // prepare + cookieOpts.SameSite = sameSiteLax + CSRF, _ := NewCSRF(cookieOpts, "verifier") + rw := httptest.NewRecorder() + CSRF.(*csrf).clock = func() time.Time { return testNow } + + // test + _, err := CSRF.SetCookie(rw, req) + + // validate + Expect(err).ToNot(HaveOccurred()) + Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring( + fmt.Sprintf( + "; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure; SameSite=Lax", + cookiePath, + cookieDomain, + int(cookieOpts.CSRFExpire.Seconds()), + ), + )) + }) + + It("Call SetCookie when CSRF SameSite is an empty string. Expected result: CSRF cookie SameSite is the same as session cookie.", func() { + // prepare + cookieOpts.SameSite = sameSiteLax + cookieOpts.CSRFSameSite = "" + CSRF, _ := NewCSRF(cookieOpts, "verifier") + rw := httptest.NewRecorder() + CSRF.(*csrf).clock = func() time.Time { return testNow } + + // test + _, err := CSRF.SetCookie(rw, req) + + // validate + Expect(err).ToNot(HaveOccurred()) + Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring( + fmt.Sprintf( + "; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure; SameSite=Lax", + cookiePath, + cookieDomain, + int(cookieOpts.CSRFExpire.Seconds()), + ), + )) + }) + + It("Call SetCookie when CSRF SameSite is 'none'. Expected result: CSRF cookie SameSite is None.", func() { + // prepare + cookieOpts.SameSite = sameSiteLax + cookieOpts.CSRFSameSite = sameSiteNone + CSRF, _ := NewCSRF(cookieOpts, "verifier") + rw := httptest.NewRecorder() + CSRF.(*csrf).clock = func() time.Time { return testNow } + + // test + _, err := CSRF.SetCookie(rw, req) + + // validate + Expect(err).ToNot(HaveOccurred()) + Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring( + fmt.Sprintf( + "; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure; SameSite=None", + cookiePath, + cookieDomain, + int(cookieOpts.CSRFExpire.Seconds()), + ), + )) + }) + + It("Call SetCookie when CSRF SameSite is 'strict'. Expected result: CSRF cookie SameSite is Strict.", func() { + // prepare + cookieOpts.SameSite = sameSiteLax + cookieOpts.CSRFSameSite = sameSiteStrict + CSRF, _ := NewCSRF(cookieOpts, "verifier") + rw := httptest.NewRecorder() + CSRF.(*csrf).clock = func() time.Time { return testNow } + + // test + _, err := CSRF.SetCookie(rw, req) + + // validate + Expect(err).ToNot(HaveOccurred()) + Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring( + fmt.Sprintf( + "; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure; SameSite=Strict", + cookiePath, + cookieDomain, + int(cookieOpts.CSRFExpire.Seconds()), + ), + )) + }) + + It("Call SetCookie when CSRF SameSite is 'lax'. Expected result: CSRF cookie SameSite is Lax.", func() { + // prepare + cookieOpts.SameSite = sameSiteStrict + cookieOpts.CSRFSameSite = sameSiteLax + CSRF, _ := NewCSRF(cookieOpts, "verifier") + rw := httptest.NewRecorder() + CSRF.(*csrf).clock = func() time.Time { return testNow } + + // test + _, err := CSRF.SetCookie(rw, req) + + // validate + Expect(err).ToNot(HaveOccurred()) + Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring( + fmt.Sprintf( + "; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure; SameSite=Lax", + cookiePath, + cookieDomain, + int(cookieOpts.CSRFExpire.Seconds()), + ), + )) + }) + + It("Call ClearCookie when CSRF SameSite is not defined. Expected result: CSRF cookie SameSite is the same as session cookie.", func() { + // prepare + cookieOpts.SameSite = sameSiteLax + CSRF, _ := NewCSRF(cookieOpts, "verifier") + rw := httptest.NewRecorder() + CSRF.(*csrf).clock = func() time.Time { return testNow } + + // test + CSRF.ClearCookie(rw, req) + + // validate + Expect(rw.Header().Get("Set-Cookie")).To(Equal( + fmt.Sprintf( + "%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure; SameSite=Lax", + CSRF.(*csrf).cookieName(), + cookiePath, + cookieDomain, + ), + )) + }) + + It("Call ClearCookie when CSRF SameSite is an empty string. Expected result: CSRF cookie SameSite is the same as session cookie.", func() { + // prepare + cookieOpts.SameSite = sameSiteLax + cookieOpts.CSRFSameSite = "" + CSRF, _ := NewCSRF(cookieOpts, "verifier") + rw := httptest.NewRecorder() + CSRF.(*csrf).clock = func() time.Time { return testNow } + + // test + CSRF.ClearCookie(rw, req) + + // validate + Expect(rw.Header().Get("Set-Cookie")).To(Equal( + fmt.Sprintf( + "%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure; SameSite=Lax", + CSRF.(*csrf).cookieName(), + cookiePath, + cookieDomain, + ), + )) + }) + + It("Call ClearCookie when CSRF SameSite is 'none'. Expected result: CSRF cookie SameSite is None.", func() { + // prepare + cookieOpts.SameSite = sameSiteLax + cookieOpts.CSRFSameSite = sameSiteNone + CSRF, _ := NewCSRF(cookieOpts, "verifier") + rw := httptest.NewRecorder() + CSRF.(*csrf).clock = func() time.Time { return testNow } + + // test + CSRF.ClearCookie(rw, req) + + // validate + Expect(rw.Header().Get("Set-Cookie")).To(Equal( + fmt.Sprintf( + "%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure; SameSite=None", + CSRF.(*csrf).cookieName(), + cookiePath, + cookieDomain, + ), + )) + }) + + It("Call ClearCookie when CSRF SameSite is 'strict'. Expected result: CSRF cookie SameSite is Strict.", func() { + // prepare + cookieOpts.SameSite = sameSiteLax + cookieOpts.CSRFSameSite = sameSiteStrict + CSRF, _ := NewCSRF(cookieOpts, "verifier") + rw := httptest.NewRecorder() + CSRF.(*csrf).clock = func() time.Time { return testNow } + + // test + CSRF.ClearCookie(rw, req) + + // validate + Expect(rw.Header().Get("Set-Cookie")).To(Equal( + fmt.Sprintf( + "%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure; SameSite=Strict", + CSRF.(*csrf).cookieName(), + cookiePath, + cookieDomain, + ), + )) + }) + + It("Call ClearCookie when CSRF SameSite is 'lax'. Expected result: CSRF cookie SameSite is Lax.", func() { + // prepare + cookieOpts.SameSite = sameSiteStrict + cookieOpts.CSRFSameSite = sameSiteLax + CSRF, _ := NewCSRF(cookieOpts, "verifier") + rw := httptest.NewRecorder() + CSRF.(*csrf).clock = func() time.Time { return testNow } + + // test + CSRF.ClearCookie(rw, req) + + // validate + Expect(rw.Header().Get("Set-Cookie")).To(Equal( + fmt.Sprintf( + "%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure; SameSite=Lax", + CSRF.(*csrf).cookieName(), + cookiePath, + cookieDomain, + ), + )) + }) + }) }) diff --git a/pkg/sessions/cookie/session_store.go b/pkg/sessions/cookie/session_store.go index 095bc0e7..a4da3734 100644 --- a/pkg/sessions/cookie/session_store.go +++ b/pkg/sessions/cookie/session_store.go @@ -76,7 +76,17 @@ func (s *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) error { for _, c := range req.Cookies() { if cookieNameRegex.MatchString(c.Name) { - clearCookie := s.makeCookie(req, c.Name, "", time.Hour*-1) + sessionCookieOptions := &pkgcookies.CookieOptions{ + Name: c.Name, + Value: "", + Domains: s.Cookie.Domains, + Expiration: time.Hour * -1, + SameSite: s.Cookie.SameSite, + Path: s.Cookie.Path, + HTTPOnly: s.Cookie.HTTPOnly, + Secure: s.Cookie.Secure, + } + clearCookie := pkgcookies.MakeCookieFromOptions(req, sessionCookieOptions) http.SetCookie(rw, clearCookie) } @@ -117,7 +127,7 @@ func (s *SessionStore) setSessionCookie(rw http.ResponseWriter, req *http.Reques return nil } -// makeSessionCookie creates an http.Cookie containing the authenticated user's +// makeSessionCookie creates a http.Cookie containing the authenticated user's // authentication details func (s *SessionStore) makeSessionCookie(req *http.Request, value []byte, now time.Time) ([]*http.Cookie, error) { strValue := string(value) @@ -132,23 +142,23 @@ func (s *SessionStore) makeSessionCookie(req *http.Request, value []byte, now ti return nil, err } } - c := s.makeCookie(req, s.Cookie.Name, strValue, s.Cookie.Expire) + sessionCookieOptions := &pkgcookies.CookieOptions{ + Name: s.Cookie.Name, + Value: strValue, + Domains: s.Cookie.Domains, + Expiration: s.Cookie.Expire, + SameSite: s.Cookie.SameSite, + Path: s.Cookie.Path, + HTTPOnly: s.Cookie.HTTPOnly, + Secure: s.Cookie.Secure, + } + c := pkgcookies.MakeCookieFromOptions(req, sessionCookieOptions) if len(c.String()) > maxCookieLength { return splitCookie(c), nil } return []*http.Cookie{c}, nil } -func (s *SessionStore) makeCookie(req *http.Request, name string, value string, expiration time.Duration) *http.Cookie { - return pkgcookies.MakeCookieFromOptions( - req, - name, - value, - s.Cookie, - expiration, - ) -} - // NewCookieSessionStore initialises a new instance of the SessionStore from // the configuration given func NewCookieSessionStore(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessions.SessionStore, error) { diff --git a/pkg/sessions/persistence/ticket.go b/pkg/sessions/persistence/ticket.go index 56d6bd9b..c955143a 100644 --- a/pkg/sessions/persistence/ticket.go +++ b/pkg/sessions/persistence/ticket.go @@ -221,13 +221,17 @@ func (t *ticket) setCookie(rw http.ResponseWriter, req *http.Request, s *session // clearCookie removes any cookies that would be where this ticket // would set them func (t *ticket) clearCookie(rw http.ResponseWriter, req *http.Request) { - http.SetCookie(rw, cookies.MakeCookieFromOptions( - req, - t.options.Name, - "", - t.options, - time.Hour*-1, - )) + cookieOptions := &cookies.CookieOptions{ + Name: t.options.Name, + Value: "", + Domains: t.options.Domains, + Expiration: time.Hour * -1, + SameSite: t.options.SameSite, + Path: t.options.Path, + HTTPOnly: t.options.HTTPOnly, + Secure: t.options.Secure, + } + http.SetCookie(rw, cookies.MakeCookieFromOptions(req, cookieOptions)) } // makeCookie makes a cookie, signing the value if present @@ -244,13 +248,18 @@ func (t *ticket) makeCookie(req *http.Request, value string, expires time.Durati } } - return cookies.MakeCookieFromOptions( - req, - t.options.Name, - value, - t.options, - expires, - ), nil + cookieOptions := &cookies.CookieOptions{ + Name: t.options.Name, + Value: value, + Domains: t.options.Domains, + Expiration: expires, + SameSite: t.options.SameSite, + Path: t.options.Path, + HTTPOnly: t.options.HTTPOnly, + Secure: t.options.Secure, + } + + return cookies.MakeCookieFromOptions(req, cookieOptions), nil } // makeCipher makes a AES-GCM cipher out of the ticket's secret diff --git a/pkg/sessions/tests/session_store_tests.go b/pkg/sessions/tests/session_store_tests.go index 05b67d8d..dd678042 100644 --- a/pkg/sessions/tests/session_store_tests.go +++ b/pkg/sessions/tests/session_store_tests.go @@ -422,7 +422,17 @@ func SessionStoreInterfaceTests(in *testInput) { broken := "BrokenSessionFromADifferentSessionImplementation" value, err := encryption.SignedValue(in.cookieOpts.Secret, in.cookieOpts.Name, []byte(broken), time.Now()) Expect(err).ToNot(HaveOccurred()) - cookie := cookiesapi.MakeCookieFromOptions(in.request, in.cookieOpts.Name, value, in.cookieOpts, in.cookieOpts.Expire) + cookieOptions := &cookiesapi.CookieOptions{ + Name: in.cookieOpts.Name, + Value: value, + Domains: in.cookieOpts.Domains, + Expiration: in.cookieOpts.Expire, + SameSite: in.cookieOpts.SameSite, + Path: in.cookieOpts.Path, + HTTPOnly: in.cookieOpts.HTTPOnly, + Secure: in.cookieOpts.Secure, + } + cookie := cookiesapi.MakeCookieFromOptions(in.request, cookieOptions) in.request.AddCookie(cookie) err = in.ss().Save(in.response, in.request, in.session) From 9ae0b325a6d75b163c6f1fefb66ca4817c133438 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Thu, 19 Mar 2026 00:08:50 +0800 Subject: [PATCH 25/53] feat: add support for setting a unix binding's socket file mode (#3376) fix: linter issues and set default unix socket permissions to 0660 Signed-off-by: Jan Larwig Co-authored-by: Tristan --- CHANGELOG.md | 1 + docs/docs/configuration/alpha_config.md | 4 +- docs/docs/configuration/overview.md | 2 +- pkg/apis/options/server.go | 9 +++++ pkg/proxyhttp/server.go | 52 ++++++++++++++++++++++++- pkg/proxyhttp/server_test.go | 50 ++++++++++++++++++++++++ 6 files changed, 113 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e0a4b23..ffd8f6de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ - [#3365](https://github.com/oauth2-proxy/oauth2-proxy/pull/3365) fix: filter empty strings from allowed groups (@Br1an67) - [#3338](https://github.com/oauth2-proxy/oauth2-proxy/pull/3338) feat: add --config-test flag for validating configuration (@MayorFaj) - [#3347](https://github.com/oauth2-proxy/oauth2-proxy/pull/3347) feat: add same site option for csrf cookies (@jvnoije) +- [#3376](https://github.com/oauth2-proxy/oauth2-proxy/pull/3376) feat: allow setting unix socket file mode when declaring listener (@Tristan971 / @tuunit) # V7.14.3 diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index d8cce916..ee1883bb 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -584,8 +584,8 @@ Server represents the configuration for an HTTP(S) server | Field | Type | Description | | ----- | ---- | ----------- | -| `bindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Leave blank or set to "-" to disable. | -| `secureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Leave blank or set to "-" to disable. | +| `bindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Different types of bind addresses are supported:
* `[http://]:`
* `fd:` (case insensitive)
* `unix://`
Unix sockets are created with default system umask mode, which can be overridden, e.g.: `unix://my-socket,mode=0777`
Square brackets are required for ipv6 address, e.g. `http://[::1]:4180`
Leave blank or set to "-" to disable. | +| `secureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Secure bind addresses need to respond with valid SSL and use the following format:
* `[https://]:`
Square brackets are required for ipv6 address, e.g. `https://[::1]:4180`
Leave blank or set to "-" to disable. | | `tls` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the
secure traffic and further configuration for the TLS server. | ### TLS diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index c225228e..37f385c7 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -264,7 +264,7 @@ Provider specific options can be found on their respective subpages. | Flag / Config Field | Type | Description | Default | | ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | -| flag: `--http-address`
toml: `http_address` | string | `[http://]:` or `unix://` or `fd:` (case insensitive) to listen on for HTTP clients. Square brackets are required for ipv6 address, e.g. `http://[::1]:4180` | `"127.0.0.1:4180"` | +| flag: `--http-address`
toml: `http_address` | string | `[http://]:` or `unix://` or `fd:` (case insensitive) to listen on for HTTP clients. Unix sockets are created with default system umask mode, which can be overridden, e.g. `unix://my-socket,mode=0777`. Square brackets are required for ipv6 address, e.g. `http://[::1]:4180` | `"127.0.0.1:4180"` | | flag: `--https-address`
toml: `https_address` | string | `[https://]:` to listen on for HTTPS clients. Square brackets are required for ipv6 address, e.g. `https://[::1]:443` | `":443"` | | flag: `--metrics-address`
toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` | | flag: `--metrics-secure-address`
toml: `metrics_secure_address` | string | the address prometheus metrics will be scraped from if using HTTPS | `""` | diff --git a/pkg/apis/options/server.go b/pkg/apis/options/server.go index 8fa41af8..830ea09a 100644 --- a/pkg/apis/options/server.go +++ b/pkg/apis/options/server.go @@ -3,10 +3,19 @@ package options // Server represents the configuration for an HTTP(S) server type Server struct { // BindAddress is the address on which to serve traffic. + // Different types of bind addresses are supported: + // * `[http://]:` + // * `fd:` (case insensitive) + // * `unix://` + // Unix sockets are created with default system umask mode, which can be overridden, e.g.: `unix://my-socket,mode=0777` + // Square brackets are required for ipv6 address, e.g. `http://[::1]:4180` // Leave blank or set to "-" to disable. BindAddress string `yaml:"bindAddress,omitempty"` // SecureBindAddress is the address on which to serve secure traffic. + // Secure bind addresses need to respond with valid SSL and use the following format: + // * `[https://]:` + // Square brackets are required for ipv6 address, e.g. `https://[::1]:4180` // Leave blank or set to "-" to disable. SecureBindAddress string `yaml:"secureBindAddress,omitempty"` diff --git a/pkg/proxyhttp/server.go b/pkg/proxyhttp/server.go index a0fc6054..2982e1fc 100644 --- a/pkg/proxyhttp/server.go +++ b/pkg/proxyhttp/server.go @@ -8,6 +8,7 @@ import ( "net" "net/http" "os" + "strconv" "strings" "time" @@ -95,15 +96,62 @@ func (s *server) setupListener(opts Opts) error { networkType := getNetworkScheme(opts.BindAddress) listenAddr := getListenAddress(opts.BindAddress) - listener, err := net.Listen(networkType, listenAddr) + listener, err := func() (net.Listener, error) { + if networkType == "unix" { + return setupUnixSocketListener(networkType, listenAddr) + } + return net.Listen(networkType, listenAddr) + }() + if err != nil { return fmt.Errorf("listen (%s, %s) failed: %w", networkType, listenAddr, err) } - s.listener = listener + s.listener = listener return nil } +func setupUnixSocketListener(networkType string, address string) (net.Listener, error) { + socketOpts := strings.Split(address, ",") + if len(socketOpts) < 2 { + return net.Listen(networkType, address) + } + + socketPath := socketOpts[0] + var socketMode os.FileMode + hasSocketMode := false + + for _, socketOpt := range socketOpts[1:] { + socketOpt := strings.SplitN(socketOpt, "=", 2) + if len(socketOpt) != 2 { + return nil, fmt.Errorf("unix socket option %s expects a value", socketOpt[0]) + } + + if socketOpt[0] == "mode" { + mode, err := strconv.ParseUint(socketOpt[1], 8, 32) + if err != nil { + return nil, fmt.Errorf("unix socket file mode has invalid value %s", socketOpt[1]) + } + socketMode = os.FileMode(mode) + hasSocketMode = true + } + } + + listener, err := net.Listen(networkType, socketPath) + if err != nil { + return nil, err + } + + if hasSocketMode { + err = os.Chmod(socketPath, socketMode) + if err != nil { + return nil, fmt.Errorf("cannot set unix socket file mode on %s: %v", socketPath, err) + } + } + + return listener, nil +} + func parseCipherSuites(names []string) ([]uint16, error) { cipherNameMap := make(map[string]uint16) diff --git a/pkg/proxyhttp/server_test.go b/pkg/proxyhttp/server_test.go index d97dcec2..f6d12436 100644 --- a/pkg/proxyhttp/server_test.go +++ b/pkg/proxyhttp/server_test.go @@ -28,6 +28,8 @@ var _ = Describe("Server", func() { expectedErr error expectHTTPListener bool expectTLSListener bool + expectedSocketMode os.FileMode + socketPath string fdAddr string ipv6 bool } @@ -57,6 +59,12 @@ var _ = Describe("Server", func() { s, ok := srv.(*server) Expect(ok).To(BeTrue()) + if in.socketPath != "" { + fileInfo, err := os.Stat(in.socketPath) + Expect(err).ToNot(HaveOccurred()) + Expect(fileInfo.Mode().Perm()).To(Equal(in.expectedSocketMode.Perm())) + } + Expect(s.listener != nil).To(Equal(in.expectHTTPListener)) if in.expectHTTPListener { Expect(s.listener.Close()).To(Succeed()) @@ -648,6 +656,48 @@ var _ = Describe("Server", func() { expectTLSListener: true, ipv6: true, }), + Entry("with a valid unix socket path", &newServerTableInput{ + opts: Opts{ + Handler: handler, + BindAddress: "unix:///tmp/oauth2-proxy.sock", + }, + expectedErr: nil, + expectHTTPListener: true, + expectTLSListener: false, + ipv6: false, + }), + Entry("with a valid unix socket path and a valid socket file mode", &newServerTableInput{ + opts: Opts{ + Handler: handler, + BindAddress: "unix:///tmp/oauth2-proxy.sock,mode=0777", + }, + expectedErr: nil, + expectHTTPListener: true, + expectTLSListener: false, + expectedSocketMode: 0o777, + socketPath: "/tmp/oauth2-proxy.sock", + ipv6: false, + }), + Entry("with a valid unix socket path and a value-less socket file mode argument", &newServerTableInput{ + opts: Opts{ + Handler: handler, + BindAddress: "unix:///tmp/oauth2-proxy.sock,mode", + }, + expectedErr: errors.New("error setting up listener: listen (unix, /tmp/oauth2-proxy.sock,mode) failed: unix socket option mode expects a value"), + expectHTTPListener: false, + expectTLSListener: false, + ipv6: false, + }), + Entry("with a valid unix socket path and an invalid socket file mode value", &newServerTableInput{ + opts: Opts{ + Handler: handler, + BindAddress: "unix:///tmp/oauth2-proxy.sock,mode=-1", + }, + expectedErr: errors.New("error setting up listener: listen (unix, /tmp/oauth2-proxy.sock,mode=-1) failed: unix socket file mode has invalid value -1"), + expectHTTPListener: false, + expectTLSListener: false, + ipv6: false, + }), ) }) From 96c9ec69868e2bcd307ee837ca9fd24e77dcc48b Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 19 Mar 2026 01:10:21 +0800 Subject: [PATCH 26/53] release v7.15.0 (#3378) * add new docs version 7.15.x * update to release version v7.15.0 * doc: changelog for v7.15.0 and extended docs for additional claims * ci: fix trivy failure for release PR --------- Signed-off-by: Jan Larwig Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Jan Larwig --- .github/workflows/ci.yml | 1 + CHANGELOG.md | 23 + Makefile | 2 +- .../docker-compose-alpha-config.yaml | 2 +- .../docker-compose-gitea.yaml | 2 +- .../docker-compose-keycloak.yaml | 2 +- .../docker-compose-nginx.yaml | 2 +- .../docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/configuration/alpha_config.md | 52 ++ docs/docs/configuration/alpha_config.md.tmpl | 52 ++ docs/docs/installation.md | 2 +- .../version-7.15.x/behaviour.md | 26 + .../version-7.15.x/community/contribution.md | 91 +++ .../version-7.15.x/community/security.md | 49 ++ .../configuration/alpha_config.md | 702 ++++++++++++++++++ .../configuration/alpha_config.md.tmpl | 281 +++++++ .../configuration/integrations/caddy.md | 63 ++ .../configuration/integrations/headlamp.md | 105 +++ .../configuration/integrations/index.md | 41 + .../integrations/kubernetes-dashboard.md | 289 +++++++ .../configuration/integrations/nginx.md | 174 +++++ .../configuration/integrations/traefik.md | 192 +++++ .../version-7.15.x/configuration/overview.md | 446 +++++++++++ .../configuration/providers/adfs.md | 19 + .../configuration/providers/bitbucket.md | 25 + .../configuration/providers/cidaas.md | 37 + .../configuration/providers/cisco_duo.md | 44 ++ .../configuration/providers/digitalocean.md | 21 + .../configuration/providers/facebook.md | 7 + .../configuration/providers/gitea.md | 24 + .../configuration/providers/github.md | 81 ++ .../configuration/providers/gitlab.md | 49 ++ .../configuration/providers/google.md | 84 +++ .../configuration/providers/index.md | 46 ++ .../configuration/providers/keycloak.md | 36 + .../configuration/providers/keycloak_oidc.md | 151 ++++ .../configuration/providers/linkedin.md | 13 + .../configuration/providers/login_gov.md | 79 ++ .../configuration/providers/ms_azure_ad.md | 59 ++ .../configuration/providers/ms_entra_id.md | 201 +++++ .../configuration/providers/nextcloud.md | 28 + .../configuration/providers/openid_connect.md | 146 ++++ .../configuration/providers/sourcehut.md | 25 + .../version-7.15.x/configuration/sessions.md | 99 +++ .../configuration/systemd_socket.md | 43 ++ .../version-7.15.x/configuration/tls.md | 85 +++ .../version-7.15.x/features/endpoints.md | 73 ++ .../version-7.15.x/installation.md | 32 + docs/versioned_docs/version-7.15.x/welcome.md | 33 + .../version-7.15.x-sidebars.json | 100 +++ docs/versions.json | 1 + 52 files changed, 4236 insertions(+), 8 deletions(-) create mode 100644 docs/versioned_docs/version-7.15.x/behaviour.md create mode 100644 docs/versioned_docs/version-7.15.x/community/contribution.md create mode 100644 docs/versioned_docs/version-7.15.x/community/security.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/alpha_config.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/alpha_config.md.tmpl create mode 100644 docs/versioned_docs/version-7.15.x/configuration/integrations/caddy.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/integrations/headlamp.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/integrations/index.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/integrations/kubernetes-dashboard.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/integrations/nginx.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/integrations/traefik.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/overview.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/adfs.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/bitbucket.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/cidaas.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/cisco_duo.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/digitalocean.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/facebook.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/gitea.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/github.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/gitlab.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/google.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/index.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/keycloak.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/keycloak_oidc.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/linkedin.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/login_gov.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/ms_azure_ad.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/ms_entra_id.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/nextcloud.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/openid_connect.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/providers/sourcehut.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/sessions.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/systemd_socket.md create mode 100644 docs/versioned_docs/version-7.15.x/configuration/tls.md create mode 100644 docs/versioned_docs/version-7.15.x/features/endpoints.md create mode 100644 docs/versioned_docs/version-7.15.x/installation.md create mode 100644 docs/versioned_docs/version-7.15.x/welcome.md create mode 100644 docs/versioned_sidebars/version-7.15.x-sidebars.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 47ca7f93..e0610cad 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -92,6 +92,7 @@ jobs: exit-code: '0' - name: Upload Trivy scan results + if: (!startsWith(github.head_ref, 'release')) uses: github/codeql-action/upload-sarif@v4 with: sarif_file: 'trivy-results.sarif' diff --git a/CHANGELOG.md b/CHANGELOG.md index ffd8f6de..8da01f83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,29 @@ ## Breaking Changes +## Changes since v7.15.0 + +# V7.15.0 + +## Release Highlights + +- 🔒 OIDC JWT signing algorithms can now be configured +- 🍪 CSRF cookie improvements (SameSite option, proper expiration validation) +- 🧪 Configuration validation flag: --config-test +- 🔌 Unix socket file mode support +- 👤 Session state can now be extend with arbitrary claims from ID Token and upstream IDP user profiles endpoint + - This opens the door for multiple features like: + - Additional arbitrary header values for any claims your IDP provides + - Extended OAuth2 Proxy UserInfo endpoint with all additional claims + - Read the docs [here](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#how-to-utilize-arbitrary-claims-provided-by-your-identity-provider) + +## Important Notes + +CSRF cookie validation now correctly uses `CSRFExpire` instead of `Expire`. If you relied on the previous behavior, review your session timeout configuration. +Check the [documentation(https://oauth2-proxy.github.io/oauth2-proxy/configuration/overview#cookie-options) for `cookie-csrf-expire`. + +## Breaking Changes + ## Changes since v7.14.3 - [#3352](https://github.com/oauth2-proxy/oauth2-proxy/pull/3352) fix: backend logout URL call on sign out (#3172)(@vsejpal) diff --git a/Makefile b/Makefile index ed9d2186..319d3ddb 100644 --- a/Makefile +++ b/Makefile @@ -147,7 +147,7 @@ test: lint ## Run all Go tests GO111MODULE=on $(GO) test $(TESTCOVER) -v -race ./... .PHONY: release -release: validate-go-version lint test ## Create a full release for all architectures (binaries and checksums) +release: validate-go-version ## Create a full release for all architectures (binaries and checksums) BINARY=${BINARY} VERSION=${VERSION} ./dist.sh .PHONY: clean diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index 4f245f65..aee1af0b 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -14,7 +14,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.3 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.0 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 8190d4ea..2ada1062 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.3 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index ea86ea82..e6de0744 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.3 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 45758e88..dac1b0b5 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,7 +22,7 @@ version: "3.0" services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.3 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.0 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 73107b7d..d83cf032 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.3 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.0 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index a213544d..edc5af24 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.3 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index ee1883bb..680741ba 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -171,6 +171,58 @@ injectResponseHeaders: **Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest` +### How to utilize arbitrary claims provided by your Identity Provider + +With the additionalClaims attribute you can specify which claims you want to extract +from the ID Token or userinfo (ProfileURL) endpoint. + +Configure these on the relevant provider entry: + +```yaml +providers: + - id: my-oidc-provider + provider: oidc + clientID: ${OAUTH_CLIENT_ID} + clientSecret: ${OAUTH_CLIENT_SECRET} + oidcConfig: + issuerURL: https://issuer.example.com + profileURL: https://issuer.example.com/oauth2/userinfo + additionalClaims: + - department + - employee_id + - organization.name +``` + +OAuth2 Proxy resolves each configured claim using the following order: + +1. The raw ID token is checked first. +2. If the claim is not present there and `profileURL` is configured, the userinfo endpoint is queried. +3. If `skipClaimsFromProfileURL: true` is set, only the ID token is used. + +Claims that are not found are ignored rather than causing authentication to fail. + +You can use dot-separated paths for nested JSON objects, for example `organization.name`. +Array indexes are not supported. + +Once loaded, these claims are stored in the session as `additionalClaims`. They can then be +used anywhere session claims are accepted, including header injection: + +```yaml +injectRequestHeaders: + - name: X-Department + values: + - claimSource: + claim: department + - name: X-Organization + values: + - claimSource: + claim: organization.name +``` + +This is useful when your IdP exposes application-specific attributes such as department, +tenant, employee ID, entitlement, or other custom claims that are not part of the default +OAuth2 Proxy session fields. + ## Removed options The following flags/options and their respective environment variables are no diff --git a/docs/docs/configuration/alpha_config.md.tmpl b/docs/docs/configuration/alpha_config.md.tmpl index 2a9684da..e7982055 100644 --- a/docs/docs/configuration/alpha_config.md.tmpl +++ b/docs/docs/configuration/alpha_config.md.tmpl @@ -171,6 +171,58 @@ injectResponseHeaders: **Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest` +### How to utilize arbitrary claims provided by your Identity Provider + +With the additionalClaims attribute you can specify which claims you want to extract +from the ID Token or userinfo (ProfileURL) endpoint. + +Configure these on the relevant provider entry: + +```yaml +providers: + - id: my-oidc-provider + provider: oidc + clientID: ${OAUTH_CLIENT_ID} + clientSecret: ${OAUTH_CLIENT_SECRET} + oidcConfig: + issuerURL: https://issuer.example.com + profileURL: https://issuer.example.com/oauth2/userinfo + additionalClaims: + - department + - employee_id + - organization.name +``` + +OAuth2 Proxy resolves each configured claim using the following order: + +1. The raw ID token is checked first. +2. If the claim is not present there and `profileURL` is configured, the userinfo endpoint is queried. +3. If `skipClaimsFromProfileURL: true` is set, only the ID token is used. + +Claims that are not found are ignored rather than causing authentication to fail. + +You can use dot-separated paths for nested JSON objects, for example `organization.name`. +Array indexes are not supported. + +Once loaded, these claims are stored in the session as `additionalClaims`. They can then be +used anywhere session claims are accepted, including header injection: + +```yaml +injectRequestHeaders: + - name: X-Department + values: + - claimSource: + claim: department + - name: X-Organization + values: + - claimSource: + claim: organization.name +``` + +This is useful when your IdP exposes application-specific attributes such as department, +tenant, employee ID, entitlement, or other custom claims that are not part of the default +OAuth2 Proxy session fields. + ## Removed options The following flags/options and their respective environment variables are no diff --git a/docs/docs/installation.md b/docs/docs/installation.md index 75603801..497b3e0d 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.3`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.15.0`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.15.x/behaviour.md b/docs/versioned_docs/version-7.15.x/behaviour.md new file mode 100644 index 00000000..d0be452e --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/behaviour.md @@ -0,0 +1,26 @@ +--- +id: behaviour +title: Behaviour +--- + +1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints. + - Exception: If the request matches a skipped route (configured via `--skip-auth-route`): + - Authentication is not enforced, but the proxy will opportunistically attempt to validate a session cookie (`--cookie-name`) or JWT (`--skip-jwt-bearer-tokens`) if present in the request. + - Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds. + +2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default. + - Ajax Requests: If the request has `Accept: application/json` header: + - Returns `401 Unauthorized`. + - Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT: + - Redirects to the login page by default. + - Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`. + +3. Post-Authentication: After successful authentication with the IdP, OAuth tokens are stored in the configured session store (cookie or Redis), and a cookie is set. + +4. Request Forwarding: The authenticated request is processed based on configuration: + - Forwarded to the configured upstream application with added user info and authentication headers, or + - Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik). + +--- + +Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management. diff --git a/docs/versioned_docs/version-7.15.x/community/contribution.md b/docs/versioned_docs/version-7.15.x/community/contribution.md new file mode 100644 index 00000000..a4f9dc16 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/community/contribution.md @@ -0,0 +1,91 @@ +--- +id: contribution +title: Contribution Guide +--- + +We track bugs and issues using Github. + +If you find a bug, please open an Issue. When opening an Issue or Pull Request please follow the preconfigured template and take special note of the checkboxes. + +If you want to fix a bug, add a new feature or extend existing functionality, please create a fork, create a feature branch and open a PR back to this repo. +Please mention open bug issue number(s) within your PR if applicable. + +We suggest using [Visual Studio Code](https://code.visualstudio.com/docs/languages/go) with the official [Go for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=golang.go) extension. + + +# Go version + +See the `go.mod` file in the root of this repository for the version of Go used by this project. +You can follow [the installation guide for Go](https://go.dev/doc/install), +and you can find this specific Go version on [the Go downloads page](https://go.dev/dl/). + +# Preparing your fork +Clone your fork, create a feature branch and update the depedencies to get started. +```bash +git clone git@github.com:/oauth2-proxy +cd oauth2-proxy +git branch feature/ +git push --set-upstream origin feature/ +go mod download +``` + + +# Testing / Debugging +For starting oauth2-proxy locally open the debugging tab and create the `launch.json` and select `Go: Launch Package`. + +![Debugging Tab](/img/debug-tab.png) +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch OAuth2 Proxy with Dex", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and dex as an idetity provider + "contrib/local-environment/oauth2-proxy.cfg" + ] + }, + { + "name": "Launch OAuth2 Proxy with Keycloak", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and keycloak as an idetity provider + "contrib/local-environment/oauth2-proxy-keycloak.cfg" + ] + } + ] +} +``` + +Before you can start your local version of oauth2-proxy, you will have to use the provided docker compose files to start a local upstream service and identity provider. We suggest using [httpbin](https://hub.docker.com/r/kennethreitz/httpbin) as your upstream for testing as it allows for request and response introspection of all things HTTP. + +Inside the `contrib/local-environment` directory you can use the `Makefile` for +starting different example setups: + +- Dex as your IdP: `make up` or `make down` +- Dex as your IdP using the alpha-config: `make alpha-config-up` +- Keycloak as your IdP: `make keycloak-up` +- Dex as your IdP & nginx reverse proxy: `make nginx-up` +- and many more... + +Check out the `Makefile` to see what is available. + +The username and password for all setups is usually `admin@example.com` and `password`. + +The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me + +- OAuth2 Proxy: http://oauth2-proxy.localtest.me:4180 +- Upstream: http://httpbin.localtest.me:8080 +- Dex: http://dex.localtest.me:5556 + diff --git a/docs/versioned_docs/version-7.15.x/community/security.md b/docs/versioned_docs/version-7.15.x/community/security.md new file mode 100644 index 00000000..00cdb724 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/community/security.md @@ -0,0 +1,49 @@ +--- +id: security +title: Security +--- + +:::note +OAuth2 Proxy is a community project. +Maintainers do not work on this project full time, and as such, +while we endeavour to respond to disclosures as quickly as possible, +this may take longer than in projects with corporate sponsorship. +::: + +## Security Disclosures + +:::important +If you believe you have found a vulnerability within OAuth2 Proxy or any of its +dependencies, please do NOT open an issue or PR on GitHub, please do NOT post +any details publicly. +::: + +Security disclosures MUST be done in private. +If you have found an issue that you would like to bring to the attention of the +maintenance team for OAuth2 Proxy, please compose an email and send it to the +list of maintainers in our [MAINTAINERS.md](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS.md) file. + +Please include as much detail as possible. +Ideally, your disclosure should include: +- A reproducible case that can be used to demonstrate the exploit +- How you discovered this vulnerability +- A potential fix for the issue (if you have thought of one) +- Versions affected (if not present in master) +- Your GitHub ID + +### How will we respond to disclosures? + +We use [GitHub Security Advisories](https://docs.github.com/en/github/managing-security-vulnerabilities/about-github-security-advisories) +to privately discuss fixes for disclosed vulnerabilities. +If you include a GitHub ID with your disclosure we will add you as a collaborator +for the advisory so that you can join the discussion and validate any fixes +we may propose. + +For minor issues and previously disclosed vulnerabilities (typically for +dependencies), we may use regular PRs for fixes and forego the security advisory. + +Once a fix has been agreed upon, we will merge the fix and create a new release. +If we have multiple security issues in flight simultaneously, we may delay +merging fixes until all patches are ready. +We may also backport the fix to previous releases, +but this will be at the discretion of the maintainers. diff --git a/docs/versioned_docs/version-7.15.x/configuration/alpha_config.md b/docs/versioned_docs/version-7.15.x/configuration/alpha_config.md new file mode 100644 index 00000000..680741ba --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/alpha_config.md @@ -0,0 +1,702 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +providers: + - id: ... + ...: ... +cookie: + secret: ... + ...: ... +injectRequestHeaders: + - secretSource: + ...: ... +injectResponseHeaders: + - claimSource: + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +# Migration Guide + +This section details breaking changes and migration steps for moving to the new +alpha configuration format. + +## Migrating header injections in v7.14.0 + +From v7.14.0 onward, header injection sources must be explicitly nested. If you +previously relied on squashed fields, update to the new structure before +upgrading: + +```yaml +# before v7.14.0 +injectRequestHeaders: +- name: X-Forwarded-User + values: + - claim: user +- name: X-Custom-Secret-header + values: + - value: my-super-secret + +# v7.14.0 and later +injectRequestHeaders: +- name: X-Forwarded-User + values: + - claimSource: + claim: user +- name: X-Custom-Secret-header + values: + - secretSource: + value: my-super-secret +``` + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +### Validating Alpha Configuration + +Use `--config-test` to validate your alpha configuration without starting the proxy: + +```bash +oauth2-proxy --config core.cfg --alpha-config alpha.yaml --config-test +``` + +This is useful for CI/CD pipelines to catch configuration errors before deployment. +See the [Configuration Validation](./overview.md#configuration-validation) section for more details. + +### How to use environment variables + +The alpha package supports the use of environment variables in place of yaml values, allowing sensitive data to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +### How to inject custom headers + +Configure `injectRequestHeaders` and `injectResponseHeaders` in alpha config YAML. + +```yaml +injectRequestHeaders: + - name: "X-User-Email" + values: + - claimSource: + claim: "email" # extract the email claim contents from the id token + - name: "X-Static-Secret" + values: + # secrets need to be encoded with base64 when directly in the yaml config but will be send decoded + - secretSource: + value: "c3VwZXItc2VjcmV0" + - name: "X-Static-File-Secret" + - secretSource: + fromFile: "/path/to/my/secret" + - name: "X-Static-Env-Secret" + - secretSource: + value: "${MY_SECRET_ENV}" # content still needs to be base64 encoded +injectResponseHeaders: + # Following will result in a header "Authorization: Basic (encoded)" + - name: "Authorization" + values: + - claimSource: + claim: user + prefix: "Basic " + basicAuthPassword: + value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk # base64 encoded password +``` + +**Value sources:** +* `claimSource` - `claim` (session claims either from id token or from profile URL) +* `secretSource` - `value` (base64), `fromFile` (file path) + +**Request option:** `preserveRequestValue: true` retains existing header values + +**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest` + +### How to utilize arbitrary claims provided by your Identity Provider + +With the additionalClaims attribute you can specify which claims you want to extract +from the ID Token or userinfo (ProfileURL) endpoint. + +Configure these on the relevant provider entry: + +```yaml +providers: + - id: my-oidc-provider + provider: oidc + clientID: ${OAUTH_CLIENT_ID} + clientSecret: ${OAUTH_CLIENT_SECRET} + oidcConfig: + issuerURL: https://issuer.example.com + profileURL: https://issuer.example.com/oauth2/userinfo + additionalClaims: + - department + - employee_id + - organization.name +``` + +OAuth2 Proxy resolves each configured claim using the following order: + +1. The raw ID token is checked first. +2. If the claim is not present there and `profileURL` is configured, the userinfo endpoint is queried. +3. If `skipClaimsFromProfileURL: true` is set, only the ID token is used. + +Claims that are not found are ignored rather than causing authentication to fail. + +You can use dot-separated paths for nested JSON objects, for example `organization.name`. +Array indexes are not supported. + +Once loaded, these claims are stored in the session as `additionalClaims`. They can then be +used anywhere session claims are accepted, including header injection: + +```yaml +injectRequestHeaders: + - name: X-Department + values: + - claimSource: + claim: department + - name: X-Organization + values: + - claimSource: + claim: organization.name +``` + +This is useful when your IdP exposes application-specific attributes such as department, +tenant, employee ID, entitlement, or other custom claims that are not part of the default +OAuth2 Proxy session fields. + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference + + + +### ADFSOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `skipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | + +### AlphaOptions + +AlphaOptions contains alpha structured configuration options. +Usage of these options allows users to access alpha features that are not +available as part of the primary configuration structure for OAuth2 Proxy. + +:::warning +The options within this structure are considered alpha. +They may change between releases without notice. +::: + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | +| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | + +### AzureOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | +| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | + +### BitbucketOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repository` | _string_ | Repository sets restrict logins to user with access to this repository | + +### ClaimSource + +(**Appears on:** [HeaderValue](#headervalue)) + +ClaimSource allows loading a header value from a claim within the session + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### GitHubOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `org` | _string_ | Org sets restrict logins to members of this organisation | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository | +| `token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | +| `users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | + +### GitLabOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Group sets restrict logins to members of this group | +| `projects` | _[]string_ | Projects restricts logins to members of these projects | + +### GoogleOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Groups sets restrict logins to members of this Google group | +| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | +| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | +| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | +| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | +| `useOrganizationID` | _bool_ | UseOrganizationId indicates whether to use the organization ID as the UserName claim | +| `adminAPIUserScope` | _string_ | admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly | + +### Header + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Header represents an individual header that will be added to a request or +response header. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | +| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `InsecureSkipHeaderNormalization` | _bool_ | InsecureSkipHeaderNormalization disables normalizing the header name
According to RFC 7230 Section 3.2 there aren't any rules about
capitalization of header names, but the standard practice is to use
Title-Case (e.g. X-Forwarded-For). By default, header names will be
normalized to Title-Case and any incoming headers that match will be
treated as the same header. Additionally underscores (_) in header names
will be converted to dashes (-) when normalizing.
Defaults to false (header names will be normalized). | +| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | + +### HeaderValue + +(**Appears on:** [Header](#header)) + +HeaderValue represents a single header value and the sources that can +make up the header value + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### KeycloakOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `groups` | _[]string_ | Group enables to restrict login to members of indicated group | +| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | + +### LoginGovOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | +| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | +| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | + +### LoginURLParameter + +(**Appears on:** [Provider](#provider)) + +LoginURLParameter is the configuration for a single query parameter that +can be passed through from the `/oauth2/start` endpoint to the IdP login +URL. The "default" option specifies the default value or values (if any) +that will be passed to the IdP for this parameter, and "allow" is a list +of options for ways in which this parameter can be set or overridden via +the query string to `/oauth2/start`. +If _only_ a default is specified and no "allow" then the parameter is +effectively fixed - the default value will always be used and anything +passed to the start URL will be ignored. If _only_ "allow" is specified +but no default then the parameter will only be passed on to the IdP if +the caller provides it, and no value will be sent otherwise. + +Examples: + +# A parameter whose value is fixed + +``` +name: organization +default: +- myorg +``` + +A parameter that is not passed by default, but may be set to one of a +fixed set of values + +``` +name: prompt +allow: +- value: login +- value: consent +- value: select_account +``` + +A parameter that is passed by default but may be overridden by one of +a fixed set of values + +``` +name: prompt +default: ["login"] +allow: +- value: consent +- value: select_account +``` + +A parameter that may be overridden, but only by values that match a +regular expression. For example to restrict `login_hint` to email +addresses in your organization's domain: + +``` +name: login_hint +allow: +- pattern: '^[^@]*@example\.com$' +# this allows at most one "@" sign, and requires "example.com" domain. +``` + +Note that the YAML rules around exactly which characters are allowed +and/or require escaping in different types of string literals are +convoluted. For regular expressions the single quoted form is simplest +as backslash is not considered to be an escape character. Alternatively +use the "chomped block" format `|-`: + +``` + - pattern: |- + ^[^@]*@example\.com$ + +``` + +The hyphen is important, a `|` block would have a trailing newline +character. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name specifies the name of the query parameter. | +| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | +| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | + +### MicrosoftEntraIDOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | +| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | + +### OIDCOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | +| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | +| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | +| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | +| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | +| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | +| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | +| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | +| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | +| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | +| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | +| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | +| `enabledSigningAlgs` | _[]string_ | EnabledSigningAlgs is a list of allowed JWT signing algorithms.
When discovery is enabled, the effective set is the intersection
between this list and the provider's discovered supported algorithms.
By default `RS256` is used if nothing has been discovered or specified. | + +### Provider + +(**Appears on:** [Providers](#providers)) + +Provider holds all configuration for a single provider + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | +| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | +| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | +| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | +| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | +| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | +| `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. | +| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | +| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | +| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | +| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | +| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | +| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | +| `id` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | +| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | +| `name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | +| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | +| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | +| `loginURL` | _string_ | LoginURL is the authentication endpoint | +| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | +| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | +| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint | +| `profileURL` | _string_ | ProfileURL is the profile access endpoint | +| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | +| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | +| `validateURL` | _string_ | ValidateURL is the access token validation endpoint | +| `scope` | _string_ | Scope is the OAuth scope specification | +| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | +| `code_challenge_method` | _string_ | The code challenge method | +| `additionalClaims` | _[]string_ | Additional claims to be obtained from the upstream IDP, either from the id_token or from the userinfo endpoint if configured. | +| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | + +### ProviderType +#### (`string` alias) + +(**Appears on:** [Provider](#provider)) + +ProviderType is used to enumerate the different provider type options +Valid options are: adfs, azure, bitbucket, digitalocean facebook, github, +gitlab, google, keycloak, keycloak-oidc, linkedin, login.gov, nextcloud +and oidc. + +### Providers + +#### ([[]Provider](#provider) alias) + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +The provider can be selected using the `provider` configuration value, or +set in the [`providers` array using +AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). +However, [**the feature to implement multiple providers is not +complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +### SecretSource + +(**Appears on:** [ClaimSource](#claimsource), [HeaderValue](#headervalue), [TLS](#tls)) + +SecretSource references an individual secret value. +Only one source within the struct should be defined at any time. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | + +### Server + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Server represents the configuration for an HTTP(S) server + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `bindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Different types of bind addresses are supported:
* `[http://]:`
* `fd:` (case insensitive)
* `unix://`
Unix sockets are created with default system umask mode, which can be overridden, e.g.: `unix://my-socket,mode=0777`
Square brackets are required for ipv6 address, e.g. `http://[::1]:4180`
Leave blank or set to "-" to disable. | +| `secureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Secure bind addresses need to respond with valid SSL and use the following format:
* `[https://]:`
Square brackets are required for ipv6 address, e.g. `https://[::1]:4180`
Leave blank or set to "-" to disable. | +| `tls` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the
secure traffic and further configuration for the TLS server. | + +### TLS + +(**Appears on:** [Server](#server)) + +TLS contains the information for loading a TLS certificate and key +as well as an optional minimal TLS version that is acceptable. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `key` | _[SecretSource](#secretsource)_ | Key is the TLS key data to use.
Typically this will come from a file. | +| `cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.
Typically this will come from a file. | +| `minVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.
E.g. Set to "TLS1.3" to select TLS version 1.3 | +| `cipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.
E.g.:
- TLS_RSA_WITH_RC4_128_SHA
- TLS_RSA_WITH_AES_256_GCM_SHA384
If not specified, the default Go safe cipher list is used.
List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | + +### URLParameterRule + +(**Appears on:** [LoginURLParameter](#loginurlparameter)) + +URLParameterRule represents a rule by which query parameters +passed to the `/oauth2/start` endpoint are checked to determine whether +they are valid overrides for the given parameter passed to the IdP's +login URL. Either Value or Pattern should be supplied, not both. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _string_ | A Value rule matches just this specific value | +| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | + +### Upstream + +(**Appears on:** [UpstreamConfig](#upstreamconfig)) + +Upstream represents the configuration for an upstream server. +Requests will be proxied to this upstream if the path matches the request path. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `id` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | +| `path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | +| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | +| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | +| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | +| `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | +| `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | +| `flushInterval` | _duration_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | +| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | +| `timeout` | _duration_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | +| `disableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | + +### UpstreamConfig + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +UpstreamConfig is a collection of definitions for upstream servers. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | +| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | diff --git a/docs/versioned_docs/version-7.15.x/configuration/alpha_config.md.tmpl b/docs/versioned_docs/version-7.15.x/configuration/alpha_config.md.tmpl new file mode 100644 index 00000000..e7982055 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/alpha_config.md.tmpl @@ -0,0 +1,281 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +providers: + - id: ... + ...: ... +cookie: + secret: ... + ...: ... +injectRequestHeaders: + - secretSource: + ...: ... +injectResponseHeaders: + - claimSource: + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +# Migration Guide + +This section details breaking changes and migration steps for moving to the new +alpha configuration format. + +## Migrating header injections in v7.14.0 + +From v7.14.0 onward, header injection sources must be explicitly nested. If you +previously relied on squashed fields, update to the new structure before +upgrading: + +```yaml +# before v7.14.0 +injectRequestHeaders: +- name: X-Forwarded-User + values: + - claim: user +- name: X-Custom-Secret-header + values: + - value: my-super-secret + +# v7.14.0 and later +injectRequestHeaders: +- name: X-Forwarded-User + values: + - claimSource: + claim: user +- name: X-Custom-Secret-header + values: + - secretSource: + value: my-super-secret +``` + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +### Validating Alpha Configuration + +Use `--config-test` to validate your alpha configuration without starting the proxy: + +```bash +oauth2-proxy --config core.cfg --alpha-config alpha.yaml --config-test +``` + +This is useful for CI/CD pipelines to catch configuration errors before deployment. +See the [Configuration Validation](./overview.md#configuration-validation) section for more details. + +### How to use environment variables + +The alpha package supports the use of environment variables in place of yaml values, allowing sensitive data to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +### How to inject custom headers + +Configure `injectRequestHeaders` and `injectResponseHeaders` in alpha config YAML. + +```yaml +injectRequestHeaders: + - name: "X-User-Email" + values: + - claimSource: + claim: "email" # extract the email claim contents from the id token + - name: "X-Static-Secret" + values: + # secrets need to be encoded with base64 when directly in the yaml config but will be send decoded + - secretSource: + value: "c3VwZXItc2VjcmV0" + - name: "X-Static-File-Secret" + - secretSource: + fromFile: "/path/to/my/secret" + - name: "X-Static-Env-Secret" + - secretSource: + value: "${MY_SECRET_ENV}" # content still needs to be base64 encoded +injectResponseHeaders: + # Following will result in a header "Authorization: Basic (encoded)" + - name: "Authorization" + values: + - claimSource: + claim: user + prefix: "Basic " + basicAuthPassword: + value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk # base64 encoded password +``` + +**Value sources:** +* `claimSource` - `claim` (session claims either from id token or from profile URL) +* `secretSource` - `value` (base64), `fromFile` (file path) + +**Request option:** `preserveRequestValue: true` retains existing header values + +**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest` + +### How to utilize arbitrary claims provided by your Identity Provider + +With the additionalClaims attribute you can specify which claims you want to extract +from the ID Token or userinfo (ProfileURL) endpoint. + +Configure these on the relevant provider entry: + +```yaml +providers: + - id: my-oidc-provider + provider: oidc + clientID: ${OAUTH_CLIENT_ID} + clientSecret: ${OAUTH_CLIENT_SECRET} + oidcConfig: + issuerURL: https://issuer.example.com + profileURL: https://issuer.example.com/oauth2/userinfo + additionalClaims: + - department + - employee_id + - organization.name +``` + +OAuth2 Proxy resolves each configured claim using the following order: + +1. The raw ID token is checked first. +2. If the claim is not present there and `profileURL` is configured, the userinfo endpoint is queried. +3. If `skipClaimsFromProfileURL: true` is set, only the ID token is used. + +Claims that are not found are ignored rather than causing authentication to fail. + +You can use dot-separated paths for nested JSON objects, for example `organization.name`. +Array indexes are not supported. + +Once loaded, these claims are stored in the session as `additionalClaims`. They can then be +used anywhere session claims are accepted, including header injection: + +```yaml +injectRequestHeaders: + - name: X-Department + values: + - claimSource: + claim: department + - name: X-Organization + values: + - claimSource: + claim: organization.name +``` + +This is useful when your IdP exposes application-specific attributes such as department, +tenant, employee ID, entitlement, or other custom claims that are not part of the default +OAuth2 Proxy session fields. + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference diff --git a/docs/versioned_docs/version-7.15.x/configuration/integrations/caddy.md b/docs/versioned_docs/version-7.15.x/configuration/integrations/caddy.md new file mode 100644 index 00000000..1805e559 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/integrations/caddy.md @@ -0,0 +1,63 @@ +--- +id: caddy +title: Caddy +--- + +Integrate OAuth2 Proxy with Caddy v2 using the `forward_auth` directive. + +**Key features:** +- Simple forward_auth setup +- Automatic header handling +- Custom error handling and redirects + +## Configuring for use with the Caddy (v2) `forward_auth` directive + +The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. + +This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. + +**Following options need to be set on `oauth2-proxy`:** +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```nginx title="Caddyfile" +example.com { + # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. + # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. + handle /oauth2/* { + reverse_proxy oauth2-proxy.internal:4180 { + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. + header_up X-Real-IP {remote_host} + header_up X-Forwarded-Uri {uri} + } + } + + # Requests to other paths are first processed by oauth2-proxy for authentication. + handle { + forward_auth oauth2-proxy.internal:4180 { + uri /oauth2/auth + + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. + header_up X-Real-IP {remote_host} + + # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. + # Make sure to configure the --set-xauthrequest flag to enable this feature. + #copy_headers X-Auth-Request-User X-Auth-Request-Email + + # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. + @error status 401 + handle_response @error { + redir * /oauth2/sign_in?rd={scheme}://{host}{uri} + } + } + + # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. + reverse_proxy upstream.internal:3000 + } +} +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.15.x/configuration/integrations/headlamp.md b/docs/versioned_docs/version-7.15.x/configuration/integrations/headlamp.md new file mode 100644 index 00000000..a6f6ac73 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/integrations/headlamp.md @@ -0,0 +1,105 @@ +--- +id: headlamp +title: Headlamp +--- + +Modern, actively maintained Kubernetes web UI with OAuth2 Proxy integration examples. + +**Key features:** +- Active development and maintenance +- Modern, intuitive interface +- Multi-cluster support +- Plugin system +- Works with all OAuth2 providers + +## Configuring for use with Headlamp + +[Headlamp](https://headlamp.dev/) is a modern, user-friendly Kubernetes web UI that can be integrated with OAuth2 Proxy for authentication. This is a recommended alternative to the deprecated Kubernetes Dashboard. + +### Architecture + +``` +User → Ingress → OAuth2 Proxy → Authentication Provider (e.g., Azure Entra ID) + ↓ + Headlamp +``` + +### Prerequisites + +- Kubernetes cluster (e.g., AKS, EKS, GKE, or self-hosted) +- Headlamp installed in the cluster +- OAuth2 provider configured (Azure Entra ID, Google, GitHub, etc.) +- Ingress controller (Nginx, Traefik, etc.) + +### Configuration Overview + +When integrating Headlamp with OAuth2 Proxy, the OAuth2 Proxy acts as a reverse proxy in front of Headlamp: + +1. User requests access to Headlamp +2. Ingress forwards to OAuth2 Proxy +3. OAuth2 Proxy authenticates the user via the OAuth2 provider +4. After successful authentication, OAuth2 Proxy proxies requests to Headlamp +5. Headlamp receives the authenticated user information via headers + +### OAuth2 Proxy Configuration + +Configure OAuth2 Proxy to proxy to the Headlamp service: + +```yaml +upstreamConfig: + upstreams: + - id: headlamp + path: / + uri: http://headlamp-service.headlamp-namespace.svc.cluster.local:4466 +``` + +Enable the necessary headers: + +```yaml +extraArgs: + reverse-proxy: true + pass-authorization-header: true + set-xauthrequest: true + email-domain: "*" # Or restrict to your organization +``` + +### Example with Azure Entra ID on AKS + +For detailed instructions on deploying Headlamp with OAuth2 Proxy on Azure Kubernetes Service using Azure Entra ID, see the official Headlamp documentation: + +https://headlamp.dev/docs/latest/installation/in-cluster/aks-cluster-oauth/ + +Key steps include: + +1. **Set up AKS with OIDC**: Enable Microsoft Entra ID authentication with Kubernetes RBAC +2. **Create Azure App Registration**: Configure redirect URI and create client secret +3. **Deploy Headlamp**: Install Headlamp via Helm in your cluster +4. **Deploy OAuth2 Proxy**: Configure OAuth2 Proxy with Entra ID provider settings and upstream pointing to Headlamp +5. **Configure Ingress**: Set up Ingress to route traffic through OAuth2 Proxy to Headlamp +6. **Set RBAC Policies**: Apply Kubernetes RBAC bindings based on users or groups + +### Integration with Other Providers + +The same integration pattern works with other OAuth2 providers supported by OAuth2 Proxy: + +- **Google**: Use the Google provider configuration +- **GitHub**: Use the GitHub provider configuration +- **GitLab**: Use the GitLab provider configuration +- **Keycloak**: Use the Keycloak OIDC provider configuration +- **Any OIDC Provider**: Use the generic OIDC provider configuration + +For provider-specific configuration examples, see the [OAuth Provider Configuration](../providers/index.md) documentation. + +### Benefits Over Kubernetes Dashboard + +Headlamp offers several advantages: + +- **Active Development**: Headlamp is actively maintained and developed +- **Modern UI**: Clean, intuitive interface with better UX +- **Plugin System**: Extensible with custom plugins +- **Multi-cluster Support**: Built-in support for managing multiple clusters +- **Desktop App**: Available as both web UI and desktop application + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.15.x/configuration/integrations/index.md b/docs/versioned_docs/version-7.15.x/configuration/integrations/index.md new file mode 100644 index 00000000..b773910b --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/integrations/index.md @@ -0,0 +1,41 @@ +--- +id: index +title: Integrations +--- + +This section provides configuration examples for integrating OAuth2 Proxy with various reverse proxies, ingress controllers, and Kubernetes web UIs. + +## Reverse Proxies and Ingress Controllers + +OAuth2 Proxy can be integrated with popular reverse proxies and ingress controllers to add authentication to your applications: + +- [Nginx](nginx.md) +- [Traefik](traefik.md) +- [caddy](caddy.md) + +## Kubernetes Web UIs + +OAuth2 Proxy can also be used to add authentication to Kubernetes web user interfaces: + +- [Headlamp](headlamp.md) ✨ *Recommended* +- [Kubernetes Dashboard](kubernetes-dashboard.md) ⚠️ *Deprecated* + +:::tip +When integrating with Kubernetes web UIs, make sure to: +1. Configure the Ingress to pass the Authorization header with the bearer token +2. Increase buffer sizes for large OIDC tokens (especially with Azure Entra ID) +3. Set up appropriate Kubernetes RBAC permissions for your users or groups +::: + +## General Requirements + +Most integrations require the following OAuth2 Proxy configuration: + +- `--reverse-proxy=true`: Required to correctly handle `X-Forwarded-*` headers +- **Session storage**: For production deployments with large tokens due to a lot of claims like AD groups, use `--session-store-type=redis` + +For provider-specific configuration, see the [OAuth Provider Configuration](../providers/index.md) documentation. + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.15.x/configuration/integrations/kubernetes-dashboard.md b/docs/versioned_docs/version-7.15.x/configuration/integrations/kubernetes-dashboard.md new file mode 100644 index 00000000..5f210768 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/integrations/kubernetes-dashboard.md @@ -0,0 +1,289 @@ +--- +id: kubernetes-dashboard +title: Kubernetes Dashboard +--- + +:::warning Deprecated Project +Kubernetes Dashboard has been deprecated and discontinued as of January 2025. See the [official announcement](https://github.com/kubernetes/dashboard/commit/0ba796dce6916bb6ca5da5ca0b3ab22cecfd1e18) for more information. + +You may want to consider alternative solutions such as [Headlamp](./headlamp.md). +::: + +## Kubernetes Dashboard on AKS with Azure Entra ID + +Integration guide for the deprecated Kubernetes Dashboard, including comprehensive Azure Entra ID configuration on AKS with detailed troubleshooting and RBAC setup. + +### Architecture + +``` +User → Nginx Ingress → OAuth2 Proxy → Entra ID + ↓ + Kubernetes Dashboard +``` + +The integration flow: +1. Unauthenticated requests to Dashboard are intercepted by Nginx Ingress +2. Nginx redirects to OAuth2 Proxy for authentication +3. OAuth2 Proxy redirects to Entra ID login +4. After successful authentication, OAuth2 Proxy receives ID token from Entra ID +5. OAuth2 Proxy sets Authorization header with the bearer token +6. Nginx forwards the request with token to Kubernetes Dashboard +7. Dashboard validates the token and grants access based on AKS RBAC configuration + +### Prerequisites + +- AKS cluster with Entra ID integration enabled +- Kubernetes Dashboard installed (version 7.x or later) +- NGINX Ingress Controller installed +- Entra ID App Registration configured with: + - Redirect URI: `https://your-oauth2-domain.com/oauth2/callback` + - API Permissions: `openid`, `email`, `profile` + - Groups claim enabled (if using group-based RBAC) +- Users or groups assigned appropriate Kubernetes RBAC permissions + +### Alpha Configuration Example + +Using [Alpha Configuration](../alpha_config.md) with the OAuth2 Proxy Helm chart: + +```yaml +alphaConfig: + enabled: true + configData: + providers: + - id: azure-entra + provider: entra-id + clientID: YOUR_CLIENT_ID + clientSecret: YOUR_CLIENT_SECRET + oidcConfig: + issuerURL: https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0 + audienceClaims: + - aud + emailClaim: email + groupsClaim: groups + userIDClaim: oid + scope: openid email profile + + upstreamConfig: + upstreams: + - id: static + path: / + static: true + staticCode: 200 + + # Response headers passed to Dashboard via Nginx + injectResponseHeaders: + - name: Authorization + values: + - claim: id_token + prefix: "Bearer " + - name: X-Auth-Request-User + values: + - claim: email + - name: X-Auth-Request-Email + values: + - claim: email + - name: X-Auth-Request-Groups + values: + - claim: groups + + server: + BindAddress: "0.0.0.0:4180" + +extraArgs: + cookie-domain: ".your-domain.com" + whitelist-domain: ".your-domain.com" + email-domain: "*" # Or restrict to your organization + skip-provider-button: true + reverse-proxy: true + pass-authorization-header: true + set-xauthrequest: true + +sessionStorage: + type: redis + +redis: + enabled: true + auth: + enabled: true + +ingress: + enabled: true + className: nginx + hosts: + - OAuth2 Proxy.your-domain.com + path: /oauth2 + pathType: Prefix +``` + +### Kubernetes Dashboard Ingress + +**Critical**: The Ingress must include `Authorization` in the `auth-response-headers` annotation: + +```yaml +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: kubernetes-dashboard + namespace: kubernetes-dashboard + annotations: + nginx.ingress.kubernetes.io/backend-protocol: "HTTPS" + nginx.ingress.kubernetes.io/force-ssl-redirect: "true" + + # OAuth2 Proxy authentication + nginx.ingress.kubernetes.io/auth-url: "https://OAuth2 Proxy.your-domain.com/oauth2/auth" + nginx.ingress.kubernetes.io/auth-signin: "https://OAuth2 Proxy.your-domain.com/oauth2/start?rd=$scheme://$best_http_host$request_uri" + + # Include Authorization header with bearer token + nginx.ingress.kubernetes.io/auth-response-headers: "Authorization, X-Auth-Request-User, X-Auth-Request-Email" + + # Buffer sizes for large tokens (Entra tokens can exceed 4KB) + nginx.ingress.kubernetes.io/proxy-buffer-size: "256k" + nginx.ingress.kubernetes.io/proxy-buffers-number: "4" + nginx.ingress.kubernetes.io/proxy-busy-buffers-size: "256k" +spec: + ingressClassName: nginx + tls: + - hosts: + - dashboard.your-domain.com + secretName: dashboard-tls + rules: + - host: dashboard.your-domain.com + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: kubernetes-dashboard-kong-proxy + port: + number: 443 +``` + +### RBAC Configuration + +Assign Kubernetes permissions to Entra ID users or groups. + +**User-based:** +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: dashboard-user-admin +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: cluster-admin +subjects: + - kind: User + name: "user@your-domain.com" # Email from Entra ID token + apiGroup: rbac.authorization.k8s.io +``` + +**Group-based (recommended):** +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: dashboard-admins-group +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: cluster-admin +subjects: + - kind: Group + name: "YOUR_ENTRA_GROUP_OBJECT_ID" # Entra ID Group Object ID + apiGroup: rbac.authorization.k8s.io +``` + +For production, create custom roles with limited permissions instead of using `cluster-admin`. + +### Troubleshooting + +**Dashboard still asks for token after authentication** + +Verify that: +1. `injectResponseHeaders` in alphaConfig includes Authorization header with id_token claim +2. Dashboard Ingress includes `Authorization` in `auth-response-headers` annotation +3. Buffer sizes are sufficient for large tokens (set to 256k as shown above) +4. Check OAuth2 Proxy logs for successful token generation: `kubectl logs -n OAuth2 Proxy ` + +**"Unauthorized" or "Invalid token" errors** + +Common causes: +1. User/group not configured in Kubernetes RBAC + - Check: `kubectl get clusterrolebindings | grep ` +2. Token validation failed + - Verify AKS Entra ID integration is enabled + - Check Dashboard logs: `kubectl logs -n kubernetes-dashboard ` +3. Incorrect OAuth2 Proxy configuration + - Ensure `reverse-proxy: true` is set + - Verify issuer URL matches your tenant + +**Groups not included in token** + +To include groups in the token: +1. In Entra ID App Registration, go to **Token configuration** +2. Add **groups claim** and select security groups +3. Or edit the manifest and add: `"groupMembershipClaims": "SecurityGroup"` +4. For 200+ groups, ensure scope includes `User.Read` for group overage handling +5. Verify groups appear in token: check OAuth2 Proxy logs + +**Session expires too quickly** + +Configure cookie expiration: +```yaml +extraArgs: + cookie-expire: "24h" + cookie-refresh: "1h" +``` + +### Using Workload Identity (Passwordless) + +For production environments, use Workload Identity instead of client secrets: + +```yaml +config: + clientID: "YOUR_CLIENT_ID" + secretKeys: # Exclude client-secret + - client-id + - cookie-secret + cookieSecret: "YOUR_COOKIE_SECRET" + +serviceAccount: + annotations: + azure.workload.identity/client-id: YOUR_CLIENT_ID + azure.workload.identity/tenant-id: YOUR_TENANT_ID + +podLabels: + azure.workload.identity/use: "true" + +alphaConfig: + enabled: true + configData: + providers: + - id: azure-entra + provider: entra-id + clientID: YOUR_CLIENT_ID + oidcConfig: + issuerURL: https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0 + # ... other config + entraIdConfig: + federatedTokenAuth: true +``` + +This requires: +- AKS with OIDC issuer and Workload Identity enabled +- Federated identity credential configured in Entra ID App Registration +- Service account annotated with `azure.workload.identity/client-id` + +For detailed Workload Identity setup instructions, see the [Workload Identity section](../providers/ms_entra_id.md#workload-identity) in the Microsoft Entra ID provider documentation. + +## Integration with Other Providers + +While this guide focuses on Azure Entra ID, Kubernetes Dashboard can be integrated with other OAuth2 providers supported by OAuth2 Proxy. The key requirements remain the same: + +1. **Authorization Header**: Pass the bearer token via the `Authorization` header +2. **RBAC Configuration**: Configure Kubernetes RBAC for your authentication provider's users/groups +3. **Buffer Sizes**: Ensure adequate buffer sizes for tokens (especially important for OIDC providers) + +For provider-specific configuration examples, see the [OAuth Provider Configuration](../providers/index.md) documentation. diff --git a/docs/versioned_docs/version-7.15.x/configuration/integrations/nginx.md b/docs/versioned_docs/version-7.15.x/configuration/integrations/nginx.md new file mode 100644 index 00000000..ca6402a9 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/integrations/nginx.md @@ -0,0 +1,174 @@ +--- +id: nginx +title: Nginx +--- + +Configure OAuth2 Proxy with Nginx using the `auth_request` directive. Includes examples for both standalone Nginx configurations and Kubernetes ingress-nginx with annotations. + +**Key features:** +- Support for `auth_request` directive +- Kubernetes Ingress annotations +- Multi-part cookie handling for large tokens +- Session refresh support + +## Configuring for use with the Nginx `auth_request` directive + +**This option requires `--reverse-proxy` option to be set.** + +The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: + +```nginx +server { + listen 443 ssl; + server_name ...; + include ssl/ssl.conf; + + location /oauth2/ { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Auth-Request-Redirect $request_uri; + # or, if you are handling multiple domains: + # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; + } + location = /oauth2/auth { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; + # nginx auth_request includes headers but not body + proxy_set_header Content-Length ""; + proxy_pass_request_body off; + } + + location / { + auth_request /oauth2/auth; + error_page 401 = @oauth2_signin; + + # pass information via X-User and X-Email headers to backend, + # requires running with --set-xauthrequest flag + auth_request_set $user $upstream_http_x_auth_request_user; + auth_request_set $email $upstream_http_x_auth_request_email; + proxy_set_header X-User $user; + proxy_set_header X-Email $email; + + # if you enabled --pass-access-token, this will pass the token to the backend + auth_request_set $token $upstream_http_x_auth_request_access_token; + proxy_set_header X-Access-Token $token; + + # if you enabled --cookie-refresh, this is needed for it to work with auth_request + auth_request_set $auth_cookie $upstream_http_set_cookie; + add_header Set-Cookie $auth_cookie; + + # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb + # limit and so the OAuth2 Proxy splits these into multiple parts. + # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, + # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. + auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; + + # Extract the Cookie attributes from the first Set-Cookie header and append them + # to the second part ($upstream_cookie_* variables only contain the raw cookie content) + if ($auth_cookie ~* "(; .*)") { + set $auth_cookie_name_0 $auth_cookie; + set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; + } + + # Send both Set-Cookie headers now if there was a second part + if ($auth_cookie_name_upstream_1) { + add_header Set-Cookie $auth_cookie_name_0; + add_header Set-Cookie $auth_cookie_name_1; + } + + proxy_pass http://backend/; + # or "root /path/to/site;" or "fastcgi_pass ..." etc + } + + # Named location for handling OAuth2 sign-in redirects + # This ensures the browser receives a proper 302 redirect that it will follow + location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; + } +} +``` + +### Understanding the `error_page` redirect pattern + +The `auth_request` directive expects the authentication endpoint (`/oauth2/auth`) to return: +- **2xx**: Request is authenticated, allow access +- **401 or 403**: Request is not authenticated, deny access + +When a 401 is returned, nginx triggers the `error_page` directive. The recommended pattern uses a **named location** (`@oauth2_signin`) that returns a proper **302 redirect**: + +```nginx +error_page 401 = @oauth2_signin; + +location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; +} +``` + +:::warning Avoid `error_page 401 =403` with sign_in +Some older configurations use `error_page 401 =403 /oauth2/sign_in`. While this works for displaying the sign-in page, it returns a **403 status code** with a `Location` header. Browsers do not automatically follow redirects on 403 responses, which can cause issues when using `--skip-provider-button=true` (users see a "Found." link instead of being automatically redirected). + +The named location pattern above ensures the browser receives a standard **302 redirect** that works correctly with all oauth2-proxy configurations. +::: + +### Browser vs API Routes + +:::important When to use redirects +Redirecting authentication failures (302 to `/oauth2/sign_in`) should **only be used for browser-facing routes**. API or machine clients should receive a plain 401/403 response without redirect. +::: + +#### Browser-facing routes (HTML, UI) + +For interactive browser routes where users should be redirected to sign in: + +```nginx +location / { + auth_request /oauth2/auth; + error_page 401 = @oauth2_signin; + proxy_pass http://backend/; +} + +location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; +} +``` + +#### API / Machine routes (no redirect) + +For API endpoints where clients expect a 401/403 status code (not a redirect): + +```nginx +location /api/ { + auth_request /oauth2/auth; + error_page 401 =401; # Pass through the 401 status + proxy_pass http://backend/; +} +``` + +This ensures: +- ✅ Browsers get a redirect and smooth login flow +- ✅ API clients fail fast with appropriate HTTP status codes +- ✅ `/oauth2/auth` remains a pure boolean oracle (2xx/401) + +When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: + +```yaml +nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" +nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" +``` + +This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. + +It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). + +:::tip Kubernetes Dashboard with Azure Entra ID +For a complete example of integrating oauth2-proxy with Kubernetes Dashboard on AKS using Azure Entra ID, including RBAC configuration and troubleshooting, see the [Kubernetes Dashboard on AKS](../providers/ms_entra_id.md#kubernetes-dashboard-on-aks) section in the Microsoft Entra ID provider documentation. +::: + +You have to substitute *name* with the actual cookie name you configured via --cookie-name parameter. If you don't set a custom cookie name the variable should be "$upstream_cookie__oauth2_proxy_1" instead of "$upstream_cookie_name_1" and the new cookie-name should be "_oauth2_proxy_1=" instead of "name_1=". + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.15.x/configuration/integrations/traefik.md b/docs/versioned_docs/version-7.15.x/configuration/integrations/traefik.md new file mode 100644 index 00000000..43830d43 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/integrations/traefik.md @@ -0,0 +1,192 @@ +--- +id: traefik +title: Traefik +--- + +Set up OAuth2 Proxy with Traefik v2 using the `ForwardAuth` middleware. Includes examples for both error-based redirects and static upstream configurations. + +**Key features:** +- ForwardAuth middleware integration +- Error middleware for 401 redirects +- Static upstream configuration (202 responses) +- Dynamic file configuration examples + + +## Configuring for use with the Traefik (v2) `ForwardAuth` middleware + +**This option requires `--reverse-proxy` option to be set.** + +### ForwardAuth with 401 errors middleware + +The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: + +```yaml +http: + routers: + a-service: + rule: "Host(`a-service.example.com`)" + service: a-service-backend + middlewares: + - oauth-errors + - oauth-auth + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth: + rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + oauth-errors: + errors: + status: + - "401-403" + service: oauth-backend + query: "/oauth2/sign_in?rd={url}" + statusRewrites: + "401": 302 +``` + +:::caution Troubleshooting: Browser shows "Found." instead of redirecting +When using the Errors middleware without `statusRewrites`, the redirect response from oauth2-proxy can be served within the original 401/403 status context. This causes some browsers to display a "Found." link instead of automatically following the redirect to the identity provider. + +Adding `statusRewrites` to rewrite `401 -> 302` ensures the browser treats the response as a proper redirect and follows it automatically. +::: + +### ForwardAuth with static upstreams configuration + +Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint + +**Following options need to be set on `oauth2-proxy`:** +- `--upstream=static://202`: Configures a static response for authenticated sessions +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```yaml +http: + routers: + a-service-route-1: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" + service: a-service-backend + middlewares: + - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + a-service-route-2: + rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" + service: a-service-backend + middlewares: + - oauth-auth-wo-redirect # unauthenticated session will return a 401 + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + services-oauth2-route: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth2-proxy-route: + rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + b-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.3:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth-redirect: + forwardAuth: + address: https://oauth.example.com/ + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization + oauth-auth-wo-redirect: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.15.x/configuration/overview.md b/docs/versioned_docs/version-7.15.x/configuration/overview.md new file mode 100644 index 00000000..37f385c7 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/overview.md @@ -0,0 +1,446 @@ +--- +id: overview +title: Overview +--- + +`oauth2-proxy` can be configured via [command line options](#command-line-options), [environment variables](#environment-variables) or [config file](#config-file) (in decreasing order of precedence, i.e. command line options will overwrite environment variables and environment variables will overwrite configuration file settings). + +## Generating a Cookie Secret + +To generate a strong cookie secret use one of the below commands: + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + + +```shell +python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())' +``` + + + + +```shell +dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64 | tr -d -- '\n' | tr -- '+/' '-_' ; echo +``` + + + + +```shell +openssl rand -base64 32 | tr -- '+/' '-_' +``` + + + + +```powershell +# Add System.Web assembly to session, just in case +Add-Type -AssemblyName System.Web +[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([System.Web.Security.Membership]::GeneratePassword(32,4))).Replace("+","-").Replace("/","_") +``` + + + + +```hcl +# Valid 32 Byte Base64 URL encoding set that will decode to 24 []byte AES-192 secret +resource "random_password" "cookie_secret" { + length = 32 + override_special = "-_" +} +``` + + + + +## Config File + +Every command line argument can be specified in a config file by replacing hyphens (-) with underscores (\_). If the argument can be specified multiple times, the config option should be plural (trailing s). + +An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/oauth2-proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `--config=/etc/oauth2-proxy.cfg` + +## Config Options + +### Command Line Options + +| Flag | Description | +| ---------------- | ------------------------------------------------------- | +| `--config` | path to config file | +| `--config-test` | test configuration and exit (for CI/CD validation) | +| `--version` | print version string | + +## Configuration Validation + +The `--config-test` flag validates your configuration file without starting the proxy server. This is useful for: +- **CI/CD pipelines**: Pre-deployment validation +- **Configuration management**: Testing before applying changes +- **Debugging**: Verifying syntax and required fields + +### Usage + +```bash +# Test legacy config +oauth2-proxy --config /etc/oauth2-proxy.cfg --config-test + +# Test alpha config +oauth2-proxy --config /etc/core.cfg --alpha-config /etc/alpha.yaml --config-test + +# CI/CD pre-deployment check +# Returns with exit code 1 if any validation errors occur +oauth2-proxy --config new-config.cfg --config-test +``` + +### Exit Codes + +- **0**: Configuration is valid ✅ +- **1**: Configuration is invalid (errors printed to stderr) ❌ + +### Validation Coverage + +The `--config-test` flag performs the **same comprehensive validation** as normal startup, including: +- Required fields (client ID, client secret, cookie secret, etc.) +- Syntax validation (TOML/YAML parsing) +- Provider configuration +- Upstream server definitions +- Session store connectivity (e.g., Redis network checks if configured) + +**Note**: Cannot be combined with `--convert-config-to-alpha`. + +### General Provider Options + +Provider specific options can be found on their respective subpages. + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| flag: `--acr-values`
toml: `acr_values` | string | optional, see [docs](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues) | `""` | +| flag: `--allowed-group`
toml: `allowed_groups` | string \| list | Restrict login to members of a group or list of groups. Furthermore, if you aren't setting the `scope` and use `allowed_groups` with the generic OIDC provider the scope `groups` gets added implicitly. | | +| flag: `--approval-prompt`
toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` | +| flag: `--backend-logout-url`
toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | | +| flag: `--client-id`
toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | | +| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret. The file must contain the secret only, with no trailing newline | | +| flag: `--client-secret`
toml: `client_secret` | string | the OAuth Client Secret | | +| flag: `--code-challenge-method`
toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | | +| flag: `--insecure-oidc-allow-unverified-email`
toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false | +| flag: `--insecure-oidc-skip-issuer-verification`
toml: `insecure_oidc_skip_issuer_verification` | bool | allow the OIDC issuer URL to differ from the expected (currently required for Azure multi-tenant compatibility) | false | +| flag: `--insecure-oidc-skip-nonce`
toml: `insecure_oidc_skip_nonce` | bool | skip verifying the OIDC ID Token's nonce claim | true | +| flag: `--jwt-key-file`
toml: `jwt_key_file` | string | path to the private key file in PEM format used to sign the JWT so that you can say something like `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem`: required by login.gov | | +| flag: `--jwt-key`
toml: `jwt_key` | string | private key in PEM format used to sign JWT, so that you can say something like `--jwt-key="${OAUTH2_PROXY_JWT_KEY}"`: required by login.gov | | +| flag: `--login-url`
toml: `login_url` | string | Authentication endpoint | | +| flag: `--auth-request-response-mode`
toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | | +| flag: `--oidc-audience-claim`
toml: `oidc_audience_claims` | string | which OIDC claim contains the audience | `"aud"` | +| flag: `--oidc-email-claim`
toml: `oidc_email_claim` | string | which OIDC claim contains the user's email | `"email"` | +| flag: `--oidc-extra-audience`
toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` | +| flag: `--oidc-groups-claim`
toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` | +| flag: `--oidc-issuer-url`
toml: `oidc_issuer_url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | | +| flag: `--oidc-jwks-url`
toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled and public key files are not provided | | +| flag: `--oidc-public-key-file`
toml: `oidc_public_key_files` | string | Path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times). Required if OIDC discovery is disabled na JWKS URL isn't provided | | +| flag: `--oidc-enabled-signing-alg`
toml: `oidc_enabled_signing_algs` | string \| list | List of allowed JWT signing algorithms. When oidc discovery is enabled, the effective set is the intersection between this list and the provider's discovered supported algorithms. | | +| flag: `--profile-url`
toml: `profile_url` | string | Profile access endpoint | | +| flag: `--prompt`
toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` | +| flag: `--provider-ca-file`
toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. | | +| flag: `--provider-display-name`
toml: `provider_display_name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) | +| flag: `--provider`
toml: `provider` | string | OAuth provider | google | +| flag: `--pubjwk-url`
toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | | +| flag: `--redeem-url`
toml: `redeem_url` | string | Token redemption endpoint | | +| flag: `--scope`
toml:`scope` | string | OAuth scope specification. Every provider has a default list of scopes which will be used in case no scope is configured. | | +| flag: `--skip-claims-from-profile-url`
toml: `skip_claims_from_profile_url` | bool | skip request to Profile URL for resolving claims not present in id_token | false | +| flag: `--skip-oidc-discovery`
toml: `skip_oidc_discovery` | bool | bypass OIDC endpoint discovery. `--login-url`, `--redeem-url` and `--oidc-jwks-url` must be configured in this case | false | +| flag: `--use-system-trust-store`
toml: `use_system_trust_store` | bool | Determines if `provider-ca-file` files and the system trust store are used. If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | false | +| flag: `--validate-url`
toml: `validate_url` | string | Access token validation endpoint | | + +### Cookie Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | +| flag: `--cookie-csrf-expire`
toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m | +| flag: `--cookie-csrf-per-request`
toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false | +| flag: `--cookie-csrf-per-request-limit`
toml: `cookie_csrf_per_request_limit` | int | Sets a limit on the number of CSRF requests cookies that oauth2-proxy will create. The oldest cookie will be removed. Useful if users end up with 431 Request headers too large status codes. Only effective if --cookie-csrf-per-request is true | "infinite" | +| flag: `--cookie-csrf-samesite`
toml: `cookie_csrf_samesite` | string | set SameSite CSRF cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). When using the default setting, the CSRF cookie samesite value is taken from the session cookie configuration. | `""` | +| flag: `--cookie-domain`
toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | | +| flag: `--cookie-expire`
toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s | +| flag: `--cookie-httponly`
toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true | +| flag: `--cookie-name`
toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` | +| flag: `--cookie-path`
toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` | +| flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | +| flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | +| flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | +| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | File containing the cookie secret (must be raw binary, exactly 16, 24, or 32 bytes). Use dd if=/dev/urandom bs=32 count=1 > cookie.secret to generate | | +| flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | + +[^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) + +### Header Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--basic-auth-password`
toml: `basic_auth_password` | string | the password to set when passing the HTTP Basic Auth header | | +| flag: `--set-xauthrequest`
toml: `set_xauthrequest` | bool | set X-Auth-Request-User, X-Auth-Request-Groups, X-Auth-Request-Email and X-Auth-Request-Preferred-Username response headers (useful in Nginx auth_request mode). When used with `--pass-access-token`, X-Auth-Request-Access-Token is added to response headers. | false | +| flag: `--set-authorization-header`
toml: `set_authorization_header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false | +| flag: `--set-basic-auth`
toml: `set_basic_auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false | +| flag: `--skip-auth-strip-headers`
toml: `skip_auth_strip_headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy | true | +| flag: `--pass-access-token`
toml: `pass_access_token` | bool | pass OAuth access_token to upstream via X-Forwarded-Access-Token header. When used with `--set-xauthrequest` this adds the X-Auth-Request-Access-Token header to the response | false | +| flag: `--pass-authorization-header`
toml: `pass_authorization_header` | bool | pass OIDC IDToken to upstream via Authorization Bearer header | false | +| flag: `--pass-basic-auth`
toml: `pass_basic_auth` | bool | pass HTTP Basic Auth, X-Forwarded-User, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | +| flag: `--prefer-email-to-user`
toml: `prefer_email_to_user` | bool | Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, e.g. htaccess authentication. Used in conjunction with `--pass-basic-auth` and `--pass-user-headers` | false | +| flag: `--pass-user-headers`
toml: `pass_user_headers` | bool | pass X-Forwarded-User, X-Forwarded-Groups, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | + +### Logging Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------- | --------------------------------------------------- | +| flag: `--auth-logging-format`
toml: `auth_logging_format` | string | Template for authentication log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--auth-logging`
toml: `auth_logging` | bool | Log authentication attempts | true | +| flag: `--errors-to-info-log`
toml: `errors_to_info_log` | bool | redirects error-level logging to default log channel instead of stderr | false | +| flag: `--exclude-logging-path`
toml: `exclude_logging_paths` | string | comma separated list of paths to exclude from logging, e.g. `"/ping,/path2"` | `""` (no paths excluded) | +| flag: `--logging-compress`
toml: `logging_compress` | bool | Should rotated log files be compressed using gzip | false | +| flag: `--logging-filename`
toml: `logging_filename` | string | File to log requests to, empty for `stdout` | `""` (stdout) | +| flag: `--logging-local-time`
toml: `logging_local_time` | bool | Use local time in log files and backup filenames instead of UTC | true (local time) | +| flag: `--logging-max-age`
toml: `logging_max_age` | int | Maximum number of days to retain old log files | 7 | +| flag: `--logging-max-backups`
toml: `logging_max_backups` | int | Maximum number of old log files to retain; 0 to disable | 0 | +| flag: `--logging-max-size`
toml: `logging_max_size` | int | Maximum size in megabytes of the log file before rotation | 100 | +| flag: `--request-id-header`
toml: `request_id_header` | string | Request header to use as the request ID in logging | X-Request-Id | +| flag: `--request-logging-format`
toml: `request_logging_format` | string | Template for request log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--request-logging`
toml: `request_logging` | bool | Log requests | true | +| flag: `--silence-ping-logging`
toml: `silence_ping_logging` | bool | disable logging of requests to ping & ready endpoints | false | +| flag: `--standard-logging-format`
toml: `standard_logging_format` | string | Template for standard log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--standard-logging`
toml: `standard_logging` | bool | Log standard runtime information | true | + +### Page Template Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--banner`
toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | | +| flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | | +| flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | +| flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | +| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | | +| flag: `--show-debug-on-error`
toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false | + +### Probe Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------- | ------ | ---------------------------------------------------------- | ----------------------------- | +| flag: `--ping-path`
toml: `ping_path` | string | the ping endpoint that can be used for basic health checks | `"/ping"` | +| flag: `--ping-user-agent`
toml: `ping_user_agent` | string | a User-Agent that can be used for basic health checks | `""` (don't check user agent) | +| flag: `--ready-path`
toml: `ready_path` | string | the ready endpoint that can be used for deep health checks | `"/ready"` | +| flag: `--gcp-healthchecks`
toml: `gcp_healthchecks` | bool | Enable GCP/GKE healthcheck endpoints (deprecated) | false | + +### Proxy Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--bearer-token-login-fallback`
toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | + +[^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. + +### Server Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | +| flag: `--http-address`
toml: `http_address` | string | `[http://]:` or `unix://` or `fd:` (case insensitive) to listen on for HTTP clients. Unix sockets are created with default system umask mode, which can be overridden, e.g. `unix://my-socket,mode=0777`. Square brackets are required for ipv6 address, e.g. `http://[::1]:4180` | `"127.0.0.1:4180"` | +| flag: `--https-address`
toml: `https_address` | string | `[https://]:` to listen on for HTTPS clients. Square brackets are required for ipv6 address, e.g. `https://[::1]:443` | `":443"` | +| flag: `--metrics-address`
toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` | +| flag: `--metrics-secure-address`
toml: `metrics_secure_address` | string | the address prometheus metrics will be scraped from if using HTTPS | `""` | +| flag: `--metrics-tls-cert-file`
toml: `metrics_tls_cert_file` | string | path to certificate file for secure metrics server | `""` | +| flag: `--metrics-tls-key-file`
toml: `metrics_tls_key_file` | string | path to private key file for secure metrics server | `""` | +| flag: `--tls-cert-file`
toml: `tls_cert_file` | string | path to certificate file | | +| flag: `--tls-key-file`
toml: `tls_key_file` | string | path to private key file | | +| flag: `--tls-cipher-suite`
toml: `tls_cipher_suites` | string \| list | Restricts TLS cipher suites used by server to those listed (e.g. TLS_RSA_WITH_RC4_128_SHA) (may be given multiple times). If not specified, the default Go safe cipher list is used. List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | | +| flag: `--tls-min-version`
toml: `tls_min_version` | string | minimum TLS version that is acceptable, either `"TLS1.2"` or `"TLS1.3"` | `"TLS1.2"` | + +### Session Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--session-cookie-minimal`
toml: `session_cookie_minimal` | bool | strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only) | false | +| flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | +| flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | +| flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-ca-path`
toml: `redis_ca_path` | string | Path to a CA certificates file that should be used when connecting to redis. If not specified, the system cert pool is used instead. | | +| flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | +| flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | +| flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | +| flag: `--redis-sentinel-master-name`
toml: `redis_sentinel_master_name` | string | Redis sentinel master name. Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-sentinel-connection-urls`
toml: `redis_sentinel_connection_urls` | string \| list | List of Redis sentinel connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-use-cluster`
toml: `redis_use_cluster` | bool | Connect to redis cluster. Must set `--redis-cluster-connection-urls` to use this feature | false | +| flag: `--redis-use-sentinel`
toml: `redis_use_sentinel` | bool | Connect to redis via sentinels. Must set `--redis-sentinel-master-name` and `--redis-sentinel-connection-urls` to use this feature | false | +| flag: `--redis-connection-idle-timeout`
toml: `redis_connection_idle_timeout` | int | Redis connection idle timeout seconds. If Redis [timeout](https://redis.io/docs/reference/clients/#client-timeouts) option is set to non-zero, the `--redis-connection-idle-timeout` must be less than Redis timeout option. Example: if either redis.conf includes `timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` | 0 | + +### Upstream Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | +| flag: `--flush-interval`
toml: `flush_interval` | duration | period between flushing response buffers when streaming responses | `"1s"` | +| flag: `--pass-host-header`
toml: `pass_host_header` | bool | pass the request Host Header to upstream | true | +| flag: `--proxy-websockets`
toml: `proxy_websockets` | bool | enables WebSocket proxying | true | +| flag: `--ssl-upstream-insecure-skip-verify`
toml: `ssl_upstream_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false | +| flag: `--disable-keep-alives`
toml: `disable_keep_alives` | bool | disable HTTP keep-alive connections to the upstream server | false | +| flag: `--upstream-timeout`
toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s | +| flag: `--upstream`
toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://` for static response. Routing is based on the path | | + +## Upstreams Configuration + +`oauth2-proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers, unix socket or serve static files from the file system. + +To configure **HTTP and HTTPS upstreams**, provide such a URL in `--upstream=URL`. The scheme+host portion and the path portion are extracted to configure proxying behavior. When processing incoming requests, the path portion becomes a lookup key for selecting the destination server of the proxied request. + +* Upstream URLs *without a trailing slash,* like in `--upstream=http://service2.internal/foo`, will match an incoming request exactly to `/foo` in `https://this.o2p.example.com/foo`, and forward the request on to service2.internal, but not match a request to `https://this.o2p.example.com/foo/more` nor ...`.com/food`. +* Upstream URLs *with a trailing slash,* like in `--upstream=http://service1.internal/foo/`, will match any incoming request to any incoming requests's path *starting with* `/foo/`, like `/foo/` and `/foo/more` and `/foo/lots/more?etc`. + +If multiple `--upstream` URLs' paths match an incoming request, the one with the longest matching path (the most specific match) takes priority over shorter (less specific) ones. + +**Unix socket upstreams** are configured as `unix:///path/to/unix.sock`. + +**Static file paths** are configured as a file:// URL. `file:///var/www/static/` will serve the files from that directory at `http://[oauth2-proxy url]/var/www/static/`, which may not be what you want. You can provide the path to where the files should be available by adding a fragment to the configured URL. The value of the fragment will then be used to specify which path the files are available at, e.g. `file:///var/www/static/#/static/` will make `/var/www/static/` available at `http://[oauth2-proxy url]/static/`. + +Multiple upstreams can either be configured by supplying a comma separated list to the `--upstream` parameter, supplying the parameter multiple times or providing a list in the [config file](#config-file). When multiple upstreams are used routing to them will be based on the path they are set up with. + +## Environment variables + +Every command line argument can be specified as an environment variable by +prefixing it with `OAUTH2_PROXY_`, capitalising it, and replacing hyphens (`-`) +with underscores (`_`). If the argument can be specified multiple times, the +environment variable should be plural (trailing `S`). + +This is particularly useful for storing secrets outside a configuration file +or the command line. + +For example, the `--cookie-secret` flag becomes `OAUTH2_PROXY_COOKIE_SECRET`. +If a flag has the type `string | list` like the `--email-domain` flag it is +available as an environment variable in plural form e.g. `OAUTH2_PROXY_EMAIL_DOMAINS` + +Values for type `string | list` usually have a plural environment variable name +and need to be seperated by `,` e.g. +`OAUTH2_PROXY_SKIP_AUTH_ROUTES="GET=^/api/status,POST=^/api/saved_objects/_import"` + +Please check the type for each [config option](#config-options) first. + +## Logging Configuration + +By default, OAuth2 Proxy logs all output to stdout. Logging can be configured to output to a rotating log file using the `--logging-filename` command. + +If logging to a file you can also configure the maximum file size (`--logging-max-size`), age (`--logging-max-age`), max backup logs (`--logging-max-backups`), and if backup logs should be compressed (`--logging-compress`). + +There are three different types of logging: standard, authentication, and HTTP requests. These can each be enabled or disabled with `--standard-logging`, `--auth-logging`, and `--request-logging`. + +Each type of logging has its own configurable format and variables. By default, these formats are similar to the Apache Combined Log. + +Logging of requests to the `/ping` endpoint (or using `--ping-user-agent`) and the `/ready` endpoint can be disabled with `--silence-ping-logging` reducing log volume. + +## Auth Log Format + +Authentication logs are logs which are guaranteed to contain a username or email address of a user attempting to authenticate. These logs are output by default in the below format: + +``` + - - [2015/03/19 17:20:19] [] +``` + +The status block will contain one of the below strings: + +- `AuthSuccess` If a user has authenticated successfully by any method +- `AuthFailure` If the user failed to authenticate explicitly +- `AuthError` If there was an unexpected error during authentication + +If you require a different format than that, you can configure it with the `--auth-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}} +``` + +Available variables for auth logging: + +| Variable | Example | Description | +| ------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Message | Authenticated via OAuth2 | The details of the auth attempt. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | +| Status | AuthSuccess | The status of the auth request. See above for details. | + +## Request Log Format + +HTTP request logs will output by default in the below format: + +``` + - - [2015/03/19 17:20:19] GET "/path/" HTTP/1.1 "" +``` + +If you require a different format than that, you can configure it with the `--request-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}} +``` + +Available variables for request logging: + +| Variable | Example | Description | +| --------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestDuration | 0.001 | The time in seconds that a request took to process. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| RequestURI | "/oauth2/auth" | The URI path of the request. | +| ResponseSize | 12 | The size in bytes of the response. | +| StatusCode | 200 | The HTTP status code of the response. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| Upstream | - | The upstream data of the HTTP request. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | + +## Standard Log Format + +All other logging that is not covered by the above two types of logging will be output in this standard logging format. This includes configuration information at startup and errors that occur outside of a session. The default format is below: + +``` +[2015/03/19 17:20:19] [main.go:40] +``` + +If you require a different format than that, you can configure it with the `--standard-logging-format` flag. The default format is configured as follows: + +``` +[{{.Timestamp}}] [{{.File}}] {{.Message}} +``` + +Available variables for standard logging: + +| Variable | Example | Description | +| --------- | --------------------------------- | -------------------------------------------------- | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| File | main.go:40 | The file and line number of the logging statement. | +| Message | HTTP: listening on 127.0.0.1:4180 | The details of the log statement. | diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/adfs.md b/docs/versioned_docs/version-7.15.x/configuration/providers/adfs.md new file mode 100644 index 00000000..ec8d72d2 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/adfs.md @@ -0,0 +1,19 @@ +--- +id: adfs +title: ADFS +--- + +1. Open the ADFS administration console on your Windows Server and add a new Application Group +2. Provide a name for the integration, select Server Application from the Standalone applications section and click Next +3. Follow the wizard to get the client-id, client-secret and configure the application credentials +4. Configure the proxy with + +``` + --provider=adfs + --client-id= + --client-secret= +``` + +Note: When using the ADFS Auth provider with nginx and the cookie session store you may find the cookie is too large and +doesn't get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the +[redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/bitbucket.md b/docs/versioned_docs/version-7.15.x/configuration/providers/bitbucket.md new file mode 100644 index 00000000..e31de752 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/bitbucket.md @@ -0,0 +1,25 @@ +--- +id: bitbucket +title: BitBucket +--- + +1. [Add a new OAuth consumer](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html) + * In "Callback URL" use `https:///oauth2/callback`, substituting `` with the actual + hostname that oauth2-proxy is running on. + * In Permissions section select: + * Account -> Email + * Team membership -> Read + * Repositories -> Read +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=bitbucket + --client-id= + --client-secret= +``` + +The default configuration allows everyone with Bitbucket account to authenticate. To restrict the access to the team +members use additional configuration option: `--bitbucket-team=`. To restrict the access to only these users +who have access to one selected repository use `--bitbucket-repository=`. diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/cidaas.md b/docs/versioned_docs/version-7.15.x/configuration/providers/cidaas.md new file mode 100644 index 00000000..7a987018 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/cidaas.md @@ -0,0 +1,37 @@ +--- +id: cidaas +title: Cidaas +--- + +[Cidaas](https://www.cidaas.com/) is an Identity as a Service (IDaaS) solution that provides authentication and authorization services. +It supports various protocols including OpenID Connect, OAuth 2.0, and SAML. + +However, Cidaas provides groups and their roles as hierarchical claims, which are not supported by oauth2-proxy yet. +The Cidaas provider transforms the hierarchical claims into a flat list of groups, which can be used by oauth2-proxy. + +Example of groups and roles in Cidaas: + +```json +{ + "groups": [ + { + "groupId": "group1", + "roles": ["role1", "role2"] + }, + { + "groupId": "group2", + "roles": ["role3"] + } + ] +} +``` + +This will be transformed into a flat list of groups: + +```json +{ + "groups": ["group1:role1", "group2:role2", "group2:role3"] +} +``` + +Apart from that the Cidaas provider inherits all the features of the [OpenID Connect provider](openid_connect.md). \ No newline at end of file diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/cisco_duo.md b/docs/versioned_docs/version-7.15.x/configuration/providers/cisco_duo.md new file mode 100644 index 00000000..a92eccdb --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/cisco_duo.md @@ -0,0 +1,44 @@ +--- +id: cisco_duo +title: Cisco Duo +--- + +Cisco Duo SSO can be configured with OAuth2 Proxy using the OIDC provider. + +1. Create a new **Generic OIDC Relying Party - Single Sign-On** application in the Duo Admin Portal +2. Configure OAuth2 Proxy with the following options: + +``` +provider = "oidc" +provider_display_name = "Duo SSO" +scope = "openid email profile" +pass_access_token = true +code_challenge_method = "S256" +``` + +3. Configure Provider endpoints. Copy the following values from the corresponding fields in the Duo Admin Portal: + +``` +# Copy from "Client ID" field +client_id = "XXXXXXXX" + +# Copy from "Client Secret" field +client_secret = "XXXXXXXX" + +# Copy from "Issuer" field +oidc_issuer_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx" + +# Copy from "JWKS URL" field +oidc_jwks_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/jwks" + +# Copy from "Token Introspection URL" field +validate_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/token_introspection" + +# Copy from "UserInfo" field +profile_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/userinfo" + +# Copy from "Token URL" field +redeem_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/token" +``` + +4. Complete Configuration by filling in any remaining required fields and save your configuration. diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/digitalocean.md b/docs/versioned_docs/version-7.15.x/configuration/providers/digitalocean.md new file mode 100644 index 00000000..f6a1e891 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/digitalocean.md @@ -0,0 +1,21 @@ +--- +id: digitalocean +title: DigitalOcean +--- + +1. [Create a new OAuth application](https://cloud.digitalocean.com/account/api/applications) + * You can fill in the name, homepage, and description however you wish. + * In the "Application callback URL" field, enter: `https://oauth-proxy/oauth2/callback`, substituting `oauth2-proxy` + with the actual hostname that oauth2-proxy is running on. The URL must match oauth2-proxy's configured redirect URL. +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=digitalocean + --client-id= + --client-secret= +``` + +Alternatively, set the equivalent options in the config file. The redirect URL defaults to +`https:///oauth2/callback`. If you need to change it, you can use the `--redirect-url` command-line option. diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/facebook.md b/docs/versioned_docs/version-7.15.x/configuration/providers/facebook.md new file mode 100644 index 00000000..352c95ce --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/facebook.md @@ -0,0 +1,7 @@ +--- +id: facebook +title: Facebook +--- + +1. Create a new FB App from https://developers.facebook.com/ +2. Under FB Login, set your Valid OAuth redirect URIs to `https://internal.yourcompany.com/oauth2/callback` diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/gitea.md b/docs/versioned_docs/version-7.15.x/configuration/providers/gitea.md new file mode 100644 index 00000000..6c679dd0 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/gitea.md @@ -0,0 +1,24 @@ +--- +id: gitea +title: Gitea / Forgejo +--- + +:::note +This is not actually a fully serparate provider. For more details and options please refer to the [GitHub Provider Options](github.md) +::: + +1. Create a new application: `https://< your gitea host >/user/settings/applications` +2. Under `Redirect URI` enter the correct URL i.e. `https:///oauth2/callback` +3. Note the Client ID and Client Secret. +4. Pass the following options to the proxy: + +``` + --provider="github" + --redirect-url="https:///oauth2/callback" + --provider-display-name="Gitea" + --client-id="< client_id as generated by Gitea >" + --client-secret="< client_secret as generated by Gitea >" + --login-url="https://< your gitea host >/login/oauth/authorize" + --redeem-url="https://< your gitea host >/login/oauth/access_token" + --validate-url="https://< your gitea host >/api/v1/user/emails" +``` diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/github.md b/docs/versioned_docs/version-7.15.x/configuration/providers/github.md new file mode 100644 index 00000000..cebca314 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/github.md @@ -0,0 +1,81 @@ +--- +id: github +title: GitHub +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------- | ------- | +| `--github-org` | `github_org` | string | restrict logins to members of this organisation | | +| `--github-team` | `github_team` | string | restrict logins to members of any of these teams (slug) or (org:team), comma separated | | +| `--github-repo` | `github_repo` | string | restrict logins to collaborators of this repository formatted as `orgname/repo` | | +| `--github-token` | `github_token` | string | the token to use when verifying repository collaborators (must have push access to the repository) | | +| `--github-user` | `github_users` | string \| list | To allow users to login by username even if they do not belong to the specified org and team or collaborators | | + +## Usage + +1. Create a new project: https://github.com/settings/developers +2. Under `Authorization callback URL` enter the correct url ie `https://internal.yourcompany.com/oauth2/callback` + +The GitHub auth provider supports two additional ways to restrict authentication to either organization and optional +team level access, or to collaborators of a repository. Restricting by these options is normally accompanied with `--email-domain=*`. Additionally, all the organizations and teams a user belongs to are set as part of the `X-Forwarded-Groups` header. e.g. `org1:team1,org1:team2,org2:team1` + +NOTE: When `--github-user` is set, the specified users are allowed to log in even if they do not belong to the specified +org and team or collaborators. + +To restrict access to your organization: + +```shell + # restrict logins to members of this organisation + --github-org="your-org" +``` + +To restrict access to specific teams within an organization: + +```shell + --github-org="your-org" + # restrict logins to members of any of these teams (slug), comma separated + --github-team="team1,team2,team3" +``` + +To restrict to teams within different organizations, keep the organization flag empty and use `--github-team` like so: + +```shell + # keep empty + --github-org="" + # restrict logins to members to any of the following teams (format :, like octo:team1), comma separated + --github-team="org1:team1,org2:team1,org3:team42,octo:cat" +``` + +If you would rather restrict access to collaborators of a repository, those users must either have push access to a +public repository or any access to a private repository: + +```shell + # restrict logins to collaborators of this repository formatted as orgname/repo + --github-repo="" +``` + +If you'd like to allow access to users with **read only** access to a **public** repository you will need to provide a +[token](https://github.com/settings/tokens) for a user that has write access to the repository. The token must be +created with at least the `public_repo` scope: + +```shell + # the token to use when verifying repository collaborators + --github-token="" +``` + +To allow a user to log in with their username even if they do not belong to the specified org and team or collaborators: + +```shell + # allow logins by username, comma separated + --github-user="" +``` + +If you are using GitHub enterprise, make sure you set the following to the appropriate url: + +```shell + --login-url="http(s):///login/oauth/authorize" + --redeem-url="http(s):///login/oauth/access_token" + --validate-url="http(s):///api/v3" +``` diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.15.x/configuration/providers/gitlab.md new file mode 100644 index 00000000..fe259ab2 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/gitlab.md @@ -0,0 +1,49 @@ +--- +id: gitlab +title: GitLab +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | +| `--gitlab-project` | `gitlab_projects` | string \| list | restrict logins to members of any of these projects (may be given multiple times) formatted as `orgname/repo=accesslevel`. Access level should be a value matching [Gitlab access levels](https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent | | + +## Usage + +This auth provider has been tested against Gitlab version 12.X. Due to Gitlab API changes, it may not work for version +prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)). + +Whether you are using GitLab.com or self-hosting GitLab, follow +[these steps to add an application](https://docs.gitlab.com/integration/oauth_provider/). Make sure to enable at +least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. +https://myapp.com/oauth2/callback. + +If you need projects filtering, add the extra `read_api` scope to your application. + +The following config should be set to ensure that the oauth will work properly. To get a cookie secret follow +[these steps](../overview.md#generating-a-cookie-secret) + +``` + --provider="gitlab" + --redirect-url="https://myapp.com/oauth2/callback" // Should be the same as the redirect url for the application in gitlab + --client-id=GITLAB_CLIENT_ID + --client-secret=GITLAB_CLIENT_SECRET + --cookie-secret=COOKIE_SECRET +``` + +Restricting by group membership is possible with the following option: + +```shell + --gitlab-group="mygroup,myothergroup" # restrict logins to members of any of these groups (slug), separated by a comma +``` + +If you are using self-hosted GitLab, make sure you set the following to the appropriate URL: + +```shell + --oidc-issuer-url="" +``` + +If your self-hosted GitLab is on a subdirectory (e.g. domain.tld/gitlab), as opposed to its own subdomain +(e.g. gitlab.domain.tld), you may need to add a redirect from domain.tld/oauth pointing at e.g. domain.tld/gitlab/oauth. diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/google.md b/docs/versioned_docs/version-7.15.x/configuration/providers/google.md new file mode 100644 index 00000000..0de5bb74 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/google.md @@ -0,0 +1,84 @@ +--- +id: google +title: Google (default) +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +|-------------------------------------------------|----------------------------------------------| ------ |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------| +| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | +| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). If not specified and service account or default credentials are configured, all user groups will be allowed. | | +| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | +| `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | +| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | +| `--google-use-organization-id` | `google_use_organization_id` | bool | use organization id as preferred username | false | +| `--google-admin-api-user-scope` | `google_admin_api_user_scope` | string | the OAuth scope to use when querying the Google Admin SDK for organization id, can be 'readonly', 'user' or 'cloud'
| `readonly` | + +## Usage + +For Google, the registration steps are: + +1. Create a new project: https://console.developers.google.com/project +2. Choose the new project from the top right project dropdown (only if another project is selected) +3. In the project Dashboard center pane, choose **"APIs & Services"** +4. In the left Nav pane, choose **"Credentials"** +5. In the center pane, choose **"OAuth consent screen"** tab. Fill in **"Product name shown to users"** and hit save. +6. In the center pane, choose **"Credentials"** tab. + - Open the **"New credentials"** drop down + - Choose **"OAuth client ID"** + - Choose **"Web application"** + - Application name is freeform, choose something appropriate + - Authorized JavaScript origins is your domain ex: `https://internal.yourcompany.com` + - Authorized redirect URIs is the location of oauth2/callback ex: `https://internal.yourcompany.com/oauth2/callback` + - Choose **"Create"** +7. Take note of the **Client ID** and **Client Secret** + +It's recommended to refresh sessions on a short interval (1h) with `cookie-refresh` setting which validates that the +account is still authorized. + +#### Restrict auth to specific Google groups on your domain. (optional) + +1. Create a [service account](https://developers.google.com/identity/protocols/oauth2/service-account) and configure it + to use [Application Default Credentials / Workload Identity / Workload Identity Federation (recommended)](#using-application-default-credentials-adc--workload-identity--workload-identity-federation-recommended) or, + alternatively download the JSON. +2. Make note of the Client ID for a future step. +3. Under "APIs & Auth", choose APIs. +4. Click on Admin SDK and then Enable API. +5. Follow the steps on [Set up domain-wide delegation for a service account](https://developers.google.com/workspace/guides/create-credentials#optional_set_up_domain-wide_delegation_for_a_service_account) + and give the client id from step 2 the following oauth scopes: + + ``` + https://www.googleapis.com/auth/admin.directory.group.member.readonly + ``` + +6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access. +7. Create or choose an existing administrative email address on the Gmail domain to assign to the `google-admin-email` + flag. This email will be impersonated by this client to make calls to the Admin SDK. See the note on the link from + step 5 for the reason why. +8. Create or choose an existing email group and set that email to the `google-group` flag. You can pass multiple instances + of this flag with different groups and the user will be checked against all the provided groups. + +(Only if using a JSON file (see step 1)) + +9. Lock down the permissions on the json file downloaded from step 1 so only oauth2-proxy is able to read the file and + set the path to the file in the `google-service-account-json` flag. +10. Restart oauth2-proxy. + +Note: The user is checked against the group members list on initial authentication and every time the token is +refreshed ( about once an hour ). + +##### Using Application Default Credentials (ADC) / Workload Identity / Workload Identity Federation (recommended) +oauth2-proxy can make use of [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials). +When deployed within GCP, this means that it can automatically use the service account attached to the resource. When deployed to GKE, ADC +can be leveraged through a feature called Workload Identity. Follow Google's [guide](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity) +to set up Workload Identity. + +When deployed outside of GCP, [Workload Identity Federation](https://cloud.google.com/docs/authentication/provide-credentials-adc#wlif) might be an option. + +##### Using Organization ID as Preferred Username (optional) +By default, the google provider uses the google id as username. If you would like to use an organization id instead, you can set the `google-use-organization-id` flag to true. +This requires that the service account used to query the Google Admin SDK has one of the following scopes granted in step 5 above: +- `https://www.googleapis.com/auth/admin.directory.user.readonly`, +- `https://www.googleapis.com/auth/admin.directory.user` +- `https://www.googleapis.com/auth/cloud-platform` diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/index.md b/docs/versioned_docs/version-7.15.x/configuration/providers/index.md new file mode 100644 index 00000000..6f333e5a --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/index.md @@ -0,0 +1,46 @@ +--- +id: index +title: OAuth Provider Configuration +--- + +You will need to register an OAuth application with a Provider (Google, GitHub or another provider), and configure it +with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on. + +Valid providers are : + +- [ADFS](adfs.md) +- [Bitbucket](bitbucket.md) +- [Cidaas](cidaas.md) +- [CiscoDuo](cisco_duo.md) +- [DigitalOcean](digitalocean.md) +- [Facebook](facebook.md) +- [Gitea](gitea.md) +- [GitHub](github.md) +- [GitLab](gitlab.md) +- [Google](google.md) _default_ +- [Keycloak](keycloak.md) (Deprecated) +- [Keycloak OIDC](keycloak_oidc.md) +- [LinkedIn](linkedin.md) +- [login.gov](login_gov.md) +- [Microsoft Azure](ms_azure_ad.md) (Deprecated) +- [Microsoft Entra ID](ms_entra_id.md) +- [Nextcloud](nextcloud.md) +- [OpenID Connect](openid_connect.md) +- [SourceHut](sourcehut.md) + +The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the +OpenID Connect provider. + +## Email Authentication + +To authorize a specific email-domain use `--email-domain=yourcompany.com`. To authorize individual email addresses use +`--authenticated-emails-file=/path/to/file` with one email per line. To authorize all email addresses use `--email-domain=*`. + +## Adding a new Provider + +Follow the examples in the [`providers` package](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/) to define a new +`Provider` instance. Add a new `case` to +[`providers.New()`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/providers.go) to allow `oauth2-proxy` to use the +new `Provider`. diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/keycloak.md b/docs/versioned_docs/version-7.15.x/configuration/providers/keycloak.md new file mode 100644 index 00000000..11a1abca --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/keycloak.md @@ -0,0 +1,36 @@ +--- +id: keycloak +title: Keycloak (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Keycloak, use [Keycloak OIDC Auth Provider](keycloak_oidc.md) if possible. +::: + +1. Create new client in your Keycloak realm with **Access Type** 'confidential' and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. + +Make sure you set the following to the appropriate url: + +``` + --provider=keycloak + --client-id= + --client-secret= + --login-url="http(s):///auth/realms//protocol/openid-connect/auth" + --redeem-url="http(s):///auth/realms//protocol/openid-connect/token" + --profile-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --validate-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --keycloak-group= + --keycloak-group= +``` + +For group based authorization, the optional `--keycloak-group` (legacy) or `--allowed-group` (global standard) +flags can be used to specify which groups to limit access to. + +If these are unset but a `groups` mapper is set up above in step (3), the provider will still +populate the `X-Forwarded-Groups` header to your upstream server with the `groups` data in the +Keycloak userinfo endpoint response. + +The group management in keycloak is using a tree. If you create a group named admin in keycloak +you should define the 'keycloak-group' value to /admin. diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/keycloak_oidc.md b/docs/versioned_docs/version-7.15.x/configuration/providers/keycloak_oidc.md new file mode 100644 index 00000000..b29096e3 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/keycloak_oidc.md @@ -0,0 +1,151 @@ +--- +id: keycloak_oidc +title: Keycloak OIDC +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------ | ------- | +| `--allowed-role` | `allowed_roles` | string \| list | restrict logins to users with this role (may be given multiple times). Only works with the keycloak-oidc provider. | | + +## Usage + +``` + --provider=keycloak-oidc + --client-id= + --client-secret= + --redirect-url=https://internal.yourcompany.com/oauth2/callback + --oidc-issuer-url=https:///realms/ // For Keycloak versions <17: --oidc-issuer-url=https:///auth/realms/ + --email-domain= // Validate email domain for users, see option documentation + --allowed-role= // Optional, required realm role + --allowed-role=: // Optional, required client role + --allowed-group= // Optional, requires group client scope + --code-challenge-method=S256 // PKCE +``` + +:::note +Keycloak has updated its admin console and as of version 19.0.0, the new admin console is enabled by default. The +legacy admin console has been announced for removal with the release of version 21.0.0. +::: + +**Keycloak legacy admin console** + +1. Create new client in your Keycloak realm with **Access Type** 'confidential', **Client protocol** 'openid-connect' + and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. +4. Create a mapper with **Mapper Type** 'Audience' and **Included Client Audience** and **Included Custom Audience** set + to your client name. + +**Keycloak new admin console (default as of v19.0.0)** + +The following example shows how to create a simple OIDC client using the new Keycloak admin2 console. However, for best +practices, it is recommended to consult the Keycloak documentation. + +The OIDC client must be configured with an _audience mapper_ to include the client's name in the `aud` claim of the JWT token. +The `aud` claim specifies the intended recipient of the token, and OAuth2 Proxy expects a match against the values of +either `--client-id` or `--oidc-extra-audience`. + +_In Keycloak, claims are added to JWT tokens through the use of mappers at either the realm level using "client scopes" or +through "dedicated" client mappers._ + +**Creating the client** + +1. Create a new OIDC client in your Keycloak realm by navigating to: + **Clients** -> **Create client** + * **Client Type** 'OpenID Connect' + * **Client ID** ``, please complete the remaining fields as appropriate and click **Next**. + * **Client authentication** 'On' + * **Authentication flow** + * **Standard flow** 'selected' + * **Direct access grants** 'deselect' + * _Save the configuration._ + * **Settings / Access settings**: + * **Valid redirect URIs** `https://internal.yourcompany.com/oauth2/callback` + * _Save the configuration._ + * Under the **Credentials** tab you will now be able to locate ``. +2. Configure a dedicated *audience mapper* for your client by navigating to **Clients** -> **\** -> **Client scopes**. +* Access the dedicated mappers pane by clicking **\-dedicated**, located under *Assigned client scope*. + _(It should have a description of "Dedicated scope and mappers for this client")_ + * Click **Configure a new mapper** and select **Audience** + * **Name** 'aud-mapper-\' + * **Included Client Audience** select `` from the dropdown. + * _OAuth2 proxy can be set up to pass both the access and ID JWT tokens to your upstream services. + If you require additional audience entries, you can use the **Included Custom Audience** field in addition + to the "Included Client Audience" dropdown. Note that the "aud" claim of a JWT token should be limited and + only specify its intended recipients._ + * **Add to ID token** 'On' + * **Add to access token** 'On' - [#1916](https://github.com/oauth2-proxy/oauth2-proxy/pull/1916) + * _Save the configuration._ +* Any subsequent dedicated client mappers can be defined by clicking **Dedicated scopes** -> **Add mapper** -> + **By configuration** -> *Select mapper* + +You should now be able to create a test user in Keycloak and get access to the OAuth2 Proxy instance, make sure to set +an email address matching `` and select _Email verified_. + +**Authorization** + +_OAuth2 Proxy will perform authorization by requiring a valid user, this authorization can be extended to take into +account a user's membership in Keycloak `groups`, `realm roles`, and `client roles` using the keycloak-oidc provider options +`--allowed-role` or `--allowed-group`_ + +**Roles** + +_A standard Keycloak installation comes with the required mappers for **realm roles** and **client roles** through the +pre-defined client scope "roles". This ensures that any roles assigned to a user are included in the `JWT` tokens when +using an OIDC client that has the "Full scope allowed" feature activated, the feature is enabled by default._ + +_Creating a realm role_ +* Navigate to **Realm roles** -> **Create role** + * **Role name**, *``* -> **save** + +_Creating a client role_ +* Navigate to **Clients** -> `` -> **Roles** -> **Create role** + * **Role name**, *``* -> **save** + + +_Assign a role to a user_ + +**Users** -> _Username_ -> **Role mapping** -> **Assign role** -> _filter by roles or clients and select_ -> **Assign**. + +Keycloak "realm roles" can be authorized using the `--allowed-role=` option, while "client roles" can be +evaluated using `--allowed-role=:`. + +You may limit the _realm roles_ included in the JWT tokens for any given client by navigating to: +**Clients** -> `` -> **Client scopes** -> _\-dedicated_ -> **Scope** +Disabling **Full scope allowed** activates the **Assign role** option, allowing you to select which roles, if assigned +to a user, will be included in the user's JWT tokens. This can be useful when a user has many associated roles, and you +want to reduce the size and impact of the JWT token. + + +**Groups** + +You may also do authorization on group memberships by using the OAuth2 Proxy option `--allowed-group`. +We will only do a brief description of creating the required _client scope_ **groups** and refer you to read the Keycloak +documentation. + +To summarize, the steps required to authorize Keycloak group membership with OAuth2 Proxy are as follows: + +* Create a new Client Scope with the name **groups** in Keycloak. + * Include a mapper of type **Group Membership**. + * Set the "Token Claim Name" to **groups** or customize by matching it to the `--oidc-groups-claim` option of OAuth2 Proxy. + * If the "Full group path" option is selected, you need to include a "/" separator in the group names defined in the + `--allowed-group` option of OAuth2 Proxy. Example: "/groupname" or "/groupname/child_group". + +After creating the _Client Scope_ named _groups_ you will need to attach it to your client. +**Clients** -> `` -> **Client scopes** -> **Add client scope** -> Select **groups** and choose Optional +and you should now have a client that maps group memberships into the JWT tokens so that Oauth2 Proxy may evaluate them. + +Create a group by navigating to **Groups** -> **Create group** and _add_ your test user as a member. + +The OAuth2 Proxy option `--allowed-group=/groupname` will now allow you to filter on group membership + +Keycloak also has the option of attaching roles to groups, please refer to the Keycloak documentation for more information. + +**Tip** + +To check if roles or groups are added to JWT tokens, you can preview a users token in the Keycloak console by following +these steps: **Clients** -> `` -> **Client scopes** -> **Evaluate**. +Select a _realm user_ and optional _scope parameters_ such as groups, and generate the JSON representation of an access +or id token to examine its contents. diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/linkedin.md b/docs/versioned_docs/version-7.15.x/configuration/providers/linkedin.md new file mode 100644 index 00000000..7d26ec43 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/linkedin.md @@ -0,0 +1,13 @@ +--- +id: linkedin +title: LinkedIn +--- + +For LinkedIn, the registration steps are: + +1. Create a new project: https://www.linkedin.com/secure/developer +2. In the OAuth User Agreement section: + - In default scope, select r_basicprofile and r_emailaddress. + - In "OAuth 2.0 Redirect URLs", enter `https://internal.yourcompany.com/oauth2/callback` +3. Fill in the remaining required fields and Save. +4. Take note of the **Consumer Key / API Key** and **Consumer Secret / Secret Key** diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/login_gov.md b/docs/versioned_docs/version-7.15.x/configuration/providers/login_gov.md new file mode 100644 index 00000000..badbe48e --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/login_gov.md @@ -0,0 +1,79 @@ +--- +id: login_gov +title: Login.gov +--- + +login.gov is an OIDC provider for the US Government. +If you are a US Government agency, you can contact the login.gov team through the contact information +that you can find on https://login.gov/developers/ and work with them to understand how to get login.gov +accounts for integration/test and production access. + +A developer guide is available here: https://developers.login.gov/, though this proxy handles everything +but the data you need to create to register your application in the login.gov dashboard. + +As a demo, we will assume that you are running your application that you want to secure locally on +http://localhost:3000/, that you will be starting your proxy up on http://localhost:4180/, and that +you have an agency integration account for testing. + +First, register your application in the dashboard. The important bits are: +* Identity protocol: make this `Openid connect` +* Issuer: do what they say for OpenID Connect. We will refer to this string as `${LOGINGOV_ISSUER}`. +* Public key: This is a self-signed certificate in .pem format generated from a 2048-bit RSA private key. + A quick way to do this is + `openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -nodes -subj '/C=US/ST=Washington/L=DC/O=GSA/OU=18F/CN=localhost'`. + The contents of the `key.pem` shall be referred to as `${OAUTH2_PROXY_JWT_KEY}`. +* Return to App URL: Make this be `http://localhost:4180/` +* Redirect URIs: Make this be `http://localhost:4180/oauth2/callback`. +* Attribute Bundle: Make sure that email is selected. + +Now start the proxy up with the following options: +``` +./oauth2-proxy -provider login.gov \ + -client-id=${LOGINGOV_ISSUER} \ + -redirect-url=http://localhost:4180/oauth2/callback \ + -oidc-issuer-url=https://idp.int.identitysandbox.gov/ \ + -cookie-secure=false \ + -email-domain=gsa.gov \ + -upstream=http://localhost:3000/ \ + -cookie-secret=somerandomstring12341234567890AB \ + -cookie-domain=localhost \ + -skip-provider-button=true \ + -pubjwk-url=https://idp.int.identitysandbox.gov/api/openid_connect/certs \ + -profile-url=https://idp.int.identitysandbox.gov/api/openid_connect/userinfo \ + -jwt-key="${OAUTH2_PROXY_JWT_KEY}" +``` +You can also set all these options with environment variables, for use in cloud/docker environments. +One tricky thing that you may encounter is that some cloud environments will pass in environment +variables in a docker env-file, which does not allow multiline variables like a PEM file. +If you encounter this, then you can create a `jwt_signing_key.pem` file in the top level +directory of the repo which contains the key in PEM format and then do your docker build. +The docker build process will copy that file into your image which you can then access by +setting the `OAUTH2_PROXY_JWT_KEY_FILE=/etc/ssl/private/jwt_signing_key.pem` +environment variable, or by setting `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem` on the commandline. + +Once it is running, you should be able to go to `http://localhost:4180/` in your browser, +get authenticated by the login.gov integration server, and then get proxied on to your +application running on `http://localhost:3000/`. In a real deployment, you would secure +your application with a firewall or something so that it was only accessible from the +proxy, and you would use real hostnames everywhere. + +#### Skip OIDC discovery + +Some providers do not support OIDC discovery via their issuer URL, so oauth2-proxy cannot simply grab the authorization, +token and jwks URI endpoints from the provider's metadata. + +In this case, you can set the `--skip-oidc-discovery` option, and supply those required endpoints manually: + +``` + -provider oidc + -client-id oauth2-proxy + -client-secret proxy + -redirect-url http://127.0.0.1:4180/oauth2/callback + -oidc-issuer-url http://127.0.0.1:5556 + -skip-oidc-discovery + -login-url http://127.0.0.1:5556/authorize + -redeem-url http://127.0.0.1:5556/token + -oidc-jwks-url http://127.0.0.1:5556/keys + -cookie-secure=false + -email-domain example.com +``` diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/ms_azure_ad.md b/docs/versioned_docs/version-7.15.x/configuration/providers/ms_azure_ad.md new file mode 100644 index 00000000..4feefc68 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/ms_azure_ad.md @@ -0,0 +1,59 @@ +--- +id: azure +title: Azure (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Azure, use [Microsoft Entra ID](ms_entra_id.md) if possible. +::: + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | ------ | ---------------------------------------------------------------- | ---------- | +| `--azure-tenant` | `azure_tenant` | string | go to a tenant-specific or common (tenant-independent) endpoint. | `"common"` | +| `--resource` | `resource` | string | The resource that is protected (Azure AD only) | | + +## Usage + +1. Add an application: go to [https://portal.azure.com](https://portal.azure.com), choose **Azure Active Directory**, select + **App registrations** and then click on **New registration**. +2. Pick a name, check the supported account type(single-tenant, multi-tenant, etc). In the **Redirect URI** section create a new + **Web** platform entry for each app that you want to protect by the oauth2 proxy(e.g. + https://internal.yourcompanycom/oauth2/callback). Click **Register**. +3. Next we need to add group read permissions for the app registration, on the **API Permissions** page of the app, click on + **Add a permission**, select **Microsoft Graph**, then select **Application permissions**, then click on **Group** and select + **Group.Read.All**. Hit **Add permissions** and then on **Grant admin consent** (you might need an admin to do this). +
**IMPORTANT**: Even if this permission is listed with **"Admin consent required=No"** the consent might actually + be required, due to AAD policies you won't be able to see. If you get a **"Need admin approval"** during login, + most likely this is what you're missing! +4. Next, if you are planning to use v2.0 Azure Auth endpoint, go to the **Manifest** page and set `"accessTokenAcceptedVersion": 2` + in the App registration manifest file. +5. On the **Certificates & secrets** page of the app, add a new client secret and note down the value after hitting **Add**. +6. Configure the proxy with: +- for V1 Azure Auth endpoint (Azure Active Directory Endpoints - https://login.microsoftonline.com/common/oauth2/authorize) + +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://sts.windows.net/{tenant-id}/ +``` + +- for V2 Azure Auth endpoint (Microsoft Identity Platform Endpoints - https://login.microsoftonline.com/common/oauth2/v2.0/authorize) +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://login.microsoftonline.com/{tenant-id}/v2.0 +``` + +***Notes***: +- When using v2.0 Azure Auth endpoint (`https://login.microsoftonline.com/{tenant-id}/v2.0`) as `--oidc_issuer_url`, in conjunction + with `--resource` flag, be sure to append `/.default` at the end of the resource name. See + https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope for more details. +- When using the Azure Auth provider with nginx and the cookie session store you may find the cookie is too large and doesn't + get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the + [redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.15.x/configuration/providers/ms_entra_id.md new file mode 100644 index 00000000..b9b9e1f8 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/ms_entra_id.md @@ -0,0 +1,201 @@ +--- +id: ms_entra_id +title: Microsoft Entra ID +--- + +Provider for Microsoft Entra ID. Fully compliant with OIDC, with support for group overage and multi-tenant apps. + +## Config Options + +The provider is OIDC-compliant, so all the OIDC parameters are honored. Additional provider-specific configuration parameters are: + +| Flag | Toml Field | Type | Description | Default | +| --------------------------- | -------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--entra-id-allowed-tenant` | `entra_id_allowed_tenants` | string \| list | List of allowed tenants. In case of multi-tenant apps, incoming tokens are issued by different issuers and OIDC issuer verification needs to be disabled. When not specified, all tenants are allowed. Redundant for single-tenant apps (regular ID token validation matches the issuer). | | +| `--entra-id-federated-token-auth` | `entra_id_federated_token_auth` | boolean | Enable oAuth2 client authentication with federated token projected by Entra Workload Identity plugin, instead of client secret. | false | + +## Configure App registration +To begin, create an App registration, set a redirect URI, and generate a secret. All account types are supported, including single-tenant, multi-tenant, multi-tenant with Microsoft accounts, and Microsoft accounts only. + +
+ See Azure Portal example +
+ +
+
+ +
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" # Others are also supported + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + // We don't specify any required API permissions - we allow user consent only + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Configure groups +If you want to make use of groups, you can configure *groups claim* to be present in ID Tokens issued by the App registration. +
+ See Azure Portal example +
+
+ +
+
+
+
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" + + group_membership_claims = [ + "SecurityGroup" + ] + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Scopes and claims +For single-tenant and multi-tenant apps without groups, the only required scope is `openid` (See: [Scopes and permissions](https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#the-openid-scope)). + +To make use of groups - for example use `allowed_groups` setting or authorize based on groups inside your service - you need to enable *groups claims* in the App Registration. When enabled, list of groups is present in the issued ID token. No additional scopes are required besides `openid`. This works up to 200 groups. + +When user has more than 200 group memberships, OAuth2-Proxy attempts to retrieve the complete list from Microsoft Graph API's [`transitiveMemberOf`](https://learn.microsoft.com/en-us/graph/api/user-list-transitivememberof). Endpoint requires `User.Read` scope (delegated permission). This permission can be by default consented by user during first login. Set scope to `openid User.Read` to request user consent. Without proper scope, user with 200+ groups will authenticate with 0 groups. See: [group overages](https://learn.microsoft.com/en-us/security/zero-trust/develop/configure-tokens-group-claims-app-roles#group-overages). + +Alternatively to user consent, both `openid` and `User.Read` permissions can be consented by admistrator. Then, user is not asked for consent on the first login, and group overage works with `openid` scope only. Admin consent can also be required for some tenants. It can be granted with [azuread_service_principal_delegated_permission_grant](https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/service_principal_delegated_permission_grant) terraform resource. + +For personal microsoft accounts, required scope is `openid profile email`. + +See: [Overview of permissions and consent in the Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview). + +### Multi-tenant apps +To authenticate apps from multiple tenants (including personal Microsoft accounts), set the common OIDC issuer url and disable verification: +```toml +oidc_issuer_url=https://login.microsoftonline.com/common/v2.0 +insecure_oidc_skip_issuer_verification=true +``` +`insecure_oidc_skip_issuer_verification` setting is required to disable following checks: +* Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). + +To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. + +### Workload Identity +Provider supports authentication with federated token, without need of using client secret. Following conditions have to be met: + +* Cluster has public OIDC provider URL. For major cloud providers, it can be enabled with a single flag, for example for [Azure Kubernetes Service deployed with Terraform](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster), it's `oidc_issuer_enabled`. +* Workload Identity admission webhook is deployed on the cluster. For AKS, it can be enabled with a flag (`workload_identity_enabled` in Terraform resource), for clusters outside of Azure, it can be installed from [helm chart](https://github.com/Azure/azure-workload-identity). +* Appropriate federated credential is added to application registration. +
+ See federated credential terraform example +``` + resource "azuread_application_federated_identity_credential" "fedcred" { + application_id = azuread_application.application.id # ID of your application + display_name = "federation-cred" + description = "Workload identity for oauth2-proxy" + audiences = ["api://AzureADTokenExchange"] # Fixed value + issuer = "https://cluster-oidc-issuer-url..." + subject = "system:serviceaccount:oauth2-proxy-namespace-name:oauth2-proxy-sa-name" # set proper NS and SA name + } +``` +
+ +* Kubernetes service account associated with oauth2-proxy deployment, is annotated with `azure.workload.identity/client-id: ` +* oauth2-proxy pod is labeled with `azure.workload.identity/use: "true"` +* oauth2-proxy is configured with `entra_id_federated_token_auth` set to `true`. + +`client_secret` setting can be omitted when using federated token authentication. + +See: [Azure Workload Identity documentation](https://azure.github.io/azure-workload-identity/docs/). + +### Example configurations +Single-tenant app without groups (*groups claim* not enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +``` + +Single-tenant app with up to 200 groups (*groups claim* enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +allowed_groups=["ac51800c-2679-4ecb-8130-636380a3b491"] +``` + +Single-tenant app with more than 200 groups: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +``` + +Single-tenant app with more than 200 groups and workload identity enabled: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +entra_id_federated_token_auth=true +``` + +Multi-tenant app with Microsoft personal accounts & one Entra tenant allowed, with group overage considered: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com/common/v2.0" +client_id="" +client_secret="" +insecure_oidc_skip_issuer_verification=true +scope="openid profile email User.Read" +entra_id_allowed_tenants=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant +email_domains="*" +``` + +## Kubernetes Dashboard Integration + +For a complete guide on integrating oauth2-proxy with Kubernetes Dashboard on AKS using Azure Entra ID authentication, including detailed configuration examples, RBAC setup, troubleshooting, and Workload Identity setup, see the [Kubernetes Dashboard integration guide](../integrations/kubernetes-dashboard.md). diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/nextcloud.md b/docs/versioned_docs/version-7.15.x/configuration/providers/nextcloud.md new file mode 100644 index 00000000..85ebff03 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/nextcloud.md @@ -0,0 +1,28 @@ +--- +id: nextcloud +title: NextCloud +--- + +The Nextcloud provider allows you to authenticate against users in your +Nextcloud instance. + +When you are using the Nextcloud provider, you must specify the urls via +configuration, environment variable, or command line argument. Depending +on whether your Nextcloud instance is using pretty urls your urls may be of the +form `/index.php/apps/oauth2/*` or `/apps/oauth2/*`. + +Refer to the [OAuth2 +documentation](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/oauth2.html) +to set up the client id and client secret. Your "Redirection URI" will be +`https://internalapp.yourcompany.com/oauth2/callback`. + +``` + -provider nextcloud + -client-id + -client-secret + -login-url="/index.php/apps/oauth2/authorize" + -redeem-url="/index.php/apps/oauth2/api/v1/token" + -validate-url="/ocs/v2.php/cloud/user?format=json" +``` + +Note: in *all* cases the validate-url will *not* have the `index.php`. diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/openid_connect.md b/docs/versioned_docs/version-7.15.x/configuration/providers/openid_connect.md new file mode 100644 index 00000000..de170058 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/openid_connect.md @@ -0,0 +1,146 @@ +--- +id: openid_connect +title: OpenID Connect +--- + +OpenID Connect is a spec for OAUTH 2.0 + identity that is implemented by many major providers and several open source projects. + +This provider was originally built against CoreOS Dex, and we will use it as an example. +The OpenID Connect Provider (OIDC) can also be used to connect to other Identity Providers such as Okta, an example can be found below. + +#### Dex + +To configure the OIDC provider for Dex, perform the following steps: + +1. Download Dex: + + ``` + go get github.com/dexidp/dex + ``` + + See the [getting started guide](https://dexidp.io/docs/getting-started/) for more details. + +2. Setup oauth2-proxy with the correct provider and using the default ports and callbacks. Add a configuration block to + the `staticClients` section of `examples/config-dev.yaml`: + + ``` + - id: oauth2-proxy + redirectURIs: + - 'http://127.0.0.1:4180/oauth2/callback' + name: 'oauth2-proxy' + secret: proxy + ``` + +3. Launch Dex: from `$GOPATH/github.com/dexidp/dex`, run: + + ``` + bin/dex serve examples/config-dev.yaml + ``` + +4. In a second terminal, run the oauth2-proxy with the following args: + + ```shell + --provider oidc + --provider-display-name "My OIDC Provider" + --client-id oauth2-proxy + --client-secret proxy + --redirect-url http://127.0.0.1:4180/oauth2/callback + --oidc-issuer-url http://127.0.0.1:5556/dex + --cookie-secure=false + --cookie-secret=secret + --email-domain kilgore.trout + ``` + + To serve the current working directory as a website under the `/static` endpoint, add: + + ```shell + --upstream file://$PWD/#/static/ + ``` + +5. Test the setup by visiting http://127.0.0.1:4180 or http://127.0.0.1:4180/static . + +See also [our local testing environment](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/local-environment) for a self-contained example using Docker and etcd as storage for Dex. + +#### Okta + +To configure the OIDC provider for Okta, perform the following steps: + +1. Log in to Okta using an administrative account. It is suggested you try this in preview first, `example.oktapreview.com` +2. (OPTIONAL) If you want to configure authorization scopes and claims to be passed on to multiple applications, + you may wish to configure an authorization server for each application. Otherwise, the provided `default` will work. + * Navigate to **Security** then select **API** + * Click **Add Authorization Server**, if this option is not available you may require an additional license for a custom + authorization server. + * Fill out the **Name** with something to describe the application you are protecting. e.g. 'Example App'. + * For **Audience**, pick the URL of the application you wish to protect: https://example.corp.com + * Fill out a **Description** + * Add any **Access Policies** you wish to configure to limit application access. + * The default settings will work for other options. + [See Okta documentation for more information on Authorization Servers](https://developer.okta.com/docs/guides/customize-authz-server/overview/) +3. Navigate to **Applications** then select **Add Application**. + * Select **Web** for the **Platform** setting. + * Select **OpenID Connect** and click **Create** + * Pick an **Application Name** such as `Example App`. + * Set the **Login redirect URI** to `https://example.corp.com`. + * Under **General** set the **Allowed grant types** to `Authorization Code` and `Refresh Token`. + * Leave the rest as default, taking note of the `Client ID` and `Client Secret`. + * Under **Assignments** select the users or groups you wish to access your application. +4. Create a configuration file like the following: + + ``` + provider = "oidc" + redirect_url = "https://example.corp.com/oauth2/callback" + oidc_issuer_url = "https://corp.okta.com/oauth2/abCd1234" + upstreams = [ + "https://example.corp.com" + ] + email_domains = [ + "corp.com" + ] + client_id = "XXXXX" + client_secret = "YYYYY" + pass_access_token = true + cookie_secret = "ZZZZZ" + skip_provider_button = true + ``` + +The `oidc_issuer_url` is based on URL from your **Authorization Server**'s **Issuer** field in step 2, or simply +https://corp.okta.com. The `client_id` and `client_secret` are configured in the application settings. +Generate a unique `cookie_secret` to encrypt the cookie. + +Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/example.cfg` + +#### Okta - localhost + +1. Signup for developer account: https://developer.okta.com/signup/ +2. Create New `Web` Application: https://$\{your-okta-domain\}/dev/console/apps/new +3. Example Application Settings for localhost: + * **Name:** My Web App + * **Base URIs:** http://localhost:4180/ + * **Login redirect URIs:** http://localhost:4180/oauth2/callback + * **Logout redirect URIs:** http://localhost:4180/ + * **Group assignments:** `Everyone` + * **Grant type allowed:** `Authorization Code` and `Refresh Token` +4. Make note of the `Client ID` and `Client secret`, they are needed in a future step +5. Make note of the **default** Authorization Server Issuer URI from: https://$\{your-okta-domain\}/admin/oauth2/as +6. Example config file `/etc/localhost.cfg` + ```shell + provider = "oidc" + redirect_url = "http://localhost:4180/oauth2/callback" + oidc_issuer_url = "https://$\{your-okta-domain\}/oauth2/default" + upstreams = [ + "http://0.0.0.0:8080" + ] + email_domains = [ + "*" + ] + client_id = "XXX" + client_secret = "YYY" + pass_access_token = true + cookie_secret = "ZZZ" + cookie_secure = false + skip_provider_button = true + # Note: use the following for testing within a container + # http_address = "0.0.0.0:4180" + ``` +7. Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/localhost.cfg` diff --git a/docs/versioned_docs/version-7.15.x/configuration/providers/sourcehut.md b/docs/versioned_docs/version-7.15.x/configuration/providers/sourcehut.md new file mode 100644 index 00000000..2c196bda --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/providers/sourcehut.md @@ -0,0 +1,25 @@ +--- +id: sourcehut +title: SourceHut +--- + +1. Create a new OAuth client: https://meta.sr.ht/oauth2 +2. Under `Redirection URI` enter the correct URL, i.e. + `https://internal.yourcompany.com/oauth2/callback` + +To use the provider, start with `--provider=sourcehut`. + +If you are hosting your own SourceHut instance, make sure you set the following +to the appropriate URLs: + +```shell + --login-url="https:///oauth2/authorize" + --redeem-url="https:///oauth2/access-token" + --profile-url="https:///query" + --validate-url="https:///profile" +``` + +The default configuration allows everyone with an account to authenticate. +Restricting access is currently only supported by +[email](index.md#email-authentication). + diff --git a/docs/versioned_docs/version-7.15.x/configuration/sessions.md b/docs/versioned_docs/version-7.15.x/configuration/sessions.md new file mode 100644 index 00000000..c1e5fc17 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/sessions.md @@ -0,0 +1,99 @@ +--- +id: session_storage +title: Session Storage +--- + +Sessions allow a user's authentication to be tracked between multiple HTTP +requests to a service. + +The OAuth2 Proxy uses a Cookie to track user sessions and will store the session +data in one of the available session storage backends. + +At present the available backends are (as passed to `--session-store-type`): +- [cookie](#cookie-storage) (default) +- [redis](#redis-storage) + +### Cookie Storage + +The Cookie storage backend is the default backend implementation and has +been used in the OAuth2 Proxy historically. + +With the Cookie storage backend, all session information is stored in client +side cookies and transferred with each and every request. + +The following should be known when using this implementation: +- Since all state is stored client side, this storage backend means that the OAuth2 Proxy is completely stateless +- Cookies are signed server side to prevent modification client-side +- It is mandatory to set a `cookie-secret` which will ensure data is encrypted within the cookie data. +- Since multiple requests can be made concurrently to the OAuth2 Proxy, this session implementation +cannot lock sessions and while updating and refreshing sessions, there can be conflicts which force +users to re-authenticate + + +### Redis Storage + +The Redis Storage backend stores encrypted sessions in redis. Instead of sending all the information +back the client for storage, as in the [Cookie storage](#cookie-storage), a ticket is sent back +to the user as the cookie value instead. + +A ticket is composed as the following: + +`{CookieName}-{ticketID}.{secret}` + +Where: + +- The `CookieName` is the OAuth2 cookie name (_oauth2_proxy by default) +- The `ticketID` is a 128-bit random number, hex-encoded +- The `secret` is a 128-bit random number, base64url encoded (no padding). The secret is unique for every session. +- The pair of `{CookieName}-{ticketID}` comprises a ticket handle, and thus, the redis key +to which the session is stored. The encoded session is encrypted with the secret and stored +in redis via the `SETEX` command. + +Encrypting every session uniquely protects the refresh/access/id tokens stored in the session from +disclosure. Additionally, the browser only has to send a short Cookie with every request and not the whole JWT, +which can get quite big. + +Two settings are used to configure the OAuth2 Proxy cookie lifetime: + + --cookie-refresh duration refresh the cookie after this duration; 0 to disable + --cookie-expire duration expire timeframe for cookie 168h0m0s + +The "cookie-expire" value should be equal to the lifetime of the Refresh-Token that is issued by the OAuth2 authorization server. +If it expires earlier and is deleted by the browser, OAuth2 Proxy cannot find the stored Refresh-Tokens in Redis and thus cannot start +the refresh flow to get a new Access-Token. If it is longer, it might be that the old Refresh-Token will be found in Redis but has already +expired. + +The "cookie-refresh" value controls when OAuth2 Proxy tries to refresh an Access-Token. If it is set to "0", the +Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2 Proxy will +refresh the Access-Token after this many seconds whether it is still valid or not. According to the official OAuth2.0 specification +Access-Tokens are not required to follow a specific format. Therefore OAuth2 Proxy cannot check for any expiry date without an +introspection endpoint. If an Access-Token expires and you have not set a corresponding "cookie-refresh" value, you will likely +encounter expiry issues. + +Caveat: It can happen that the Access-Token is valid for e.g. "1m" and a request happens after exactly "59s". +It would pass OAuth2 Proxy and be forwarded to the backend but is just expired when the backend tries to validate +it. This is especially relevant if the backend uses the JWT to make requests to other backends. +For this reason, it's advised to set the cookie-refresh a couple of seconds less than the Access-Token lifespan. + +Recommended settings: + +* cookie_refresh := Access-Token lifespan - 1m +* cookie_expire := Refresh-Token lifespan (i.e. Keycloak client_session_idle) + +#### Usage + +When using the redis store, specify `--session-store-type=redis` as well as the Redis connection URL, via +`--redis-connection-url=redis://host[:port][/db-number]`. + +You may also configure the store for Redis Sentinel. In this case, you will want to use the +`--redis-use-sentinel=true` flag, as well as configure the flags `--redis-sentinel-master-name` +and `--redis-sentinel-connection-urls` appropriately. + +Redis Cluster is available to be the backend store as well. To leverage it, you will need to set the +`--redis-use-cluster=true` flag, and configure the flags `--redis-cluster-connection-urls` appropriately. + +Note that flags `--redis-use-sentinel=true` and `--redis-use-cluster=true` are mutually exclusive. + +Note, if Redis timeout option is set to non-zero, the `--redis-connection-idle-timeout` +must be less than [Redis timeout option](https://redis.io/docs/reference/clients/#client-timeouts). For example: if either redis.conf includes +`timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` diff --git a/docs/versioned_docs/version-7.15.x/configuration/systemd_socket.md b/docs/versioned_docs/version-7.15.x/configuration/systemd_socket.md new file mode 100644 index 00000000..642e6f3f --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/systemd_socket.md @@ -0,0 +1,43 @@ +--- +id: systemd_socket +title: Systemd Socket Activation +--- + +Pass an existing listener created by systemd.socket to oauth2-proxy. + +To do this create a socket: + +oauth2-proxy.socket +``` +[Socket] +ListenStream=%t/oauth2.sock +SocketGroup=www-data +SocketMode=0660 +``` + +Now it's possible to call this socket from e.g. nginx: +``` +server { + location /oauth2/ { + proxy_pass http://unix:/run/oauth2-proxy/oauth2.sock; +} +``` + +The oauth2-proxy should have `--http-address=fd:3` as a parameter. +Here fd is case insensitive and means file descriptor. The number 3 refers to the first non-stdin/stdout/stderr file descriptor, +systemd-socket-activate (which is what systemd.socket uses), listens to what it is told and passes +the listener it created onto the process, starting with file descriptor 3. + +``` +./oauth2-proxy \ + --http-address="fd:3" \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... +``` + +Currently TLS is not supported (but it's doable). diff --git a/docs/versioned_docs/version-7.15.x/configuration/tls.md b/docs/versioned_docs/version-7.15.x/configuration/tls.md new file mode 100644 index 00000000..68344b22 --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/configuration/tls.md @@ -0,0 +1,85 @@ +--- +id: tls +title: TLS Configuration +--- + +There are two recommended configurations: +- [At OAuth2 Proxy](#terminate-tls-at-oauth2-proxy) +- [At Reverse Proxy](#terminate-tls-at-reverse-proxy-eg-nginx) + +### Terminate TLS at OAuth2 Proxy + +1. Configure SSL Termination with OAuth2 Proxy by providing a `--tls-cert-file=/path/to/cert.pem` and `--tls-key-file=/path/to/cert.key`. + + The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --tls-cert-file=/path/to/cert.pem \ + --tls-key-file=/path/to/cert.key \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... + ``` + +2. With this configuration approach the customization of the TLS settings is limited. + + The minimal acceptable TLS version can be set with `--tls-min-version=TLS1.3`. + The defaults set `TLS1.2` as the minimal version. + Regardless of the minimum version configured, `TLS1.3` is currently always used as the maximal version. + + TLS server side cipher suites can be specified with `--tls-cipher-suite=TLS_RSA_WITH_RC4_128_SHA`. + If not specified, the defaults from [`crypto/tls`](https://pkg.go.dev/crypto/tls#CipherSuites) of the currently used `go` version for building `oauth2-proxy` will be used. + A complete list of valid TLS cipher suite names can be found in [`crypto/tls`](https://pkg.go.dev/crypto/tls#pkg-constants). + +### Terminate TLS at Reverse Proxy, e.g. Nginx + +1. Configure SSL Termination with [Nginx](http://nginx.org/) (example config below), Amazon ELB, Google Cloud Platform Load Balancing, or ... + + Because `oauth2-proxy` listens on `127.0.0.1:4180` by default, to listen on all interfaces (needed when using an + external load balancer like Amazon ELB or Google Platform Load Balancing) use `--http-address="0.0.0.0:4180"` or + `--http-address="http://:4180"`. + + Nginx will listen on port `443` and handle SSL connections while proxying to `oauth2-proxy` on port `4180`. + `oauth2-proxy` will then authenticate requests for an upstream application. The external endpoint for this example + would be `https://internal.yourcompany.com/`. + + An example Nginx config follows. Note the use of `Strict-Transport-Security` header to pin requests to SSL + via [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security): + + ``` + server { + listen 443 default ssl; + server_name internal.yourcompany.com; + ssl_certificate /path/to/cert.pem; + ssl_certificate_key /path/to/cert.key; + add_header Strict-Transport-Security max-age=2592000; + + location / { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_connect_timeout 1; + proxy_send_timeout 30; + proxy_read_timeout 30; + } + } + ``` + +2. The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --reverse-proxy=true \ + --client-id=... \ + --client-secret=... + ``` diff --git a/docs/versioned_docs/version-7.15.x/features/endpoints.md b/docs/versioned_docs/version-7.15.x/features/endpoints.md new file mode 100644 index 00000000..f310e48a --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/features/endpoints.md @@ -0,0 +1,73 @@ +--- +id: endpoints +title: Endpoints +--- + +OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable. + +- / - the proxy endpoint provides authentication and returns the appropriate 40x error if not authenticated or authorized then passes the request upstream. +- /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info +- /ping - returns a 200 OK response, which is intended for use with health checks +- /ready - returns a 200 OK response if all the underlying connections (e.g., Redis store) are connected +- /metrics - Metrics endpoint for Prometheus to scrape, serve on the address specified by `--metrics-address`, disabled by default +- /oauth2/sign_in - the login page, which also doubles as a sign-out page (it clears cookies) +- /oauth2/sign_out - this URL is used to clear the session cookie +- /oauth2/start - a URL that will redirect to start the OAuth cycle +- /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url. +- /oauth2/userinfo - the URL is used to return user's email from the session in JSON format. +- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integrations/nginx) +- /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages + +### Sign out + +To sign the user out, redirect them to `/oauth2/sign_out`. This endpoint only removes oauth2-proxy's own cookies, i.e. the user is still logged in with the authentication provider and may automatically re-login when accessing the application again. You will also need to redirect the user to the authentication provider's sign-out page afterward using the `rd` query parameter, i.e. redirect the user to something like (notice the url-encoding!): + +``` +/oauth2/sign_out?rd=https%3A%2F%2Fmy-oidc-provider.example.com%2Fsign_out_page +``` + +Alternatively, include the redirect URL in the `X-Auth-Request-Redirect` header: + +``` +GET /oauth2/sign_out HTTP/1.1 +X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page +... +``` + +(The "sign_out_page" should be the [`end_session_endpoint`](https://openid.net/specs/openid-connect-session-1_0.html#rfc.section.2.1) from [the metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) if your OIDC provider supports Session Management and Discovery.) + +BEWARE that the domain you want to redirect to (`my-oidc-provider.example.com` in the example) must be added to the [`--whitelist-domain`](../configuration/overview) configuration option otherwise the redirect will be ignored. Make sure to include the actual domain and port (if needed) and not the URL (e.g "localhost:8081" instead of "http://localhost:8081"). + +ID Token can be injected in the redirect url by using `{id_token}` placeholder. For example to redirect to `https://my-oidc-provider.example.com/sign_out_page?id_token_hint={id_token}&post_logout_redirect_uri=https://my-app.example.com`; + +``` +/oauth2/sign_out?rd=https%3A%2F%2Fmy-oidc-provider.example.com%2Fsign_out_page%3Fid_token_hint%3D%7Bid_token%7D%26post_logout_redirect_uri%3Dhttps%3A%2F%2Fmy-app.example.com +``` + +or alternatively in the header: + +``` +GET /oauth2/sign_out HTTP/1.1 +X-Auth-Request-Redirect: https://my-oidc-provider.example.com/sign_out_page?id_token_hint={id_token}&post_logout_redirect_uri=https://my-app.example.com +... +``` + +### Auth + +This endpoint returns 202 Accepted response or a 401 Unauthorized response. + +It can be configured using the following query parameters: +- `allowed_groups`: comma separated list of allowed groups +- `allowed_email_domains`: comma separated list of allowed email domains +- `allowed_emails`: comma separated list of allowed emails + +### Proxy (/) + +This endpoint returns the upstream response if authenticated. +If unauthenticated it returns a 401 Unauthorized. If the authenticatd user +is not in one of the allowed groups, or emails then it returns a 403 forbidden + +It can be configured using the following query parameters: +- `allowed_groups`: comma separated list of allowed groups +- `allowed_email_domains`: comma separated list of allowed email domains +- `allowed_emails`: comma separated list of allowed emails diff --git a/docs/versioned_docs/version-7.15.x/installation.md b/docs/versioned_docs/version-7.15.x/installation.md new file mode 100644 index 00000000..497b3e0d --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/installation.md @@ -0,0 +1,32 @@ +--- +id: installation +title: Installation +--- + +1. Choose how to deploy: + + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.15.0`) + + b. Using Go to install the latest release + ```bash + $ go install github.com/oauth2-proxy/oauth2-proxy/v7@latest + ``` + This will install the binary into `$GOPATH/bin`. Make sure you include `$GOPATH` in your `$PATH`. Otherwise your system won't find binaries installed via `go install` + + c. Using a [Prebuilt Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy) (AMD64, PPC64LE, S390x, ARMv6, ARMv7, and ARM64 available) + + d. Using a [Pre-Release Nightly Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy-nightly) (AMD64, PPC64LE, ARMv6, ARMv7, and ARM64 available) + + e. Using the official [Kubernetes manifest](https://github.com/oauth2-proxy/manifests) (Helm) + + Prebuilt binaries can be validated by extracting the file and verifying it against the `sha256sum.txt` checksum file provided for each release starting with version `v3.0.0`. + + ``` + $ sha256sum -c sha256sum.txt + oauth2-proxy-x.y.z.linux-amd64: OK + ``` + +2. [Select a Provider and Register an OAuth Application with a Provider](configuration/providers/index.md) +3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration/overview.md) +4. [Configure SSL or Deploy behind an SSL endpoint](configuration/tls.md) (example provided for Nginx) +5. [Configure OAuth2 Proxy using systemd.socket](configuration/systemd_socket.md) (example provided for Nginx/Systemd) diff --git a/docs/versioned_docs/version-7.15.x/welcome.md b/docs/versioned_docs/version-7.15.x/welcome.md new file mode 100644 index 00000000..1cfd569f --- /dev/null +++ b/docs/versioned_docs/version-7.15.x/welcome.md @@ -0,0 +1,33 @@ +--- +id: welcome +title: Welcome +hide_table_of_contents: true +slug: / +--- + +![OAuth2 Proxy](/img/logos/OAuth2_Proxy_horizontal.svg) + +A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others) +to validate accounts by email, domain or group. + +:::note +This repository was forked from [bitly/OAuth2_Proxy](https://github.com/bitly/oauth2_proxy) on 27/11/2018. +Versions v3.0.0 and up are from this fork and will have diverged from any changes in the original fork. +A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/CHANGELOG.md). +::: + +![Sign In Page](/img/sign-in-page.png) + +## Architecture + +![OAuth2 Proxy Architecture](/img/simplified-architecture.svg) + + +## Cloud Native Computing Foundation + +OAuth2 Proxy is a [Cloud Native Computing Foundation](https://cncf.io) Sandbox project. + +![CNCF](https://www.cncf.io/wp-content/uploads/2023/04/cncf-main-site-logo.svg) + +The Linux Foundation® (TLF) has registered trademarks and uses trademarks. For a list of TLF trademarks, see [Trademark Usage](https://www.linuxfoundation.org/legal/trademark-usage). + diff --git a/docs/versioned_sidebars/version-7.15.x-sidebars.json b/docs/versioned_sidebars/version-7.15.x-sidebars.json new file mode 100644 index 00000000..cc52cf48 --- /dev/null +++ b/docs/versioned_sidebars/version-7.15.x-sidebars.json @@ -0,0 +1,100 @@ +{ + "docs": [ + { + "type": "doc", + "id": "welcome" + }, + { + "type": "doc", + "id": "installation" + }, + { + "type": "doc", + "id": "behaviour" + }, + { + "type": "category", + "label": "Configuration", + "link": { + "type": "doc", + "id": "configuration/overview" + }, + "collapsed": false, + "items": [ + "configuration/overview", + { + "type": "category", + "label": "Integration Guides", + "link": { + "type": "doc", + "id": "configuration/integrations/index" + }, + "items": [ + "configuration/integrations/nginx", + "configuration/integrations/traefik", + "configuration/integrations/caddy", + "configuration/integrations/headlamp", + "configuration/integrations/kubernetes-dashboard" + ] + }, + { + "type": "category", + "label": "OAuth Provider Configuration", + "link": { + "type": "doc", + "id": "configuration/providers/index" + }, + "items": [ + "configuration/providers/adfs", + "configuration/providers/azure", + "configuration/providers/bitbucket", + "configuration/providers/cidaas", + "configuration/providers/cisco_duo", + "configuration/providers/digitalocean", + "configuration/providers/facebook", + "configuration/providers/gitea", + "configuration/providers/github", + "configuration/providers/gitlab", + "configuration/providers/google", + "configuration/providers/keycloak", + "configuration/providers/keycloak_oidc", + "configuration/providers/linkedin", + "configuration/providers/login_gov", + "configuration/providers/ms_entra_id", + "configuration/providers/nextcloud", + "configuration/providers/openid_connect", + "configuration/providers/sourcehut" + ] + }, + "configuration/session_storage", + "configuration/tls", + "configuration/alpha-config" + ] + }, + { + "type": "category", + "label": "Features", + "link": { + "type": "doc", + "id": "features/endpoints" + }, + "collapsed": false, + "items": [ + "features/endpoints" + ] + }, + { + "type": "category", + "label": "Community", + "link": { + "type": "doc", + "id": "community/security" + }, + "collapsed": false, + "items": [ + "community/contribution", + "community/security" + ] + } + ] +} diff --git a/docs/versions.json b/docs/versions.json index 8e8acf79..83f5cf22 100644 --- a/docs/versions.json +++ b/docs/versions.json @@ -1,4 +1,5 @@ [ + "7.15.x", "7.14.x", "7.13.x", "7.12.x", From 0ecc35ea41a25f4ec89649533b51aa927ad64f85 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Mon, 23 Mar 2026 09:38:12 +0100 Subject: [PATCH 27/53] chore(deps): update gomod and golangci/golangci-lint to v2.11.4 (#3382) Signed-off-by: Jan Larwig --- .github/workflows/ci.yml | 2 +- .github/workflows/publish-release.yml | 2 +- CHANGELOG.md | 5 + go.mod | 59 +++++------ go.sum | 138 ++++++++++++++------------ oauthproxy.go | 2 + pkg/apis/options/legacy_options.go | 2 +- pkg/validation/providers.go | 3 +- providers/ms_entra_id.go | 2 + 9 files changed, 116 insertions(+), 99 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e0610cad..1d036ec0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,7 +39,7 @@ jobs: uses: golangci/golangci-lint-action@v9 with: install-only: true - version: v2.8.0 # renovate: datasource=github-tags depName=golangci/golangci-lint + version: v2.11.4 # renovate: datasource=github-tags depName=golangci/golangci-lint - name: Verify Code Generation run: | diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 4a1f2696..ed58edd9 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -59,7 +59,7 @@ jobs: uses: golangci/golangci-lint-action@v9 with: install-only: true - version: v2.8.0 # renovate: datasource=github-tags depName=golangci/golangci-lint + version: v2.11.4 # renovate: datasource=github-tags depName=golangci/golangci-lint - name: Get go dependencies run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index 8da01f83..5d740cb9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Release Highlights +- Fixes [CVE-2026-33186](https://nvd.nist.gov/vuln/detail/CVE-2026-33186) + - OAuth2 Proxy was not impacted by this vulnerability as it isn't in the path of execution + ## Important Notes ## Breaking Changes @@ -10,6 +13,8 @@ # V7.15.0 +- [#3382](https://github.com/oauth2-proxy/oauth2-proxy/pull/3382) chore(deps): update gomod and golangci/golangci-lint to v2.11.4 (@tuunit) + ## Release Highlights - 🔒 OIDC JWT signing algorithms can now be configured diff --git a/go.mod b/go.mod index 4f54660f..a379e58d 100644 --- a/go.mod +++ b/go.mod @@ -6,42 +6,43 @@ require ( cloud.google.com/go/compute/metadata v0.9.0 github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb github.com/a8m/envsubst v1.4.3 - github.com/alicebob/miniredis/v2 v2.35.0 + github.com/alicebob/miniredis/v2 v2.37.0 github.com/bitly/go-simplejson v0.5.1 github.com/bsm/redislock v0.9.4 github.com/coreos/go-oidc/v3 v3.17.0 github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf github.com/fsnotify/fsnotify v1.9.0 github.com/go-jose/go-jose/v3 v3.0.4 + github.com/go-jose/go-jose/v4 v4.1.3 github.com/go-viper/mapstructure/v2 v2.4.0 - github.com/golang-jwt/jwt/v5 v5.3.0 + github.com/golang-jwt/jwt/v5 v5.3.1 github.com/google/go-cmp v0.7.0 github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 github.com/justinas/alice v1.2.0 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 - github.com/onsi/ginkgo/v2 v2.27.5 - github.com/onsi/gomega v1.39.0 - github.com/pierrec/lz4/v4 v4.1.25 + github.com/onsi/ginkgo/v2 v2.28.1 + github.com/onsi/gomega v1.39.1 + github.com/pierrec/lz4/v4 v4.1.26 github.com/prometheus/client_golang v1.23.2 - github.com/redis/go-redis/v9 v9.17.2 + github.com/redis/go-redis/v9 v9.18.0 github.com/spf13/cast v1.10.0 github.com/spf13/pflag v1.0.10 github.com/spf13/viper v1.21.0 github.com/stretchr/testify v1.11.1 github.com/vmihailenco/msgpack/v5 v5.4.1 go.yaml.in/yaml/v3 v3.0.4 - golang.org/x/crypto v0.47.0 - golang.org/x/net v0.49.0 - golang.org/x/oauth2 v0.34.0 - golang.org/x/sync v0.19.0 - google.golang.org/api v0.260.0 + golang.org/x/crypto v0.49.0 + golang.org/x/net v0.52.0 + golang.org/x/oauth2 v0.36.0 + golang.org/x/sync v0.20.0 + google.golang.org/api v0.272.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 - k8s.io/apimachinery v0.35.0 + k8s.io/apimachinery v0.35.3 ) require ( - cloud.google.com/go/auth v0.18.0 // indirect + cloud.google.com/go/auth v0.18.2 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect github.com/Masterminds/semver/v3 v3.4.0 // indirect github.com/beorn7/perks v1.0.1 // indirect @@ -49,38 +50,38 @@ require ( github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/go-jose/go-jose/v4 v4.1.3 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-task/slim-sprig/v3 v3.0.0 // indirect - github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 // indirect + github.com/google/pprof v0.0.0-20260302011040-a15ffb7f9dcc // indirect github.com/google/s2a-go v0.1.9 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.11 // indirect - github.com/googleapis/gax-go/v2 v2.16.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.14 // indirect + github.com/googleapis/gax-go/v2 v2.19.0 // indirect github.com/kylelemons/godebug v1.1.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/common v0.67.5 // indirect - github.com/prometheus/procfs v0.19.2 // indirect + github.com/prometheus/procfs v0.20.1 // indirect github.com/sagikazarmark/locafero v0.12.0 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/yuin/gopher-lua v1.1.1 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0 // indirect - go.opentelemetry.io/otel v1.39.0 // indirect - go.opentelemetry.io/otel/metric v1.39.0 // indirect - go.opentelemetry.io/otel/trace v1.39.0 // indirect - go.yaml.in/yaml/v2 v2.4.3 // indirect - golang.org/x/mod v0.32.0 // indirect - golang.org/x/sys v0.40.0 // indirect - golang.org/x/text v0.33.0 // indirect - golang.org/x/tools v0.41.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260114163908-3f89685c29c3 // indirect - google.golang.org/grpc v1.78.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect + go.opentelemetry.io/otel v1.42.0 // indirect + go.opentelemetry.io/otel/metric v1.42.0 // indirect + go.opentelemetry.io/otel/trace v1.42.0 // indirect + go.uber.org/atomic v1.11.0 // indirect + go.yaml.in/yaml/v2 v2.4.4 // indirect + golang.org/x/mod v0.34.0 // indirect + golang.org/x/sys v0.42.0 // indirect + golang.org/x/text v0.35.0 // indirect + golang.org/x/tools v0.43.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260319201613-d00831a3d3e7 // indirect + google.golang.org/grpc v1.79.3 // indirect google.golang.org/protobuf v1.36.11 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index ac6b56d4..48ddf1f2 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -cloud.google.com/go/auth v0.18.0 h1:wnqy5hrv7p3k7cShwAU/Br3nzod7fxoqG+k0VZ+/Pk0= -cloud.google.com/go/auth v0.18.0/go.mod h1:wwkPM1AgE1f2u6dG443MiWoD8C3BtOywNsUMcUTVDRo= +cloud.google.com/go/auth v0.18.2 h1:+Nbt5Ev0xEqxlNjd6c+yYUeosQ5TtEUaNcN/3FozlaM= +cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= @@ -14,8 +14,8 @@ github.com/a8m/envsubst v1.4.3 h1:kDF7paGK8QACWYaQo6KtyYBozY2jhQrTuNNuUxQkhJY= github.com/a8m/envsubst v1.4.3/go.mod h1:4jjHWQlZoaXPoLQUb7H2qT4iLkZDdmEQiOUogdUmqVU= github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= github.com/alicebob/miniredis/v2 v2.11.1/go.mod h1:UA48pmi7aSazcGAvcdKcBB49z521IC9VjTTRz2nIaJE= -github.com/alicebob/miniredis/v2 v2.35.0 h1:QwLphYqCEAo1eu1TqPRN2jgVMPBweeQcR21jeqDCONI= -github.com/alicebob/miniredis/v2 v2.35.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM= +github.com/alicebob/miniredis/v2 v2.37.0 h1:RheObYW32G1aiJIj81XVt78ZHJpHonHLHW7OLIshq68= +github.com/alicebob/miniredis/v2 v2.37.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bitly/go-simplejson v0.5.1 h1:xgwPbetQScXt1gh9BmoJ6j9JMr3TElvuIyjR8pgdoow= @@ -67,8 +67,8 @@ github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9L github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= -github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo= -github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3 h1:6amM4HsNPOvMLVc2ZnyqrjeQ92YAVWn7T4WBKK87inY= @@ -76,17 +76,17 @@ github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3/go.mod h1:B4C85q github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 h1:z2ogiKUYzX5Is6zr/vP9vJGqPwcdqsWjOt+V8J7+bTc= -github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= +github.com/google/pprof v0.0.0-20260302011040-a15ffb7f9dcc h1:VBbFa1lDYWEeV5FZKUiYKYT0VxCp9twUmmaq9eb8sXw= +github.com/google/pprof v0.0.0-20260302011040-a15ffb7f9dcc/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.11 h1:vAe81Msw+8tKUxi2Dqh/NZMz7475yUvmRIkXr4oN2ao= -github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8= -github.com/googleapis/gax-go/v2 v2.16.0 h1:iHbQmKLLZrexmb0OSsNGTeSTS0HO4YvFOG8g5E4Zd0Y= -github.com/googleapis/gax-go/v2 v2.16.0/go.mod h1:o1vfQjjNZn4+dPnRdl/4ZD7S9414Y4xA+a/6Icj6l14= +github.com/googleapis/enterprise-certificate-proxy v0.3.14 h1:yh8ncqsbUY4shRD5dA6RlzjJaT4hi3kII+zYw8wmLb8= +github.com/googleapis/enterprise-certificate-proxy v0.3.14/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg= +github.com/googleapis/gax-go/v2 v2.19.0 h1:fYQaUOiGwll0cGj7jmHT/0nPlcrZDFPrZRhTsoCr8hE= +github.com/googleapis/gax-go/v2 v2.19.0/go.mod h1:w2ROXVdfGEVFXzmlciUU4EdjHgWvB5h2n6x/8XSTTJA= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE= @@ -95,6 +95,8 @@ github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo= github.com/justinas/alice v1.2.0/go.mod h1:fN5HRH/reO/zrUflLfTN43t3vXvKzvZIENsNEe7i7qA= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -111,14 +113,14 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw= -github.com/onsi/ginkgo/v2 v2.27.5 h1:ZeVgZMx2PDMdJm/+w5fE/OyG6ILo1Y3e+QX4zSR0zTE= -github.com/onsi/ginkgo/v2 v2.27.5/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= -github.com/onsi/gomega v1.39.0 h1:y2ROC3hKFmQZJNFeGAMeHZKkjBL65mIZcvrLQBF9k6Q= -github.com/onsi/gomega v1.39.0/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4= +github.com/onsi/ginkgo/v2 v2.28.1 h1:S4hj+HbZp40fNKuLUQOYLDgZLwNUVn19N3Atb98NCyI= +github.com/onsi/ginkgo/v2 v2.28.1/go.mod h1:CLtbVInNckU3/+gC8LzkGUb9oF+e8W8TdUsxPwvdOgE= +github.com/onsi/gomega v1.39.1 h1:1IJLAad4zjPn2PsnhH70V4DKRFlrCzGBNrNaru+Vf28= +github.com/onsi/gomega v1.39.1/go.mod h1:hL6yVALoTOxeWudERyfppUcZXjMwIMLnuSfruD2lcfg= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= -github.com/pierrec/lz4/v4 v4.1.25 h1:kocOqRffaIbU5djlIBr7Wh+cx82C0vtFb0fOurZHqD0= -github.com/pierrec/lz4/v4 v4.1.25/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= +github.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY= +github.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -128,10 +130,10 @@ github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNw github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4= github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw= -github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws= -github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw= -github.com/redis/go-redis/v9 v9.17.2 h1:P2EGsA4qVIM3Pp+aPocCJ7DguDHhqrXNhVcEp4ViluI= -github.com/redis/go-redis/v9 v9.17.2/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370= +github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc= +github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo= +github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs= +github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4= @@ -167,51 +169,55 @@ github.com/yuin/gopher-lua v0.0.0-20190206043414-8bfc7677f583/go.mod h1:gqRgreBU github.com/yuin/gopher-lua v0.0.0-20191213034115-f46add6fdb5c/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ= github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M= github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= +github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0= +github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0 h1:ssfIgGNANqpVFCndZvcuyKbl0g+UAVcbBcqGkG28H0Y= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0/go.mod h1:GQ/474YrbE4Jx8gZ4q5I4hrhUzM6UPzyrqJYV2AqPoQ= -go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48= -go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8= -go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0= -go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs= -go.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18= -go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE= -go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8= -go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew= -go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI= -go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg= +go.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho= +go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc= +go.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4= +go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI= +go.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo= +go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts= +go.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA= +go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc= +go.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY= +go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= -go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0= -go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8= +go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= +go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= -golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8= -golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A= +golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4= +golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c= -golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU= +golang.org/x/mod v0.34.0 h1:xIHgNUUnW6sYkcM5Jleh05DvLOtwc6RitGHbDk4akRI= +golang.org/x/mod v0.34.0/go.mod h1:ykgH52iCZe79kzLLMhyCUzhMci+nQj+0XkbXpNYtVjY= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o= -golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= -golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw= -golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= +golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0= +golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= +golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= +golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= -golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -221,8 +227,8 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= -golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= +golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -234,29 +240,29 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE= -golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= -golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= -golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= +golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= +golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= +golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= +golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc= -golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg= +golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s= +golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= -google.golang.org/api v0.260.0 h1:XbNi5E6bOVEj/uLXQRlt6TKuEzMD7zvW/6tNwltE4P4= -google.golang.org/api v0.260.0/go.mod h1:Shj1j0Phr/9sloYrKomICzdYgsSDImpTxME8rGLaZ/o= -google.golang.org/genproto v0.0.0-20251202230838-ff82c1b0f217 h1:GvESR9BIyHUahIb0NcTum6itIWtdoglGX+rnGxm2934= -google.golang.org/genproto v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:yJ2HH4EHEDTd3JiLmhds6NkJ17ITVYOdV3m3VKOnws0= -google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls= -google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:+rXWjjaukWZun3mLfjmVnQi18E1AsFbDN9QdJ5YXLto= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260114163908-3f89685c29c3 h1:C4WAdL+FbjnGlpp2S+HMVhBeCq2Lcib4xZqfPNF6OoQ= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260114163908-3f89685c29c3/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ= -google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc= -google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U= +google.golang.org/api v0.272.0 h1:eLUQZGnAS3OHn31URRf9sAmRk3w2JjMx37d2k8AjJmA= +google.golang.org/api v0.272.0/go.mod h1:wKjowi5LNJc5qarNvDCvNQBn3rVK8nSy6jg2SwRwzIA= +google.golang.org/genproto v0.0.0-20260316180232-0b37fe3546d5 h1:JNfk58HZ8lfmXbYK2vx/UvsqIL59TzByCxPIX4TDmsE= +google.golang.org/genproto v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:x5julN69+ED4PcFk/XWayw35O0lf/nGa4aNgODCmNmw= +google.golang.org/genproto/googleapis/api v0.0.0-20260316180232-0b37fe3546d5 h1:CogIeEXn4qWYzzQU0QqvYBM8yDF9cFYzDq9ojSpv0Js= +google.golang.org/genproto/googleapis/api v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:EIQZ5bFCfRQDV4MhRle7+OgjNtZ6P1PiZBgAKuxXu/Y= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260319201613-d00831a3d3e7 h1:ndE4FoJqsIceKP2oYSnUZqhTdYufCYYkqwtFzfrhI7w= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE= +google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -267,5 +273,5 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYs gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/apimachinery v0.35.0 h1:Z2L3IHvPVv/MJ7xRxHEtk6GoJElaAqDCCU0S6ncYok8= -k8s.io/apimachinery v0.35.0/go.mod h1:jQCgFZFR1F4Ik7hvr2g84RTJSZegBc8yHgFWKn//hns= +k8s.io/apimachinery v0.35.3 h1:MeaUwQCV3tjKP4bcwWGgZ/cp/vpsRnQzqO6J6tJyoF8= +k8s.io/apimachinery v0.35.3/go.mod h1:jQCgFZFR1F4Ik7hvr2g84RTJSZegBc8yHgFWKn//hns= diff --git a/oauthproxy.go b/oauthproxy.go index 1610507b..dc3f8b57 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -875,6 +875,8 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) { remoteAddr := ip.GetClientString(p.realClientIPParser, req, true) // finish the oauth cycle + // #nosec G120 -- The default max size in Go is already capped at 10MB so this would be the absolute max and is + // unlikely to be hit in practice. err := req.ParseForm() if err != nil { logger.Errorf("Error while parsing OAuth2 callback: %v", err) diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index 99e3679f..e53fd480 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -694,7 +694,7 @@ func (l LegacyServer) convert() (Server, Server) { } func (l *LegacyProvider) convert() (Providers, error) { - providers := Providers{} + providers := make(Providers, 0, 1) provider := Provider{ ClientID: l.ClientID, diff --git a/pkg/validation/providers.go b/pkg/validation/providers.go index ecc3277a..0c8e28db 100644 --- a/pkg/validation/providers.go +++ b/pkg/validation/providers.go @@ -165,7 +165,8 @@ func validateEntraConfig(provider options.Provider) []string { return msgs } - _, err := os.ReadFile(federatedTokenPath) + // #nosec G703 -- AZURE_FEDERATED_TOKEN_FILE is set by the operator, not user input + _, err := os.Stat(federatedTokenPath) if err != nil { msgs = append(msgs, "could not read entra federated token file") } diff --git a/providers/ms_entra_id.go b/providers/ms_entra_id.go index f9445d69..f30176fd 100644 --- a/providers/ms_entra_id.go +++ b/providers/ms_entra_id.go @@ -110,6 +110,7 @@ func (p *MicrosoftEntraIDProvider) Redeem(ctx context.Context, redirectURL, code // redeemWithFederatedToken performs custom token exchange with federated token instead of client secret func (p *MicrosoftEntraIDProvider) redeemWithFederatedToken(ctx context.Context, redirectURL, code, codeVerifier string) (*sessions.SessionState, error) { federatedTokenPath := os.Getenv("AZURE_FEDERATED_TOKEN_FILE") + // #nosec G703 -- AZURE_FEDERATED_TOKEN_FILE is set by the operator, not user input federatedToken, err := os.ReadFile(federatedTokenPath) if err != nil { return nil, fmt.Errorf("error reading federated token file %s: %s", federatedTokenPath, err) @@ -162,6 +163,7 @@ func (p *MicrosoftEntraIDProvider) RefreshSession(ctx context.Context, s *sessio // Refresh Token, Access Token and ID Token func (p *MicrosoftEntraIDProvider) redeemRefreshTokenWithFederatedToken(ctx context.Context, s *sessions.SessionState) error { federatedTokenPath := os.Getenv("AZURE_FEDERATED_TOKEN_FILE") + // #nosec G703 -- AZURE_FEDERATED_TOKEN_FILE is set by the operator, not user input federatedToken, err := os.ReadFile(federatedTokenPath) if err != nil { return fmt.Errorf("error reading federated token file %s: %s", federatedTokenPath, err) From 9f09d54ba4481aa69f336381cd106d058f118930 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 23 Mar 2026 09:39:22 +0100 Subject: [PATCH 28/53] chore(deps): update actions/upload-artifact action to v7 (#3358) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/publish-release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index ed58edd9..bac76bee 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -70,7 +70,7 @@ jobs: # Upload artifacts in case of workflow failure - name: Upload Artifacts - uses: actions/upload-artifact@v5 + uses: actions/upload-artifact@v7 with: name: oauth2-proxy-artifacts path: | From a4d89036ec102509fbb0d393f77cc90af6d083c8 Mon Sep 17 00:00:00 2001 From: H1net Date: Mon, 23 Mar 2026 09:22:36 +0000 Subject: [PATCH 29/53] fix: handle Unix socket RemoteAddr in IP resolution (#3374) * fix: handle Unix socket RemoteAddr in IP resolution When oauth2-proxy listens on a Unix socket, Go sets RemoteAddr to "@" instead of the usual "host:port" format. This caused net.SplitHostPort to fail on every request, flooding logs with errors: Error obtaining real IP for trusted IP list: unable to get ip and port from http.RemoteAddr (@) Fix by handling the "@" RemoteAddr at the source in getRemoteIP, returning nil without error since Unix sockets have no meaningful client IP. Also simplify the isTrustedIP guard and add a nil check in GetClientString to prevent calling String() on nil net.IP. Fixes #3373 Signed-off-by: h1net * docs: add changelog entry and Unix socket trusted IPs documentation Add changelog entry for #3374. Document that trusted IPs cannot match against RemoteAddr for Unix socket listeners since Go sets it to "@", and that IP-based trust still works via X-Forwarded-For with reverse-proxy. Signed-off-by: Ben Newbery Signed-off-by: h1net * doc: fix changelog entry for #3374 Signed-off-by: Jan Larwig * doc: add trusted ip a section to versioned docs as well Signed-off-by: Jan Larwig --------- Signed-off-by: h1net Signed-off-by: Ben Newbery Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 2 ++ docs/docs/configuration/systemd_socket.md | 8 ++++++ .../configuration/systemd_socket.md | 8 ++++++ oauthproxy.go | 4 +-- oauthproxy_test.go | 26 +++++++++++++++++++ pkg/ip/realclientip.go | 8 +++++- pkg/ip/realclientip_test.go | 4 +++ 7 files changed, 56 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d740cb9..aabc1385 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,8 @@ # V7.15.0 - [#3382](https://github.com/oauth2-proxy/oauth2-proxy/pull/3382) chore(deps): update gomod and golangci/golangci-lint to v2.11.4 (@tuunit) +- [#3374](https://github.com/oauth2-proxy/oauth2-proxy/pull/3374) fix: handle Unix socket RemoteAddr in IP resolution (@H1net) + ## Release Highlights diff --git a/docs/docs/configuration/systemd_socket.md b/docs/docs/configuration/systemd_socket.md index 642e6f3f..490dabbf 100644 --- a/docs/docs/configuration/systemd_socket.md +++ b/docs/docs/configuration/systemd_socket.md @@ -40,4 +40,12 @@ the listener it created onto the process, starting with file descriptor 3. --client-secret=... ``` +## Trusted IPs + +When listening on a Unix socket, Go sets `http.Request.RemoteAddr` to `"@"` instead of the usual `"host:port"` format. This means there is no client IP available from the connection itself. + +As a result, `--trusted-ip` entries cannot match against the direct connection address for Unix socket listeners. Requests arriving over a Unix socket will never be considered "trusted" based on their `RemoteAddr`. IP-based trust decisions will still work if a trusted reverse proxy sets `X-Forwarded-For` or `X-Real-IP` headers and `--reverse-proxy=true` is configured. + +## TLS + Currently TLS is not supported (but it's doable). diff --git a/docs/versioned_docs/version-7.15.x/configuration/systemd_socket.md b/docs/versioned_docs/version-7.15.x/configuration/systemd_socket.md index 642e6f3f..490dabbf 100644 --- a/docs/versioned_docs/version-7.15.x/configuration/systemd_socket.md +++ b/docs/versioned_docs/version-7.15.x/configuration/systemd_socket.md @@ -40,4 +40,12 @@ the listener it created onto the process, starting with file descriptor 3. --client-secret=... ``` +## Trusted IPs + +When listening on a Unix socket, Go sets `http.Request.RemoteAddr` to `"@"` instead of the usual `"host:port"` format. This means there is no client IP available from the connection itself. + +As a result, `--trusted-ip` entries cannot match against the direct connection address for Unix socket listeners. Requests arriving over a Unix socket will never be considered "trusted" based on their `RemoteAddr`. IP-based trust decisions will still work if a trusted reverse proxy sets `X-Forwarded-For` or `X-Real-IP` headers and `--reverse-proxy=true` is configured. + +## TLS + Currently TLS is not supported (but it's doable). diff --git a/oauthproxy.go b/oauthproxy.go index dc3f8b57..f260acc6 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -613,9 +613,7 @@ func (p *OAuthProxy) isAPIPath(req *http.Request) bool { // isTrustedIP is used to check if a request comes from a trusted client IP address. func (p *OAuthProxy) isTrustedIP(req *http.Request) bool { - // RemoteAddr @ means unix socket - // https://github.com/golang/go/blob/0fa53e41f122b1661d0678a6d36d71b7b5ad031d/src/syscall/syscall_linux.go#L506-L511 - if p.trustedIPs == nil && req.RemoteAddr != "@" { + if p.trustedIPs == nil { return false } diff --git a/oauthproxy_test.go b/oauthproxy_test.go index 38cdccab..e06f50e9 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -2150,6 +2150,32 @@ func TestTrustedIPs(t *testing.T) { }(), expectTrusted: false, }, + // Check Unix socket with no trusted IPs configured does not error. + { + name: "UnixSocketWithoutTrustedIPs", + trustedIPs: nil, + reverseProxy: false, + realClientIPHeader: "X-Real-IP", + req: func() *http.Request { + req, _ := http.NewRequest("GET", "/", nil) + req.RemoteAddr = "@" + return req + }(), + expectTrusted: false, + }, + // Check Unix socket with trusted IPs configured returns false (no IP to match). + { + name: "UnixSocketWithTrustedIPs", + trustedIPs: []string{"127.0.0.1"}, + reverseProxy: false, + realClientIPHeader: "X-Real-IP", + req: func() *http.Request { + req, _ := http.NewRequest("GET", "/", nil) + req.RemoteAddr = "@" + return req + }(), + expectTrusted: false, + }, // Check using req.RemoteAddr (Options.ReverseProxy == false). { name: "WithRemoteAddr", diff --git a/pkg/ip/realclientip.go b/pkg/ip/realclientip.go index 8bfc7ea3..db8f2595 100644 --- a/pkg/ip/realclientip.go +++ b/pkg/ip/realclientip.go @@ -73,6 +73,12 @@ func GetClientIP(p ipapi.RealClientIPParser, req *http.Request) (net.IP, error) // getRemoteIP obtains the IP of the low-level connected network host func getRemoteIP(req *http.Request) (net.IP, error) { + // Unix domain sockets set RemoteAddr to "@" which has no meaningful IP. + // https://github.com/golang/go/blob/0fa53e41f122b1661d0678a6d36d71b7b5ad031d/src/syscall/syscall_linux.go#L506-L511 + if req.RemoteAddr == "@" { + return nil, nil + } + //revive:disable:indent-error-flow if ipStr, _, err := net.SplitHostPort(req.RemoteAddr); err != nil { return nil, fmt.Errorf("unable to get ip and port from http.RemoteAddr (%s)", req.RemoteAddr) @@ -94,7 +100,7 @@ func GetClientString(p ipapi.RealClientIPParser, req *http.Request, full bool) ( } var remoteIPStr string - if remoteIP, err := getRemoteIP(req); err == nil { + if remoteIP, err := getRemoteIP(req); err == nil && remoteIP != nil { remoteIPStr = remoteIP.String() } diff --git a/pkg/ip/realclientip_test.go b/pkg/ip/realclientip_test.go index c56e0170..3cbca114 100644 --- a/pkg/ip/realclientip_test.go +++ b/pkg/ip/realclientip_test.go @@ -112,6 +112,8 @@ func TestGetRemoteIP(t *testing.T) { errString string expectedIP net.IP }{ + // Unix domain sockets set RemoteAddr to "@" + {"@", "", nil}, {"", "unable to get ip and port from http.RemoteAddr ()", nil}, {"nil", "unable to get ip and port from http.RemoteAddr (nil)", nil}, {"235.28.129.186", "unable to get ip and port from http.RemoteAddr (235.28.129.186)", nil}, @@ -155,6 +157,8 @@ func TestGetClientString(t *testing.T) { }{ // Should fail quietly, only printing warnings to the log {nil, "", "", "", ""}, + // Unix domain socket — no IP available + {nil, "@", "", "", ""}, {p, "127.0.0.1:11950", "", "127.0.0.1", "127.0.0.1"}, {p, "[::1]:28660", "99.103.56.12", "99.103.56.12", "::1 (99.103.56.12)"}, {nil, "10.254.244.165:62750", "", "10.254.244.165", "10.254.244.165"}, From 44236f0314ebaeed8d9f57ece7e2ab05a80b81e6 Mon Sep 17 00:00:00 2001 From: artificiosus Date: Mon, 23 Mar 2026 05:27:49 -0400 Subject: [PATCH 30/53] fix: do not log error for backend logout 204 (#3381) * Don't log error for backend logout 204 Signed-off-by: artificiosus * doc: add changelog entry for #3381 Signed-off-by: Jan Larwig * refactor: use http.StatusOK and http.StatusNoContent instead of integers Signed-off-by: Jan Larwig --------- Signed-off-by: artificiosus Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + oauthproxy.go | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aabc1385..9cffcc91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ - [#3382](https://github.com/oauth2-proxy/oauth2-proxy/pull/3382) chore(deps): update gomod and golangci/golangci-lint to v2.11.4 (@tuunit) - [#3374](https://github.com/oauth2-proxy/oauth2-proxy/pull/3374) fix: handle Unix socket RemoteAddr in IP resolution (@H1net) +- [#3381](https://github.com/oauth2-proxy/oauth2-proxy/pull/3381) fix: do not log error for backend logout 204 (@artificiosus) ## Release Highlights diff --git a/oauthproxy.go b/oauthproxy.go index f260acc6..3efe66fd 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -798,7 +798,7 @@ func (p *OAuthProxy) backendLogout(rw http.ResponseWriter, req *http.Request) { } defer resp.Body.Close() - if resp.StatusCode != 200 { + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent { logger.Errorf("error while calling backend logout url, returned error code %v", resp.StatusCode) } } From 5ca3012652893d34e41d069fa4156e78ba0b4751 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Mon, 23 Mar 2026 10:36:19 +0100 Subject: [PATCH 31/53] doc: update PR template with additional checklist items --- .github/PULL_REQUEST_TEMPLATE.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 20aad512..042a0394 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -20,7 +20,8 @@ -- [ ] My change requires a change to the documentation or CHANGELOG. -- [ ] I have updated the documentation/CHANGELOG accordingly. +- [ ] I have added an entry for my changes to the [CHANGELOG.md](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/CHANGELOG.md). +- [ ] I have [signed off](https://github.com/apps/dco) all my commits. - [ ] I have created a feature (non-master) branch for my PR. +- [ ] I have used [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/#examples) for the PR title. - [ ] I have written tests for my code changes. From e2682f759539fe735b18fc655b677cb0a935637f Mon Sep 17 00:00:00 2001 From: Yosri Barhoumi <44350807+yosri-brh@users.noreply.github.com> Date: Mon, 23 Mar 2026 10:54:32 +0100 Subject: [PATCH 32/53] fix: improve logging when session refresh token is missing (#3327) * Improve logging for session refresh token status Signed-off-by: Yosri Barhoumi * doc: add changelog entry for #3327 Signed-off-by: Jan Larwig * test: fix existing test cases for new behaviour Signed-off-by: Jan Larwig --------- Signed-off-by: Yosri Barhoumi Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + pkg/apis/sessions/session_state.go | 2 ++ pkg/apis/sessions/session_state_test.go | 39 +++++++++++++++++++++---- pkg/middleware/stored_session.go | 1 + 4 files changed, 38 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cffcc91..f5d63cd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ - [#3382](https://github.com/oauth2-proxy/oauth2-proxy/pull/3382) chore(deps): update gomod and golangci/golangci-lint to v2.11.4 (@tuunit) - [#3374](https://github.com/oauth2-proxy/oauth2-proxy/pull/3374) fix: handle Unix socket RemoteAddr in IP resolution (@H1net) - [#3381](https://github.com/oauth2-proxy/oauth2-proxy/pull/3381) fix: do not log error for backend logout 204 (@artificiosus) +- [#3327](https://github.com/oauth2-proxy/oauth2-proxy/pull/3327) fix: improve logging when session refresh token is missing (@yosri-brh) ## Release Highlights diff --git a/pkg/apis/sessions/session_state.go b/pkg/apis/sessions/session_state.go index fef20aab..6c55e2c8 100644 --- a/pkg/apis/sessions/session_state.go +++ b/pkg/apis/sessions/session_state.go @@ -127,6 +127,8 @@ func (s *SessionState) String() string { } if s.RefreshToken != "" { o += " refresh_token:true" + } else { + o += " refresh_token:false" } if len(s.Groups) > 0 { o += fmt.Sprintf(" groups:%v", s.Groups) diff --git a/pkg/apis/sessions/session_state_test.go b/pkg/apis/sessions/session_state_test.go index 1dc6d3ad..ec131393 100644 --- a/pkg/apis/sessions/session_state_test.go +++ b/pkg/apis/sessions/session_state_test.go @@ -4,6 +4,7 @@ import ( "crypto/rand" "fmt" "io" + "strings" "testing" "time" @@ -57,7 +58,7 @@ func TestString(t *testing.T) { User: "some.user", PreferredUsername: "preferred.user", }, - expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user}", + expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user refresh_token:false}", }, { name: "Full Session", @@ -81,7 +82,7 @@ func TestString(t *testing.T) { PreferredUsername: "preferred.user", CreatedAt: &created, }, - expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user created:2000-01-01 00:00:00 +0000 UTC}", + expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user created:2000-01-01 00:00:00 +0000 UTC refresh_token:false}", }, { name: "With an ExpiresOn", @@ -91,7 +92,7 @@ func TestString(t *testing.T) { PreferredUsername: "preferred.user", ExpiresOn: &expires, }, - expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user expires:2000-01-01 01:00:00 +0000 UTC}", + expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user expires:2000-01-01 01:00:00 +0000 UTC refresh_token:false}", }, { name: "With an AccessToken", @@ -101,7 +102,7 @@ func TestString(t *testing.T) { PreferredUsername: "preferred.user", AccessToken: "access.token", }, - expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user token:true}", + expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user token:true refresh_token:false}", }, { name: "With an IDToken", @@ -111,7 +112,7 @@ func TestString(t *testing.T) { PreferredUsername: "preferred.user", IDToken: "id.token", }, - expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user id_token:true}", + expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user id_token:true refresh_token:false}", }, { name: "With a RefreshToken", @@ -353,3 +354,31 @@ func TestGetClaim(t *testing.T) { }) } } + +func TestSessionState_String_RefreshTokenFalse(t *testing.T) { + session := &SessionState{ + Email: "test@example.com", + User: "testuser", + // No RefreshToken set + } + + result := session.String() + + if !strings.Contains(result, "refresh_token:false") { + t.Errorf("Expected 'refresh_token:false' in output, got: %s", result) + } +} + +func TestSessionState_String_RefreshTokenTrue(t *testing.T) { + session := &SessionState{ + Email: "test@example.com", + User: "testuser", + RefreshToken: "some-token", + } + + result := session.String() + + if !strings.Contains(result, "refresh_token:true") { + t.Errorf("Expected 'refresh_token:true' in output, got: %s", result) + } +} diff --git a/pkg/middleware/stored_session.go b/pkg/middleware/stored_session.go index f861c756..72c364e7 100644 --- a/pkg/middleware/stored_session.go +++ b/pkg/middleware/stored_session.go @@ -222,6 +222,7 @@ func (s *storedSessionLoader) refreshSession(rw http.ResponseWriter, req *http.R // Session not refreshed, nothing to persist. if !refreshed { + logger.Printf("Session not refreshed - User: %s; no refresh token available or provider returned false", session.User) return nil } From 46be69c276f0ab17cd30d0cc0f309a187a23d92a Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Mon, 23 Mar 2026 11:25:20 +0100 Subject: [PATCH 33/53] fix: propagate errors during route building (#3383) * Propagate errors during route building This fixes cases such as invalid paths being silently discarded after creation by throwing a visible error in such cases. Due to the way gorilla/mux's fluent API is designed, it is necessary to manually call `.GetError()` to check for errors while building routes. Signed-off-by: Simon Engmann * Add test for route building error propagation Signed-off-by: Simon Engmann * Add route building error propagation to changelog Signed-off-by: Simon Engmann --------- Signed-off-by: Simon Engmann Co-authored-by: Simon Engmann --- CHANGELOG.md | 1 + pkg/upstream/proxy.go | 28 ++++++++++++++-------------- pkg/upstream/proxy_test.go | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5d63cd6..c259b733 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ - [#3374](https://github.com/oauth2-proxy/oauth2-proxy/pull/3374) fix: handle Unix socket RemoteAddr in IP resolution (@H1net) - [#3381](https://github.com/oauth2-proxy/oauth2-proxy/pull/3381) fix: do not log error for backend logout 204 (@artificiosus) - [#3327](https://github.com/oauth2-proxy/oauth2-proxy/pull/3327) fix: improve logging when session refresh token is missing (@yosri-brh) +- [#2767](https://github.com/oauth2-proxy/oauth2-proxy/pull/2767) fix: propagate errors during route building (@sybereal) ## Release Highlights diff --git a/pkg/upstream/proxy.go b/pkg/upstream/proxy.go index af4d2e84..857395ec 100644 --- a/pkg/upstream/proxy.go +++ b/pkg/upstream/proxy.go @@ -58,7 +58,9 @@ func NewProxy(upstreams options.UpstreamConfig, sigData *options.SignatureData, } } - registerTrailingSlashHandler(m.serveMux) + if err := registerTrailingSlashHandler(m.serveMux); err != nil { + return nil, fmt.Errorf("could not register trailing slash handler: %w", err) + } return m, nil } @@ -94,8 +96,7 @@ func (m *multiUpstreamProxy) registerHTTPUpstreamProxy(upstream options.Upstream // registerHandler ensures the given handler is regiestered with the serveMux. func (m *multiUpstreamProxy) registerHandler(upstream options.Upstream, handler http.Handler, writer pagewriter.Writer) error { if upstream.RewriteTarget == "" { - m.registerSimpleHandler(upstream.Path, handler) - return nil + return m.registerSimpleHandler(upstream.Path, handler) } return m.registerRewriteHandler(upstream, handler, writer) @@ -103,12 +104,12 @@ func (m *multiUpstreamProxy) registerHandler(upstream options.Upstream, handler // registerSimpleHandler maintains the behaviour of the go standard serveMux // by ensuring any path with a trailing `/` matches all paths under that prefix. -func (m *multiUpstreamProxy) registerSimpleHandler(path string, handler http.Handler) { +func (m *multiUpstreamProxy) registerSimpleHandler(path string, handler http.Handler) error { if strings.HasSuffix(path, "/") { - m.serveMux.PathPrefix(path).Handler(handler) - } else { - m.serveMux.Path(path).Handler(handler) + return m.serveMux.PathPrefix(path).Handler(handler).GetError() } + + return m.serveMux.Path(path).Handler(handler).GetError() } // registerRewriteHandler ensures the handler is registered for all paths @@ -123,19 +124,18 @@ func (m *multiUpstreamProxy) registerRewriteHandler(upstream options.Upstream, h rewrite := newRewritePath(rewriteRegExp, upstream.RewriteTarget, writer) h := alice.New(rewrite).Then(handler) - m.serveMux.MatcherFunc(func(req *http.Request, _ *mux.RouteMatch) bool { - return rewriteRegExp.MatchString(req.URL.Path) - }).Handler(h) - return nil + return m.serveMux.MatcherFunc(func(req *http.Request, _ *mux.RouteMatch) bool { + return rewriteRegExp.MatchString(req.URL.Path) + }).Handler(h).GetError() } // registerTrailingSlashHandler creates a new matcher that will check if the // requested path would match if it had a trailing slash appended. // If the path matches with a trailing slash, we send back a redirect. // This allows us to be consistent with the built in go servemux implementation. -func registerTrailingSlashHandler(serveMux *mux.Router) { - serveMux.MatcherFunc(func(req *http.Request, _ *mux.RouteMatch) bool { +func registerTrailingSlashHandler(serveMux *mux.Router) error { + return serveMux.MatcherFunc(func(req *http.Request, _ *mux.RouteMatch) bool { if strings.HasSuffix(req.URL.Path, "/") { return false } @@ -149,7 +149,7 @@ func registerTrailingSlashHandler(serveMux *mux.Router) { return serveMux.Match(slashReq, m) }).Handler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { http.Redirect(rw, req, req.URL.String()+"/", http.StatusMovedPermanently) - })) + })).GetError() } // sortByPathLongest ensures that the upstreams are sorted by longest path. diff --git a/pkg/upstream/proxy_test.go b/pkg/upstream/proxy_test.go index b9b8cf9c..aba4a730 100644 --- a/pkg/upstream/proxy_test.go +++ b/pkg/upstream/proxy_test.go @@ -383,6 +383,38 @@ var _ = Describe("Proxy Suite", func() { ) }) + Context("multiUpstreamProxy errors", func() { + type proxyErrorTableInput struct { + upstreams options.UpstreamConfig + expectedError string + } + + DescribeTable("NewProxy", func(in *proxyErrorTableInput) { + sigData := &options.SignatureData{Hash: crypto.SHA256, Key: "secret"} + + writer := &pagewriter.WriterFuncs{ + ProxyErrorFunc: func(rw http.ResponseWriter, _ *http.Request, _ error) { + rw.WriteHeader(502) + rw.Write([]byte("Proxy Error")) + }, + } + + _, err := NewProxy(in.upstreams, sigData, writer) + Expect(err).To(MatchError(in.expectedError)) + }, + Entry("regex matcher without rewrite target", &proxyErrorTableInput{ + upstreams: options.UpstreamConfig{ + Upstreams: []options.Upstream{{ + ID: "api", + Path: "^/api/$", + URI: "http://example.com", + }}, + }, + expectedError: `could not register http upstream "api": mux: path must start with a slash, got "^/api/$"`, + }), + ) + }) + Context("sortByPathLongest", func() { type sortByPathLongestTableInput struct { input []options.Upstream From 848ec8ba82e8097bf52c16b3ba825dacef8fcbcb Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 23 Mar 2026 15:46:15 +0100 Subject: [PATCH 34/53] release v7.15.1 (#3384) * update to release version v7.15.1 * doc: release notes for v7.15.1 Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Jan Larwig --- CHANGELOG.md | 16 ++++++++++++++-- .../docker-compose-alpha-config.yaml | 2 +- .../local-environment/docker-compose-gitea.yaml | 2 +- .../docker-compose-keycloak.yaml | 2 +- .../local-environment/docker-compose-nginx.yaml | 2 +- .../docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/installation.md | 2 +- .../version-7.15.x/installation.md | 2 +- 9 files changed, 22 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c259b733..a3b4018a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,20 @@ ## Release Highlights -- Fixes [CVE-2026-33186](https://nvd.nist.gov/vuln/detail/CVE-2026-33186) - - OAuth2 Proxy was not impacted by this vulnerability as it isn't in the path of execution +## Important Notes + +## Breaking Changes + +## Changes since v7.15.1 + +# V7.15.1 + +## Release Highlights + +- 🐛 Squashed some bugs +- 🕵️‍♀️ Vulnerabilities have been addressed + - [CVE-2026-33186](https://nvd.nist.gov/vuln/detail/CVE-2026-33186) + OAuth2 Proxy was not impacted by this vulnerability as it isn't in the path of execution ## Important Notes diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index aee1af0b..515c42e0 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -14,7 +14,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.1 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 2ada1062..3e57ef2d 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.1 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index e6de0744..ba3db49a 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.1 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index dac1b0b5..ed93d57c 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,7 +22,7 @@ version: "3.0" services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.1 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index d83cf032..94d9239b 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.1 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index edc5af24..4832eb92 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.1 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/installation.md b/docs/docs/installation.md index 497b3e0d..d329bd55 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.15.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.15.1`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.15.x/installation.md b/docs/versioned_docs/version-7.15.x/installation.md index 497b3e0d..d329bd55 100644 --- a/docs/versioned_docs/version-7.15.x/installation.md +++ b/docs/versioned_docs/version-7.15.x/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.15.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.15.1`) b. Using Go to install the latest release ```bash From 7bc4b5e5df39349bfe54e0721d161fbebb6b2ebb Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Mon, 23 Mar 2026 15:54:46 +0100 Subject: [PATCH 35/53] doc: fix changelog for v7.15.0 --- CHANGELOG.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a3b4018a..fc4c2379 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,14 +23,13 @@ ## Changes since v7.15.0 -# V7.15.0 - - [#3382](https://github.com/oauth2-proxy/oauth2-proxy/pull/3382) chore(deps): update gomod and golangci/golangci-lint to v2.11.4 (@tuunit) - [#3374](https://github.com/oauth2-proxy/oauth2-proxy/pull/3374) fix: handle Unix socket RemoteAddr in IP resolution (@H1net) - [#3381](https://github.com/oauth2-proxy/oauth2-proxy/pull/3381) fix: do not log error for backend logout 204 (@artificiosus) - [#3327](https://github.com/oauth2-proxy/oauth2-proxy/pull/3327) fix: improve logging when session refresh token is missing (@yosri-brh) - [#2767](https://github.com/oauth2-proxy/oauth2-proxy/pull/2767) fix: propagate errors during route building (@sybereal) +# V7.15.0 ## Release Highlights From da9123f740d570374df9bf36ea66d3b94f712284 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Mon, 23 Mar 2026 16:05:54 +0100 Subject: [PATCH 36/53] doc: fix config validation formatting (#3386) Signed-off-by: Jan Larwig --- docs/docs/configuration/overview.md | 74 +++++++++---------- .../version-7.15.x/configuration/overview.md | 74 +++++++++---------- 2 files changed, 74 insertions(+), 74 deletions(-) diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index 37f385c7..a73e3acd 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -72,43 +72,6 @@ An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/ | `--config-test` | test configuration and exit (for CI/CD validation) | | `--version` | print version string | -## Configuration Validation - -The `--config-test` flag validates your configuration file without starting the proxy server. This is useful for: -- **CI/CD pipelines**: Pre-deployment validation -- **Configuration management**: Testing before applying changes -- **Debugging**: Verifying syntax and required fields - -### Usage - -```bash -# Test legacy config -oauth2-proxy --config /etc/oauth2-proxy.cfg --config-test - -# Test alpha config -oauth2-proxy --config /etc/core.cfg --alpha-config /etc/alpha.yaml --config-test - -# CI/CD pre-deployment check -# Returns with exit code 1 if any validation errors occur -oauth2-proxy --config new-config.cfg --config-test -``` - -### Exit Codes - -- **0**: Configuration is valid ✅ -- **1**: Configuration is invalid (errors printed to stderr) ❌ - -### Validation Coverage - -The `--config-test` flag performs the **same comprehensive validation** as normal startup, including: -- Required fields (client ID, client secret, cookie secret, etc.) -- Syntax validation (TOML/YAML parsing) -- Provider configuration -- Upstream server definitions -- Session store connectivity (e.g., Redis network checks if configured) - -**Note**: Cannot be combined with `--convert-config-to-alpha`. - ### General Provider Options Provider specific options can be found on their respective subpages. @@ -305,6 +268,43 @@ Provider specific options can be found on their respective subpages. | flag: `--upstream-timeout`
toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s | | flag: `--upstream`
toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://` for static response. Routing is based on the path | | +## Configuration Validation + +The `--config-test` flag validates your configuration file without starting the proxy server. This is useful for: +- **CI/CD pipelines**: Pre-deployment validation +- **Configuration management**: Testing before applying changes +- **Debugging**: Verifying syntax and required fields + +### Usage + +```bash +# Test legacy config +oauth2-proxy --config /etc/oauth2-proxy.cfg --config-test + +# Test alpha config +oauth2-proxy --config /etc/core.cfg --alpha-config /etc/alpha.yaml --config-test + +# CI/CD pre-deployment check +# Returns with exit code 1 if any validation errors occur +oauth2-proxy --config new-config.cfg --config-test +``` + +### Exit Codes + +- **0**: Configuration is valid ✅ +- **1**: Configuration is invalid (errors printed to stderr) ❌ + +### Validation Coverage + +The `--config-test` flag performs the **same comprehensive validation** as normal startup, including: +- Required fields (client ID, client secret, cookie secret, etc.) +- Syntax validation (TOML/YAML parsing) +- Provider configuration +- Upstream server definitions +- Session store connectivity (e.g., Redis network checks if configured) + +**Note**: Cannot be combined with `--convert-config-to-alpha`. + ## Upstreams Configuration `oauth2-proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers, unix socket or serve static files from the file system. diff --git a/docs/versioned_docs/version-7.15.x/configuration/overview.md b/docs/versioned_docs/version-7.15.x/configuration/overview.md index 37f385c7..a73e3acd 100644 --- a/docs/versioned_docs/version-7.15.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.15.x/configuration/overview.md @@ -72,43 +72,6 @@ An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/ | `--config-test` | test configuration and exit (for CI/CD validation) | | `--version` | print version string | -## Configuration Validation - -The `--config-test` flag validates your configuration file without starting the proxy server. This is useful for: -- **CI/CD pipelines**: Pre-deployment validation -- **Configuration management**: Testing before applying changes -- **Debugging**: Verifying syntax and required fields - -### Usage - -```bash -# Test legacy config -oauth2-proxy --config /etc/oauth2-proxy.cfg --config-test - -# Test alpha config -oauth2-proxy --config /etc/core.cfg --alpha-config /etc/alpha.yaml --config-test - -# CI/CD pre-deployment check -# Returns with exit code 1 if any validation errors occur -oauth2-proxy --config new-config.cfg --config-test -``` - -### Exit Codes - -- **0**: Configuration is valid ✅ -- **1**: Configuration is invalid (errors printed to stderr) ❌ - -### Validation Coverage - -The `--config-test` flag performs the **same comprehensive validation** as normal startup, including: -- Required fields (client ID, client secret, cookie secret, etc.) -- Syntax validation (TOML/YAML parsing) -- Provider configuration -- Upstream server definitions -- Session store connectivity (e.g., Redis network checks if configured) - -**Note**: Cannot be combined with `--convert-config-to-alpha`. - ### General Provider Options Provider specific options can be found on their respective subpages. @@ -305,6 +268,43 @@ Provider specific options can be found on their respective subpages. | flag: `--upstream-timeout`
toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s | | flag: `--upstream`
toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://` for static response. Routing is based on the path | | +## Configuration Validation + +The `--config-test` flag validates your configuration file without starting the proxy server. This is useful for: +- **CI/CD pipelines**: Pre-deployment validation +- **Configuration management**: Testing before applying changes +- **Debugging**: Verifying syntax and required fields + +### Usage + +```bash +# Test legacy config +oauth2-proxy --config /etc/oauth2-proxy.cfg --config-test + +# Test alpha config +oauth2-proxy --config /etc/core.cfg --alpha-config /etc/alpha.yaml --config-test + +# CI/CD pre-deployment check +# Returns with exit code 1 if any validation errors occur +oauth2-proxy --config new-config.cfg --config-test +``` + +### Exit Codes + +- **0**: Configuration is valid ✅ +- **1**: Configuration is invalid (errors printed to stderr) ❌ + +### Validation Coverage + +The `--config-test` flag performs the **same comprehensive validation** as normal startup, including: +- Required fields (client ID, client secret, cookie secret, etc.) +- Syntax validation (TOML/YAML parsing) +- Provider configuration +- Upstream server definitions +- Session store connectivity (e.g., Redis network checks if configured) + +**Note**: Cannot be combined with `--convert-config-to-alpha`. + ## Upstreams Configuration `oauth2-proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers, unix socket or serve static files from the file system. From 761bf3b42b6aba963baec3647c4943c358a687c3 Mon Sep 17 00:00:00 2001 From: Justus <91261422+Juqsi@users.noreply.github.com> Date: Wed, 8 Apr 2026 21:25:17 +0200 Subject: [PATCH 37/53] build(deps): bump github.com/go-jose/go-jose/v4 to 4.1.4 (#3400) Signed-off-by: Juqsi <91261422+Juqsi@users.noreply.github.com> --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index a379e58d..d45e4b6d 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,7 @@ require ( github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf github.com/fsnotify/fsnotify v1.9.0 github.com/go-jose/go-jose/v3 v3.0.4 - github.com/go-jose/go-jose/v4 v4.1.3 + github.com/go-jose/go-jose/v4 v4.1.4 github.com/go-viper/mapstructure/v2 v2.4.0 github.com/golang-jwt/jwt/v5 v5.3.1 github.com/google/go-cmp v0.7.0 diff --git a/go.sum b/go.sum index 48ddf1f2..ea2aab21 100644 --- a/go.sum +++ b/go.sum @@ -54,8 +54,8 @@ github.com/gkampitakis/go-snaps v0.5.15 h1:amyJrvM1D33cPHwVrjo9jQxX8g/7E2wYdZ+01 github.com/gkampitakis/go-snaps v0.5.15/go.mod h1:HNpx/9GoKisdhw9AFOBT1N7DBs9DiHo/hGheFGBZ+mc= github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY= github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= -github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs= -github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= +github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= From 26de082a787225aabd4b18f56e1eeea9f676ae85 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sun, 12 Apr 2026 14:21:47 +0200 Subject: [PATCH 38/53] chore(deps): update gomod dependencies (#3411) - github.com/coreos/go-oidc/v3 v3.17.0 + github.com/coreos/go-oidc/v3 v3.18.0 - github.com/go-jose/go-jose/v3 v3.0.4 + github.com/go-jose/go-jose/v3 v3.0.5 - github.com/go-viper/mapstructure/v2 v2.4.0 + github.com/go-viper/mapstructure/v2 v2.5.0 - golang.org/x/crypto v0.49.0 + golang.org/x/crypto v0.50.0 - golang.org/x/net v0.52.0 + golang.org/x/net v0.53.0 - google.golang.org/api v0.272.0 + google.golang.org/api v0.275.0 --------- Signed-off-by: Jan Larwig --- CHANGELOG.md | 2 ++ go.mod | 40 +++++++++++++++--------------- go.sum | 46 +++++++++++++++++++++++++++++++++++ main_test.go | 4 +-- pkg/apis/options/load_test.go | 2 +- 5 files changed, 71 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fc4c2379..beb1452b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ # V7.15.1 +- [#3411](https://github.com/oauth2-proxy/oauth2-proxy/pull/3411) chore(deps): update gomod dependencies (@tuunit) + ## Release Highlights - 🐛 Squashed some bugs diff --git a/go.mod b/go.mod index d45e4b6d..ade9c4e8 100644 --- a/go.mod +++ b/go.mod @@ -9,12 +9,12 @@ require ( github.com/alicebob/miniredis/v2 v2.37.0 github.com/bitly/go-simplejson v0.5.1 github.com/bsm/redislock v0.9.4 - github.com/coreos/go-oidc/v3 v3.17.0 + github.com/coreos/go-oidc/v3 v3.18.0 github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf github.com/fsnotify/fsnotify v1.9.0 - github.com/go-jose/go-jose/v3 v3.0.4 + github.com/go-jose/go-jose/v3 v3.0.5 github.com/go-jose/go-jose/v4 v4.1.4 - github.com/go-viper/mapstructure/v2 v2.4.0 + github.com/go-viper/mapstructure/v2 v2.5.0 github.com/golang-jwt/jwt/v5 v5.3.1 github.com/google/go-cmp v0.7.0 github.com/google/uuid v1.6.0 @@ -32,17 +32,17 @@ require ( github.com/stretchr/testify v1.11.1 github.com/vmihailenco/msgpack/v5 v5.4.1 go.yaml.in/yaml/v3 v3.0.4 - golang.org/x/crypto v0.49.0 - golang.org/x/net v0.52.0 + golang.org/x/crypto v0.50.0 + golang.org/x/net v0.53.0 golang.org/x/oauth2 v0.36.0 golang.org/x/sync v0.20.0 - google.golang.org/api v0.272.0 + google.golang.org/api v0.275.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 k8s.io/apimachinery v0.35.3 ) require ( - cloud.google.com/go/auth v0.18.2 // indirect + cloud.google.com/go/auth v0.20.0 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect github.com/Masterminds/semver/v3 v3.4.0 // indirect github.com/beorn7/perks v1.0.1 // indirect @@ -53,13 +53,13 @@ require ( github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-task/slim-sprig/v3 v3.0.0 // indirect - github.com/google/pprof v0.0.0-20260302011040-a15ffb7f9dcc // indirect + github.com/google/pprof v0.0.0-20260402051712-545e8a4df936 // indirect github.com/google/s2a-go v0.1.9 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.14 // indirect - github.com/googleapis/gax-go/v2 v2.19.0 // indirect + github.com/googleapis/gax-go/v2 v2.21.0 // indirect github.com/kylelemons/godebug v1.1.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/pelletier/go-toml/v2 v2.3.0 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/common v0.67.5 // indirect @@ -70,18 +70,18 @@ require ( github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/yuin/gopher-lua v1.1.1 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect - go.opentelemetry.io/otel v1.42.0 // indirect - go.opentelemetry.io/otel/metric v1.42.0 // indirect - go.opentelemetry.io/otel/trace v1.42.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 // indirect + go.opentelemetry.io/otel v1.43.0 // indirect + go.opentelemetry.io/otel/metric v1.43.0 // indirect + go.opentelemetry.io/otel/trace v1.43.0 // indirect go.uber.org/atomic v1.11.0 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect - golang.org/x/mod v0.34.0 // indirect - golang.org/x/sys v0.42.0 // indirect - golang.org/x/text v0.35.0 // indirect - golang.org/x/tools v0.43.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260319201613-d00831a3d3e7 // indirect - google.golang.org/grpc v1.79.3 // indirect + golang.org/x/mod v0.35.0 // indirect + golang.org/x/sys v0.43.0 // indirect + golang.org/x/text v0.36.0 // indirect + golang.org/x/tools v0.44.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d // indirect + google.golang.org/grpc v1.80.0 // indirect google.golang.org/protobuf v1.36.11 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index ea2aab21..622f2dac 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,7 @@ cloud.google.com/go/auth v0.18.2 h1:+Nbt5Ev0xEqxlNjd6c+yYUeosQ5TtEUaNcN/3FozlaM= cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M= +cloud.google.com/go/auth v0.20.0 h1:kXTssoVb4azsVDoUiF8KvxAqrsQcQtB53DcSgta74CA= +cloud.google.com/go/auth v0.20.0/go.mod h1:942/yi/itH1SsmpyrbnTMDgGfdy2BUqIKyd0cyYLc5Q= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= @@ -33,6 +35,8 @@ github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5P github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/coreos/go-oidc/v3 v3.17.0 h1:hWBGaQfbi0iVviX4ibC7bk8OKT5qNr4klBaCHVNvehc= github.com/coreos/go-oidc/v3 v3.17.0/go.mod h1:wqPbKFrVnE90vty060SB40FCJ8fTHTxSwyXJqZH+sI8= +github.com/coreos/go-oidc/v3 v3.18.0 h1:V9orjXynvu5wiC9SemFTWnG4F45v403aIcjWo0d41+A= +github.com/coreos/go-oidc/v3 v3.18.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf h1:iW4rZ826su+pqaw19uhpSCzhj44qo35pNgKFGqzDKkU= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -54,6 +58,8 @@ github.com/gkampitakis/go-snaps v0.5.15 h1:amyJrvM1D33cPHwVrjo9jQxX8g/7E2wYdZ+01 github.com/gkampitakis/go-snaps v0.5.15/go.mod h1:HNpx/9GoKisdhw9AFOBT1N7DBs9DiHo/hGheFGBZ+mc= github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY= github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= +github.com/go-jose/go-jose/v3 v3.0.5 h1:BLLJWbC4nMZOfuPVxoZIxeYsn6Nl2r1fITaJ78UQlVQ= +github.com/go-jose/go-jose/v3 v3.0.5/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -65,6 +71,8 @@ github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1v github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= +github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= @@ -78,6 +86,8 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/pprof v0.0.0-20260302011040-a15ffb7f9dcc h1:VBbFa1lDYWEeV5FZKUiYKYT0VxCp9twUmmaq9eb8sXw= github.com/google/pprof v0.0.0-20260302011040-a15ffb7f9dcc/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= +github.com/google/pprof v0.0.0-20260402051712-545e8a4df936 h1:EwtI+Al+DeppwYX2oXJCETMO23COyaKGP6fHVpkpWpg= +github.com/google/pprof v0.0.0-20260402051712-545e8a4df936/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -87,6 +97,8 @@ github.com/googleapis/enterprise-certificate-proxy v0.3.14 h1:yh8ncqsbUY4shRD5dA github.com/googleapis/enterprise-certificate-proxy v0.3.14/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg= github.com/googleapis/gax-go/v2 v2.19.0 h1:fYQaUOiGwll0cGj7jmHT/0nPlcrZDFPrZRhTsoCr8hE= github.com/googleapis/gax-go/v2 v2.19.0/go.mod h1:w2ROXVdfGEVFXzmlciUU4EdjHgWvB5h2n6x/8XSTTJA= +github.com/googleapis/gax-go/v2 v2.21.0 h1:h45NjjzEO3faG9Lg/cFrBh2PgegVVgzqKzuZl/wMbiI= +github.com/googleapis/gax-go/v2 v2.21.0/go.mod h1:But/NJU6TnZsrLai/xBAQLLz+Hc7fHZJt/hsCz3Fih4= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE= @@ -119,6 +131,8 @@ github.com/onsi/gomega v1.39.1 h1:1IJLAad4zjPn2PsnhH70V4DKRFlrCzGBNrNaru+Vf28= github.com/onsi/gomega v1.39.1/go.mod h1:hL6yVALoTOxeWudERyfppUcZXjMwIMLnuSfruD2lcfg= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pelletier/go-toml/v2 v2.3.0 h1:k59bC/lIZREW0/iVaQR8nDHxVq8OVlIzYCOJf421CaM= +github.com/pelletier/go-toml/v2 v2.3.0/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY= github.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -175,18 +189,29 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 h1:CqXxU8VOmDefoh0+ztfGaymYbhdB/tT3zs79QaZTNGY= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0/go.mod h1:BuhAPThV8PBHBvg8ZzZ/Ok3idOdhWIodywz2xEcRbJo= go.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho= go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc= +go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I= +go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0= go.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4= go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI= +go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM= +go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY= go.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo= go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts= +go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg= go.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA= go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc= +go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw= go.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY= go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc= +go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A= +go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= @@ -200,10 +225,14 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4= golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA= +golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI= +golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.34.0 h1:xIHgNUUnW6sYkcM5Jleh05DvLOtwc6RitGHbDk4akRI= golang.org/x/mod v0.34.0/go.mod h1:ykgH52iCZe79kzLLMhyCUzhMci+nQj+0XkbXpNYtVjY= +golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM= +golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= @@ -211,6 +240,8 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0= golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= +golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA= +golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -229,6 +260,8 @@ golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI= +golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -242,6 +275,8 @@ golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= +golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg= +golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -250,19 +285,30 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s= golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0= +golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c= +golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= google.golang.org/api v0.272.0 h1:eLUQZGnAS3OHn31URRf9sAmRk3w2JjMx37d2k8AjJmA= google.golang.org/api v0.272.0/go.mod h1:wKjowi5LNJc5qarNvDCvNQBn3rVK8nSy6jg2SwRwzIA= +google.golang.org/api v0.275.0 h1:vfY5d9vFVJeWEZT65QDd9hbndr7FyZ2+6mIzGAh71NI= +google.golang.org/api v0.275.0/go.mod h1:Fnag/EWUPIcJXuIkP1pjoTgS5vdxlk3eeemL7Do6bvw= google.golang.org/genproto v0.0.0-20260316180232-0b37fe3546d5 h1:JNfk58HZ8lfmXbYK2vx/UvsqIL59TzByCxPIX4TDmsE= google.golang.org/genproto v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:x5julN69+ED4PcFk/XWayw35O0lf/nGa4aNgODCmNmw= +google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0= google.golang.org/genproto/googleapis/api v0.0.0-20260316180232-0b37fe3546d5 h1:CogIeEXn4qWYzzQU0QqvYBM8yDF9cFYzDq9ojSpv0Js= google.golang.org/genproto/googleapis/api v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:EIQZ5bFCfRQDV4MhRle7+OgjNtZ6P1PiZBgAKuxXu/Y= +google.golang.org/genproto/googleapis/api v0.0.0-20260319201613-d00831a3d3e7 h1:41r6JMbpzBMen0R/4TZeeAmGXSJC7DftGINUodzTkPI= google.golang.org/genproto/googleapis/rpc v0.0.0-20260319201613-d00831a3d3e7 h1:ndE4FoJqsIceKP2oYSnUZqhTdYufCYYkqwtFzfrhI7w= google.golang.org/genproto/googleapis/rpc v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d h1:wT2n40TBqFY6wiwazVK9/iTWbsQrgk5ZfCSVFLO9LQA= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE= google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= +google.golang.org/grpc v1.80.0 h1:Xr6m2WmWZLETvUNvIUmeD5OAagMw3FiKmMlTdViWsHM= +google.golang.org/grpc v1.80.0/go.mod h1:ho/dLnxwi3EDJA4Zghp7k2Ec1+c2jqup0bFkw07bwF4= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/main_test.go b/main_test.go index c7c7057d..58b8ae7e 100644 --- a/main_test.go +++ b/main_test.go @@ -278,7 +278,7 @@ redirect_url="http://localhost:4180/oauth2/callback" Entry("with bad legacy configuration", loadConfigurationTableInput{ configContent: testCoreConfig + "unknown_field=\"something\"", expectedOptions: func() *options.Options { return nil }, - expectedErr: errors.New("failed to load legacy options: failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"), + expectedErr: errors.New("failed to load legacy options: failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'options.LegacyOptions' has invalid keys: unknown_field"), }), Entry("with bad alpha configuration", loadConfigurationTableInput{ configContent: testCoreConfig, @@ -290,7 +290,7 @@ redirect_url="http://localhost:4180/oauth2/callback" configContent: testCoreConfig + "unknown_field=\"something\"", alphaConfigContent: testAlphaConfig, expectedOptions: func() *options.Options { return nil }, - expectedErr: errors.New("failed to load legacy options: failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"), + expectedErr: errors.New("failed to load legacy options: failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'options.LegacyOptions' has invalid keys: unknown_field"), }), ) diff --git a/pkg/apis/options/load_test.go b/pkg/apis/options/load_test.go index 42083f76..40f9a725 100644 --- a/pkg/apis/options/load_test.go +++ b/pkg/apis/options/load_test.go @@ -329,7 +329,7 @@ var _ = Describe("Load", func() { Entry("with an unknown option in the config file", &testOptionsTableInput{ configFile: []byte(`unknown_option="foo"`), flagSet: func() *pflag.FlagSet { return testOptionsFlagSet }, - expectedErr: fmt.Errorf("error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_option"), + expectedErr: fmt.Errorf("error unmarshalling config: decoding failed due to the following error(s):\n\n'options.TestOptions' has invalid keys: unknown_option"), // Viper will unmarshal before returning the error, so this is the default output expectedOutput: &TestOptions{ StringOption: "default", From 2e1261c4bec8f092a42df3ac57ae54ea2acf0142 Mon Sep 17 00:00:00 2001 From: Francesco Pasqualini Date: Sun, 12 Apr 2026 14:48:55 +0200 Subject: [PATCH 39/53] fix: invalidate session on fatal OAuth2 refresh errors (#3333) * fix: invalidate session on fatal OAuth2 refresh errors When a token refresh fails with a fatal OAuth2 error (invalid_grant, invalid_client), the session is now cleared from the session store and the cookie is removed, forcing re-authentication. Previously, fatal refresh errors were logged but the stale session continued to be served, leaving users logged in indefinitely after their session was revoked at the provider level. Transient errors (network timeouts, server errors) continue to preserve the existing session as before. Fixes #1945 Signed-off-by: Francesco Pasqualini * fix: apply review nits and add CHANGELOG entry Signed-off-by: Francesco Pasqualini Signed-off-by: Jan Larwig --------- Signed-off-by: Francesco Pasqualini Signed-off-by: Jan Larwig --- CHANGELOG.md | 5 +-- pkg/middleware/stored_session.go | 47 ++++++++++++++++++++++-- pkg/middleware/stored_session_test.go | 51 +++++++++++++++++++++++++++ 3 files changed, 99 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index beb1452b..e8f2d777 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,9 +8,10 @@ ## Changes since v7.15.1 -# V7.15.1 - - [#3411](https://github.com/oauth2-proxy/oauth2-proxy/pull/3411) chore(deps): update gomod dependencies (@tuunit) +- [#3333](https://github.com/oauth2-proxy/oauth2-proxy/pull/3333) fix: invalidate session on fatal OAuth2 refresh errors (@frhack) + +# V7.15.1 ## Release Highlights diff --git a/pkg/middleware/stored_session.go b/pkg/middleware/stored_session.go index 72c364e7..53238f19 100644 --- a/pkg/middleware/stored_session.go +++ b/pkg/middleware/stored_session.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "net/http" + "strings" "time" "github.com/justinas/alice" @@ -31,6 +32,33 @@ const ( sessionRefreshRetryPeriod = 10 * time.Millisecond ) +// isFatalRefreshError checks if a refresh error indicates a revoked or +// non-existent session that should be immediately invalidated. +// Fatal errors indicate the session is no longer valid at the provider level. +// Non-fatal errors (network issues, timeouts) should not invalidate the session. +// +// Only checks standard OAuth2 error codes (RFC 6749 Section 5.2). +// Does NOT check error_description strings as they are optional and provider-specific. +func isFatalRefreshError(err error) bool { + if err == nil { + return false + } + + // Only check standard OAuth2 error codes (RFC 6749 Section 5.2) + // Do NOT check error_description strings as they are optional and provider-specific + fatalErrors := []string{ + "invalid_grant", // refresh token revoked, expired, or session terminated + "invalid_client", // client credentials no longer valid + } + + for _, fe := range fatalErrors { + if strings.Contains(err.Error(), fe) { + return true + } + } + return false +} + // StoredSessionLoaderOptions contains all of the requirements to construct // a stored session loader. // All options must be provided. @@ -188,9 +216,24 @@ func (s *storedSessionLoader) refreshSessionIfNeeded(rw http.ResponseWriter, req // We are holding the lock and the session needs a refresh logger.Printf("Refreshing session - User: %s; SessionAge: %s", session.User, session.Age()) if err := s.refreshSession(rw, req, session); err != nil { - // If a preemptive refresh fails, we still keep the session - // if validateSession succeeds. logger.Errorf("Unable to refresh session: %v", err) + + // Check if this is a fatal error that indicates the session is revoked + // or no longer valid at the provider level + if isFatalRefreshError(err) { + logger.Printf("Fatal refresh error detected (session revoked or invalid), clearing session for user: %s", session.User) + + // Clear the session from storage (Redis) and remove the cookie + if err := s.store.Clear(rw, req); err != nil { + logger.Errorf("failed clearing session: %v", err) + } + + // Return error immediately to force re-authentication + return fmt.Errorf("session invalidated due to fatal refresh error: %w", err) + } + + // For non-fatal errors (network issues, timeouts), keep the session + // and let validateSession determine if it's still usable } // Validate all sessions after any Redeem/Refresh operation (fail or success) diff --git a/pkg/middleware/stored_session_test.go b/pkg/middleware/stored_session_test.go index d8e78f2f..c913a4ef 100644 --- a/pkg/middleware/stored_session_test.go +++ b/pkg/middleware/stored_session_test.go @@ -7,6 +7,7 @@ import ( "net/http" "net/http/httptest" "sync" + "testing" "time" middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" @@ -801,3 +802,53 @@ func (f *fakeSessionStore) Clear(rw http.ResponseWriter, req *http.Request) erro func (f *fakeSessionStore) VerifyConnection(_ context.Context) error { return nil } + +// TestIsFatalRefreshError tests the isFatalRefreshError function to ensure +// it correctly identifies fatal OAuth2 errors that should invalidate a session. +func TestIsFatalRefreshError(t *testing.T) { + tests := []struct { + name string + err error + expected bool + }{ + { + name: "nil error", + err: nil, + expected: false, + }, + { + name: "invalid_grant error", + err: fmt.Errorf("failed to get token: oauth2: \"invalid_grant\" \"Session not active\""), + expected: true, + }, + { + name: "invalid_client error", + err: fmt.Errorf("invalid_client: client not found"), + expected: true, + }, + { + name: "network timeout - not fatal", + err: fmt.Errorf("Post \"https://keycloak/token\": dial tcp: connect: connection refused"), + expected: false, + }, + { + name: "server error - not fatal", + err: fmt.Errorf("unexpected status code 500"), + expected: false, + }, + { + name: "generic refresh error - not fatal", + err: fmt.Errorf("error refreshing tokens: context deadline exceeded"), + expected: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := isFatalRefreshError(tt.err) + if result != tt.expected { + t.Errorf("isFatalRefreshError(%v) = %v, want %v", tt.err, result, tt.expected) + } + }) + } +} From 0337a95fc6bb4c2798e555b28ae61500b30a6b9b Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Mon, 13 Apr 2026 18:17:50 +0200 Subject: [PATCH 40/53] Merge commit from fork * fix: clear session cookie at beginning of signinpage handler Co-authored-by: Christopher Schrewing Signed-off-by: Michael Bella Signed-off-by: Jan Larwig * test: clear session cookie at beginning of signinpage handler Signed-off-by: Jan Larwig * doc: changelog entry for GHSA-f24x-5g9q-753f Signed-off-by: Jan Larwig --------- Signed-off-by: Michael Bella Signed-off-by: Jan Larwig Co-authored-by: Christopher Schrewing --- CHANGELOG.md | 1 + oauthproxy.go | 8 ++++---- oauthproxy_test.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e8f2d777..2dccaaf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - [#3411](https://github.com/oauth2-proxy/oauth2-proxy/pull/3411) chore(deps): update gomod dependencies (@tuunit) - [#3333](https://github.com/oauth2-proxy/oauth2-proxy/pull/3333) fix: invalidate session on fatal OAuth2 refresh errors (@frhack) +- [GHSA-f24x-5g9q-753f](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-f24x-5g9q-753f) fix: clear session cookie at beginning of signinpage handler (@fnoehWM / @bella-WI / @tuunit) # V7.15.1 diff --git a/oauthproxy.go b/oauthproxy.go index 3efe66fd..0685bbbb 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -634,6 +634,10 @@ func (p *OAuthProxy) isTrustedIP(req *http.Request) bool { // SignInPage writes the sign in template to the response func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code int) { prepareNoCache(rw) + + if err := p.ClearSessionCookie(rw, req); err != nil { + logger.Printf("Error clearing session cookie: %v", err) + } rw.WriteHeader(code) redirectURL, err := p.appDirector.GetRedirect(req) @@ -647,10 +651,6 @@ func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code redirectURL = "/" } - if err := p.ClearSessionCookie(rw, req); err != nil { - logger.Printf("Error clearing session cookie: %v", err) - } - p.pageWriter.WriteSignInPage(rw, req, redirectURL, code) } diff --git a/oauthproxy_test.go b/oauthproxy_test.go index e06f50e9..46e39a90 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -713,6 +713,50 @@ func TestManualSignInCorrectCredentials(t *testing.T) { assert.Equal(t, http.StatusFound, statusCode) } +func TestSignInPageClearsExistingSessionCookie(t *testing.T) { + opts := baseTestOptions() + err := validation.Validate(opts) + require.NoError(t, err) + + proxy, err := NewOAuthProxy(opts, func(string) bool { + return true + }) + require.NoError(t, err) + + // Create a real session cookie using the actual session store. + saveRW := httptest.NewRecorder() + saveReq := httptest.NewRequest(http.MethodGet, "/", nil) + err = proxy.sessionStore.Save(saveRW, saveReq, &sessions.SessionState{ + Email: "john.doe@example.com", + }) + require.NoError(t, err) + + cookies := saveRW.Result().Cookies() + require.NotEmpty(t, cookies) + + // Send that cookie to the sign-in page. + req := httptest.NewRequest(http.MethodGet, "/oauth2/sign_in", nil) + for _, c := range cookies { + req.AddCookie(c) + } + + rw := httptest.NewRecorder() + proxy.ServeHTTP(rw, req) + + assert.Equal(t, http.StatusOK, rw.Code) + + cleared := false + for _, c := range rw.Result().Cookies() { + if c.Name == proxy.CookieOptions.Name { + cleared = true + assert.Equal(t, "", c.Value) + assert.Less(t, c.MaxAge, 0) + } + } + + assert.True(t, cleared, "expected sign-in page to clear existing session cookie") +} + func TestSignInPageIncludesTargetRedirect(t *testing.T) { sipTest, err := NewSignInPageTest(false) if err != nil { From 43596a7bab2053e091ddc513c865e20b4e4b08ea Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Mon, 13 Apr 2026 18:20:36 +0200 Subject: [PATCH 41/53] Merge commit from fork Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + pkg/middleware/healthcheck.go | 11 +++++--- pkg/middleware/healthcheck_test.go | 40 +++++++++++++++++++++++------- 3 files changed, 39 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2dccaaf1..3e1dc347 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - [#3411](https://github.com/oauth2-proxy/oauth2-proxy/pull/3411) chore(deps): update gomod dependencies (@tuunit) - [#3333](https://github.com/oauth2-proxy/oauth2-proxy/pull/3333) fix: invalidate session on fatal OAuth2 refresh errors (@frhack) - [GHSA-f24x-5g9q-753f](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-f24x-5g9q-753f) fix: clear session cookie at beginning of signinpage handler (@fnoehWM / @bella-WI / @tuunit) +- [GHSA-5hvv-m4w4-gf6v](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-5hvv-m4w4-gf6v) fix: health check user-agent authentication bypass (@tuunit) # V7.15.1 diff --git a/pkg/middleware/healthcheck.go b/pkg/middleware/healthcheck.go index 2dcfc1d4..de3b63d2 100644 --- a/pkg/middleware/healthcheck.go +++ b/pkg/middleware/healthcheck.go @@ -43,10 +43,13 @@ func healthCheck(paths, userAgents []string, next http.Handler) http.Handler { func isHealthCheckRequest(paths, userAgents map[string]struct{}, req *http.Request) bool { if _, ok := paths[req.URL.EscapedPath()]; ok { - return true - } - if _, ok := userAgents[req.Header.Get("User-Agent")]; ok { - return true + if len(userAgents) == 0 { + return true + } + + if _, ok := userAgents[req.Header.Get("User-Agent")]; ok { + return true + } } return false } diff --git a/pkg/middleware/healthcheck_test.go b/pkg/middleware/healthcheck_test.go index 78e1e6d4..68a8d3ec 100644 --- a/pkg/middleware/healthcheck_test.go +++ b/pkg/middleware/healthcheck_test.go @@ -45,6 +45,16 @@ var _ = Describe("HealthCheck suite", func() { healthCheckPaths: []string{"/ping"}, healthCheckUserAgents: []string{"hc/1.0"}, requestString: "http://example.com/ping", + headers: map[string]string{ + "User-Agent": "hc/1.0", + }, + expectedStatus: 200, + expectedBody: "OK", + }), + Entry("when requesting the healthcheck path with no health check user agents configured", &requestTableInput{ + healthCheckPaths: []string{"/ping"}, + healthCheckUserAgents: []string{}, + requestString: "http://example.com/ping", headers: map[string]string{}, expectedStatus: 200, expectedBody: "OK", @@ -85,15 +95,25 @@ var _ = Describe("HealthCheck suite", func() { expectedStatus: 404, expectedBody: "404 page not found\n", }), - Entry("with a request from the health check user agent", &requestTableInput{ + Entry("with a request from the health check user agent on a non-healthcheck path", &requestTableInput{ healthCheckPaths: []string{"/ping"}, healthCheckUserAgents: []string{"hc/1.0"}, requestString: "http://example.com/abc", headers: map[string]string{ "User-Agent": "hc/1.0", }, - expectedStatus: 200, - expectedBody: "OK", + expectedStatus: 404, + expectedBody: "404 page not found\n", + }), + Entry("when an auth_request endpoint receives the configured health check user agent", &requestTableInput{ + healthCheckPaths: []string{"/ping"}, + healthCheckUserAgents: []string{"GoogleHC/1.0"}, + requestString: "http://example.com/oauth2/auth", + headers: map[string]string{ + "User-Agent": "GoogleHC/1.0", + }, + expectedStatus: 404, + expectedBody: "404 page not found\n", }), Entry("when a blank string is configured as a health check agent and a request has no user agent", &requestTableInput{ healthCheckPaths: []string{"/ping"}, @@ -107,9 +127,11 @@ var _ = Describe("HealthCheck suite", func() { healthCheckPaths: []string{"/ping", "/liveness_check", "/readiness_check"}, healthCheckUserAgents: []string{"hc/1.0"}, requestString: "http://example.com/readiness_check", - headers: map[string]string{}, - expectedStatus: 200, - expectedBody: "OK", + headers: map[string]string{ + "User-Agent": "hc/1.0", + }, + expectedStatus: 200, + expectedBody: "OK", }), Entry("with multiple paths, request none of the healthcheck paths", &requestTableInput{ healthCheckPaths: []string{"/ping", "/liveness_check", "/readiness_check"}, @@ -121,15 +143,15 @@ var _ = Describe("HealthCheck suite", func() { expectedStatus: 404, expectedBody: "404 page not found\n", }), - Entry("with multiple user agents, request from a health check user agent", &requestTableInput{ + Entry("with multiple user agents, request from a health check user agent on a non-healthcheck path", &requestTableInput{ healthCheckPaths: []string{"/ping"}, healthCheckUserAgents: []string{"hc/1.0", "GoogleHC/1.0"}, requestString: "http://example.com/abc", headers: map[string]string{ "User-Agent": "GoogleHC/1.0", }, - expectedStatus: 200, - expectedBody: "OK", + expectedStatus: 404, + expectedBody: "404 page not found\n", }), Entry("with multiple user agents, request from none of the health check user agents", &requestTableInput{ healthCheckPaths: []string{"/ping"}, From aff369dfa31ca6b8166b4e14613e8fb2d7dac88a Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Mon, 13 Apr 2026 18:22:56 +0200 Subject: [PATCH 42/53] Merge commit from fork Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + .../docker-compose-nginx.yaml | 5 +- contrib/local-environment/nginx.conf | 54 +------- .../local-environment/oauth2-proxy-nginx.cfg | 17 ++- docs/docs/configuration/overview.md | 5 + .../version-7.15.x/configuration/overview.md | 5 + oauthproxy.go | 33 +++-- oauthproxy_test.go | 38 ++++++ pkg/apis/middleware/scope.go | 49 +++++++- pkg/apis/middleware/scope_test.go | 34 +++++ pkg/apis/options/options.go | 2 + pkg/app/redirect/director_test.go | 35 +++++- pkg/cookies/cookies_test.go | 8 +- pkg/ip/parse_ip_net.go | 16 +++ pkg/ip/parse_ip_net_test.go | 118 ++++++++++++++++++ pkg/middleware/redirect_to_https_test.go | 15 +++ pkg/middleware/scope.go | 8 +- pkg/middleware/scope_test.go | 22 +++- pkg/requests/util/util.go | 27 ++-- pkg/requests/util/util_test.go | 64 ++++++++-- pkg/upstream/http_test.go | 4 +- pkg/validation/allowlist.go | 12 ++ pkg/validation/allowlist_test.go | 30 +++++ 23 files changed, 498 insertions(+), 104 deletions(-) create mode 100644 pkg/ip/parse_ip_net_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e1dc347..8be9736e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - [#3333](https://github.com/oauth2-proxy/oauth2-proxy/pull/3333) fix: invalidate session on fatal OAuth2 refresh errors (@frhack) - [GHSA-f24x-5g9q-753f](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-f24x-5g9q-753f) fix: clear session cookie at beginning of signinpage handler (@fnoehWM / @bella-WI / @tuunit) - [GHSA-5hvv-m4w4-gf6v](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-5hvv-m4w4-gf6v) fix: health check user-agent authentication bypass (@tuunit) +- [GHSA-7x63-xv5r-3p2x](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-7x63-xv5r-3p2x) fix: authentication bypass via X-Forwarded-Uri header spoofing (@tuunit) # V7.15.1 diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index ed93d57c..23138eb4 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -23,7 +23,8 @@ version: "3.0" services: oauth2-proxy: image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.1 - ports: [] + ports: + - 4180:4180/tcp hostname: oauth2-proxy container_name: oauth2-proxy command: --config /oauth2-proxy.cfg @@ -44,7 +45,7 @@ services: image: nginx:1.29 restart: unless-stopped ports: - - 80:80/tcp + - 8080:8080/tcp hostname: nginx volumes: - "./nginx.conf:/etc/nginx/conf.d/default.conf" diff --git a/contrib/local-environment/nginx.conf b/contrib/local-environment/nginx.conf index 15005bf6..f3761387 100644 --- a/contrib/local-environment/nginx.conf +++ b/contrib/local-environment/nginx.conf @@ -1,11 +1,12 @@ # Reverse proxy to oauth2-proxy server { - listen 80; - server_name oauth2-proxy.oauth2-proxy.localhost; + listen 8080; + server_name oauth2-proxy.localtest.me; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; proxy_pass http://oauth2-proxy:4180/; } @@ -13,8 +14,8 @@ server { # Reverse proxy to httpbin server { - listen 80; - server_name httpbin.oauth2-proxy.localhost; + listen 8080; + server_name httpbin.localtest.me; auth_request /internal-auth/oauth2/auth; @@ -29,50 +30,7 @@ server { # Named location for OAuth2 sign-in redirect # Returns a proper 302 that works with --skip-provider-button location @oauth2_signin { - return 302 http://oauth2-proxy.oauth2-proxy.localhost/oauth2/sign_in?rd=$scheme://$host$request_uri; - } - - # auth_request must be a URI so this allows an internal path to then proxy to - # the real auth_request path. - # The trailing /'s are required so that nginx strips the prefix before proxying. - location /internal-auth/ { - internal; # Ensure external users can't access this path - - # Make sure the OAuth2 Proxy knows where the original request came from. - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-Uri $request_uri; - - proxy_pass http://oauth2-proxy:4180/; - } -} - -# Statically serve the nginx welcome -server { - listen 80; - server_name oauth2-proxy.localhost; - - location / { - auth_request /internal-auth/oauth2/auth; - - # On 401, redirect to the sign_in page via a named location - # This ensures a proper 302 redirect that browsers will follow - error_page 401 = @oauth2_signin; - - root /usr/share/nginx/html; - index index.html index.htm; - } - - # Named location for OAuth2 sign-in redirect - # Returns a proper 302 that works with --skip-provider-button - location @oauth2_signin { - return 302 http://oauth2-proxy.oauth2-proxy.localhost/oauth2/sign_in?rd=$scheme://$host$request_uri; - } - - # redirect server error pages to the static page /50x.html - error_page 500 502 503 504 /50x.html; - location = /50x.html { - root /usr/share/nginx/html; + return 302 http://oauth2-proxy.localtest.me:8080/oauth2/sign_in?rd=$scheme://$host$request_uri; } # auth_request must be a URI so this allows an internal path to then proxy to diff --git a/contrib/local-environment/oauth2-proxy-nginx.cfg b/contrib/local-environment/oauth2-proxy-nginx.cfg index 01b64a55..0a383ab7 100644 --- a/contrib/local-environment/oauth2-proxy-nginx.cfg +++ b/contrib/local-environment/oauth2-proxy-nginx.cfg @@ -1,14 +1,19 @@ http_address="0.0.0.0:4180" cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w=" -provider="oidc" email_domains="example.com" -oidc_issuer_url="http://dex.localtest.me:5556/dex" +cookie_secure="false" +upstreams="static://200" +cookie_domains=[".localtest.me"] # Required so cookie can be read on all subdomains. +whitelist_domains=[".localtest.me"] # Required to allow redirection back to original requested target. + +# dex provider client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK" client_id="oauth2-proxy" -cookie_secure="false" +redirect_url="http://oauth2-proxy.localtest.me:4180/oauth2/callback" + +oidc_issuer_url="http://dex.localtest.me:5556/dex" +provider="oidc" +provider_display_name="Dex" -redirect_url="http://oauth2-proxy.oauth2-proxy.localhost/oauth2/callback" -cookie_domains=".oauth2-proxy.localhost" # Required so cookie can be read on all subdomains. -whitelist_domains=".oauth2-proxy.localhost" # Required to allow redirection back to original requested target. # Enables the use of `X-Forwarded-*` headers to determine request correctly reverse_proxy="true" diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index a73e3acd..b145065a 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -193,6 +193,10 @@ Provider specific options can be found on their respective subpages. ### Proxy Options +:::warning +When `--reverse-proxy` is enabled, configure `--trusted-proxy-ip` to the IPs or CIDR ranges of the reverse proxies that are allowed to send `X-Forwarded-*` headers. If you leave it unset, OAuth2 Proxy currently trusts all source IPs for backwards compatibility, which means a client that can reach OAuth2 Proxy directly may be able to spoof forwarded headers. +::: + | Flag / Config Field | Type | Description | Default | | ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | | flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | @@ -211,6 +215,7 @@ Provider specific options can be found on their respective subpages. | flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | | flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | | flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--trusted-proxy-ip`
toml: `trusted_proxy_ips` | string \| list | list of IPs or CIDR ranges allowed to supply `X-Forwarded-*` headers when `--reverse-proxy` is enabled. If not set, OAuth2 Proxy preserves backwards compatibility by trusting all source IPs (`0.0.0.0/0`, `::/0`) and logs a warning at startup. Configure this to your reverse proxy addresses to prevent forwarded header spoofing. | `"0.0.0.0/0", "::/0"` | | flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | | flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | | flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | diff --git a/docs/versioned_docs/version-7.15.x/configuration/overview.md b/docs/versioned_docs/version-7.15.x/configuration/overview.md index a73e3acd..b145065a 100644 --- a/docs/versioned_docs/version-7.15.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.15.x/configuration/overview.md @@ -193,6 +193,10 @@ Provider specific options can be found on their respective subpages. ### Proxy Options +:::warning +When `--reverse-proxy` is enabled, configure `--trusted-proxy-ip` to the IPs or CIDR ranges of the reverse proxies that are allowed to send `X-Forwarded-*` headers. If you leave it unset, OAuth2 Proxy currently trusts all source IPs for backwards compatibility, which means a client that can reach OAuth2 Proxy directly may be able to spoof forwarded headers. +::: + | Flag / Config Field | Type | Description | Default | | ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | | flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | @@ -211,6 +215,7 @@ Provider specific options can be found on their respective subpages. | flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | | flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | | flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--trusted-proxy-ip`
toml: `trusted_proxy_ips` | string \| list | list of IPs or CIDR ranges allowed to supply `X-Forwarded-*` headers when `--reverse-proxy` is enabled. If not set, OAuth2 Proxy preserves backwards compatibility by trusting all source IPs (`0.0.0.0/0`, `::/0`) and logs a warning at startup. Configure this to your reverse proxy addresses to prevent forwarded header spoofing. | `"0.0.0.0/0", "::/0"` | | flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | | flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | | flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | diff --git a/oauthproxy.go b/oauthproxy.go index 0685bbbb..e2357c8d 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -59,6 +59,8 @@ const ( ) var ( + defaultTrustedProxyIPs = []string{"0.0.0.0/0", "::/0"} + // ErrNeedsLogin means the user should be redirected to the login page ErrNeedsLogin = errors.New("redirect to login page") @@ -183,13 +185,14 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr logger.Printf("Cookie settings: name:%s secure(https):%v httponly:%v expiry:%s domains:%s path:%s samesite:%s refresh:%s", opts.Cookie.Name, opts.Cookie.Secure, opts.Cookie.HTTPOnly, opts.Cookie.Expire, strings.Join(opts.Cookie.Domains, ","), opts.Cookie.Path, opts.Cookie.SameSite, refresh) - trustedIPs := ip.NewNetSet() - for _, ipStr := range opts.TrustedIPs { - if ipNet := ip.ParseIPNet(ipStr); ipNet != nil { - trustedIPs.AddIPNet(*ipNet) - } else { - return nil, fmt.Errorf("could not parse IP network (%s)", ipStr) - } + trustedIPs, err := ip.ParseNetSet(opts.TrustedIPs) + if err != nil { + return nil, err + } + + trustedProxies, err := buildTrustedProxyNetSet(opts) + if err != nil { + return nil, err } allowedRoutes, err := buildRoutesAllowlist(opts) @@ -202,7 +205,7 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr return nil, err } - preAuthChain, err := buildPreAuthChain(opts, sessionStore) + preAuthChain, err := buildPreAuthChain(opts, sessionStore, trustedProxies) if err != nil { return nil, fmt.Errorf("could not build pre-auth chain: %v", err) } @@ -355,8 +358,8 @@ func (p *OAuthProxy) buildProxySubrouter(s *mux.Router) { // buildPreAuthChain constructs a chain that should process every request before // the OAuth2 Proxy authentication logic kicks in. // For example forcing HTTPS or health checks. -func buildPreAuthChain(opts *options.Options, sessionStore sessionsapi.SessionStore) (alice.Chain, error) { - chain := alice.New(middleware.NewScope(opts.ReverseProxy, opts.Logging.RequestIDHeader)) +func buildPreAuthChain(opts *options.Options, sessionStore sessionsapi.SessionStore, trustedProxies *ip.NetSet) (alice.Chain, error) { + chain := alice.New(middleware.NewScope(opts.ReverseProxy, opts.Logging.RequestIDHeader, trustedProxies)) if opts.ForceHTTPS { _, httpsPort, err := net.SplitHostPort(opts.Server.SecureBindAddress) @@ -395,6 +398,16 @@ func buildPreAuthChain(opts *options.Options, sessionStore sessionsapi.SessionSt return chain, nil } +func buildTrustedProxyNetSet(opts *options.Options) (*ip.NetSet, error) { + trustedProxyIPs := opts.TrustedProxyIPs + if opts.ReverseProxy && len(trustedProxyIPs) == 0 { + logger.Print("WARNING: --reverse-proxy is enabled but no --trusted-proxy-ip CIDRs were configured. All connecting IPs are trusted to supply X-Forwarded-* headers by default (0.0.0.0/0, ::/0). This preserves backwards compatibility but is a potential security risk; configure --trusted-proxy-ip to match your reverse proxy addresses.") + trustedProxyIPs = defaultTrustedProxyIPs + } + + return ip.ParseNetSet(trustedProxyIPs) +} + func buildSessionChain(opts *options.Options, provider providers.Provider, sessionStore sessionsapi.SessionStore, validator basic.Validator) alice.Chain { chain := alice.New() diff --git a/oauthproxy_test.go b/oauthproxy_test.go index 46e39a90..df5912a0 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -2843,6 +2843,7 @@ func TestAllowedRequestWithForwardedUriHeader(t *testing.T) { t.Run(tc.name, func(t *testing.T) { req, err := http.NewRequest(tc.method, opts.ProxyPrefix+authOnlyPath, nil) req.Header.Set("X-Forwarded-Uri", tc.url) + req.RemoteAddr = "127.0.0.1:4180" assert.NoError(t, err) rw := httptest.NewRecorder() @@ -2857,6 +2858,43 @@ func TestAllowedRequestWithForwardedUriHeader(t *testing.T) { } } +func TestAllowedRequestWithForwardedUriHeaderRequiresTrustedProxy(t *testing.T) { + upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(200) + })) + t.Cleanup(upstreamServer.Close) + + opts := baseTestOptions() + opts.ReverseProxy = true + opts.TrustedProxyIPs = []string{"127.0.0.1/32"} + opts.UpstreamServers = options.UpstreamConfig{ + Upstreams: []options.Upstream{ + { + ID: upstreamServer.URL, + Path: "/", + URI: upstreamServer.URL, + }, + }, + } + opts.SkipAuthRegex = []string{"^/skip/auth/regex$"} + + err := validation.Validate(opts) + assert.NoError(t, err) + + proxy, err := NewOAuthProxy(opts, func(_ string) bool { return true }) + assert.NoError(t, err) + + req, err := http.NewRequest(http.MethodGet, opts.ProxyPrefix+authOnlyPath, nil) + assert.NoError(t, err) + req.RemoteAddr = "192.0.2.10:4180" + req.Header.Set("X-Forwarded-Uri", "/skip/auth/regex") + + rw := httptest.NewRecorder() + proxy.ServeHTTP(rw, req) + + assert.Equal(t, 401, rw.Code) +} + func TestAllowedRequestNegateWithoutMethod(t *testing.T) { upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) diff --git a/pkg/apis/middleware/scope.go b/pkg/apis/middleware/scope.go index 2d84f00e..b778bd54 100644 --- a/pkg/apis/middleware/scope.go +++ b/pkg/apis/middleware/scope.go @@ -2,9 +2,12 @@ package middleware import ( "context" + "net" "net/http" + "strings" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip" ) type scopeKey string @@ -18,9 +21,13 @@ const RequestScopeKey scopeKey = "request-scope" // within the chain. type RequestScope struct { // ReverseProxy tracks whether OAuth2-Proxy is operating in reverse proxy - // mode and if request `X-Forwarded-*` headers should be trusted + // mode and if request `X-Forwarded-*` headers may be trusted ReverseProxy bool + // TrustedProxies tracks which direct callers are allowed to supply + // forwarded headers when ReverseProxy mode is enabled. + TrustedProxies *ip.NetSet + // RequestID is set to the request's `X-Request-Id` header if set. // Otherwise a random UUID is set. RequestID string @@ -58,3 +65,43 @@ func AddRequestScope(req *http.Request, scope *RequestScope) *http.Request { ctx := context.WithValue(req.Context(), RequestScopeKey, scope) return req.WithContext(ctx) } + +// CanTrustForwardedHeaders returns whether forwarded headers should be +// processed for this request. +func (s *RequestScope) CanTrustForwardedHeaders(req *http.Request) bool { + if s == nil || req == nil || !s.ReverseProxy || s.TrustedProxies == nil { + return false + } + + if isUnixSocketRemoteAddr(req.RemoteAddr) { + return true + } + + remoteIP := parseRemoteAddrIP(req.RemoteAddr) + if remoteIP == nil { + return false + } + + return s.TrustedProxies.Has(remoteIP) +} + +func parseRemoteAddrIP(remoteAddr string) net.IP { + if remoteAddr == "" { + return nil + } + + if ip := net.ParseIP(remoteAddr); ip != nil { + return ip + } + + host, _, err := net.SplitHostPort(remoteAddr) + if err != nil { + return nil + } + + return net.ParseIP(host) +} + +func isUnixSocketRemoteAddr(remoteAddr string) bool { + return remoteAddr == "@" || strings.HasPrefix(remoteAddr, "/") +} diff --git a/pkg/apis/middleware/scope_test.go b/pkg/apis/middleware/scope_test.go index f1845518..ec485b47 100644 --- a/pkg/apis/middleware/scope_test.go +++ b/pkg/apis/middleware/scope_test.go @@ -4,6 +4,7 @@ import ( "net/http" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -53,4 +54,37 @@ var _ = Describe("Scope Suite", func() { }) }) }) + + Context("CanTrustForwardedHeaders", func() { + var request *http.Request + var scope *middleware.RequestScope + + BeforeEach(func() { + var err error + request, err = http.NewRequest("", "http://127.0.0.1/", nil) + Expect(err).ToNot(HaveOccurred()) + + trustedProxies, err := ip.ParseNetSet([]string{"127.0.0.1"}) + Expect(err).ToNot(HaveOccurred()) + scope = &middleware.RequestScope{ + ReverseProxy: true, + TrustedProxies: trustedProxies, + } + }) + + It("returns true for a trusted remote address", func() { + request.RemoteAddr = "127.0.0.1:4180" + Expect(scope.CanTrustForwardedHeaders(request)).To(BeTrue()) + }) + + It("returns false for an untrusted remote address", func() { + request.RemoteAddr = "192.0.2.10:4180" + Expect(scope.CanTrustForwardedHeaders(request)).To(BeFalse()) + }) + + It("returns true for unix socket callers", func() { + request.RemoteAddr = "@" + Expect(scope.CanTrustForwardedHeaders(request)).To(BeTrue()) + }) + }) }) diff --git a/pkg/apis/options/options.go b/pkg/apis/options/options.go index b57d5aed..ac2b13c8 100644 --- a/pkg/apis/options/options.go +++ b/pkg/apis/options/options.go @@ -24,6 +24,7 @@ type Options struct { ReadyPath string `flag:"ready-path" cfg:"ready_path"` ReverseProxy bool `flag:"reverse-proxy" cfg:"reverse_proxy"` RealClientIPHeader string `flag:"real-client-ip-header" cfg:"real_client_ip_header"` + TrustedProxyIPs []string `flag:"trusted-proxy-ip" cfg:"trusted_proxy_ips"` TrustedIPs []string `flag:"trusted-ip" cfg:"trusted_ips"` ForceHTTPS bool `flag:"force-https" cfg:"force_https"` RawRedirectURL string `flag:"redirect-url" cfg:"redirect_url"` @@ -119,6 +120,7 @@ func NewFlagSet() *pflag.FlagSet { flagSet.Bool("reverse-proxy", false, "are we running behind a reverse proxy, controls whether headers like X-Real-Ip are accepted") flagSet.String("real-client-ip-header", "X-Real-IP", "Header used to determine the real IP of the client (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP)") + flagSet.StringSlice("trusted-proxy-ip", []string{}, "list of IPs or CIDR ranges that are allowed to set X-Forwarded-* headers when --reverse-proxy is enabled. Defaults to trusting all IPs for backwards compatibility; configure this to your reverse proxy addresses to prevent header spoofing.") flagSet.StringSlice("trusted-ip", []string{}, "list of IPs or CIDR ranges to allow to bypass authentication. WARNING: trusting by IP has inherent security flaws, read the configuration documentation for more information.") flagSet.Bool("force-https", false, "force HTTPS redirect for HTTP requests") flagSet.String("redirect-url", "", "the OAuth Redirect URL. ie: \"https://internalapp.yourcompany.com/oauth2/callback\"") diff --git a/pkg/app/redirect/director_test.go b/pkg/app/redirect/director_test.go index 69c01d95..58d0e8c3 100644 --- a/pkg/app/redirect/director_test.go +++ b/pkg/app/redirect/director_test.go @@ -4,6 +4,7 @@ import ( "net/http" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -33,9 +34,16 @@ var _ = Describe("Director Suite", func() { req.Header.Add(header, value) } } - req = middleware.AddRequestScope(req, &middleware.RequestScope{ + scope := &middleware.RequestScope{ ReverseProxy: in.reverseProxy, - }) + } + if in.reverseProxy { + req.RemoteAddr = "127.0.0.1:4180" + trustedProxies, err := ip.ParseNetSet([]string{"127.0.0.1"}) + Expect(err).ToNot(HaveOccurred()) + scope.TrustedProxies = trustedProxies + } + req = middleware.AddRequestScope(req, scope) redirect, err := appDirector.GetRedirect(req) Expect(err).ToNot(HaveOccurred()) @@ -174,4 +182,27 @@ var _ = Describe("Director Suite", func() { expectedRedirect: "https://a-service.example.com/foo/bar", }), ) + + It("ignores forwarded headers from an untrusted remote address", func() { + appDirector := NewAppDirector(AppDirectorOpts{ + ProxyPrefix: testProxyPrefix, + Validator: testValidator(true), + }) + + req, _ := http.NewRequest("GET", "https://oauth.example.com/foo?bar", nil) + req.RemoteAddr = "192.0.2.10:4180" + req.Header.Add("X-Forwarded-Proto", "https") + req.Header.Add("X-Forwarded-Host", "a-service.example.com") + req.Header.Add("X-Forwarded-Uri", fooBar) + trustedProxies, err := ip.ParseNetSet([]string{"127.0.0.1"}) + Expect(err).ToNot(HaveOccurred()) + req = middleware.AddRequestScope(req, &middleware.RequestScope{ + ReverseProxy: true, + TrustedProxies: trustedProxies, + }) + + redirect, err := appDirector.GetRedirect(req) + Expect(err).ToNot(HaveOccurred()) + Expect(redirect).To(Equal("/foo?bar")) + }) }) diff --git a/pkg/cookies/cookies_test.go b/pkg/cookies/cookies_test.go index b67f8a69..ba8b5480 100644 --- a/pkg/cookies/cookies_test.go +++ b/pkg/cookies/cookies_test.go @@ -6,6 +6,7 @@ import ( "time" middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -30,8 +31,13 @@ var _ = Describe("Cookie Tests", func() { if in.xForwardedHost != "" { req.Header.Add("X-Forwarded-Host", in.xForwardedHost) + req.RemoteAddr = "127.0.0.1:4180" + trustedProxies, err := ip.ParseNetSet([]string{"127.0.0.1"}) + Expect(err).ToNot(HaveOccurred()) + req = middlewareapi.AddRequestScope(req, &middlewareapi.RequestScope{ - ReverseProxy: true, + ReverseProxy: true, + TrustedProxies: trustedProxies, }) } diff --git a/pkg/ip/parse_ip_net.go b/pkg/ip/parse_ip_net.go index 9cb37de2..4fc63664 100644 --- a/pkg/ip/parse_ip_net.go +++ b/pkg/ip/parse_ip_net.go @@ -1,6 +1,7 @@ package ip import ( + "fmt" "net" "strings" ) @@ -37,3 +38,18 @@ func ParseIPNet(s string) *net.IPNet { return ipNet } } + +func ParseNetSet(ipStrs []string) (*NetSet, error) { + netSet := NewNetSet() + + for _, ipStr := range ipStrs { + ipNet := ParseIPNet(ipStr) + if ipNet == nil { + return nil, fmt.Errorf("could not parse IP network (%s)", ipStr) + } + + netSet.AddIPNet(*ipNet) + } + + return netSet, nil +} diff --git a/pkg/ip/parse_ip_net_test.go b/pkg/ip/parse_ip_net_test.go new file mode 100644 index 00000000..41c1b4b9 --- /dev/null +++ b/pkg/ip/parse_ip_net_test.go @@ -0,0 +1,118 @@ +package ip + +import ( + "net" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestParseIPNet(t *testing.T) { + tests := []struct { + name string + input string + expectedIP net.IP + expectedMask net.IPMask + }{ + { + name: "ipv4 address", + input: "127.0.0.1", + expectedIP: net.ParseIP("127.0.0.1"), + expectedMask: net.CIDRMask(32, 32), + }, + { + name: "ipv6 address", + input: "::1", + expectedIP: net.ParseIP("::1"), + expectedMask: net.CIDRMask(128, 128), + }, + { + name: "ipv4 cidr", + input: "10.0.0.0/24", + expectedIP: net.ParseIP("10.0.0.0"), + expectedMask: net.CIDRMask(24, 32), + }, + { + name: "ipv6 cidr", + input: "2001:db8::/64", + expectedIP: net.ParseIP("2001:db8::"), + expectedMask: net.CIDRMask(64, 128), + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + ipNet := ParseIPNet(test.input) + + assert.NotNil(t, ipNet) + if ipNet == nil { + return + } + + assert.True(t, test.expectedIP.Equal(ipNet.IP)) + assert.Equal(t, test.expectedMask, ipNet.Mask) + }) + } +} + +func TestParseIPNetRejectsInvalidNetworks(t *testing.T) { + tests := []struct { + name string + input string + }{ + { + name: "invalid ip", + input: "not-an-ip", + }, + { + name: "ipv4 cidr with host bits set", + input: "10.0.0.1/24", + }, + { + name: "ipv6 cidr with host bits set", + input: "2001:db8::1/64", + }, + { + name: "invalid cidr mask", + input: "10.0.0.0/33", + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + assert.Nil(t, ParseIPNet(test.input)) + }) + } +} + +func TestParseNetSet(t *testing.T) { + netSet, err := ParseNetSet([]string{ + "127.0.0.1", + "10.0.0.0/24", + "::1", + "2001:db8::/64", + }) + + assert.NoError(t, err) + assert.NotNil(t, netSet) + if netSet == nil { + return + } + + assert.True(t, netSet.Has(net.ParseIP("127.0.0.1"))) + assert.True(t, netSet.Has(net.ParseIP("10.0.0.55"))) + assert.True(t, netSet.Has(net.ParseIP("::1"))) + assert.True(t, netSet.Has(net.ParseIP("2001:db8::abcd"))) + + assert.False(t, netSet.Has(net.ParseIP("127.0.0.2"))) + assert.False(t, netSet.Has(net.ParseIP("10.0.1.1"))) + assert.False(t, netSet.Has(net.ParseIP("::2"))) + assert.False(t, netSet.Has(net.ParseIP("2001:db9::1"))) +} + +func TestParseNetSetReturnsErrorForInvalidNetwork(t *testing.T) { + netSet, err := ParseNetSet([]string{"127.0.0.1", "10.0.0.1/24"}) + + assert.Nil(t, netSet) + assert.EqualError(t, err, "could not parse IP network (10.0.0.1/24)") +} diff --git a/pkg/middleware/redirect_to_https_test.go b/pkg/middleware/redirect_to_https_test.go index 6e8a4368..9c7fb751 100644 --- a/pkg/middleware/redirect_to_https_test.go +++ b/pkg/middleware/redirect_to_https_test.go @@ -6,6 +6,7 @@ import ( "net/http/httptest" middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -39,6 +40,10 @@ var _ = Describe("RedirectToHTTPS suite", func() { scope := &middlewareapi.RequestScope{ ReverseProxy: in.reverseProxy, } + if in.reverseProxy { + req.RemoteAddr = "127.0.0.1:4180" + scope.TrustedProxies = newRedirectTrustedProxySet("127.0.0.1") + } req = middlewareapi.AddRequestScope(req, scope) rw := httptest.NewRecorder() @@ -207,3 +212,13 @@ var _ = Describe("RedirectToHTTPS suite", func() { }), ) }) + +func newRedirectTrustedProxySet(cidrs ...string) *ip.NetSet { + set := ip.NewNetSet() + for _, cidr := range cidrs { + ipNet := ip.ParseIPNet(cidr) + Expect(ipNet).ToNot(BeNil()) + set.AddIPNet(*ipNet) + } + return set +} diff --git a/pkg/middleware/scope.go b/pkg/middleware/scope.go index d0dd81ec..84b1573c 100644 --- a/pkg/middleware/scope.go +++ b/pkg/middleware/scope.go @@ -6,14 +6,16 @@ import ( "github.com/google/uuid" "github.com/justinas/alice" middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip" ) -func NewScope(reverseProxy bool, idHeader string) alice.Constructor { +func NewScope(reverseProxy bool, idHeader string, trustedProxies *ip.NetSet) alice.Constructor { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { scope := &middlewareapi.RequestScope{ - ReverseProxy: reverseProxy, - RequestID: genRequestID(req, idHeader), + ReverseProxy: reverseProxy, + TrustedProxies: trustedProxies, + RequestID: genRequestID(req, idHeader), } req = middlewareapi.AddRequestScope(req, scope) next.ServeHTTP(rw, req) diff --git a/pkg/middleware/scope_test.go b/pkg/middleware/scope_test.go index fa680667..db2c3016 100644 --- a/pkg/middleware/scope_test.go +++ b/pkg/middleware/scope_test.go @@ -6,6 +6,7 @@ import ( "github.com/google/uuid" middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -32,7 +33,7 @@ var _ = Describe("Scope Suite", func() { Context("ReverseProxy is false", func() { BeforeEach(func() { - handler := NewScope(false, testRequestHeader)( + handler := NewScope(false, testRequestHeader, nil)( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { nextRequest = r w.WriteHeader(200) @@ -60,8 +61,15 @@ var _ = Describe("Scope Suite", func() { }) Context("ReverseProxy is true", func() { + var trustedProxies *ip.NetSet + BeforeEach(func() { - handler := NewScope(true, testRequestHeader)( + var err error + + trustedProxies, err = ip.ParseNetSet([]string{"127.0.0.1"}) + Expect(err).ToNot(HaveOccurred()) + + handler := NewScope(true, testRequestHeader, trustedProxies)( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { nextRequest = r w.WriteHeader(200) @@ -74,12 +82,18 @@ var _ = Describe("Scope Suite", func() { Expect(scope).ToNot(BeNil()) Expect(scope.ReverseProxy).To(BeTrue()) }) + + It("stores the trusted proxies on the scope", func() { + scope := middlewareapi.GetRequestScope(nextRequest) + Expect(scope).ToNot(BeNil()) + Expect(scope.TrustedProxies).To(BeIdenticalTo(trustedProxies)) + }) }) Context("Request ID header is present", func() { BeforeEach(func() { request.Header.Add(testRequestHeader, testRequestID) - handler := NewScope(false, testRequestHeader)( + handler := NewScope(false, testRequestHeader, nil)( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { nextRequest = r w.WriteHeader(200) @@ -97,7 +111,7 @@ var _ = Describe("Scope Suite", func() { BeforeEach(func() { uuid.SetRand(mockRand{}) - handler := NewScope(true, testRequestHeader)( + handler := NewScope(true, testRequestHeader, nil)( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { nextRequest = r w.WriteHeader(200) diff --git a/pkg/requests/util/util.go b/pkg/requests/util/util.go index 290f8059..7b9b4919 100644 --- a/pkg/requests/util/util.go +++ b/pkg/requests/util/util.go @@ -15,30 +15,30 @@ const ( ) // GetRequestProto returns the request scheme or X-Forwarded-Proto if present -// and the request is proxied. +// and the request came from a trusted reverse proxy. func GetRequestProto(req *http.Request) string { proto := req.Header.Get(XForwardedProto) - if !IsProxied(req) || proto == "" { + if !CanTrustForwardedHeaders(req) || proto == "" { proto = req.URL.Scheme } return proto } // GetRequestHost returns the request host header or X-Forwarded-Host if -// present and the request is proxied. +// present and the request came from a trusted reverse proxy. func GetRequestHost(req *http.Request) string { host := req.Header.Get(XForwardedHost) - if !IsProxied(req) || host == "" { + if !CanTrustForwardedHeaders(req) || host == "" { host = req.Host } return host } // GetRequestURI return the request URI or X-Forwarded-Uri if present and the -// request is proxied. +// request came from a trusted reverse proxy. func GetRequestURI(req *http.Request) string { uri := req.Header.Get(XForwardedURI) - if !IsProxied(req) || uri == "" { + if !CanTrustForwardedHeaders(req) || uri == "" { // Use RequestURI to preserve ?query uri = req.URL.RequestURI() } @@ -46,8 +46,8 @@ func GetRequestURI(req *http.Request) string { } // GetRequestPath returns the request URI or X-Forwarded-Uri if present and the -// request is proxied but always strips the query parameters and only returns -// the pure path +// request came from a trusted reverse proxy but always strips the query +// parameters and only returns the pure path. func GetRequestPath(req *http.Request) string { uri := GetRequestURI(req) @@ -64,17 +64,18 @@ func GetRequestPath(req *http.Request) string { return uri } -// IsProxied determines if a request was from a proxy based on the RequestScope -// ReverseProxy tracker. -func IsProxied(req *http.Request) bool { +// CanTrustForwardedHeaders determines if forwarded headers should be processed +// based on the RequestScope and the direct caller's address. +func CanTrustForwardedHeaders(req *http.Request) bool { scope := middlewareapi.GetRequestScope(req) if scope == nil { return false } - return scope.ReverseProxy + + return scope.CanTrustForwardedHeaders(req) } func IsForwardedRequest(req *http.Request) bool { - return IsProxied(req) && + return CanTrustForwardedHeaders(req) && req.Host != GetRequestHost(req) } diff --git a/pkg/requests/util/util_test.go b/pkg/requests/util/util_test.go index ba72c66d..ed7a88a6 100644 --- a/pkg/requests/util/util_test.go +++ b/pkg/requests/util/util_test.go @@ -6,6 +6,7 @@ import ( "net/http/httptest" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests/util" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -19,8 +20,13 @@ var _ = Describe("Util Suite", func() { uriNoQueryParams = "/test/endpoint" ) var req *http.Request + var trustedProxies *ip.NetSet BeforeEach(func() { + var err error + trustedProxies, err = ip.ParseNetSet([]string{"127.0.0.1"}) + Expect(err).ToNot(HaveOccurred()) + req = httptest.NewRequest( http.MethodGet, fmt.Sprintf("%s://%s%s", proto, host, uriWithQueryParams), @@ -29,7 +35,7 @@ var _ = Describe("Util Suite", func() { }) Context("GetRequestHost", func() { - Context("IsProxied is false", func() { + Context("trusted forwarded headers are disabled", func() { BeforeEach(func() { req = middleware.AddRequestScope(req, &middleware.RequestScope{}) }) @@ -44,10 +50,12 @@ var _ = Describe("Util Suite", func() { }) }) - Context("IsProxied is true", func() { + Context("trusted forwarded headers are enabled", func() { BeforeEach(func() { + req.RemoteAddr = "127.0.0.1:4180" req = middleware.AddRequestScope(req, &middleware.RequestScope{ - ReverseProxy: true, + ReverseProxy: true, + TrustedProxies: trustedProxies, }) }) @@ -63,7 +71,7 @@ var _ = Describe("Util Suite", func() { }) Context("GetRequestProto", func() { - Context("IsProxied is false", func() { + Context("trusted forwarded headers are disabled", func() { BeforeEach(func() { req = middleware.AddRequestScope(req, &middleware.RequestScope{}) }) @@ -78,10 +86,12 @@ var _ = Describe("Util Suite", func() { }) }) - Context("IsProxied is true", func() { + Context("trusted forwarded headers are enabled", func() { BeforeEach(func() { + req.RemoteAddr = "127.0.0.1:4180" req = middleware.AddRequestScope(req, &middleware.RequestScope{ - ReverseProxy: true, + ReverseProxy: true, + TrustedProxies: trustedProxies, }) }) @@ -97,7 +107,7 @@ var _ = Describe("Util Suite", func() { }) Context("GetRequestURI", func() { - Context("IsProxied is false", func() { + Context("trusted forwarded headers are disabled", func() { BeforeEach(func() { req = middleware.AddRequestScope(req, &middleware.RequestScope{}) }) @@ -112,10 +122,12 @@ var _ = Describe("Util Suite", func() { }) }) - Context("IsProxied is true", func() { + Context("trusted forwarded headers are enabled", func() { BeforeEach(func() { + req.RemoteAddr = "127.0.0.1:4180" req = middleware.AddRequestScope(req, &middleware.RequestScope{ - ReverseProxy: true, + ReverseProxy: true, + TrustedProxies: trustedProxies, }) }) @@ -131,7 +143,7 @@ var _ = Describe("Util Suite", func() { }) Context("GetRequestPath", func() { - Context("IsProxied is false", func() { + Context("trusted forwarded headers are disabled", func() { BeforeEach(func() { req = middleware.AddRequestScope(req, &middleware.RequestScope{}) }) @@ -146,10 +158,12 @@ var _ = Describe("Util Suite", func() { }) }) - Context("IsProxied is true", func() { + Context("trusted forwarded headers are enabled", func() { BeforeEach(func() { + req.RemoteAddr = "127.0.0.1:4180" req = middleware.AddRequestScope(req, &middleware.RequestScope{ - ReverseProxy: true, + ReverseProxy: true, + TrustedProxies: trustedProxies, }) }) @@ -163,4 +177,30 @@ var _ = Describe("Util Suite", func() { }) }) }) + + Context("CanTrustForwardedHeaders", func() { + It("returns false when no scope is present", func() { + Expect(util.CanTrustForwardedHeaders(req)).To(BeFalse()) + }) + + It("returns true when the remote address is trusted", func() { + req.RemoteAddr = "127.0.0.1:4180" + req = middleware.AddRequestScope(req, &middleware.RequestScope{ + ReverseProxy: true, + TrustedProxies: trustedProxies, + }) + + Expect(util.CanTrustForwardedHeaders(req)).To(BeTrue()) + }) + + It("returns false when the remote address is untrusted", func() { + req.RemoteAddr = "192.0.2.10:4180" + req = middleware.AddRequestScope(req, &middleware.RequestScope{ + ReverseProxy: true, + TrustedProxies: trustedProxies, + }) + + Expect(util.CanTrustForwardedHeaders(req)).To(BeFalse()) + }) + }) }) diff --git a/pkg/upstream/http_test.go b/pkg/upstream/http_test.go index a01d5c09..70af9e7e 100644 --- a/pkg/upstream/http_test.go +++ b/pkg/upstream/http_test.go @@ -498,7 +498,7 @@ var _ = Describe("HTTP Upstream Suite", func() { handler := newHTTPUpstreamProxy(upstream, u, nil, nil) - proxyServer = httptest.NewServer(middleware.NewScope(false, "X-Request-Id")(handler)) + proxyServer = httptest.NewServer(middleware.NewScope(false, "X-Request-Id", nil)(handler)) }) AfterEach(func() { @@ -549,7 +549,7 @@ var _ = Describe("HTTP Upstream Suite", func() { Expect(err).ToNot(HaveOccurred()) handler := newHTTPUpstreamProxy(upstream, u, nil, nil) - noPassHostServer := httptest.NewServer(middleware.NewScope(false, "X-Request-Id")(handler)) + noPassHostServer := httptest.NewServer(middleware.NewScope(false, "X-Request-Id", nil)(handler)) defer noPassHostServer.Close() origin := "http://example.localhost" diff --git a/pkg/validation/allowlist.go b/pkg/validation/allowlist.go index a74f4ae9..dcc0d361 100644 --- a/pkg/validation/allowlist.go +++ b/pkg/validation/allowlist.go @@ -16,6 +16,7 @@ func validateAllowlists(o *options.Options) []string { msgs = append(msgs, validateAuthRoutes(o)...) msgs = append(msgs, validateAuthRegexes(o)...) + msgs = append(msgs, validateTrustedProxyIPs(o)...) msgs = append(msgs, validateTrustedIPs(o)...) if len(o.TrustedIPs) > 0 && o.ReverseProxy { @@ -28,6 +29,17 @@ func validateAllowlists(o *options.Options) []string { return msgs } +// validateTrustedProxyIPs validates IP/CIDRs for trusted reverse proxies. +func validateTrustedProxyIPs(o *options.Options) []string { + msgs := []string{} + for i, ipStr := range o.TrustedProxyIPs { + if ip.ParseIPNet(ipStr) == nil { + msgs = append(msgs, fmt.Sprintf("trusted_proxy_ips[%d] (%s) could not be recognized", i, ipStr)) + } + } + return msgs +} + // validateAuthRoutes validates method=path routes passed with options.SkipAuthRoutes func validateAuthRoutes(o *options.Options) []string { msgs := []string{} diff --git a/pkg/validation/allowlist_test.go b/pkg/validation/allowlist_test.go index 9f6843dd..ae4c29ef 100644 --- a/pkg/validation/allowlist_test.go +++ b/pkg/validation/allowlist_test.go @@ -23,6 +23,11 @@ var _ = Describe("Allowlist", func() { errStrings []string } + type validateTrustedProxyIPsTableInput struct { + trustedProxyIPs []string + errStrings []string + } + DescribeTable("validateRoutes", func(r *validateRoutesTableInput) { opts := &options.Options{ @@ -121,4 +126,29 @@ var _ = Describe("Allowlist", func() { }, }), ) + + DescribeTable("validateTrustedProxyIPs", + func(t *validateTrustedProxyIPsTableInput) { + opts := &options.Options{ + TrustedProxyIPs: t.trustedProxyIPs, + } + Expect(validateTrustedProxyIPs(opts)).To(ConsistOf(t.errStrings)) + }, + Entry("Valid trusted proxy IPs", &validateTrustedProxyIPsTableInput{ + trustedProxyIPs: []string{ + "127.0.0.1", + "10.32.0.1/32", + "::1", + "2a12:105:ee7:9234:0:0:0:0/64", + }, + errStrings: []string{}, + }), + Entry("Invalid trusted proxy IPs", &validateTrustedProxyIPsTableInput{ + trustedProxyIPs: []string{"[::1]", "alkwlkbn/32"}, + errStrings: []string{ + "trusted_proxy_ips[0] ([::1]) could not be recognized", + "trusted_proxy_ips[1] (alkwlkbn/32) could not be recognized", + }, + }), + ) }) From cc0e0335ea9e33c0220c7ce1181e5d41dcac7b48 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Mon, 13 Apr 2026 18:24:51 +0200 Subject: [PATCH 43/53] Merge commit from fork Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + oauthproxy_test.go | 18 ++++++++++++++++++ validator.go | 5 ++++- validator_test.go | 21 +++++++++++++++++++++ 4 files changed, 44 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8be9736e..bfce323a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ - [GHSA-f24x-5g9q-753f](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-f24x-5g9q-753f) fix: clear session cookie at beginning of signinpage handler (@fnoehWM / @bella-WI / @tuunit) - [GHSA-5hvv-m4w4-gf6v](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-5hvv-m4w4-gf6v) fix: health check user-agent authentication bypass (@tuunit) - [GHSA-7x63-xv5r-3p2x](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-7x63-xv5r-3p2x) fix: authentication bypass via X-Forwarded-Uri header spoofing (@tuunit) +- [GHSA-c5c4-8r6x-56w3](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-c5c4-8r6x-56w3) fix: email validation bypass via malformed multi-@ email claims (@tuunit) # V7.15.1 diff --git a/oauthproxy_test.go b/oauthproxy_test.go index df5912a0..fc9c34bd 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -3486,6 +3486,24 @@ func TestAuthOnlyAllowedEmailDomains(t *testing.T) { querystring: "?allowed_email_domains=a.b.c.example.com,*.c.example.com", expectedStatusCode: http.StatusAccepted, }, + { + name: "UserWithMultipleAtSignsExactDomain", + email: "attacker@evil.com@example.com", + querystring: "?allowed_email_domains=example.com", + expectedStatusCode: http.StatusForbidden, + }, + { + name: "UserWithMultipleAtSignsWildcardDomain", + email: "attacker@evil.com@foo.example.com", + querystring: "?allowed_email_domains=*.example.com", + expectedStatusCode: http.StatusForbidden, + }, + { + name: "UserWithMultipleAtSignsDotPrefixedDomain", + email: "attacker@evil.com@foo.example.com", + querystring: "?allowed_email_domains=.example.com", + expectedStatusCode: http.StatusForbidden, + }, } for _, tc := range testCases { diff --git a/validator.go b/validator.go index 587ef857..d03157a5 100644 --- a/validator.go +++ b/validator.go @@ -110,6 +110,10 @@ func NewValidator(domains []string, usersFile string) func(string) bool { // isEmailValidWithDomains checks if the authenticated email is validated against the provided domain func isEmailValidWithDomains(email string, allowedDomains []string) bool { + if strings.Count(email, "@") != 1 { + return false + } + for _, domain := range allowedDomains { // allow if the domain is perfect suffix match with the email if strings.HasSuffix(email, "@"+domain) { @@ -119,7 +123,6 @@ func isEmailValidWithDomains(email string, allowedDomains []string) bool { // allow if the domain is prefixed with . or *. and // the last element (split on @) has the suffix as the domain atoms := strings.Split(email, "@") - if (strings.HasPrefix(domain, ".") && strings.HasSuffix(atoms[len(atoms)-1], domain)) || (strings.HasPrefix(domain, "*.") && strings.HasSuffix(atoms[len(atoms)-1], domain[1:])) { return true diff --git a/validator_test.go b/validator_test.go index 976c0d7d..c406a732 100644 --- a/validator_test.go +++ b/validator_test.go @@ -404,6 +404,27 @@ func TestValidatorCases(t *testing.T) { allowedDomains: []string{"*.company.com"}, expectedAuthZ: false, }, + { + name: "CheckThatTwoAtSignsIsInvalid", + email: "attacker@evil.com@company.com", + allowedEmails: []string(nil), + allowedDomains: []string{"company.com"}, + expectedAuthZ: false, + }, + { + name: "CheckThatTwoAtSignsIsInvalidEvenWithDotPrefix", + email: "attacker@evil.com@company.com", + allowedEmails: []string(nil), + allowedDomains: []string{".company.com"}, + expectedAuthZ: false, + }, + { + name: "CheckThatTwoAtSignsIsInvalidEvenWithWildcardPrefix", + email: "attacker@evil.com@foo.company.com", + allowedEmails: []string(nil), + allowedDomains: []string{"*.company.com"}, + expectedAuthZ: false, + }, } for _, tc := range testCases { From bdfde725c6175a5b10e8b5ffe9f09159ea2db03c Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Mon, 13 Apr 2026 18:29:01 +0200 Subject: [PATCH 44/53] Merge commit from fork Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + docs/docs/configuration/overview.md | 4 +-- oauthproxy_test.go | 52 +++++++++++++++++++++++++++++ pkg/requests/util/util.go | 18 ++++++++-- pkg/requests/util/util_test.go | 22 ++++++++++++ 5 files changed, 92 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bfce323a..9f227932 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ - [GHSA-5hvv-m4w4-gf6v](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-5hvv-m4w4-gf6v) fix: health check user-agent authentication bypass (@tuunit) - [GHSA-7x63-xv5r-3p2x](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-7x63-xv5r-3p2x) fix: authentication bypass via X-Forwarded-Uri header spoofing (@tuunit) - [GHSA-c5c4-8r6x-56w3](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-c5c4-8r6x-56w3) fix: email validation bypass via malformed multi-@ email claims (@tuunit) +- [GHSA-pxq7-h93f-9jrg](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-pxq7-h93f-9jrg) fix: fragment evaluation as part of the allowed routes (@tuunit) # V7.15.1 diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index b145065a..965953fa 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -218,8 +218,8 @@ When `--reverse-proxy` is enabled, configure `--trusted-proxy-ip` to the IPs or | flag: `--trusted-proxy-ip`
toml: `trusted_proxy_ips` | string \| list | list of IPs or CIDR ranges allowed to supply `X-Forwarded-*` headers when `--reverse-proxy` is enabled. If not set, OAuth2 Proxy preserves backwards compatibility by trusting all source IPs (`0.0.0.0/0`, `::/0`) and logs a warning at startup. Configure this to your reverse proxy addresses to prevent forwarded header spoofing. | `"0.0.0.0/0", "::/0"` | | flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | | flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | -| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | -| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times). Path matching is performed against the normalized path only; fragment identifiers (`#`) and their URL-encoded form (`%23`) are stripped before evaluation. | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex. Path matching is performed against the normalized path only; fragment identifiers (`#`) and their URL-encoded form (`%23`) are stripped before evaluation. | | | flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | | flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | | flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | diff --git a/oauthproxy_test.go b/oauthproxy_test.go index fc9c34bd..e1235a4e 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -2679,9 +2679,11 @@ func TestAllowedRequest(t *testing.T) { } opts.SkipAuthRegex = []string{ "^/skip/auth/regex$", + "^/public/.*/endpoint$", } opts.SkipAuthRoutes = []string{ "GET=^/skip/auth/routes/get", + "^/foo/.*/bar$", } err := validation.Validate(opts) assert.NoError(t, err) @@ -2714,6 +2716,18 @@ func TestAllowedRequest(t *testing.T) { url: "/wrong/denied", allowed: false, }, + { + name: "Regex allowed with fragment-free path", + method: "GET", + url: "/public/legit/endpoint", + allowed: true, + }, + { + name: "Regex denied when path contains encoded fragment suffix", + method: "GET", + url: "/public/secret%23/endpoint", + allowed: false, + }, { name: "Route allowed", method: "GET", @@ -2738,6 +2752,18 @@ func TestAllowedRequest(t *testing.T) { url: "/skip/auth/routes/wrong/path", allowed: false, }, + { + name: "Route allowed with fragment-free path", + method: "GET", + url: "/foo/public/bar", + allowed: true, + }, + { + name: "Route denied when path contains encoded fragment suffix", + method: "GET", + url: "/foo/secret%23/bar", + allowed: false, + }, } for _, tc := range testCases { @@ -2778,9 +2804,11 @@ func TestAllowedRequestWithForwardedUriHeader(t *testing.T) { } opts.SkipAuthRegex = []string{ "^/skip/auth/regex$", + "^/public/.*/endpoint$", } opts.SkipAuthRoutes = []string{ "GET=^/skip/auth/routes/get", + "^/foo/.*/bar$", } err := validation.Validate(opts) assert.NoError(t, err) @@ -2813,6 +2841,18 @@ func TestAllowedRequestWithForwardedUriHeader(t *testing.T) { url: "/wrong/denied", allowed: false, }, + { + name: "Regex allowed with fragment-free path", + method: "GET", + url: "/public/legit/endpoint", + allowed: true, + }, + { + name: "Regex denied when X-Forwarded-Uri contains an encoded fragment suffix", + method: "GET", + url: "/public/secret%23/endpoint", + allowed: false, + }, { name: "Route allowed", method: "GET", @@ -2837,6 +2877,18 @@ func TestAllowedRequestWithForwardedUriHeader(t *testing.T) { url: "/skip/auth/routes/wrong/path", allowed: false, }, + { + name: "Route allowed with fragment-free path", + method: "GET", + url: "/foo/public/bar", + allowed: true, + }, + { + name: "Route denied when X-Forwarded-Uri contains an encoded fragment suffix", + method: "GET", + url: "/foo/secret%23/bar", + allowed: false, + }, } for _, tc := range testCases { diff --git a/pkg/requests/util/util.go b/pkg/requests/util/util.go index 7b9b4919..568ebcc6 100644 --- a/pkg/requests/util/util.go +++ b/pkg/requests/util/util.go @@ -47,16 +47,28 @@ func GetRequestURI(req *http.Request) string { // GetRequestPath returns the request URI or X-Forwarded-Uri if present and the // request came from a trusted reverse proxy but always strips the query -// parameters and only returns the pure path. +// parameters and fragment suffixes and only returns the pure path. func GetRequestPath(req *http.Request) string { - uri := GetRequestURI(req) + uri := stripRequestFragment(GetRequestURI(req)) // Parse URI and return only the path component if parsedURL, err := url.Parse(uri); err == nil { - return parsedURL.Path + return stripRequestFragment(parsedURL.Path) } // Fallback: strip query parameters manually + return stripRequestQuery(uri) +} + +func stripRequestFragment(uri string) string { + if idx := strings.Index(uri, "#"); idx != -1 { + return uri[:idx] + } + + return uri +} + +func stripRequestQuery(uri string) string { if idx := strings.Index(uri, "?"); idx != -1 { return uri[:idx] } diff --git a/pkg/requests/util/util_test.go b/pkg/requests/util/util_test.go index ed7a88a6..c4185b35 100644 --- a/pkg/requests/util/util_test.go +++ b/pkg/requests/util/util_test.go @@ -152,6 +152,23 @@ var _ = Describe("Util Suite", func() { Expect(util.GetRequestPath(req)).To(Equal(uriNoQueryParams)) }) + It("drops fragment content from a parsed request path", func() { + // Simulate net/http ParseRequestURI preserving '#' in URL.Path. + req.URL.Path = "/foo/secret#/bar" + req.URL.RawPath = "/foo/secret%23/bar" + Expect(util.GetRequestPath(req)).To(Equal("/foo/secret")) + }) + + It("drops fragment-like suffixes from encoded number signs", func() { + req = httptest.NewRequest( + http.MethodGet, + fmt.Sprintf("%s://%s/foo/secret%%23/bar?query=param", proto, host), + nil, + ) + req = middleware.AddRequestScope(req, &middleware.RequestScope{}) + Expect(util.GetRequestPath(req)).To(Equal("/foo/secret")) + }) + It("ignores X-Forwarded-Uri and returns the URI (without query params)", func() { req.Header.Add("X-Forwarded-Uri", "/some/other/path?query=param") Expect(util.GetRequestPath(req)).To(Equal(uriNoQueryParams)) @@ -175,6 +192,11 @@ var _ = Describe("Util Suite", func() { req.Header.Add("X-Forwarded-Uri", "/some/other/path?query=param") Expect(util.GetRequestPath(req)).To(Equal("/some/other/path")) }) + + It("drops fragment-like suffixes from the X-Forwarded-Uri", func() { + req.Header.Add("X-Forwarded-Uri", "/foo/secret%23/bar?query=param") + Expect(util.GetRequestPath(req)).To(Equal("/foo/secret")) + }) }) }) From 5961fd99b42c3625b8ef08690d38be5cb37f44b0 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 14 Apr 2026 13:12:28 +0200 Subject: [PATCH 45/53] release v7.15.2 (#3413) * update to release version v7.15.2 * doc: add changelog entry for v7.15.2 Signed-off-by: Jan Larwig * fix(deps): override webpackbar to v7 for webpack 5.106.0 compatibility As outlined in https://github.com/facebook/docusaurus/issues/11923 Signed-off-by: Jan Larwig * chore: fix local test files for nginx setup Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Jan Larwig --- CHANGELOG.md | 44 +++++++++++- contrib/local-environment/dex.yaml | 27 ++++---- .../docker-compose-alpha-config.yaml | 2 +- .../docker-compose-gitea.yaml | 2 +- .../docker-compose-keycloak.yaml | 10 +-- .../docker-compose-nginx.yaml | 6 +- .../docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- contrib/local-environment/nginx.conf | 67 +++++++++---------- .../local-environment/oauth2-proxy-nginx.cfg | 2 +- docs/docs/installation.md | 2 +- docs/package.json | 3 + .../version-7.15.x/installation.md | 2 +- 13 files changed, 106 insertions(+), 65 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f227932..320ba697 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,48 @@ ## Breaking Changes +## Changes since v7.15.2 + +# V7.15.2 + +## Release Highlights + +- 🔵 Golang version upgrade to v1.25.9 + - Upgrade of all dependencies to their latest versions + - [CVE-2026-34986](https://nvd.nist.gov/vuln/detail/CVE-2026-34986) + - [CVE-2026-32281](https://nvd.nist.gov/vuln/detail/CVE-2026-32281) + - [CVE-2026-32289](https://nvd.nist.gov/vuln/detail/CVE-2026-32289) + - [CVE-2026-32288](https://nvd.nist.gov/vuln/detail/CVE-2026-32288) + - [CVE-2026-32280](https://nvd.nist.gov/vuln/detail/CVE-2026-32280) + - [CVE-2026-32282](https://nvd.nist.gov/vuln/detail/CVE-2026-32282) + - [CVE-2026-32283](https://nvd.nist.gov/vuln/detail/CVE-2026-32283) +- 🕵️‍♀️ Vulnerabilities have been addressed + +## Important Notes + +We have had security audits performed on OAuth2 Proxy in the past couple of weeks and as a result we have fixed +several CRITICAL vulnerabilities. + +The security vulnerabilities include multiple authentication bypasses and a potential session fixation attack. +For more details and to identify if you are effects, we urge all users of OAuth2 Proxy to read the security +disclosures. + +- (Critical) [GHSA-5hvv-m4w4-gf6v](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-5hvv-m4w4-gf6v) fix: health check user-agent authentication bypass +- (Critical) [GHSA-7x63-xv5r-3p2x](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-7x63-xv5r-3p2x) fix: authentication bypass via X-Forwarded-Uri header spoofing +- (High) [GHSA-pxq7-h93f-9jrg](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-pxq7-h93f-9jrg) fix: fragment evaluation as part of the allowed routes +- (Moderate) [GHSA-c5c4-8r6x-56w3](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-c5c4-8r6x-56w3) fix: email validation bypass via malformed multi-@ email claims + +Furthermore, for improving the security of OAuth2 Proxy we introduced a new flag `--trusted-proxy-ip` that allows users +to explicitly specify trusted reverse proxy IPs for the `X-Forwarded-*` headers. This is an important step to prevent +potential header spoofing attacks and to ensure that OAuth2 Proxy only trusts headers from known and trusted sources. +We highly recommend users to review their deployment architecture and consider using this flag to enhance the security +of their OAuth2 Proxy instances. Check the docs for more details: https://oauth2-proxy.github.io/oauth2-proxy/configuration/overview#proxy-options + +Furthermore, we want to thank everyone who contributed to the audits and reported potential issues to make open source +software like OAuth2 Proxy more secure for everyone. + +## Breaking Changes + ## Changes since v7.15.1 - [#3411](https://github.com/oauth2-proxy/oauth2-proxy/pull/3411) chore(deps): update gomod dependencies (@tuunit) @@ -13,8 +55,8 @@ - [GHSA-f24x-5g9q-753f](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-f24x-5g9q-753f) fix: clear session cookie at beginning of signinpage handler (@fnoehWM / @bella-WI / @tuunit) - [GHSA-5hvv-m4w4-gf6v](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-5hvv-m4w4-gf6v) fix: health check user-agent authentication bypass (@tuunit) - [GHSA-7x63-xv5r-3p2x](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-7x63-xv5r-3p2x) fix: authentication bypass via X-Forwarded-Uri header spoofing (@tuunit) -- [GHSA-c5c4-8r6x-56w3](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-c5c4-8r6x-56w3) fix: email validation bypass via malformed multi-@ email claims (@tuunit) - [GHSA-pxq7-h93f-9jrg](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-pxq7-h93f-9jrg) fix: fragment evaluation as part of the allowed routes (@tuunit) +- [GHSA-c5c4-8r6x-56w3](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-c5c4-8r6x-56w3) fix: email validation bypass via malformed multi-@ email claims (@tuunit) # V7.15.1 diff --git a/contrib/local-environment/dex.yaml b/contrib/local-environment/dex.yaml index f0a2ead4..e3ed0f8f 100644 --- a/contrib/local-environment/dex.yaml +++ b/contrib/local-environment/dex.yaml @@ -6,7 +6,7 @@ storage: type: etcd config: endpoints: - - http://etcd:2379 + - http://etcd:2379 namespace: dex/ web: http: 0.0.0.0:5556 @@ -16,17 +16,18 @@ expiry: signingKeys: "4h" idTokens: "1h" staticClients: -- id: oauth2-proxy - redirectURIs: - # These redirect URIs point to the `--redirect-url` for OAuth2 proxy. - - 'http://oauth2-proxy.localtest.me:4180/oauth2/callback' # For basic proxy example. - - 'http://oauth2-proxy.oauth2-proxy.localhost/oauth2/callback' # For nginx and traefik example. - name: 'OAuth2 Proxy' - secret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK + - id: oauth2-proxy + redirectURIs: + # These redirect URIs point to the `--redirect-url` for OAuth2 proxy. + - "http://oauth2-proxy.localtest.me:4180/oauth2/callback" # For basic proxy example. + - "http://oauth2-proxy.localtest.me:8080/oauth2/callback" # For nginx example. + - "http://oauth2-proxy.oauth2-proxy.localhost/oauth2/callback" # For traefik example. + name: "OAuth2 Proxy" + secret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK enablePasswordDB: true staticPasswords: -- email: "admin@example.com" - # bcrypt hash of the string "password" - hash: "$2a$10$2b2cU8CPhOTaGrs1HRQuAueS7JTT5ZHsHSzYiFPm1leZck7Mc8T4W" - username: "admin" - userID: "08a8684b-db88-4b73-90a9-3cd1661f5466" + - email: "admin@example.com" + # bcrypt hash of the string "password" + hash: "$2a$10$2b2cU8CPhOTaGrs1HRQuAueS7JTT5ZHsHSzYiFPm1leZck7Mc8T4W" + username: "admin" + userID: "08a8684b-db88-4b73-90a9-3cd1661f5466" diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index 515c42e0..2dde7345 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -14,7 +14,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.2 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 3e57ef2d..17d707fb 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.2 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index ba3db49a..70d2042b 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -10,11 +10,11 @@ # # Access http://oauth2-proxy.localtest.me:4180 to initiate a login cycle using user=admin@example.com, password=password # Access http://keycloak.localtest.me:9080 with the same credentials to check out the settings -version: '3.0' +version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.2 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: @@ -43,9 +43,9 @@ services: image: keycloak/keycloak:25.0 hostname: keycloak command: - - 'start-dev' - - '--http-port=9080' - - '--import-realm' + - "start-dev" + - "--http-port=9080" + - "--import-realm" volumes: - ./keycloak:/opt/keycloak/data/import environment: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 23138eb4..2aa403ec 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,12 +22,12 @@ version: "3.0" services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.1 - ports: - - 4180:4180/tcp + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.2 + ports: [] hostname: oauth2-proxy container_name: oauth2-proxy command: --config /oauth2-proxy.cfg + restart: unless-stopped volumes: - "./oauth2-proxy-nginx.cfg:/oauth2-proxy.cfg" networks: diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 94d9239b..302f1a42 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.2 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 4832eb92..7630167d 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.2 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/nginx.conf b/contrib/local-environment/nginx.conf index f3761387..0e7bf7b4 100644 --- a/contrib/local-environment/nginx.conf +++ b/contrib/local-environment/nginx.conf @@ -1,49 +1,44 @@ -# Reverse proxy to oauth2-proxy -server { - listen 8080; - server_name oauth2-proxy.localtest.me; - - location / { - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-Uri $request_uri; - - proxy_pass http://oauth2-proxy:4180/; - } -} - # Reverse proxy to httpbin server { listen 8080; - server_name httpbin.localtest.me; + server_name oauth2-proxy.localtest.me; - auth_request /internal-auth/oauth2/auth; + location /oauth2/ { + proxy_pass http://oauth2-proxy:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; + proxy_set_header X-Auth-Request-Redirect $request_uri; + } - # On 401, redirect to the sign_in page via a named location - # This ensures a proper 302 redirect that browsers will follow - error_page 401 = @oauth2_signin; + location = /oauth2/auth { + proxy_pass http://oauth2-proxy:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; + # nginx auth_request includes headers but not body + proxy_set_header Content-Length ""; + proxy_pass_request_body off; + } location / { + auth_request /oauth2/auth; + error_page 401 = @oauth2_signin; + + # pass information via X-User and X-Email headers to backend, + # requires running with --set-xauthrequest flag + auth_request_set $user $upstream_http_x_auth_request_user; + auth_request_set $email $upstream_http_x_auth_request_email; + proxy_set_header X-User $user; + proxy_set_header X-Email $email; + proxy_pass http://httpbin/; + # or "root /path/to/site;" or "fastcgi_pass ..." etc } - # Named location for OAuth2 sign-in redirect - # Returns a proper 302 that works with --skip-provider-button + # Named location for handling OAuth2 sign-in redirects + # This ensures the browser receives a proper 302 redirect that it will follow location @oauth2_signin { - return 302 http://oauth2-proxy.localtest.me:8080/oauth2/sign_in?rd=$scheme://$host$request_uri; - } - - # auth_request must be a URI so this allows an internal path to then proxy to - # the real auth_request path. - # The trailing /'s are required so that nginx strips the prefix before proxying. - location /internal-auth/ { - internal; # Ensure external users can't access this path - - # Make sure the OAuth2 Proxy knows where the original request came from. - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-Uri $request_uri; - - proxy_pass http://oauth2-proxy:4180/; + return 302 /oauth2/sign_in?rd=$scheme://$http_host$request_uri; } } diff --git a/contrib/local-environment/oauth2-proxy-nginx.cfg b/contrib/local-environment/oauth2-proxy-nginx.cfg index 0a383ab7..2565c226 100644 --- a/contrib/local-environment/oauth2-proxy-nginx.cfg +++ b/contrib/local-environment/oauth2-proxy-nginx.cfg @@ -9,7 +9,7 @@ whitelist_domains=[".localtest.me"] # Required to allow redirection back to orig # dex provider client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK" client_id="oauth2-proxy" -redirect_url="http://oauth2-proxy.localtest.me:4180/oauth2/callback" +redirect_url="http://oauth2-proxy.localtest.me:8080/oauth2/callback" oidc_issuer_url="http://dex.localtest.me:5556/dex" provider="oidc" diff --git a/docs/docs/installation.md b/docs/docs/installation.md index d329bd55..7898f70c 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.15.1`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.15.2`) b. Using Go to install the latest release ```bash diff --git a/docs/package.json b/docs/package.json index a288a213..0bb4b494 100644 --- a/docs/package.json +++ b/docs/package.json @@ -42,5 +42,8 @@ }, "engines": { "node": ">=18.0" + }, + "overrides" : { + "webpackbar" : "^7.0.0" } } diff --git a/docs/versioned_docs/version-7.15.x/installation.md b/docs/versioned_docs/version-7.15.x/installation.md index d329bd55..7898f70c 100644 --- a/docs/versioned_docs/version-7.15.x/installation.md +++ b/docs/versioned_docs/version-7.15.x/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.15.1`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.15.2`) b. Using Go to install the latest release ```bash From 65037b086c783903a8dfc31a6f16a995ff8cf007 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 17 Apr 2026 10:56:42 +0200 Subject: [PATCH 46/53] change affiliation --- MAINTAINERS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MAINTAINERS.md b/MAINTAINERS.md index 71ec0fdc..2b98816c 100644 --- a/MAINTAINERS.md +++ b/MAINTAINERS.md @@ -6,7 +6,7 @@ by our [project governance](GOVERNANCE.md). | Name | GitHub Handle | Domains of reponsibility | Email Alias | Affiliation | | ---------------- | ------------------------------------------------------ | ------------------------ | -------------------------- | ----------- | | Joel Speed | [@JoelSpeed](https://github.com/joelspeed) | Governance, Core | joel@oauth2-proxy.dev | Red Hat | -| Jan Larwig | [@tuunit](https://github.com/tuunit) | Governance, Core | jan@oauth2-proxy.dev | IONOS Cloud | +| Jan Larwig | [@tuunit](https://github.com/tuunit) | Governance, Core | jan@oauth2-proxy.dev | STACKIT | | JJ Łakis | [@jjlakis](https://github.com/jjlakis) | Provider | jj@oauth2-proxy.dev | - | | Koen van Zuijlen | [@kvanzuijlen](https://github.com/kvanzuijlen) | CI | koen@oauth2-proxy.dev | - | | Pierluigi Lenoci | [@pierluigilenoci](https://github.com/pierluigilenoci) | Helm | pierluigi@oauth2-proxy.dev | SAP | From 9a14186a26cb7a12e51d39ed3a10ff0299d5e354 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Mon, 8 Jun 2026 12:54:40 +0200 Subject: [PATCH 47/53] chore(goconsts): use proper constants for http methods Signed-off-by: Jan Larwig --- oauthproxy.go | 4 +- oauthproxy_test.go | 150 +++++++++---------- pkg/apis/options/load.go | 2 +- pkg/authentication/hmacauth/hmacauth_test.go | 2 +- pkg/requests/builder_test.go | 30 ++-- providers/azure.go | 4 +- providers/google.go | 4 +- providers/logingov.go | 3 +- providers/ms_entra_id.go | 3 +- providers/provider_default.go | 3 +- providers/srht.go | 3 +- 11 files changed, 106 insertions(+), 102 deletions(-) diff --git a/oauthproxy.go b/oauthproxy.go index e2357c8d..f8dc5471 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -587,7 +587,7 @@ func (p *OAuthProxy) ErrorPage(rw http.ResponseWriter, req *http.Request, code i // IsAllowedRequest is used to check if auth should be skipped for this request func (p *OAuthProxy) IsAllowedRequest(req *http.Request) bool { - isPreflightRequestAllowed := p.skipAuthPreflight && req.Method == "OPTIONS" + isPreflightRequestAllowed := p.skipAuthPreflight && req.Method == http.MethodOptions return isPreflightRequestAllowed || p.isAllowedRoute(req) || p.isTrustedIP(req) } @@ -669,7 +669,7 @@ func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code // ManualSignIn handles basic auth logins to the proxy func (p *OAuthProxy) ManualSignIn(req *http.Request) (string, bool, int) { - if req.Method != "POST" || p.basicAuthValidator == nil { + if req.Method != http.MethodPost || p.basicAuthValidator == nil { return "", false, http.StatusOK } user := req.FormValue("username") diff --git a/oauthproxy_test.go b/oauthproxy_test.go index e1235a4e..b3271e5b 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -54,7 +54,7 @@ func TestRobotsTxt(t *testing.T) { t.Fatal(err) } rw := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "/robots.txt", nil) + req, _ := http.NewRequest(http.MethodGet, "/robots.txt", nil) proxy.ServeHTTP(rw, req) assert.Equal(t, 200, rw.Code) assert.Equal(t, "User-agent: *\nDisallow: /\n", rw.Body.String()) @@ -241,7 +241,7 @@ func TestBasicAuthPassword(t *testing.T) { // Save the required session rw := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequest(http.MethodGet, "/", nil) err = proxy.sessionStore.Save(rw, req, &sessions.SessionState{ Email: emailAddress, }) @@ -250,7 +250,7 @@ func TestBasicAuthPassword(t *testing.T) { // Extract the cookie value to inject into the test request cookie := rw.Header().Values("Set-Cookie")[0] - req, _ = http.NewRequest("GET", "/", nil) + req, _ = http.NewRequest(http.MethodGet, "/", nil) req.Header.Set("Cookie", cookie) rw = httptest.NewRecorder() proxy.ServeHTTP(rw, req) @@ -300,14 +300,14 @@ func TestPassGroupsHeadersWithGroups(t *testing.T) { // Save the required session rw := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequest(http.MethodGet, "/", nil) err = proxy.sessionStore.Save(rw, req, session) assert.NoError(t, err) // Extract the cookie value to inject into the test request cookie := rw.Header().Values("Set-Cookie")[0] - req, _ = http.NewRequest("GET", "/", nil) + req, _ = http.NewRequest(http.MethodGet, "/", nil) req.Header.Set("Cookie", cookie) rw = httptest.NewRecorder() proxy.ServeHTTP(rw, req) @@ -457,7 +457,7 @@ func (patTest *PassAccessTokenTest) getEndpointWithCookie(cookie string, endpoin return 0, "" } - req, err := http.NewRequest("GET", endpoint, strings.NewReader("")) + req, err := http.NewRequest(http.MethodGet, endpoint, strings.NewReader("")) if err != nil { return 0, "" } @@ -608,7 +608,7 @@ func NewSignInPageTest(skipProvider bool) (*SignInPageTest, error) { func (sipTest *SignInPageTest) GetEndpoint(endpoint string) (int, string) { rw := httptest.NewRecorder() - req, _ := http.NewRequest("GET", endpoint, strings.NewReader("")) + req, _ := http.NewRequest(http.MethodGet, endpoint, strings.NewReader("")) sipTest.proxy.ServeHTTP(rw, req) return rw.Code, rw.Body.String() } @@ -894,7 +894,7 @@ func NewProcessCookieTest(opts ProcessCookieTestOpts, modifiers ...OptionsModifi // access_token validation. pcTest.proxy.CookieOptions.Refresh = time.Duration(0) pcTest.rw = httptest.NewRecorder() - pcTest.req, _ = http.NewRequest("GET", "/", strings.NewReader("")) + pcTest.req, _ = http.NewRequest(http.MethodGet, "/", strings.NewReader("")) pcTest.validateUser = true return &pcTest, nil } @@ -1027,7 +1027,7 @@ func NewUserInfoEndpointTest() (*ProcessCookieTest, error) { if err != nil { return nil, err } - pcTest.req, _ = http.NewRequest("GET", + pcTest.req, _ = http.NewRequest(http.MethodGet, pcTest.opts.ProxyPrefix+"/userinfo", nil) return pcTest, nil } @@ -1135,7 +1135,7 @@ func NewAuthOnlyEndpointTest(querystring string, modifiers ...OptionsModifier) ( return nil, err } pcTest.req, _ = http.NewRequest( - "GET", + http.MethodGet, fmt.Sprintf("%s/auth%s", pcTest.opts.ProxyPrefix, querystring), nil) return pcTest, nil @@ -1274,7 +1274,7 @@ func TestAuthOnlyEndpointSetXAuthRequestHeaders(t *testing.T) { pcTest.validateUser = true pcTest.rw = httptest.NewRecorder() - pcTest.req, _ = http.NewRequest("GET", + pcTest.req, _ = http.NewRequest(http.MethodGet, pcTest.opts.ProxyPrefix+authOnlyPath, nil) created := time.Now() @@ -1367,7 +1367,7 @@ func TestAuthOnlyEndpointSetBasicAuthTrueRequestHeaders(t *testing.T) { pcTest.validateUser = true pcTest.rw = httptest.NewRecorder() - pcTest.req, _ = http.NewRequest("GET", + pcTest.req, _ = http.NewRequest(http.MethodGet, pcTest.opts.ProxyPrefix+authOnlyPath, nil) created := time.Now() @@ -1447,7 +1447,7 @@ func TestAuthOnlyEndpointSetBasicAuthFalseRequestHeaders(t *testing.T) { pcTest.validateUser = true pcTest.rw = httptest.NewRecorder() - pcTest.req, _ = http.NewRequest("GET", + pcTest.req, _ = http.NewRequest(http.MethodGet, pcTest.opts.ProxyPrefix+authOnlyPath, nil) created := time.Now() @@ -1495,7 +1495,7 @@ func TestAuthSkippedForPreflightRequests(t *testing.T) { } proxy.provider = NewTestProvider(upstreamURL, "") rw := httptest.NewRecorder() - req, _ := http.NewRequest("OPTIONS", "/preflight-request", nil) + req, _ := http.NewRequest(http.MethodOptions, "/preflight-request", nil) proxy.ServeHTTP(rw, req) assert.Equal(t, 200, rw.Code) @@ -1652,19 +1652,19 @@ func TestRequestSignature(t *testing.T) { resp string }{ "No request signature": { - method: "GET", + method: http.MethodGet, body: "", key: "", resp: "no signature received", }, "Get request": { - method: "GET", + method: http.MethodGet, body: "", key: "7d9e1aa87a5954e6f9fc59266b3af9d7c35fda2d", resp: "signatures match", }, "Post request": { - method: "POST", + method: http.MethodPost, body: `{ "hello": "world!" }`, key: "d90df39e2d19282840252612dd7c81421a372f61", resp: "signatures match", @@ -2189,7 +2189,7 @@ func TestTrustedIPs(t *testing.T) { reverseProxy: false, realClientIPHeader: "X-Real-IP", // Default value req: func() *http.Request { - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequest(http.MethodGet, "/", nil) return req }(), expectTrusted: false, @@ -2201,7 +2201,7 @@ func TestTrustedIPs(t *testing.T) { reverseProxy: false, realClientIPHeader: "X-Real-IP", req: func() *http.Request { - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequest(http.MethodGet, "/", nil) req.RemoteAddr = "@" return req }(), @@ -2214,7 +2214,7 @@ func TestTrustedIPs(t *testing.T) { reverseProxy: false, realClientIPHeader: "X-Real-IP", req: func() *http.Request { - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequest(http.MethodGet, "/", nil) req.RemoteAddr = "@" return req }(), @@ -2227,7 +2227,7 @@ func TestTrustedIPs(t *testing.T) { reverseProxy: false, realClientIPHeader: "X-Real-IP", // Default value req: func() *http.Request { - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequest(http.MethodGet, "/", nil) req.RemoteAddr = "127.0.0.1:43670" return req }(), @@ -2240,7 +2240,7 @@ func TestTrustedIPs(t *testing.T) { reverseProxy: true, realClientIPHeader: "X-Real-IP", // Default value req: func() *http.Request { - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequest(http.MethodGet, "/", nil) req.RemoteAddr = "127.0.0.1:44324" return req }(), @@ -2253,7 +2253,7 @@ func TestTrustedIPs(t *testing.T) { reverseProxy: true, realClientIPHeader: "X-Forwarded-For", req: func() *http.Request { - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequest(http.MethodGet, "/", nil) req.Header.Add("X-Forwarded-For", "127.0.0.1") return req }(), @@ -2266,7 +2266,7 @@ func TestTrustedIPs(t *testing.T) { reverseProxy: true, realClientIPHeader: "X-Forwarded-For", req: func() *http.Request { - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequest(http.MethodGet, "/", nil) req.Header.Add("X-Forwarded-For", "::1") return req }(), @@ -2279,7 +2279,7 @@ func TestTrustedIPs(t *testing.T) { reverseProxy: true, realClientIPHeader: "X-Forwarded-For", req: func() *http.Request { - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequest(http.MethodGet, "/", nil) req.Header.Add("X-Forwarded-For", "12.34.56.78") return req }(), @@ -2292,7 +2292,7 @@ func TestTrustedIPs(t *testing.T) { reverseProxy: true, realClientIPHeader: "X-Forwarded-For", req: func() *http.Request { - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequest(http.MethodGet, "/", nil) req.Header.Add("X-Forwarded-For", "::2") return req }(), @@ -2305,7 +2305,7 @@ func TestTrustedIPs(t *testing.T) { reverseProxy: true, realClientIPHeader: "X-Forwarded-For", req: func() *http.Request { - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequest(http.MethodGet, "/", nil) req.Header.Add("X-Real-IP", "::1") return req }(), @@ -2318,7 +2318,7 @@ func TestTrustedIPs(t *testing.T) { reverseProxy: true, realClientIPHeader: "X-Forwarded-For", req: func() *http.Request { - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequest(http.MethodGet, "/", nil) req.Header.Add("X-Forwarded-For", "adsfljk29242as!!") return req }(), @@ -2331,7 +2331,7 @@ func TestTrustedIPs(t *testing.T) { reverseProxy: false, realClientIPHeader: "X-Real-IP", req: func() *http.Request { - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequest(http.MethodGet, "/", nil) req.RemoteAddr = "adsfljk29242as!!" return req }(), @@ -2427,12 +2427,12 @@ func Test_buildRoutesAllowlist(t *testing.T) { }, expectedRoutes: []expectedAllowedRoute{ { - method: "GET", + method: http.MethodGet, negate: false, regexString: "^/foo/bar", }, { - method: "POST", + method: http.MethodPost, negate: false, regexString: "^/baz/[0-9]+/thing", }, @@ -2485,11 +2485,11 @@ func Test_buildRoutesAllowlist(t *testing.T) { regexString: "^/baz/[0-9]+/thing/regex", }, { - method: "GET", + method: http.MethodGet, regexString: "^/foo/bar", }, { - method: "POST", + method: http.MethodPost, regexString: "^/baz/[0-9]+/thing", }, { @@ -2641,7 +2641,7 @@ func TestApiRoutes(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - req, err := http.NewRequest("GET", tc.url, nil) + req, err := http.NewRequest(http.MethodGet, tc.url, nil) req.Header.Set("Accept", tc.contentType) assert.NoError(t, err) @@ -2700,37 +2700,37 @@ func TestAllowedRequest(t *testing.T) { }{ { name: "Regex GET allowed", - method: "GET", + method: http.MethodGet, url: "/skip/auth/regex", allowed: true, }, { name: "Regex POST allowed ", - method: "POST", + method: http.MethodPost, url: "/skip/auth/regex", allowed: true, }, { name: "Regex denied", - method: "GET", + method: http.MethodGet, url: "/wrong/denied", allowed: false, }, { name: "Regex allowed with fragment-free path", - method: "GET", + method: http.MethodGet, url: "/public/legit/endpoint", allowed: true, }, { name: "Regex denied when path contains encoded fragment suffix", - method: "GET", + method: http.MethodGet, url: "/public/secret%23/endpoint", allowed: false, }, { name: "Route allowed", - method: "GET", + method: http.MethodGet, url: "/skip/auth/routes/get", allowed: true, }, @@ -2742,25 +2742,25 @@ func TestAllowedRequest(t *testing.T) { }, { name: "Route denied with wrong path", - method: "GET", + method: http.MethodGet, url: "/skip/auth/routes/wrong/path", allowed: false, }, { name: "Route denied with wrong path and method", - method: "POST", + method: http.MethodPost, url: "/skip/auth/routes/wrong/path", allowed: false, }, { name: "Route allowed with fragment-free path", - method: "GET", + method: http.MethodGet, url: "/foo/public/bar", allowed: true, }, { name: "Route denied when path contains encoded fragment suffix", - method: "GET", + method: http.MethodGet, url: "/foo/secret%23/bar", allowed: false, }, @@ -2825,37 +2825,37 @@ func TestAllowedRequestWithForwardedUriHeader(t *testing.T) { }{ { name: "Regex GET allowed", - method: "GET", + method: http.MethodGet, url: "/skip/auth/regex", allowed: true, }, { name: "Regex POST allowed ", - method: "POST", + method: http.MethodPost, url: "/skip/auth/regex", allowed: true, }, { name: "Regex denied", - method: "GET", + method: http.MethodGet, url: "/wrong/denied", allowed: false, }, { name: "Regex allowed with fragment-free path", - method: "GET", + method: http.MethodGet, url: "/public/legit/endpoint", allowed: true, }, { name: "Regex denied when X-Forwarded-Uri contains an encoded fragment suffix", - method: "GET", + method: http.MethodGet, url: "/public/secret%23/endpoint", allowed: false, }, { name: "Route allowed", - method: "GET", + method: http.MethodGet, url: "/skip/auth/routes/get", allowed: true, }, @@ -2867,25 +2867,25 @@ func TestAllowedRequestWithForwardedUriHeader(t *testing.T) { }, { name: "Route denied with wrong path", - method: "GET", + method: http.MethodGet, url: "/skip/auth/routes/wrong/path", allowed: false, }, { name: "Route denied with wrong path and method", - method: "POST", + method: http.MethodPost, url: "/skip/auth/routes/wrong/path", allowed: false, }, { name: "Route allowed with fragment-free path", - method: "GET", + method: http.MethodGet, url: "/foo/public/bar", allowed: true, }, { name: "Route denied when X-Forwarded-Uri contains an encoded fragment suffix", - method: "GET", + method: http.MethodGet, url: "/foo/secret%23/bar", allowed: false, }, @@ -2986,37 +2986,37 @@ func TestAllowedRequestNegateWithoutMethod(t *testing.T) { }{ { name: "Some static file allowed", - method: "GET", + method: http.MethodGet, url: "/static/file.txt", allowed: true, }, { name: "POST to contact form allowed", - method: "POST", + method: http.MethodPost, url: "/contact", allowed: true, }, { name: "Regex POST allowed", - method: "POST", + method: http.MethodPost, url: "/api/public-entity", allowed: true, }, { name: "Regex POST with trailing slash allowed", - method: "POST", + method: http.MethodPost, url: "/api/public-entity/", allowed: true, }, { name: "Regex GET api route denied", - method: "GET", + method: http.MethodGet, url: "/api/users", allowed: false, }, { name: "Regex POST api route denied", - method: "POST", + method: http.MethodPost, url: "/api/users", allowed: false, }, @@ -3086,37 +3086,37 @@ func TestAllowedRequestNegateWithMethod(t *testing.T) { }{ { name: "Some static file allowed", - method: "GET", + method: http.MethodGet, url: "/static/file.txt", allowed: true, }, { name: "POST to contact form not allowed", - method: "POST", + method: http.MethodPost, url: "/contact", allowed: false, }, { name: "Regex POST allowed", - method: "POST", + method: http.MethodPost, url: "/api/public-entity", allowed: true, }, { name: "Regex POST with trailing slash allowed", - method: "POST", + method: http.MethodPost, url: "/api/public-entity/", allowed: true, }, { name: "Regex GET api route denied", - method: "GET", + method: http.MethodGet, url: "/api/users", allowed: false, }, { name: "Regex POST api route denied", - method: "POST", + method: http.MethodPost, url: "/api/users", allowed: false, }, @@ -3256,7 +3256,7 @@ func TestProxyAllowedGroups(t *testing.T) { t.Fatal(err) } - test.req, _ = http.NewRequest("GET", fmt.Sprintf("/%s", tt.querystring), nil) + test.req, _ = http.NewRequest(http.MethodGet, fmt.Sprintf("/%s", tt.querystring), nil) test.req.Header.Add("accept", applicationJSON) err = test.SaveSession(session) @@ -3400,7 +3400,7 @@ func TestAuthOnlyAllowedGroupsWithSkipMethods(t *testing.T) { { name: "UserWithGroupSkipAuthPreflight", groups: []string{"a", "c"}, - method: "OPTIONS", + method: http.MethodOptions, ip: "1.2.3.5:43670", withSession: true, expectedStatusCode: http.StatusAccepted, @@ -3408,7 +3408,7 @@ func TestAuthOnlyAllowedGroupsWithSkipMethods(t *testing.T) { { name: "UserWithGroupTrustedIp", groups: []string{"a", "c"}, - method: "GET", + method: http.MethodGet, ip: "1.2.3.4:43670", withSession: true, expectedStatusCode: http.StatusAccepted, @@ -3416,7 +3416,7 @@ func TestAuthOnlyAllowedGroupsWithSkipMethods(t *testing.T) { { name: "UserWithoutGroupSkipAuthPreflight", groups: []string{"c"}, - method: "OPTIONS", + method: http.MethodOptions, ip: "1.2.3.5:43670", withSession: true, expectedStatusCode: http.StatusForbidden, @@ -3424,21 +3424,21 @@ func TestAuthOnlyAllowedGroupsWithSkipMethods(t *testing.T) { { name: "UserWithoutGroupTrustedIp", groups: []string{"c"}, - method: "GET", + method: http.MethodGet, ip: "1.2.3.4:43670", withSession: true, expectedStatusCode: http.StatusForbidden, }, { name: "UserWithoutSessionSkipAuthPreflight", - method: "OPTIONS", + method: http.MethodOptions, ip: "1.2.3.5:43670", withSession: false, expectedStatusCode: http.StatusAccepted, }, { name: "UserWithoutSessionTrustedIp", - method: "GET", + method: http.MethodGet, ip: "1.2.3.4:43670", withSession: false, expectedStatusCode: http.StatusAccepted, @@ -3790,14 +3790,14 @@ func TestIdTokenPlaceholderInSignOut(t *testing.T) { // Save the required session rw := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "/", nil) + req, _ := http.NewRequest(http.MethodGet, "/", nil) err = proxy.sessionStore.Save(rw, req, session) assert.NoError(t, err) rw = httptest.NewRecorder() rdUrl := url.QueryEscape("https://my-oidc-provider.example.com/sign_out_page?id_token_hint={id_token}&post_logout_redirect_uri=https://my-app.example.com/") - req, _ = http.NewRequest("GET", "/oauth2/sign_out?rd="+rdUrl, nil) + req, _ = http.NewRequest(http.MethodGet, "/oauth2/sign_out?rd="+rdUrl, nil) req = middlewareapi.AddRequestScope(req, &middlewareapi.RequestScope{ RequestID: "11111111-2222-4333-8444-555555555555", Session: session, diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index d0dd22df..f5b300b0 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -145,7 +145,7 @@ func loadAndSubstituteEnvs(configFileName string) ([]byte, error) { func registerFlags(v *viper.Viper, prefix string, flagSet *pflag.FlagSet, options interface{}) error { val := reflect.ValueOf(options) var typ reflect.Type - if val.Kind() == reflect.Ptr { + if val.Kind() == reflect.Pointer { typ = val.Elem().Type() } else { typ = val.Type() diff --git a/pkg/authentication/hmacauth/hmacauth_test.go b/pkg/authentication/hmacauth/hmacauth_test.go index 84f257d9..00cce008 100644 --- a/pkg/authentication/hmacauth/hmacauth_test.go +++ b/pkg/authentication/hmacauth/hmacauth_test.go @@ -286,7 +286,7 @@ func TestSendAuthenticatedPostRequestToServer(t *testing.T) { upstream := httptest.NewServer( http.HandlerFunc(authenticator.Authenticate)) - req, err := http.NewRequest("POST", upstream.URL+"/foo/bar", + req, err := http.NewRequest(http.MethodPost, upstream.URL+"/foo/bar", io.NopCloser(&fakeNetConn{reqBody: payload})) if err != nil { panic(err) diff --git a/pkg/requests/builder_test.go b/pkg/requests/builder_test.go index fc12209f..4fd85f5f 100644 --- a/pkg/requests/builder_test.go +++ b/pkg/requests/builder_test.go @@ -31,7 +31,7 @@ var _ = Describe("Builder suite", func() { Context("with a basic request", func() { assertSuccessfulRequest(getBuilder, testHTTPRequest{ - Method: "GET", + Method: http.MethodGet, Header: baseHeaders, Body: []byte{}, RequestURI: "/json/path", @@ -52,7 +52,7 @@ var _ = Describe("Builder suite", func() { }) assertSuccessfulRequest(getBuilder, testHTTPRequest{ - Method: "GET", + Method: http.MethodGet, Header: baseHeaders, Body: []byte{}, RequestURI: "/json/path", @@ -78,7 +78,7 @@ var _ = Describe("Builder suite", func() { }) assertSuccessfulRequest(getBuilder, testHTTPRequest{ - Method: "GET", + Method: http.MethodGet, Header: header, Body: []byte(body), RequestURI: "/json/path", @@ -93,11 +93,11 @@ var _ = Describe("Builder suite", func() { BeforeEach(func() { buf := bytes.NewBuffer([]byte(body)) - b = b.WithMethod("POST").WithBody(buf) + b = b.WithMethod(http.MethodPost).WithBody(buf) }) assertSuccessfulRequest(getBuilder, testHTTPRequest{ - Method: "POST", + Method: http.MethodPost, Header: header, Body: []byte(body), RequestURI: "/json/path", @@ -109,11 +109,11 @@ var _ = Describe("Builder suite", func() { header.Set("Content-Length", "0") BeforeEach(func() { - b = b.WithMethod("POST") + b = b.WithMethod(http.MethodPost) }) assertSuccessfulRequest(getBuilder, testHTTPRequest{ - Method: "POST", + Method: http.MethodPost, Header: header, Body: []byte{}, RequestURI: "/json/path", @@ -122,11 +122,11 @@ var _ = Describe("Builder suite", func() { Context("OPTIONS", func() { BeforeEach(func() { - b = b.WithMethod("OPTIONS") + b = b.WithMethod(http.MethodOptions) }) assertSuccessfulRequest(getBuilder, testHTTPRequest{ - Method: "OPTIONS", + Method: http.MethodOptions, Header: baseHeaders, Body: []byte{}, RequestURI: "/json/path", @@ -152,7 +152,7 @@ var _ = Describe("Builder suite", func() { }) assertSuccessfulRequest(getBuilder, testHTTPRequest{ - Method: "GET", + Method: http.MethodGet, Header: header, Body: []byte{}, RequestURI: "/json/path", @@ -170,7 +170,7 @@ var _ = Describe("Builder suite", func() { }) assertSuccessfulRequest(getBuilder, testHTTPRequest{ - Method: "GET", + Method: http.MethodGet, Header: replacementHeaders, Body: []byte{}, RequestURI: "/json/path", @@ -190,7 +190,7 @@ var _ = Describe("Builder suite", func() { }) assertSuccessfulRequest(getBuilder, testHTTPRequest{ - Method: "GET", + Method: http.MethodGet, Header: replacementHeaders, Body: []byte{}, RequestURI: "/json/path", @@ -205,7 +205,7 @@ var _ = Describe("Builder suite", func() { }) assertSuccessfulRequest(getBuilder, testHTTPRequest{ - Method: "GET", + Method: http.MethodGet, Header: header, Body: []byte{}, RequestURI: "/json/path", @@ -219,12 +219,12 @@ var _ = Describe("Builder suite", func() { result := b.Do() Expect(result.Error()).ToNot(HaveOccurred()) - b.WithMethod("POST") + b.WithMethod(http.MethodPost) }) Context("should not redo the request", func() { assertSuccessfulRequest(getBuilder, testHTTPRequest{ - Method: "GET", + Method: http.MethodGet, Header: baseHeaders, Body: []byte{}, RequestURI: "/json/path", diff --git a/providers/azure.go b/providers/azure.go index b5610cfa..ff22ebc3 100644 --- a/providers/azure.go +++ b/providers/azure.go @@ -166,7 +166,7 @@ func (p *AzureProvider) Redeem(ctx context.Context, redirectURL, code, codeVerif err = requests.New(p.RedeemURL.String()). WithContext(ctx). - WithMethod("POST"). + WithMethod(http.MethodPost). WithBody(bytes.NewBufferString(params.Encode())). SetHeader("Content-Type", "application/x-www-form-urlencoded"). Do(). @@ -334,7 +334,7 @@ func (p *AzureProvider) redeemRefreshToken(ctx context.Context, s *sessions.Sess err = requests.New(p.RedeemURL.String()). WithContext(ctx). - WithMethod("POST"). + WithMethod(http.MethodPost). WithBody(bytes.NewBufferString(params.Encode())). SetHeader("Content-Type", "application/x-www-form-urlencoded"). Do(). diff --git a/providers/google.go b/providers/google.go index d8e4dec8..d28fb62d 100644 --- a/providers/google.go +++ b/providers/google.go @@ -219,7 +219,7 @@ func (p *GoogleProvider) Redeem(ctx context.Context, redirectURL, code, codeVeri err = requests.New(p.RedeemURL.String()). WithContext(ctx). - WithMethod("POST"). + WithMethod(http.MethodPost). WithBody(bytes.NewBufferString(params.Encode())). SetHeader("Content-Type", "application/x-www-form-urlencoded"). Do(). @@ -543,7 +543,7 @@ func (p *GoogleProvider) redeemRefreshToken(ctx context.Context, s *sessions.Ses err = requests.New(p.RedeemURL.String()). WithContext(ctx). - WithMethod("POST"). + WithMethod(http.MethodPost). WithBody(bytes.NewBufferString(params.Encode())). SetHeader("Content-Type", "application/x-www-form-urlencoded"). Do(). diff --git a/providers/logingov.go b/providers/logingov.go index eb848218..e80989f4 100644 --- a/providers/logingov.go +++ b/providers/logingov.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "math/big" + "net/http" "net/url" "os" "time" @@ -237,7 +238,7 @@ func (p *LoginGovProvider) Redeem(ctx context.Context, _, code, codeVerifier str } err = requests.New(p.RedeemURL.String()). WithContext(ctx). - WithMethod("POST"). + WithMethod(http.MethodPost). WithBody(bytes.NewBufferString(params.Encode())). SetHeader("Content-Type", "application/x-www-form-urlencoded"). Do(). diff --git a/providers/ms_entra_id.go b/providers/ms_entra_id.go index f30176fd..97a18e48 100644 --- a/providers/ms_entra_id.go +++ b/providers/ms_entra_id.go @@ -5,6 +5,7 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" "os" "regexp" @@ -304,7 +305,7 @@ func (p *MicrosoftEntraIDProvider) checkTenantMatchesTenantList(tenant string, a func (p *MicrosoftEntraIDProvider) fetchToken(ctx context.Context, params url.Values) (*oauth2.Token, error) { resp := requests.New(p.RedeemURL.String()). WithContext(ctx). - WithMethod("POST"). + WithMethod(http.MethodPost). WithBody(bytes.NewBufferString(params.Encode())). SetHeader("Content-Type", "application/x-www-form-urlencoded"). Do() diff --git a/providers/provider_default.go b/providers/provider_default.go index dbd93c91..8db79b54 100644 --- a/providers/provider_default.go +++ b/providers/provider_default.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + "net/http" "net/url" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" @@ -71,7 +72,7 @@ func (p *ProviderData) Redeem(ctx context.Context, redirectURL, code, codeVerifi result := requests.New(p.RedeemURL.String()). WithContext(ctx). - WithMethod("POST"). + WithMethod(http.MethodPost). WithBody(bytes.NewBufferString(params.Encode())). SetHeader("Content-Type", "application/x-www-form-urlencoded"). Do() diff --git a/providers/srht.go b/providers/srht.go index aa72229c..e927629e 100644 --- a/providers/srht.go +++ b/providers/srht.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "fmt" + "net/http" "net/url" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" @@ -75,7 +76,7 @@ func NewSourceHutProvider(p *ProviderData) *SourceHutProvider { func (p *SourceHutProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error { json, err := requests.New(p.ProfileURL.String()). WithContext(ctx). - WithMethod("POST"). + WithMethod(http.MethodPost). SetHeader("Content-Type", "application/json"). SetHeader("Authorization", "Bearer "+s.AccessToken). WithBody(bytes.NewBufferString(`{"query": "{ me { username, email } }"}`)). From 0de18825f64ddd37dd6795c33fef69487e9f9868 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Mon, 8 Jun 2026 13:57:21 +0200 Subject: [PATCH 48/53] chore(deps): bump Go to 1.26 and migrate upstream reverse proxies to Rewrite Signed-off-by: Jan Larwig --- .devcontainer/Dockerfile | 2 +- CHANGELOG.md | 2 + go.mod | 60 +++++++++++------------ go.sum | 62 ++++++++++++++++++++++++ pkg/upstream/http.go | 75 ++++++++++++++++++++++------- pkg/upstream/http_test.go | 56 ++++++++++++++++++++- pkg/upstream/proxy_test.go | 2 +- pkg/upstream/upstream_suite_test.go | 2 +- pkg/validation/sessions_test.go | 4 +- 9 files changed, 211 insertions(+), 54 deletions(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 7b6d5bba..022c919c 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/vscode/devcontainers/go:1-1.25 +FROM mcr.microsoft.com/vscode/devcontainers/go:1-1.26 SHELL ["/bin/bash", "-o", "pipefail", "-c"] diff --git a/CHANGELOG.md b/CHANGELOG.md index 320ba697..21addc80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ ## Changes since v7.15.2 +- [#3477](https://github.com/oauth2-proxy/oauth2-proxy/pull/3477) chore(dep): bump go to 1.26 and migrate of reverse proxy handling + # V7.15.2 ## Release Highlights diff --git a/go.mod b/go.mod index ade9c4e8..fba46d82 100644 --- a/go.mod +++ b/go.mod @@ -1,17 +1,17 @@ module github.com/oauth2-proxy/oauth2-proxy/v7 -go 1.25.0 +go 1.26.0 require ( cloud.google.com/go/compute/metadata v0.9.0 github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb github.com/a8m/envsubst v1.4.3 - github.com/alicebob/miniredis/v2 v2.37.0 + github.com/alicebob/miniredis/v2 v2.38.0 github.com/bitly/go-simplejson v0.5.1 - github.com/bsm/redislock v0.9.4 + github.com/bsm/redislock v0.10.0 github.com/coreos/go-oidc/v3 v3.18.0 github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf - github.com/fsnotify/fsnotify v1.9.0 + github.com/fsnotify/fsnotify v1.10.1 github.com/go-jose/go-jose/v3 v3.0.5 github.com/go-jose/go-jose/v4 v4.1.4 github.com/go-viper/mapstructure/v2 v2.5.0 @@ -21,30 +21,30 @@ require ( github.com/gorilla/mux v1.8.1 github.com/justinas/alice v1.2.0 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 - github.com/onsi/ginkgo/v2 v2.28.1 - github.com/onsi/gomega v1.39.1 - github.com/pierrec/lz4/v4 v4.1.26 + github.com/onsi/ginkgo/v2 v2.29.0 + github.com/onsi/gomega v1.41.0 + github.com/pierrec/lz4/v4 v4.1.27 github.com/prometheus/client_golang v1.23.2 - github.com/redis/go-redis/v9 v9.18.0 + github.com/redis/go-redis/v9 v9.20.0 github.com/spf13/cast v1.10.0 github.com/spf13/pflag v1.0.10 github.com/spf13/viper v1.21.0 github.com/stretchr/testify v1.11.1 github.com/vmihailenco/msgpack/v5 v5.4.1 go.yaml.in/yaml/v3 v3.0.4 - golang.org/x/crypto v0.50.0 - golang.org/x/net v0.53.0 + golang.org/x/crypto v0.52.0 + golang.org/x/net v0.55.0 golang.org/x/oauth2 v0.36.0 golang.org/x/sync v0.20.0 - google.golang.org/api v0.275.0 + google.golang.org/api v0.283.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 - k8s.io/apimachinery v0.35.3 + k8s.io/apimachinery v0.36.1 ) require ( cloud.google.com/go/auth v0.20.0 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect - github.com/Masterminds/semver/v3 v3.4.0 // indirect + github.com/Masterminds/semver/v3 v3.5.0 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect @@ -53,35 +53,35 @@ require ( github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-task/slim-sprig/v3 v3.0.0 // indirect - github.com/google/pprof v0.0.0-20260402051712-545e8a4df936 // indirect + github.com/google/pprof v0.0.0-20260604005048-7023385849c0 // indirect github.com/google/s2a-go v0.1.9 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.14 // indirect - github.com/googleapis/gax-go/v2 v2.21.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.16 // indirect + github.com/googleapis/gax-go/v2 v2.22.0 // indirect github.com/kylelemons/godebug v1.1.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/pelletier/go-toml/v2 v2.3.0 // indirect + github.com/pelletier/go-toml/v2 v2.3.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.67.5 // indirect + github.com/prometheus/common v0.68.1 // indirect github.com/prometheus/procfs v0.20.1 // indirect github.com/sagikazarmark/locafero v0.12.0 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect - github.com/yuin/gopher-lua v1.1.1 // indirect + github.com/yuin/gopher-lua v1.1.2 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 // indirect - go.opentelemetry.io/otel v1.43.0 // indirect - go.opentelemetry.io/otel/metric v1.43.0 // indirect - go.opentelemetry.io/otel/trace v1.43.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect + go.opentelemetry.io/otel v1.44.0 // indirect + go.opentelemetry.io/otel/metric v1.44.0 // indirect + go.opentelemetry.io/otel/trace v1.44.0 // indirect go.uber.org/atomic v1.11.0 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect - golang.org/x/mod v0.35.0 // indirect - golang.org/x/sys v0.43.0 // indirect - golang.org/x/text v0.36.0 // indirect - golang.org/x/tools v0.44.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d // indirect - google.golang.org/grpc v1.80.0 // indirect - google.golang.org/protobuf v1.36.11 // indirect + golang.org/x/mod v0.36.0 // indirect + golang.org/x/sys v0.45.0 // indirect + golang.org/x/text v0.37.0 // indirect + golang.org/x/tools v0.45.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect + google.golang.org/grpc v1.81.1 // indirect + google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 622f2dac..5b400463 100644 --- a/go.sum +++ b/go.sum @@ -12,12 +12,16 @@ github.com/FZambia/sentinel v1.0.0 h1:KJ0ryjKTZk5WMp0dXvSdNqp3lFaW1fNFuEYfrkLOYI github.com/FZambia/sentinel v1.0.0/go.mod h1:ytL1Am/RLlAoAXG6Kj5LNuw/TRRQrv2rt2FT26vP5gI= github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE= +github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= github.com/a8m/envsubst v1.4.3 h1:kDF7paGK8QACWYaQo6KtyYBozY2jhQrTuNNuUxQkhJY= github.com/a8m/envsubst v1.4.3/go.mod h1:4jjHWQlZoaXPoLQUb7H2qT4iLkZDdmEQiOUogdUmqVU= github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= github.com/alicebob/miniredis/v2 v2.11.1/go.mod h1:UA48pmi7aSazcGAvcdKcBB49z521IC9VjTTRz2nIaJE= github.com/alicebob/miniredis/v2 v2.37.0 h1:RheObYW32G1aiJIj81XVt78ZHJpHonHLHW7OLIshq68= github.com/alicebob/miniredis/v2 v2.37.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM= +github.com/alicebob/miniredis/v2 v2.38.0 h1:nZAzCR+Lj+Vxk4ZXzm2NuKq2O33RXj1XxJ2e2uP9jiw= +github.com/alicebob/miniredis/v2 v2.38.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bitly/go-simplejson v0.5.1 h1:xgwPbetQScXt1gh9BmoJ6j9JMr3TElvuIyjR8pgdoow= @@ -28,6 +32,8 @@ github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= github.com/bsm/redislock v0.9.4 h1:X/Wse1DPpiQgHbVYRE9zv6m070UcKoOGekgvpNhiSvw= github.com/bsm/redislock v0.9.4/go.mod h1:Epf7AJLiSFwLCiZcfi6pWFO/8eAYrYpQXFxEDPoDeAk= +github.com/bsm/redislock v0.10.0 h1:NAe1OHDnwPmWEzD+LpWBZXAdZrWld/xj/wmqEcQednQ= +github.com/bsm/redislock v0.10.0/go.mod h1:M05WZGjPbX/8ne7LmB7AbOsa2kv7Jzx4fqkLpDFZvJs= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= @@ -50,6 +56,8 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho= +github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= github.com/gkampitakis/ciinfo v0.3.2 h1:JcuOPk8ZU7nZQjdUhctuhQofk7BGHuIy0c9Ez8BNhXs= github.com/gkampitakis/ciinfo v0.3.2/go.mod h1:1NIwaOcFChN4fa/B0hEBdAb6npDlFL8Bwx4dfRLRqAo= github.com/gkampitakis/go-diff v1.3.2 h1:Qyn0J9XJSDTgnsgHRdz9Zp24RaJeKMUHg2+PDZZdC4M= @@ -88,6 +96,8 @@ github.com/google/pprof v0.0.0-20260302011040-a15ffb7f9dcc h1:VBbFa1lDYWEeV5FZKU github.com/google/pprof v0.0.0-20260302011040-a15ffb7f9dcc/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= github.com/google/pprof v0.0.0-20260402051712-545e8a4df936 h1:EwtI+Al+DeppwYX2oXJCETMO23COyaKGP6fHVpkpWpg= github.com/google/pprof v0.0.0-20260402051712-545e8a4df936/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= +github.com/google/pprof v0.0.0-20260604005048-7023385849c0 h1:h1QTMDl6q9wDvDCJVpKQSjgleGFYnd2fOxmg2K+6BGE= +github.com/google/pprof v0.0.0-20260604005048-7023385849c0/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -95,10 +105,14 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/enterprise-certificate-proxy v0.3.14 h1:yh8ncqsbUY4shRD5dA6RlzjJaT4hi3kII+zYw8wmLb8= github.com/googleapis/enterprise-certificate-proxy v0.3.14/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg= +github.com/googleapis/enterprise-certificate-proxy v0.3.16 h1:F/VPrx0YPBdksZJQdCAp0WUsqnNmZpUZszzfYt0M5Dw= +github.com/googleapis/enterprise-certificate-proxy v0.3.16/go.mod h1:9Yb0eAkH/Xqhvv3zbeKf/+wMJqCeocWc6KIhDvEAuYE= github.com/googleapis/gax-go/v2 v2.19.0 h1:fYQaUOiGwll0cGj7jmHT/0nPlcrZDFPrZRhTsoCr8hE= github.com/googleapis/gax-go/v2 v2.19.0/go.mod h1:w2ROXVdfGEVFXzmlciUU4EdjHgWvB5h2n6x/8XSTTJA= github.com/googleapis/gax-go/v2 v2.21.0 h1:h45NjjzEO3faG9Lg/cFrBh2PgegVVgzqKzuZl/wMbiI= github.com/googleapis/gax-go/v2 v2.21.0/go.mod h1:But/NJU6TnZsrLai/xBAQLLz+Hc7fHZJt/hsCz3Fih4= +github.com/googleapis/gax-go/v2 v2.22.0 h1:PjIWBpgGIVKGoCXuiCoP64altEJCj3/Ei+kSU5vlZD4= +github.com/googleapis/gax-go/v2 v2.22.0/go.mod h1:irWBbALSr0Sk3qlqb9SyJ1h68WjgeFuiOzI4Rqw5+aY= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE= @@ -109,6 +123,7 @@ github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zt github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -127,14 +142,22 @@ github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3Tc github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw= github.com/onsi/ginkgo/v2 v2.28.1 h1:S4hj+HbZp40fNKuLUQOYLDgZLwNUVn19N3Atb98NCyI= github.com/onsi/ginkgo/v2 v2.28.1/go.mod h1:CLtbVInNckU3/+gC8LzkGUb9oF+e8W8TdUsxPwvdOgE= +github.com/onsi/ginkgo/v2 v2.29.0 h1:rfh+ZFjgJhYWRoIqVf3Uwx/W20yLrcrE2h2GmYVRaag= +github.com/onsi/ginkgo/v2 v2.29.0/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44= github.com/onsi/gomega v1.39.1 h1:1IJLAad4zjPn2PsnhH70V4DKRFlrCzGBNrNaru+Vf28= github.com/onsi/gomega v1.39.1/go.mod h1:hL6yVALoTOxeWudERyfppUcZXjMwIMLnuSfruD2lcfg= +github.com/onsi/gomega v1.41.0 h1:OwKp4pXNgVxf6sCplzYo794OFNuoL2q2SBMU5NSWOjA= +github.com/onsi/gomega v1.41.0/go.mod h1:M/Uqpu/8qTjtzCLUA2zJHX9Iilrau25x1PdoSRbWh5A= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pelletier/go-toml/v2 v2.3.0 h1:k59bC/lIZREW0/iVaQR8nDHxVq8OVlIzYCOJf421CaM= github.com/pelletier/go-toml/v2 v2.3.0/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pelletier/go-toml/v2 v2.3.1 h1:MYEvvGnQjeNkRF1qUuGolNtNExTDwct51yp7olPtrEc= +github.com/pelletier/go-toml/v2 v2.3.1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY= github.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= +github.com/pierrec/lz4/v4 v4.1.27 h1:+PhzhWDrjRj89TH2sw43nE3+4+W8lSxIuQadEHZyjUk= +github.com/pierrec/lz4/v4 v4.1.27/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -144,10 +167,14 @@ github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNw github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4= github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw= +github.com/prometheus/common v0.68.1 h1:omjRRl4QP4komogpXuhfeOiisQg7xdy8VM1UY+pStaY= +github.com/prometheus/common v0.68.1/go.mod h1:ZzL3f6u94qUxh9p+tJTrF+FvBS1XXbbRAZCQkytAL0Y= github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc= github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo= github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs= github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0= +github.com/redis/go-redis/v9 v9.20.0 h1:WnQYxLkgO2xiXTCJY0ldIiI8dNqCDlQAG+AtaH7a2a0= +github.com/redis/go-redis/v9 v9.20.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4= @@ -183,8 +210,11 @@ github.com/yuin/gopher-lua v0.0.0-20190206043414-8bfc7677f583/go.mod h1:gqRgreBU github.com/yuin/gopher-lua v0.0.0-20191213034115-f46add6fdb5c/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ= github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M= github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= +github.com/yuin/gopher-lua v1.1.2 h1:yF/FjE3hD65tBbt0VXLE13HWS9h34fdzJmrWRXwobGA= +github.com/yuin/gopher-lua v1.1.2/go.mod h1:7aRmXIWl37SqRf0koeyylBEzJ+aPt8A+mmkQ4f1ntR8= github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0= github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= +github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= @@ -194,24 +224,34 @@ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:Oyrsyzu go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 h1:CqXxU8VOmDefoh0+ztfGaymYbhdB/tT3zs79QaZTNGY= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0/go.mod h1:BuhAPThV8PBHBvg8ZzZ/Ok3idOdhWIodywz2xEcRbJo= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI= go.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho= go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc= go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I= go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0= +go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= +go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= go.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4= go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI= go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM= go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY= +go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= +go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= go.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo= go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts= go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg= +go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58= go.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA= go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc= go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw= +go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI= go.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY= go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc= go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A= go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0= +go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= +go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= @@ -227,12 +267,16 @@ golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4= golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA= golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI= golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q= +golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988= +golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.34.0 h1:xIHgNUUnW6sYkcM5Jleh05DvLOtwc6RitGHbDk4akRI= golang.org/x/mod v0.34.0/go.mod h1:ykgH52iCZe79kzLLMhyCUzhMci+nQj+0XkbXpNYtVjY= golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM= golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU= +golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4= +golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= @@ -242,6 +286,8 @@ golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0= golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA= golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -262,6 +308,8 @@ golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI= golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY= +golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -277,6 +325,8 @@ golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg= golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -287,6 +337,8 @@ golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s= golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0= golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c= golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI= +golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8= +golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= @@ -295,6 +347,8 @@ google.golang.org/api v0.272.0 h1:eLUQZGnAS3OHn31URRf9sAmRk3w2JjMx37d2k8AjJmA= google.golang.org/api v0.272.0/go.mod h1:wKjowi5LNJc5qarNvDCvNQBn3rVK8nSy6jg2SwRwzIA= google.golang.org/api v0.275.0 h1:vfY5d9vFVJeWEZT65QDd9hbndr7FyZ2+6mIzGAh71NI= google.golang.org/api v0.275.0/go.mod h1:Fnag/EWUPIcJXuIkP1pjoTgS5vdxlk3eeemL7Do6bvw= +google.golang.org/api v0.283.0 h1:0lkp8u0MPwJVHqRL+nJlMAoZVVzbmiXmFHXMOTmSPik= +google.golang.org/api v0.283.0/go.mod h1:6Wssta4c5n9qHq5CBhmlai5h/PUa1djdDAIhYEHyvcM= google.golang.org/genproto v0.0.0-20260316180232-0b37fe3546d5 h1:JNfk58HZ8lfmXbYK2vx/UvsqIL59TzByCxPIX4TDmsE= google.golang.org/genproto v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:x5julN69+ED4PcFk/XWayw35O0lf/nGa4aNgODCmNmw= google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0= @@ -305,12 +359,18 @@ google.golang.org/genproto/googleapis/rpc v0.0.0-20260319201613-d00831a3d3e7 h1: google.golang.org/genproto/googleapis/rpc v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d h1:wT2n40TBqFY6wiwazVK9/iTWbsQrgk5ZfCSVFLO9LQA= google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE= google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= google.golang.org/grpc v1.80.0 h1:Xr6m2WmWZLETvUNvIUmeD5OAagMw3FiKmMlTdViWsHM= google.golang.org/grpc v1.80.0/go.mod h1:ho/dLnxwi3EDJA4Zghp7k2Ec1+c2jqup0bFkw07bwF4= +google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ= +google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af h1:+5/Sw3GsDNlEmu7TfklWKPdQ0Ykja5VEmq2i817+jbI= +google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= @@ -321,3 +381,5 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= k8s.io/apimachinery v0.35.3 h1:MeaUwQCV3tjKP4bcwWGgZ/cp/vpsRnQzqO6J6tJyoF8= k8s.io/apimachinery v0.35.3/go.mod h1:jQCgFZFR1F4Ik7hvr2g84RTJSZegBc8yHgFWKn//hns= +k8s.io/apimachinery v0.36.1 h1:G63Gjx2W+q0YD+72Vo8oY0nDnePVwnuzTmmy5ENrVSA= +k8s.io/apimachinery v0.36.1/go.mod h1:ibYOR00vW/I1kzvi5SF0dRuJ52BvKtfvRdOn35GPQ+8= diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index 9112756e..ca77d543 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -123,7 +123,7 @@ func (t *unixRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) // The proxy should render an error page if there are failures connecting to the // upstream server. func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler ProxyErrorHandler) http.Handler { - proxy := httputil.NewSingleHostReverseProxy(target) + proxy := newSingleHostReverseProxy(target) // Inherit default transport options from Go's stdlib transport := http.DefaultTransport.(*http.Transport).Clone() @@ -155,7 +155,7 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr } // Ensure we always pass the original request path - setProxyDirector(proxy) + setProxyRewrite(proxy) // TODO (@tuunit) - this should be inverted or get a better name in the future to set the upstream host header // only if PassHostHeader is explicitly set to true. Currently this would be a breaking change. @@ -179,32 +179,71 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr return proxy } -// setProxyUpstreamHostHeader sets the proxy.Director so that upstream requests -// receive a host header matching the target URL. -func setProxyUpstreamHostHeader(proxy *httputil.ReverseProxy, target *url.URL) { - director := proxy.Director - proxy.Director = func(req *http.Request) { - director(req) - req.Host = target.Host +func newSingleHostReverseProxy(target *url.URL) *httputil.ReverseProxy { + return &httputil.ReverseProxy{ + Rewrite: func(proxyReq *httputil.ProxyRequest) { + proxyReq.SetURL(target) + proxyReq.Out.Host = proxyReq.In.Host + setProxyForwardingHeaders(proxyReq) + }, } } -// setProxyDirector sets the proxy.Director so that request URIs are escaped +// setProxyUpstreamHostHeader sets the proxy.Rewrite so that upstream requests +// receive a host header matching the target URL. +func setProxyUpstreamHostHeader(proxy *httputil.ReverseProxy, target *url.URL) { + rewrite := proxy.Rewrite + proxy.Rewrite = func(proxyReq *httputil.ProxyRequest) { + rewrite(proxyReq) + proxyReq.Out.Host = target.Host + } +} + +// setProxyRewrite sets the proxy.Rewrite so that request URIs are escaped // when proxying to usptream servers. -func setProxyDirector(proxy *httputil.ReverseProxy) { - director := proxy.Director - proxy.Director = func(req *http.Request) { - director(req) +func setProxyRewrite(proxy *httputil.ReverseProxy) { + rewrite := proxy.Rewrite + proxy.Rewrite = func(proxyReq *httputil.ProxyRequest) { + rewrite(proxyReq) // use RequestURI so that we aren't unescaping encoded slashes in the request path - req.URL.Opaque = req.RequestURI - req.URL.RawQuery = "" - req.URL.ForceQuery = false + proxyReq.Out.URL.Opaque = proxyReq.In.RequestURI + proxyReq.Out.URL.RawQuery = "" + proxyReq.Out.URL.ForceQuery = false + } +} + +func setProxyForwardingHeaders(proxyReq *httputil.ProxyRequest) { + // TODO (@tuunit): Preserve the legacy Director-based forwarding header behavior + // for backwards compatibility. Harden this with saner defaults and/or + // explicit flags in the future. + for _, header := range []string{"Forwarded", "X-Forwarded-Host", "X-Forwarded-Proto"} { + if values, ok := proxyReq.In.Header[header]; ok { + proxyReq.Out.Header[header] = append([]string(nil), values...) + } + } + + prior, ok := proxyReq.In.Header["X-Forwarded-For"] + if ok { + proxyReq.Out.Header["X-Forwarded-For"] = append([]string(nil), prior...) + } + + clientIP, _, err := net.SplitHostPort(proxyReq.In.RemoteAddr) + if err != nil { + return + } + + omit := ok && prior == nil + if len(prior) > 0 { + clientIP = strings.Join(prior, ", ") + ", " + clientIP + } + if !omit { + proxyReq.Out.Header.Set("X-Forwarded-For", clientIP) } } // newWebSocketReverseProxy creates a new reverse proxy for proxying websocket connections. func newWebSocketReverseProxy(u *url.URL, skipTLSVerify *bool, passHostHeader *bool) http.Handler { - wsProxy := httputil.NewSingleHostReverseProxy(u) + wsProxy := newSingleHostReverseProxy(u) // Inherit default transport options from Go's stdlib transport := http.DefaultTransport.(*http.Transport).Clone() diff --git a/pkg/upstream/http_test.go b/pkg/upstream/http_test.go index 70af9e7e..92d61df5 100644 --- a/pkg/upstream/http_test.go +++ b/pkg/upstream/http_test.go @@ -361,7 +361,12 @@ var _ = Describe("HTTP Upstream Suite", func() { return http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) { proxy, ok := h.(*httputil.ReverseProxy) Expect(ok).To(BeTrue()) - proxy.Director(req) + outReq := req.Clone(req.Context()) + proxy.Rewrite(&httputil.ProxyRequest{ + In: req, + Out: outReq, + }) + req.Host = outReq.Host }) } httpUpstream.handler = requestInterceptor(httpUpstream.handler) @@ -370,6 +375,54 @@ var _ = Describe("HTTP Upstream Suite", func() { Expect(req.Host).To(Equal(strings.TrimPrefix(serverAddr, "http://"))) }) + It("ServeHTTP preserves forwarding headers when using Rewrite", func() { + req := httptest.NewRequest("", "http://example.localhost/foo", nil) + req.RemoteAddr = "192.0.2.10:1234" + req.Header.Set("Forwarded", "for=192.0.2.1;proto=https;host=example.localhost") + req.Header.Set("X-Forwarded-Host", "forwarded.example.localhost") + req.Header.Set("X-Forwarded-Proto", "https") + req.Header.Set("X-Forwarded-For", "192.0.2.1") + req = middlewareapi.AddRequestScope(req, &middlewareapi.RequestScope{}) + rw := httptest.NewRecorder() + + upstream := options.Upstream{ + ID: "preserveForwardedHeaders", + PassHostHeader: ptr.To(true), + ProxyWebSockets: ptr.To(false), + InsecureSkipTLSVerify: ptr.To(false), + FlushInterval: &defaultFlushInterval, + Timeout: &defaultTimeout, + } + + u, err := url.Parse(serverAddr) + Expect(err).ToNot(HaveOccurred()) + + handler := newHTTPUpstreamProxy(upstream, u, nil, nil) + httpUpstream, ok := handler.(*httpUpstreamProxy) + Expect(ok).To(BeTrue()) + + requestInterceptor := func(h http.Handler) http.Handler { + return http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) { + proxy, ok := h.(*httputil.ReverseProxy) + Expect(ok).To(BeTrue()) + + outReq := req.Clone(req.Context()) + proxy.Rewrite(&httputil.ProxyRequest{ + In: req, + Out: outReq, + }) + + Expect(outReq.Header.Values("Forwarded")).To(Equal([]string{"for=192.0.2.1;proto=https;host=example.localhost"})) + Expect(outReq.Header.Values("X-Forwarded-Host")).To(Equal([]string{"forwarded.example.localhost"})) + Expect(outReq.Header.Values("X-Forwarded-Proto")).To(Equal([]string{"https"})) + Expect(outReq.Header.Values("X-Forwarded-For")).To(Equal([]string{"192.0.2.1, 192.0.2.10"})) + }) + } + httpUpstream.handler = requestInterceptor(httpUpstream.handler) + + httpUpstream.ServeHTTP(rw, req) + }) + type newUpstreamTableInput struct { proxyWebSockets bool flushInterval time.Duration @@ -405,6 +458,7 @@ var _ = Describe("HTTP Upstream Suite", func() { proxy, ok := upstreamProxy.handler.(*httputil.ReverseProxy) Expect(ok).To(BeTrue()) + Expect(proxy.Rewrite).ToNot(BeNil()) Expect(proxy.FlushInterval).To(Equal(in.flushInterval)) transport, ok := proxy.Transport.(*http.Transport) Expect(ok).To(BeTrue()) diff --git a/pkg/upstream/proxy_test.go b/pkg/upstream/proxy_test.go index aba4a730..92286605 100644 --- a/pkg/upstream/proxy_test.go +++ b/pkg/upstream/proxy_test.go @@ -79,7 +79,7 @@ var _ = Describe("Proxy Suite", func() { { ID: "bad-http-backend", Path: "/bad-http/", - URI: "http://::1", + URI: invalidServer, }, { ID: "single-path-backend", diff --git a/pkg/upstream/upstream_suite_test.go b/pkg/upstream/upstream_suite_test.go index 56aa98b1..0ca23941 100644 --- a/pkg/upstream/upstream_suite_test.go +++ b/pkg/upstream/upstream_suite_test.go @@ -24,7 +24,7 @@ var ( serverAddr string unixServer *httptest.Server unixServerAddr string - invalidServer = "http://::1" + invalidServer = "http://127.0.0.1:1" ) func TestUpstreamSuite(t *testing.T) { diff --git a/pkg/validation/sessions_test.go b/pkg/validation/sessions_test.go index cb54c571..6f590ac5 100644 --- a/pkg/validation/sessions_test.go +++ b/pkg/validation/sessions_test.go @@ -193,8 +193,8 @@ var _ = Describe("Sessions", func() { unreachableRedisDelMsg = "unable to delete the redis initialization key: dial tcp 127.0.0.1:65535: connect: connection refused" unreachableSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: redis: nil" unrechableSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable: redis: nil" - refusedSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: context deadline exceeded" - refusedSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable: context deadline exceeded" + refusedSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: dial tcp 127.0.0.1:65535: connect: connection refused" + refusedSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable: dial tcp 127.0.0.1:65535: connect: connection refused" ) type redisStoreTableInput struct { From 66b3a17db09f0b51a4bc3159d4c7fe3fbeca1288 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 9 Jun 2026 13:28:24 +0200 Subject: [PATCH 49/53] release v7.15.3 (#3450) * update to release version v7.15.3 * docs: changelog for v7.15.3 Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Jan Larwig --- CHANGELOG.md | 25 +++++++++++++++++++ .../docker-compose-alpha-config.yaml | 2 +- .../docker-compose-gitea.yaml | 2 +- .../docker-compose-keycloak.yaml | 2 +- .../docker-compose-nginx.yaml | 2 +- .../docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/installation.md | 2 +- .../version-7.15.x/installation.md | 2 +- 9 files changed, 33 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 21addc80..788e82c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,31 @@ ## Breaking Changes +## Changes since v7.15.3 + +# V7.15.3 + +## Release Highlights + +- 🔵 Golang version upgrade to v1.26.4 + - Upgrade of all dependencies to their latest versions +- 🕵️‍♀️ Vulnerabilities have ben addressed + - [CVE-2026-33811](https://nvd.nist.gov/vuln/detail/) + - [CVE-2026-33814](https://nvd.nist.gov/vuln/detail/) + - [CVE-2026-39820](https://nvd.nist.gov/vuln/detail/) + - [CVE-2026-39836](https://nvd.nist.gov/vuln/detail/) + - [CVE-2026-42499](https://nvd.nist.gov/vuln/detail/) + - [CVE-2026-42504](https://nvd.nist.gov/vuln/detail/) + - [CVE-2026-39823](https://nvd.nist.gov/vuln/detail/) + - [CVE-2026-39826](https://nvd.nist.gov/vuln/detail/) + - [CVE-2026-39825](https://nvd.nist.gov/vuln/detail/) + - [CVE-2026-27145](https://nvd.nist.gov/vuln/detail/) + - [CVE-2026-42507](https://nvd.nist.gov/vuln/detail/) + +## Important Notes + +## Breaking Changes + ## Changes since v7.15.2 - [#3477](https://github.com/oauth2-proxy/oauth2-proxy/pull/3477) chore(dep): bump go to 1.26 and migrate of reverse proxy handling diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index 2dde7345..94613199 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -14,7 +14,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.3 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 17d707fb..9265afd1 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.3 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index 70d2042b..0af2c0e4 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.3 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 2aa403ec..f2f6e946 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,7 +22,7 @@ version: "3.0" services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.3 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 302f1a42..d9cd087d 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.3 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 7630167d..7a6f34a0 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.2 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.3 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/installation.md b/docs/docs/installation.md index 7898f70c..9474865d 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.15.2`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.15.3`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.15.x/installation.md b/docs/versioned_docs/version-7.15.x/installation.md index 7898f70c..9474865d 100644 --- a/docs/versioned_docs/version-7.15.x/installation.md +++ b/docs/versioned_docs/version-7.15.x/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.15.2`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.15.3`) b. Using Go to install the latest release ```bash From 09979d458a8901b1a1bc3fa89b02c78d9d37329c Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Tue, 9 Jun 2026 13:50:16 +0200 Subject: [PATCH 50/53] docs: update slack reference for CNCF Signed-off-by: Jan Larwig --- .github/ISSUE_TEMPLATE/config.yml | 4 ++-- README.md | 8 ++++---- docs/docusaurus.config.js | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index f7184200..177d691c 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,6 +1,6 @@ blank_issues_enabled: false contact_links: - - name: OAuth2-Proxy Slack - url: https://gophers.slack.com/messages/CM2RSS25N + - name: OAuth2 Proxy Slack + url: https://cloud-native.slack.com/archives/C098Y5URZ2N about: Feel free to ask any questions here. diff --git a/README.md b/README.md index 88849cb9..0252f52b 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ OAuth2 Proxy is a flexible, open-source tool that can act as either a standalone reverse proxy or a middleware component integrated into existing reverse proxy or load balancer setups. It provides a simple and secure way to protect your web applications with OAuth2 / OIDC authentication. As a reverse proxy, it intercepts requests to your application and redirects users to an OAuth2 provider for authentication. As a middleware, it can be seamlessly integrated into your existing infrastructure to handle authentication for multiple applications. -OAuth2 Proxy supports a lot of OAuth2 as well as OIDC providers. Either through a generic OIDC client or a specific implementation for Google, Microsoft Entra ID, GitHub, login.gov and others. Through specialised provider implementations oauth2-proxy can extract more details about the user like preferred usernames and groups. Those details can then be forwarded as HTTP headers to your upstream applications. +OAuth2 Proxy supports a lot of OAuth2 as well as OIDC providers. Either through a generic OIDC client or a specific implementation for Google, Microsoft Entra ID, GitHub, login.gov and others. Through specialised provider implementations OAuth2 Proxy can extract more details about the user like preferred usernames and groups. Those details can then be forwarded as HTTP headers to your upstream applications. ![Simplified Architecture](docs/static/img/simplified-architecture.svg) @@ -23,7 +23,7 @@ OAuth2 Proxy's [Installation Docs](https://oauth2-proxy.github.io/oauth2-proxy/i ## Releases ### Binaries -We publish oauth2-proxy as compiled binaries on GitHub for all major architectures as well as more exotic ones like `ppc64le` as well as `s390x`. +We publish OAuth2 Proxy as compiled binaries on GitHub for all major architectures as well as more exotic ones like `ppc64le` as well as `s390x`. Check out the [latest release](https://github.com/oauth2-proxy/oauth2-proxy/releases/latest). @@ -49,9 +49,9 @@ SAP Open Source Program Microsoft Azure credits for open source projects ## Getting Involved -[![Slack](https://img.shields.io/badge/slack-Gopher_%23oauth2--proxy-red?logo=slack)](https://gophers.slack.com/archives/CM2RSS25N) +[![Slack](https://img.shields.io/badge/slack-CNCF_%23oauth2--proxy-blue?logo=slack)](https://cloud-native.slack.com/archives/C098Y5URZ2N) -Join the #oauth2-proxy [Slack channel](https://gophers.slack.com/archives/CM2RSS25N) to chat with other users of oauth2-proxy or reach out to the maintainers directly. Use the [public invite link](https://invite.slack.golangbridge.org/) to get an invite for the Gopher Slack space. +Join the #oauth2-proxy [Slack channel](https://cloud-native.slack.com/archives/C098Y5URZ2N) to chat with other users of OAuth2 Proxy or reach out to the maintainers directly. Use the [public invite link](https://communityinviter.com/apps/cloud-native/cncf) to get an invite for the Gopher Slack space. OAuth2 Proxy is a community-driven project. We rely on the contribut️ions of our users to continually improve it. While review times can vary, we appreciate your patience and understanding. As a volunteer-driven project, we strive to keep this project stable and might take longer to merge changes. diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index 5123f943..efe17b7b 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -105,7 +105,7 @@ const config = { dropdownActiveClassDisabled: true, }, { - href: 'https://gophers.slack.com/messages/CM2RSS25N', + href: 'https://cloud-native.slack.com/archives/C098Y5URZ2N', label: 'Slack', position: 'right', }, From 2479410598cb1cfc41955efa7834e4f46f227297 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sat, 13 Jun 2026 19:57:08 +0000 Subject: [PATCH 51/53] chore(deps): update gomod --- go.mod | 18 +++++++++--------- go.sum | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/go.mod b/go.mod index fba46d82..a8d88935 100644 --- a/go.mod +++ b/go.mod @@ -21,24 +21,24 @@ require ( github.com/gorilla/mux v1.8.1 github.com/justinas/alice v1.2.0 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 - github.com/onsi/ginkgo/v2 v2.29.0 + github.com/onsi/ginkgo/v2 v2.30.0 github.com/onsi/gomega v1.41.0 github.com/pierrec/lz4/v4 v4.1.27 github.com/prometheus/client_golang v1.23.2 - github.com/redis/go-redis/v9 v9.20.0 + github.com/redis/go-redis/v9 v9.20.1 github.com/spf13/cast v1.10.0 github.com/spf13/pflag v1.0.10 github.com/spf13/viper v1.21.0 github.com/stretchr/testify v1.11.1 github.com/vmihailenco/msgpack/v5 v5.4.1 go.yaml.in/yaml/v3 v3.0.4 - golang.org/x/crypto v0.52.0 - golang.org/x/net v0.55.0 + golang.org/x/crypto v0.53.0 + golang.org/x/net v0.56.0 golang.org/x/oauth2 v0.36.0 - golang.org/x/sync v0.20.0 - google.golang.org/api v0.283.0 + golang.org/x/sync v0.21.0 + google.golang.org/api v0.284.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 - k8s.io/apimachinery v0.36.1 + k8s.io/apimachinery v0.36.2 ) require ( @@ -77,8 +77,8 @@ require ( go.uber.org/atomic v1.11.0 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect golang.org/x/mod v0.36.0 // indirect - golang.org/x/sys v0.45.0 // indirect - golang.org/x/text v0.37.0 // indirect + golang.org/x/sys v0.46.0 // indirect + golang.org/x/text v0.38.0 // indirect golang.org/x/tools v0.45.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect google.golang.org/grpc v1.81.1 // indirect diff --git a/go.sum b/go.sum index 5b400463..47907b85 100644 --- a/go.sum +++ b/go.sum @@ -144,6 +144,8 @@ github.com/onsi/ginkgo/v2 v2.28.1 h1:S4hj+HbZp40fNKuLUQOYLDgZLwNUVn19N3Atb98NCyI github.com/onsi/ginkgo/v2 v2.28.1/go.mod h1:CLtbVInNckU3/+gC8LzkGUb9oF+e8W8TdUsxPwvdOgE= github.com/onsi/ginkgo/v2 v2.29.0 h1:rfh+ZFjgJhYWRoIqVf3Uwx/W20yLrcrE2h2GmYVRaag= github.com/onsi/ginkgo/v2 v2.29.0/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44= +github.com/onsi/ginkgo/v2 v2.30.0 h1:zxM/9XneXFIy64j6/wAmBIX4zRC7Hu6U8XFNZvDnCQc= +github.com/onsi/ginkgo/v2 v2.30.0/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44= github.com/onsi/gomega v1.39.1 h1:1IJLAad4zjPn2PsnhH70V4DKRFlrCzGBNrNaru+Vf28= github.com/onsi/gomega v1.39.1/go.mod h1:hL6yVALoTOxeWudERyfppUcZXjMwIMLnuSfruD2lcfg= github.com/onsi/gomega v1.41.0 h1:OwKp4pXNgVxf6sCplzYo794OFNuoL2q2SBMU5NSWOjA= @@ -175,6 +177,8 @@ github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfS github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0= github.com/redis/go-redis/v9 v9.20.0 h1:WnQYxLkgO2xiXTCJY0ldIiI8dNqCDlQAG+AtaH7a2a0= github.com/redis/go-redis/v9 v9.20.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA= +github.com/redis/go-redis/v9 v9.20.1 h1:sfCU6A8P3dXbKyWes02uxA2baehGux9dZHfEKtsTB1w= +github.com/redis/go-redis/v9 v9.20.1/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4= @@ -269,6 +273,8 @@ golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI= golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q= golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988= golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc= +golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto= +golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.34.0 h1:xIHgNUUnW6sYkcM5Jleh05DvLOtwc6RitGHbDk4akRI= @@ -288,6 +294,8 @@ golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA= golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs= golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= +golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -295,6 +303,8 @@ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM= +golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -310,6 +320,8 @@ golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI= golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY= golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= +golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -327,6 +339,8 @@ golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg= golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164= golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE= +golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -349,6 +363,8 @@ google.golang.org/api v0.275.0 h1:vfY5d9vFVJeWEZT65QDd9hbndr7FyZ2+6mIzGAh71NI= google.golang.org/api v0.275.0/go.mod h1:Fnag/EWUPIcJXuIkP1pjoTgS5vdxlk3eeemL7Do6bvw= google.golang.org/api v0.283.0 h1:0lkp8u0MPwJVHqRL+nJlMAoZVVzbmiXmFHXMOTmSPik= google.golang.org/api v0.283.0/go.mod h1:6Wssta4c5n9qHq5CBhmlai5h/PUa1djdDAIhYEHyvcM= +google.golang.org/api v0.284.0 h1:i+cKTgeQRcRySkP7QTl5PDO7/pAm8EcMFIUMlNbk4Vc= +google.golang.org/api v0.284.0/go.mod h1:AU44fU+XVZOCcd8uLaBIa/ZgzgPf/0qqY3+m7lQaado= google.golang.org/genproto v0.0.0-20260316180232-0b37fe3546d5 h1:JNfk58HZ8lfmXbYK2vx/UvsqIL59TzByCxPIX4TDmsE= google.golang.org/genproto v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:x5julN69+ED4PcFk/XWayw35O0lf/nGa4aNgODCmNmw= google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0= @@ -383,3 +399,5 @@ k8s.io/apimachinery v0.35.3 h1:MeaUwQCV3tjKP4bcwWGgZ/cp/vpsRnQzqO6J6tJyoF8= k8s.io/apimachinery v0.35.3/go.mod h1:jQCgFZFR1F4Ik7hvr2g84RTJSZegBc8yHgFWKn//hns= k8s.io/apimachinery v0.36.1 h1:G63Gjx2W+q0YD+72Vo8oY0nDnePVwnuzTmmy5ENrVSA= k8s.io/apimachinery v0.36.1/go.mod h1:ibYOR00vW/I1kzvi5SF0dRuJ52BvKtfvRdOn35GPQ+8= +k8s.io/apimachinery v0.36.2 h1:0PE/W/WNy1UX61NLbXY5TMbJ6UwLL6E6lAPkYrKFxbQ= +k8s.io/apimachinery v0.36.2/go.mod h1:fvf/HOLXq9RId0rnDIbN1OEBvHXdQbLMM8nu0LcBUf4= From 077cd9f9cc4f4683d3622739461163c80fee5e02 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 14 Jun 2026 15:42:56 +0000 Subject: [PATCH 52/53] chore(deps): update docker-compose --- contrib/local-environment/docker-compose-alpha-config.yaml | 2 +- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 4 ++-- contrib/local-environment/docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index 94613199..d7dcabdf 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -54,7 +54,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.8 + image: gcr.io/etcd-development/etcd:v3.6.12 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 9265afd1..08385f4e 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -39,7 +39,7 @@ services: httpbin: {} gitea: - image: gitea/gitea:1.25.5 + image: gitea/gitea:1.26.2 container_name: gitea environment: - USER_UID=1000 diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index f2f6e946..d77ff186 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -42,7 +42,7 @@ services: depends_on: - oauth2-proxy container_name: nginx - image: nginx:1.29 + image: nginx:1.31 restart: unless-stopped ports: - 8080:8080/tcp @@ -79,7 +79,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.8 + image: gcr.io/etcd-development/etcd:v3.6.12 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index d9cd087d..4a56f483 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -34,7 +34,7 @@ services: # Reverse proxy gateway: container_name: traefik - image: traefik:v2.11.40 + image: traefik:v2.11.50 volumes: - "./traefik:/etc/traefik" ports: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 7a6f34a0..cd4ed532 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -52,7 +52,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.8 + image: gcr.io/etcd-development/etcd:v3.6.12 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 From 3d011d978db08ea08633a49dd2ccfecf71854a00 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 14 Jun 2026 16:10:13 +0000 Subject: [PATCH 53/53] chore(deps): update actions/upload-pages-artifact action to v5 --- .github/workflows/docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index afe33250..8dd6fe53 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -49,7 +49,7 @@ jobs: npm run build - name: Upload artifact - uses: actions/upload-pages-artifact@v3 + uses: actions/upload-pages-artifact@v5 with: path: ./docs/build