git.iko.soy/typeable/oauth2-proxy
on master help sign in
202 files changed+8956−1079
since splitsnapshots
unifiedsplit
.devcontainer/Dockerfile+1−1 .github/ISSUE_TEMPLATE/config.yml+2−2 .github/PULL_REQUEST_TEMPLATE.md+3−2 .github/renovate.json5+9 .github/workflows/ci.yml+57−20 .github/workflows/codeql.yml+4−4 .github/workflows/create-release.yml+2−2 .github/workflows/docs.yml+7−7 .github/workflows/labeler.yml+1−1 .github/workflows/nightly.yml+4−4 .github/workflows/publish-release.yml+22−22 .github/workflows/stale.yml+1−1 .github/workflows/test.sh−26 .golangci.yml+8 CHANGELOG.md+213 MAINTAINERS.md+1−1 Makefile+10−5 README.md+4−4 contrib/local-environment/Makefile+2−2 contrib/local-environment/dex-traefik.yaml+25 contrib/local-environment/dex.yaml+13−17 contrib/local-environment/docker-compose-alpha-config.yaml+3−16 contrib/local-environment/docker-compose-gitea.yaml+2−2 contrib/local-environment/docker-compose-keycloak.yaml+6−6 contrib/local-environment/docker-compose-nginx.yaml+9−33 contrib/local-environment/docker-compose-traefik.yaml+42−18 contrib/local-environment/docker-compose.yaml+3−16 contrib/local-environment/kubernetes/Chart.lock+3−3 contrib/local-environment/kubernetes/Chart.yaml+1−1 contrib/local-environment/nginx.conf+31−73 contrib/local-environment/oauth2-proxy-nginx.cfg+11−6 contrib/local-environment/oauth2-proxy-traefik.cfg+4−4 contrib/local-environment/traefik/dynamic.yaml+11−4 contrib/local-environment/traefik/traefik.yaml+2 dist.sh+10−3 docs/docs/configuration/alpha_config.md+79−3 docs/docs/configuration/alpha_config.md.tmpl+74 docs/docs/configuration/integrations/nginx.md+95−12 docs/docs/configuration/integrations/traefik.md+8 docs/docs/configuration/overview.md+59−14 docs/docs/configuration/providers/atlassian.md+26 docs/docs/configuration/providers/dtt_sso.md+45 docs/docs/configuration/providers/gitlab.md+1−1 docs/docs/configuration/providers/index.md+2 docs/docs/configuration/systemd_socket.md+8 docs/docs/features/endpoints.md+14 docs/docs/installation.md+1−1 docs/docusaurus.config.js+1−1 docs/package.json+4−1 docs/sidebars.js+2 docs/versioned_docs/version-7.10.x/configuration/integration.md+77−1 docs/versioned_docs/version-7.10.x/configuration/overview.md+1 docs/versioned_docs/version-7.10.x/configuration/providers/gitlab.md+1−1 docs/versioned_docs/version-7.11.x/configuration/integration.md+77−1 docs/versioned_docs/version-7.11.x/configuration/overview.md+1 docs/versioned_docs/version-7.11.x/configuration/providers/gitlab.md+1−1 docs/versioned_docs/version-7.12.x/configuration/integration.md+77−1 docs/versioned_docs/version-7.12.x/configuration/overview.md+1 docs/versioned_docs/version-7.12.x/configuration/providers/gitlab.md+1−1 docs/versioned_docs/version-7.13.x/configuration/integrations/nginx.md+68−1 docs/versioned_docs/version-7.13.x/configuration/integrations/traefik.md+8 docs/versioned_docs/version-7.13.x/configuration/overview.md+1 docs/versioned_docs/version-7.13.x/configuration/providers/gitlab.md+1−1 docs/versioned_docs/version-7.14.x/configuration/integrations/nginx.md+68−1 docs/versioned_docs/version-7.14.x/configuration/integrations/traefik.md+8 docs/versioned_docs/version-7.14.x/configuration/overview.md+2−1 docs/versioned_docs/version-7.14.x/configuration/providers/gitlab.md+1−1 docs/versioned_docs/version-7.14.x/installation.md+1−1 docs/versioned_docs/version-7.15.x/behaviour.md+26 docs/versioned_docs/version-7.15.x/community/contribution.md+91 docs/versioned_docs/version-7.15.x/community/security.md+49 docs/versioned_docs/version-7.15.x/configuration/alpha_config.md+702 docs/versioned_docs/version-7.15.x/configuration/alpha_config.md.tmpl+281 docs/versioned_docs/version-7.15.x/configuration/integrations/caddy.md+63 docs/versioned_docs/version-7.15.x/configuration/integrations/headlamp.md+105 docs/versioned_docs/version-7.15.x/configuration/integrations/index.md+41 docs/versioned_docs/version-7.15.x/configuration/integrations/kubernetes-dashboard.md+289 docs/versioned_docs/version-7.15.x/configuration/integrations/nginx.md+174 docs/versioned_docs/version-7.15.x/configuration/integrations/traefik.md+192 docs/versioned_docs/version-7.15.x/configuration/overview.md+451 docs/versioned_docs/version-7.15.x/configuration/providers/adfs.md+19 docs/versioned_docs/version-7.15.x/configuration/providers/bitbucket.md+25 docs/versioned_docs/version-7.15.x/configuration/providers/cidaas.md+37 docs/versioned_docs/version-7.15.x/configuration/providers/cisco_duo.md+44 docs/versioned_docs/version-7.15.x/configuration/providers/digitalocean.md+21 docs/versioned_docs/version-7.15.x/configuration/providers/facebook.md+7 docs/versioned_docs/version-7.15.x/configuration/providers/gitea.md+24 docs/versioned_docs/version-7.15.x/configuration/providers/github.md+81 docs/versioned_docs/version-7.15.x/configuration/providers/gitlab.md+49 docs/versioned_docs/version-7.15.x/configuration/providers/google.md+84 docs/versioned_docs/version-7.15.x/configuration/providers/index.md+46 docs/versioned_docs/version-7.15.x/configuration/providers/keycloak.md+36 docs/versioned_docs/version-7.15.x/configuration/providers/keycloak_oidc.md+151 docs/versioned_docs/version-7.15.x/configuration/providers/linkedin.md+13 docs/versioned_docs/version-7.15.x/configuration/providers/login_gov.md+79 docs/versioned_docs/version-7.15.x/configuration/providers/ms_azure_ad.md+59 docs/versioned_docs/version-7.15.x/configuration/providers/ms_entra_id.md+201 docs/versioned_docs/version-7.15.x/configuration/providers/nextcloud.md+28 docs/versioned_docs/version-7.15.x/configuration/providers/openid_connect.md+146 docs/versioned_docs/version-7.15.x/configuration/providers/sourcehut.md+25 docs/versioned_docs/version-7.15.x/configuration/sessions.md+99 docs/versioned_docs/version-7.15.x/configuration/systemd_socket.md+51 docs/versioned_docs/version-7.15.x/configuration/tls.md+85 docs/versioned_docs/version-7.15.x/features/endpoints.md+73 docs/versioned_docs/version-7.15.x/installation.md+32 docs/versioned_docs/version-7.15.x/welcome.md+33 docs/versioned_docs/version-7.6.x/configuration/overview.md+1 docs/versioned_docs/version-7.6.x/configuration/providers/gitlab.md+1−1 docs/versioned_docs/version-7.7.x/configuration/overview.md+1 docs/versioned_docs/version-7.7.x/configuration/providers/gitlab.md+1−1 docs/versioned_docs/version-7.8.x/configuration/overview.md+1 docs/versioned_docs/version-7.8.x/configuration/providers/gitlab.md+1−1 docs/versioned_docs/version-7.9.x/configuration/overview.md+1 docs/versioned_docs/version-7.9.x/configuration/providers/gitlab.md+1−1 docs/versioned_sidebars/version-7.15.x-sidebars.json+100 docs/versions.json+1 go.mod+45−48 go.sum+110−110 main.go+14 main_test.go+78−2 oauthproxy.go+61−39 oauthproxy_test.go+342−106 pkg/apis/middleware/scope.go+48−1 pkg/apis/middleware/scope_test.go+34 pkg/apis/options/cookie.go+3 pkg/apis/options/legacy_options.go+18−14 pkg/apis/options/legacy_options_test.go+14−12 pkg/apis/options/load.go+1−1 pkg/apis/options/load_test.go+2−2 pkg/apis/options/options.go+2 pkg/apis/options/providers.go+14 pkg/apis/options/server.go+9 pkg/apis/options/upstreams.go+28−8 pkg/apis/sessions/session_state.go+17−1 pkg/apis/sessions/session_state_test.go+98−5 pkg/app/redirect/director_test.go+33−2 pkg/authentication/hmacauth/hmacauth_test.go+1−1 pkg/cookies/cookies.go+18−8 pkg/cookies/cookies_suite_test.go+4 pkg/cookies/cookies_test.go+39−51 pkg/cookies/csrf.go+34−15 pkg/cookies/csrf_per_request_test.go+12−7 pkg/cookies/csrf_test.go+284−1 pkg/ip/parse_ip_net.go+16 pkg/ip/parse_ip_net_test.go+118 pkg/ip/realclientip.go+7−1 pkg/ip/realclientip_test.go+4 pkg/middleware/healthcheck.go+7−4 pkg/middleware/healthcheck_test.go+31−9 pkg/middleware/redirect_to_https_test.go+15 pkg/middleware/scope.go+5−3 pkg/middleware/scope_test.go+18−4 pkg/middleware/stored_session.go+46−2 pkg/middleware/stored_session_test.go+51 pkg/providers/oidc/provider_verifier.go+36−1 pkg/providers/oidc/provider_verifier_test.go+92 pkg/providers/util/claim_extractor.go+10−74 pkg/providers/util/claim_extractor_test.go+2−53 pkg/proxyhttp/server.go+50−2 pkg/proxyhttp/server_test.go+50 pkg/requests/builder_test.go+15−15 pkg/requests/util/util.go+28−15 pkg/requests/util/util_test.go+74−12 pkg/sessions/cookie/session_store.go+23−13 pkg/sessions/persistence/ticket.go+23−14 pkg/sessions/redis/redis_store.go+15−8 pkg/sessions/redis/redis_store_test.go+50 pkg/sessions/tests/session_store_tests.go+11−1 pkg/upstream/http.go+55−16 pkg/upstream/http_test.go+57−3 pkg/upstream/proxy.go+14−14 pkg/upstream/proxy_test.go+33−1 pkg/upstream/upstream_suite_test.go+1−1 pkg/util/util.go+64 pkg/util/util_test.go+70 pkg/validation/allowlist.go+13 pkg/validation/allowlist_test.go+30 pkg/validation/header.go+1 pkg/validation/providers.go+35−1 pkg/validation/providers_test.go+53 pkg/validation/sessions_test.go+2−2 pkg/validation/upstreams.go+4−3 pkg/validation/upstreams_test.go+19−1 providers/atlassian-cloud.go+99 providers/atlassian-cloud_test.go+93 providers/azure.go+3−2 providers/dtt_sso.go+202 providers/dtt_sso_test.go+237 providers/google.go+2−2 providers/keycloak_oidc.go+1 providers/logingov.go+2−1 providers/ms_entra_id.go+4−1 providers/provider_data.go+44−5 providers/provider_data_test.go+23 providers/provider_default.go+2−1 providers/provider_default_test.go+12 providers/providers.go+9−3 providers/providers_test.go+90 providers/srht.go+2−1 providers/util_test.go+33 validator.go+4−1 validator_test.go+21
.devcontainer/Dockerfile+1−1
@@ -1,4 +1,4 @@
1−FROM mcr.microsoft.com/vscode/devcontainers/go:1-1.23
1+FROM mcr.microsoft.com/vscode/devcontainers/go:1-1.26
22
33SHELL ["/bin/bash", "-o", "pipefail", "-c"]
44
.github/ISSUE_TEMPLATE/config.yml+2−2
@@ -1,6 +1,6 @@
11blank_issues_enabled: false
22contact_links:
3− - name: OAuth2-Proxy Slack
4− url: https://gophers.slack.com/messages/CM2RSS25N
3+ - name: OAuth2 Proxy Slack
4+ url: https://cloud-native.slack.com/archives/C098Y5URZ2N
55 about: Feel free to ask any questions here.
66
.github/PULL_REQUEST_TEMPLATE.md+3−2
@@ -20,7 +20,8 @@
2020<!--- Go over all the following points, and put an `x` in all the boxes that apply. -->
2121<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
2222
23−- [ ] My change requires a change to the documentation or CHANGELOG.
24−- [ ] I have updated the documentation/CHANGELOG accordingly.
23+- [ ] I have added an entry for my changes to the [CHANGELOG.md](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/CHANGELOG.md).
24+- [ ] I have [signed off](https://github.com/apps/dco) all my commits.
2525- [ ] I have created a feature (non-master) branch for my PR.
26+- [ ] I have used [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/#examples) for the PR title.
2627- [ ] I have written tests for my code changes.
.github/renovate.json5+9
@@ -46,6 +46,15 @@
4646 depNameTemplate: "alpine",
4747 datasourceTemplate: "docker",
4848 },
49+ {
50+ customType: "regex",
51+ fileMatch: [
52+ "^Makefile",
53+ ],
54+ matchStrings: [
55+ "# renovate: datasource=(?<datasource>.*?) depName=(?<depName>.*?)\\s+?GOLANGCILINT_VERSION \\?= (?<currentValue>.*)\\s",
56+ ],
57+ },
4958 {
5059 customType: "regex",
5160 fileMatch: ["(^|/)\\.github/workflows/[^/]+\\.ya?ml$"],
.github/workflows/ci.yml+57−20
@@ -7,29 +7,33 @@ on:
77 pull_request:
88 branches:
99 - '**'
10+ workflow_dispatch:
11+
12+permissions:
13+ contents: read
14+ id-token: write
15+ security-events: write
16+
1017jobs:
1118 build:
1219 runs-on: ubuntu-latest
13− env:
14− COVER: true
1520 steps:
1621 - name: Check out code
17− uses: actions/checkout@v6
18−
19− - name: Set up Go
20− uses: actions/setup-go@v6
22+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
2123 with:
22− go-version-file: go.mod
23− id: go
24+ fetch-depth: 0
2425
25− - name: Get dependencies
26− env:
27− # renovate: datasource=github-tags depName=golangci/golangci-lint
28− GOLANGCI_LINT_VERSION: v2.7.2
26+ - name: Get Go version
2927 run: |
30− curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION}
31− curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
32− chmod +x ./cc-test-reporter
28+ version=$(grep "^go " go.mod | cut -d' ' -f2 | cut -d. -f1,2)
29+ echo "version=${version}" >> "$GITHUB_OUTPUT"
30+ id: go-version
31+
32+ - name: Set up Go
33+ uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
34+ with:
35+ go-version: ${{ steps.go-version.outputs.version }}
36+ check-latest: true
3337
3438 - name: Verify Code Generation
3539 run: |
@@ -52,22 +56,55 @@ jobs:
5256
5357 - name: Test
5458 env:
55− CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
59+ COVER: true
60+ run: |
61+ make test
62+
63+ - name: Generate Coverage Report
64+ if: github.event_name == 'push'
5665 run: |
57− ./.github/workflows/test.sh
66+ go install github.com/jandelgado/gcov2lcov@25681830fb515e3d4c117e136b4f049e21efb4d0
67+ gcov2lcov -infile=c.out -outfile=lcov.info
68+
69+ - name: Upload Coverage Report
70+ if: github.event_name == 'push'
71+ uses: qltysh/qlty-action/coverage@08a0a862c159eae9b9003081da6663d96efef637 # v2.3.0
72+ with:
73+ oidc: true
74+ files: lcov.info
75+
76+ - name: Run Trivy vulnerability scanner
77+ if: (!startsWith(github.head_ref, 'release'))
78+ uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
79+ with:
80+ scan-type: 'rootfs'
81+ scan-ref: './oauth2-proxy'
82+ severity: 'CRITICAL,HIGH'
83+ hide-progress: true
84+ format: 'sarif'
85+ output: 'trivy-results.sarif'
86+ exit-code: '0'
87+
88+ - name: Upload Trivy scan results
89+ if: (!startsWith(github.head_ref, 'release'))
90+ uses: github/codeql-action/upload-sarif@ff2f1c621b7f889edc0d3c761ac2e6a3f8cdb0dd # v4.37.7
91+ with:
92+ sarif_file: 'trivy-results.sarif'
5893
5994 docker:
6095 runs-on: ubuntu-latest
6196 steps:
6297 - name: Check out code
63− uses: actions/checkout@v6
98+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
99+ with:
100+ fetch-depth: 0
64101
65102 - name: Set up QEMU
66− uses: docker/setup-qemu-action@v3
103+ uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4.2.0
67104
68105 - name: Set up Docker Buildx
69106 id: buildx
70− uses: docker/setup-buildx-action@v3
107+ uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
71108
72109 - name: Docker Build
73110 if: (!startsWith(github.head_ref, 'release'))
.github/workflows/codeql.yml+4−4
@@ -32,18 +32,18 @@ jobs:
3232
3333 steps:
3434 - name: Checkout repository
35− uses: actions/checkout@v6
35+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
3636
3737 # Initializes the CodeQL tools for scanning.
3838 - name: Initialize CodeQL
39− uses: github/codeql-action/init@v3
39+ uses: github/codeql-action/init@ff2f1c621b7f889edc0d3c761ac2e6a3f8cdb0dd # v4.37.7
4040 with:
4141 languages: go
4242
4343 # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
4444 # If this step fails, then you should remove it and run the build manually (see below)
4545 - name: Autobuild
46− uses: github/codeql-action/autobuild@v3
46+ uses: github/codeql-action/autobuild@ff2f1c621b7f889edc0d3c761ac2e6a3f8cdb0dd # v4.37.7
4747
4848 # ℹ️ Command-line programs to run using the OS shell.
4949 # 📚 https://git.io/JvXDl
@@ -57,4 +57,4 @@ jobs:
5757 # make release
5858
5959 - name: Perform CodeQL Analysis
60− uses: github/codeql-action/analyze@v3
60+ uses: github/codeql-action/analyze@ff2f1c621b7f889edc0d3c761ac2e6a3f8cdb0dd # v4.37.7
.github/workflows/create-release.yml+2−2
@@ -17,7 +17,7 @@ jobs:
1717 runs-on: ubuntu-latest
1818 steps:
1919 - name: Check out code
20− uses: actions/checkout@v6
20+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
2121 with:
2222 ref: master
2323 fetch-depth: 0
@@ -54,7 +54,7 @@ jobs:
5454 git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
5555
5656 - name: Setup node
57− uses: actions/setup-node@v6
57+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
5858 with:
5959 node-version-file: docs/package.json
6060
.github/workflows/docs.yml+7−7
@@ -14,13 +14,13 @@ jobs:
1414 if: github.event_name == 'pull_request'
1515 runs-on: ubuntu-latest
1616 steps:
17− - uses: actions/checkout@v6
17+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
1818
1919 - name: Setup Pages
2020 id: pages
21− uses: actions/configure-pages@v5
21+ uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0
2222
23− - uses: actions/setup-node@v6
23+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
2424 with:
2525 # renovate: datasource=node-version depName=node
2626 node-version: 24
@@ -35,9 +35,9 @@ jobs:
3535 if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
3636 runs-on: ubuntu-latest
3737 steps:
38− - uses: actions/checkout@v6
38+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
3939
40− - uses: actions/setup-node@v6
40+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
4141 with:
4242 # renovate: datasource=node-version depName=node
4343 node-version: 24
@@ -49,7 +49,7 @@ jobs:
4949 npm run build
5050
5151 - name: Upload artifact
52− uses: actions/upload-pages-artifact@v3
52+ uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0
5353 with:
5454 path: ./docs/build
5555
@@ -65,4 +65,4 @@ jobs:
6565 steps:
6666 - name: Deploy to GitHub Pages
6767 id: deployment
68− uses: actions/deploy-pages@v4
68+ uses: actions/deploy-pages@cd2ce8fcbc39b97be8ca5fce6e763baed58fa128 # v5.0.0
.github/workflows/labeler.yml+1−1
@@ -9,7 +9,7 @@ jobs:
99 pull-requests: write
1010 runs-on: ubuntu-latest
1111 steps:
12− - uses: actions/labeler@v6
12+ - uses: actions/labeler@bf12e9b00b37c5c0ca2b87b79b2daf7891dbda13 # v7.0.0
1313 with:
1414 sync-labels: true
1515 dot: true
.github/workflows/nightly.yml+4−4
@@ -12,21 +12,21 @@ jobs:
1212 if: github.repository == 'oauth2-proxy/oauth2-proxy'
1313 steps:
1414 - name: Check out code
15− uses: actions/checkout@v6
15+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
1616 with:
1717 ref: master
1818 fetch-depth: 0
1919 fetch-tags: true
2020
2121 - name: Set up QEMU
22− uses: docker/setup-qemu-action@v3
22+ uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4.2.0
2323
2424 - name: Set up Docker Buildx
2525 id: buildx
26− uses: docker/setup-buildx-action@v3
26+ uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
2727
2828 - name: Login to quay.io
29− uses: docker/login-action@v3
29+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
3030 with:
3131 registry: quay.io/oauth2-proxy
3232 username: ${{ secrets.REGISTRY_USERNAME_NIGHTLY }}
.github/workflows/publish-release.yml+22−22
@@ -14,49 +14,49 @@ permissions:
1414
1515jobs:
1616 publish:
17− if: github.event.pull_request.merged && startsWith(github.event.pull_request.head.ref, 'release/')
17+ if: github.event.pull_request.merged && startsWith(github.event.pull_request.head.ref, 'release/') && github.event.pull_request.head.repo.full_name == github.repository
1818 runs-on: ubuntu-latest
1919 outputs:
2020 tag: ${{ steps.tag.outputs.version }}
2121 steps:
2222 - name: Check out code
23− uses: actions/checkout@v6
23+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
2424 with:
2525 ref: ${{ github.event.pull_request.merge_commit_sha }}
2626 fetch-depth: 0
2727 fetch-tags: true
2828
2929 - name: Tag release
30+ env:
31+ BRANCH: ${{ github.event.pull_request.head.ref }}
3032 run: |
3133 # Set up github-actions[bot] user
3234 git config --local user.name "github-actions[bot]"
3335 git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
3436
3537 # Get the version from the branch name
36− branch="${{ github.event.pull_request.head.ref }}"
37− version="${branch#release/}"
38+ version="${BRANCH#release/}"
3839 echo ${version}
3940
4041 # Tag and create release
4142 git tag -a "${version}" -m "Release ${version}"
4243 echo "version=${version}" >> $GITHUB_OUTPUT
4344 id: tag
44−
45− - name: Set up go
46− uses: actions/setup-go@v6
47− with:
48− go-version-file: go.mod
4945
50− - name: Get dependencies
51− env:
52− # renovate: datasource=github-tags depName=golangci/golangci-lint
53− GOLANGCI_LINT_VERSION: v2.7.2
46+ - name: Get Go version
5447 run: |
55− curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION}
56− curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
57− chmod +x ./cc-test-reporter
48+ version=$(grep "^go " go.mod | cut -d' ' -f2 | cut -d. -f1,2)
49+ echo "version=${version}" >> "$GITHUB_OUTPUT"
50+ id: go-version
5851
59− # Install go dependencies
52+ - name: Set up Go
53+ uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
54+ with:
55+ go-version: ${{ steps.go-version.outputs.version }}
56+ check-latest: true
57+
58+ - name: Get go dependencies
59+ run: |
6060 go mod download
6161
6262 - name: Build Artifacts
@@ -64,7 +64,7 @@ jobs:
6464
6565 # Upload artifacts in case of workflow failure
6666 - name: Upload Artifacts
67− uses: actions/upload-artifact@v5
67+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
6868 with:
6969 name: oauth2-proxy-artifacts
7070 path: |
@@ -100,21 +100,21 @@ jobs:
100100 runs-on: ubuntu-latest
101101 steps:
102102 - name: Check out code
103− uses: actions/checkout@v6
103+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
104104 with:
105105 ref: ${{ needs.publish.outputs.tag }}
106106 fetch-depth: 0
107107 fetch-tags: true
108108
109109 - name: Set up QEMU
110− uses: docker/setup-qemu-action@v3
110+ uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4.2.0
111111
112112 - name: Set up Docker Buildx
113113 id: buildx
114− uses: docker/setup-buildx-action@v3
114+ uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
115115
116116 - name: Login to quay.io
117− uses: docker/login-action@v3
117+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
118118 with:
119119 registry: quay.io/oauth2-proxy
120120 username: ${{ secrets.REGISTRY_USERNAME }}
.github/workflows/stale.yml+1−1
@@ -10,7 +10,7 @@ jobs:
1010 runs-on: ubuntu-latest
1111
1212 steps:
13− - uses: actions/stale@v10
13+ - uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0
1414 with:
1515 repo-token: ${{ secrets.GITHUB_TOKEN }}
1616 days-before-stale: 180
.github/workflows/test.shdeleted−26
@@ -1,26 +0,0 @@
1−#!/bin/bash
2−# manually exiting from script, because after-build needs to run always
3−set +e
4−
5−if [ -z $CC_TEST_REPORTER_ID ]; then
6− echo "1. CC_TEST_REPORTER_ID is unset, skipping"
7−else
8− echo "1. Running before-build"
9− ./cc-test-reporter before-build
10−fi
11−
12−echo "2. Running test"
13−make test
14−TEST_STATUS=$?
15−
16−if [ -z $CC_TEST_REPORTER_ID ]; then
17− echo "3. CC_TEST_REPORTER_ID is unset, skipping"
18−else
19− echo "3. Running after-build"
20− ./cc-test-reporter after-build --exit-code $TEST_STATUS --prefix $(go list -m)
21−fi
22−
23−if [ "$TEST_STATUS" -ne 0 ]; then
24− echo "Test failed, status code: $TEST_STATUS"
25− exit $TEST_STATUS
26−fi
.golangci.yml+8
@@ -53,6 +53,14 @@ linters:
5353 - revive
5454 path: util/.*\.go$
5555 text: "var-naming: avoid meaningless package names"
56+ # pkg/version conflicts with go/version (added in Go 1.22)
57+ - linters:
58+ - revive
59+ path: pkg/version/.*\.go$
60+ text: "var-naming: avoid package names that conflict with"
61+ - linters:
62+ - prealloc
63+ path: _test\.go
5664 paths:
5765 - third_party$
5866 - builtin$
CHANGELOG.md+213
@@ -6,9 +6,222 @@
66
77## Breaking Changes
88
9+## Changes since v7.15.4
10+
11+# V7.15.4
12+
13+## Release Highlights
14+
15+- 🔵 Golang version upgrade to v1.26.7
16+ - Upgrade of all dependencies to their latest versions
17+- 🕵️‍♀️ Vulnerabilities have been addressed
18+ - [CVE-2026-33818](https://nvd.nist.gov/vuln/detail/CVE-2026-33818)
19+ - [CVE-2026-39821](https://nvd.nist.gov/vuln/detail/CVE-2026-39821)
20+ - [CVE-2026-39822](https://nvd.nist.gov/vuln/detail/CVE-2026-39822)
21+ - [CVE-2026-42505](https://nvd.nist.gov/vuln/detail/CVE-2026-42505)
22+ - [CVE-2026-46600](https://nvd.nist.gov/vuln/detail/CVE-2026-46600)
23+ - [CVE-2026-56852](https://nvd.nist.gov/vuln/detail/CVE-2026-56852)
24+ - [CVE-2026-56853](https://nvd.nist.gov/vuln/detail/CVE-2026-56853)
25+ - [CVE-2026-56858](https://nvd.nist.gov/vuln/detail/CVE-2026-56858)
26+ - [CVE-2026-56859](https://nvd.nist.gov/vuln/detail/CVE-2026-56859)
27+ - [CVE-2026-56860](https://nvd.nist.gov/vuln/detail/CVE-2026-56860)
28+ - [CVE-2026-56862](https://nvd.nist.gov/vuln/detail/CVE-2026-56862)
29+
30+## Important Notes
31+
32+## Breaking Changes
33+
34+## Changes since v7.15.3
35+
36+- [#3493](https://github.com/oauth2-proxy/oauth2-proxy/pull/3493) chore(deps): update gomod @tuunit
37+
38+# V7.15.3
39+
40+## Release Highlights
41+
42+- 🔵 Golang version upgrade to v1.26.4
43+ - Upgrade of all dependencies to their latest versions
44+- 🕵️‍♀️ Vulnerabilities have ben addressed
45+ - [CVE-2026-33811](https://nvd.nist.gov/vuln/detail/)
46+ - [CVE-2026-33814](https://nvd.nist.gov/vuln/detail/)
47+ - [CVE-2026-39820](https://nvd.nist.gov/vuln/detail/)
48+ - [CVE-2026-39836](https://nvd.nist.gov/vuln/detail/)
49+ - [CVE-2026-42499](https://nvd.nist.gov/vuln/detail/)
50+ - [CVE-2026-42504](https://nvd.nist.gov/vuln/detail/)
51+ - [CVE-2026-39823](https://nvd.nist.gov/vuln/detail/)
52+ - [CVE-2026-39826](https://nvd.nist.gov/vuln/detail/)
53+ - [CVE-2026-39825](https://nvd.nist.gov/vuln/detail/)
54+ - [CVE-2026-27145](https://nvd.nist.gov/vuln/detail/)
55+ - [CVE-2026-42507](https://nvd.nist.gov/vuln/detail/)
56+
57+## Important Notes
58+
59+## Breaking Changes
60+
61+## Changes since v7.15.2
62+
63+- [#3477](https://github.com/oauth2-proxy/oauth2-proxy/pull/3477) chore(dep): bump go to 1.26 and migrate of reverse proxy handling
64+
65+# V7.15.2
66+
67+## Release Highlights
68+
69+- 🔵 Golang version upgrade to v1.25.9
70+ - Upgrade of all dependencies to their latest versions
71+ - [CVE-2026-34986](https://nvd.nist.gov/vuln/detail/CVE-2026-34986)
72+ - [CVE-2026-32281](https://nvd.nist.gov/vuln/detail/CVE-2026-32281)
73+ - [CVE-2026-32289](https://nvd.nist.gov/vuln/detail/CVE-2026-32289)
74+ - [CVE-2026-32288](https://nvd.nist.gov/vuln/detail/CVE-2026-32288)
75+ - [CVE-2026-32280](https://nvd.nist.gov/vuln/detail/CVE-2026-32280)
76+ - [CVE-2026-32282](https://nvd.nist.gov/vuln/detail/CVE-2026-32282)
77+ - [CVE-2026-32283](https://nvd.nist.gov/vuln/detail/CVE-2026-32283)
78+- 🕵️‍♀️ Vulnerabilities have been addressed
79+
80+## Important Notes
81+
82+We have had security audits performed on OAuth2 Proxy in the past couple of weeks and as a result we have fixed
83+several CRITICAL vulnerabilities.
84+
85+The security vulnerabilities include multiple authentication bypasses and a potential session fixation attack.
86+For more details and to identify if you are effects, we urge all users of OAuth2 Proxy to read the security
87+disclosures.
88+
89+- (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
90+- (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
91+- (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
92+- (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
93+
94+Furthermore, for improving the security of OAuth2 Proxy we introduced a new flag `--trusted-proxy-ip` that allows users
95+to explicitly specify trusted reverse proxy IPs for the `X-Forwarded-*` headers. This is an important step to prevent
96+potential header spoofing attacks and to ensure that OAuth2 Proxy only trusts headers from known and trusted sources.
97+We highly recommend users to review their deployment architecture and consider using this flag to enhance the security
98+of their OAuth2 Proxy instances. Check the docs for more details: https://oauth2-proxy.github.io/oauth2-proxy/configuration/overview#proxy-options
99+
100+Furthermore, we want to thank everyone who contributed to the audits and reported potential issues to make open source
101+software like OAuth2 Proxy more secure for everyone.
102+
103+## Breaking Changes
104+
105+## Changes since v7.15.1
106+
107+- [#3411](https://github.com/oauth2-proxy/oauth2-proxy/pull/3411) chore(deps): update gomod dependencies (@tuunit)
108+- [#3333](https://github.com/oauth2-proxy/oauth2-proxy/pull/3333) fix: invalidate session on fatal OAuth2 refresh errors (@frhack)
109+- [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)
110+- [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)
111+- [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)
112+- [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)
113+- [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)
114+
115+# V7.15.1
116+
117+## Release Highlights
118+
119+- 🐛 Squashed some bugs
120+- 🕵️‍♀️ Vulnerabilities have been addressed
121+ - [CVE-2026-33186](https://nvd.nist.gov/vuln/detail/CVE-2026-33186)
122+ OAuth2 Proxy was not impacted by this vulnerability as it isn't in the path of execution
123+
124+## Important Notes
125+
126+## Breaking Changes
127+
128+## Changes since v7.15.0
129+
130+- [#3382](https://github.com/oauth2-proxy/oauth2-proxy/pull/3382) chore(deps): update gomod and golangci/golangci-lint to v2.11.4 (@tuunit)
131+- [#3374](https://github.com/oauth2-proxy/oauth2-proxy/pull/3374) fix: handle Unix socket RemoteAddr in IP resolution (@H1net)
132+- [#3381](https://github.com/oauth2-proxy/oauth2-proxy/pull/3381) fix: do not log error for backend logout 204 (@artificiosus)
133+- [#3327](https://github.com/oauth2-proxy/oauth2-proxy/pull/3327) fix: improve logging when session refresh token is missing (@yosri-brh)
134+- [#2767](https://github.com/oauth2-proxy/oauth2-proxy/pull/2767) fix: propagate errors during route building (@sybereal)
135+
136+# V7.15.0
137+
138+## Release Highlights
139+
140+- 🔒 OIDC JWT signing algorithms can now be configured
141+- 🍪 CSRF cookie improvements (SameSite option, proper expiration validation)
142+- 🧪 Configuration validation flag: --config-test
143+- 🔌 Unix socket file mode support
144+- 👤 Session state can now be extend with arbitrary claims from ID Token and upstream IDP user profiles endpoint
145+ - This opens the door for multiple features like:
146+ - Additional arbitrary header values for any claims your IDP provides
147+ - Extended OAuth2 Proxy UserInfo endpoint with all additional claims
148+ - Read the docs [here](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#how-to-utilize-arbitrary-claims-provided-by-your-identity-provider)
149+
150+## Important Notes
151+
152+CSRF cookie validation now correctly uses `CSRFExpire` instead of `Expire`. If you relied on the previous behavior, review your session timeout configuration.
153+Check the [documentation(https://oauth2-proxy.github.io/oauth2-proxy/configuration/overview#cookie-options) for `cookie-csrf-expire`.
154+
155+## Breaking Changes
156+
157+## Changes since v7.14.3
158+
159+- [#3352](https://github.com/oauth2-proxy/oauth2-proxy/pull/3352) fix: backend logout URL call on sign out (#3172)(@vsejpal)
160+- [#3332](https://github.com/oauth2-proxy/oauth2-proxy/pull/3332) ci: distribute windows binary with .exe extension (@igitur)
161+- [#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)
162+- [#3278](https://github.com/oauth2-proxy/oauth2-proxy/pull/3278) feat: possibility to inject id_token in redirect url during sign out (@albanf)
163+- [#2851](https://github.com/oauth2-proxy/oauth2-proxy/pull/2851) feat: add support for specifying allowed OIDC JWT signing algorithms (#2753) (@andoks / @tuunit)
164+- [#3369](https://github.com/oauth2-proxy/oauth2-proxy/pull/3369) fix: use CSRFExpire instead of Expire for CSRF cookie validation (@Br1an67)
165+- [#3365](https://github.com/oauth2-proxy/oauth2-proxy/pull/3365) fix: filter empty strings from allowed groups (@Br1an67)
166+- [#3338](https://github.com/oauth2-proxy/oauth2-proxy/pull/3338) feat: add --config-test flag for validating configuration (@MayorFaj)
167+- [#3347](https://github.com/oauth2-proxy/oauth2-proxy/pull/3347) feat: add same site option for csrf cookies (@jvnoije)
168+- [#3376](https://github.com/oauth2-proxy/oauth2-proxy/pull/3376) feat: allow setting unix socket file mode when declaring listener (@Tristan971 / @tuunit)
169+
170+# V7.14.3
171+
172+## Release Highlights
173+
174+- 🔵 Go1.25.7 and upgrade of dependencies to latest versions
175+ - Fixes [CVE-2025-68121](https://nvd.nist.gov/vuln/detail/cve-2025-68121)
176+- 🐛 Bug fixes
177+ - Allow Redis URL parameters to configure username, password and max idle connection timeout if the matching configuration is empty.
178+
179+## Important Notes
180+
181+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
182+
183+
184+## Breaking Changes
185+
186+## Changes since v7.14.2
187+
188+- [#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.
189+
190+# V7.14.2
191+
192+## Release Highlights
193+
194+- Revert AuthOnly endpoint change from v7.14.1 that caused issues when using `skip-provider-button` enabled
195+
196+## Important Notes
197+
198+- This release reverts the change made in v7.14.1 that caused issues when using the `skip-provider-button` enabled. Now, when a session does not exist, the AuthOnly endpoint will send a 401 status code as expected instead of a 302 redirect. And instead we extended the documentation to clarify the behavior when using `nginx` with `auth_request` and `skip-provider-button` and how to properly configure redirects for browser and API routes.
199+
200+## Breaking Changes
201+
202+## Changes since v7.14.1
203+
204+- [#3314](https://github.com/oauth2-proxy/oauth2-proxy/pull/3314) revert: fix: skip provider button auth only redirect (#3309) (@StefanMarkmann / @tuunit)
205+- [#3315](https://github.com/oauth2-proxy/oauth2-proxy/pull/3315) docs: clarify browser vs API routes for nginx auth_request redirects (@StefanMarkmann)
206+
207+# V7.14.1
208+
209+## Release Highlights
210+
211+- 🔵 Go1.25.6 and upgrade of dependencies to latest versions
212+- 🐛 Bug fixes
213+ - AuthOnly now starts the auth flow and send status code 302 if no session exists and skip-provider-button is true
214+ - Fixed static upstream validation issue due to incorrect defaults
215+
216+## Important Notes
217+
218+## Breaking Changes
219+
9220## Changes since v7.14.0
10221
11222- [#3309](https://github.com/oauth2-proxy/oauth2-proxy/pull/3309) fix: Return 302 redirect from AuthOnly endpoint when skip-provider-button is true (@StefanMarkmann)
223+- [#3302](https://github.com/oauth2-proxy/oauth2-proxy/pull/3302) fix: static upstreams failing validation due to `passHostHeader` and `proxyWebSockets` defaults being set incorrectly (@sourava01 / @tuunit)
224+- [#3312](https://github.com/oauth2-proxy/oauth2-proxy/pull/3312) chore(deps): upgrade to go1.25.6 and latest dependencies (@tuunit)
12225
13226# V7.14.0
14227
MAINTAINERS.md+1−1
@@ -6,7 +6,7 @@ by our [project governance](GOVERNANCE.md).
66| Name | GitHub Handle | Domains of reponsibility | Email Alias | Affiliation |
77| ---------------- | ------------------------------------------------------ | ------------------------ | -------------------------- | ----------- |
88| Joel Speed | [@JoelSpeed](https://github.com/joelspeed) | Governance, Core | joel@oauth2-proxy.dev | Red Hat |
9−| Jan Larwig | [@tuunit](https://github.com/tuunit) | Governance, Core | jan@oauth2-proxy.dev | IONOS Cloud |
9+| Jan Larwig | [@tuunit](https://github.com/tuunit) | Governance, Core | jan@oauth2-proxy.dev | STACKIT |
1010| JJ Łakis | [@jjlakis](https://github.com/jjlakis) | Provider | jj@oauth2-proxy.dev | - |
1111| Koen van Zuijlen | [@kvanzuijlen](https://github.com/kvanzuijlen) | CI | koen@oauth2-proxy.dev | - |
1212| Pierluigi Lenoci | [@pierluigilenoci](https://github.com/pierluigilenoci) | Helm | pierluigi@oauth2-proxy.dev | SAP |
Makefile+10−5
@@ -25,7 +25,8 @@ help: ## Display this help
2525
2626
2727GO ?= go
28−GOLANGCILINT ?= golangci-lint
28+# renovate: datasource=github-tags depName=golangci/golangci-lint
29+GOLANGCILINT_VERSION ?= v2.11.4
2930
3031BINARY := oauth2-proxy
3132VERSION ?= $(shell git describe --always --dirty --tags 2>/dev/null || echo "undefined")
@@ -66,7 +67,7 @@ DOCKER_BUILDX_PUSH := $(DOCKER_BUILDX) --push
6667DOCKER_BUILDX_PUSH_X_PLATFORM := $(DOCKER_BUILDX_PUSH) --platform ${DOCKER_BUILD_PLATFORM}
6768
6869DOCKER_BUILD_PLATFORM_ALPINE ?= linux/amd64,linux/arm64,linux/ppc64le,linux/arm/v6,linux/arm/v7,linux/s390x
69−DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.23.2
70+DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.24.1
7071DOCKER_BUILDX_ARGS_ALPINE ?= --build-arg RUNTIME_IMAGE=${DOCKER_BUILD_RUNTIME_IMAGE_ALPINE} ${DOCKER_BUILDX_COMMON_ARGS}
7172DOCKER_BUILDX_X_PLATFORM_ALPINE := docker buildx build ${DOCKER_BUILDX_ARGS_ALPINE} --platform ${DOCKER_BUILD_PLATFORM_ALPINE}
7273DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE := $(DOCKER_BUILDX_X_PLATFORM_ALPINE) --push
@@ -143,11 +144,11 @@ verify-generate: generate ## Verify command to check if alpha config docs are in
143144##@ Miscellaneous
144145
145146.PHONY: test
146−test: lint ## Run all Go tests
147+test: ## Run all Go tests
147148 GO111MODULE=on $(GO) test $(TESTCOVER) -v -race ./...
148149
149150.PHONY: release
150−release: validate-go-version lint test ## Create a full release for all architectures (binaries and checksums)
151+release: validate-go-version ## Create a full release for all architectures (binaries and checksums)
151152 BINARY=${BINARY} VERSION=${VERSION} ./dist.sh
152153
153154.PHONY: clean
@@ -157,7 +158,11 @@ clean: ## Cleanup release and build files
157158
158159.PHONY: lint
159160lint: validate-go-version ## Lint all files using golangci-lint
160− GO111MODULE=on $(GOLANGCILINT) run
161+ GO111MODULE=on $(GO) run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@$(GOLANGCILINT_VERSION) run --timeout 10m
162+
163+.PHONY: lint-fix
164+lint-fix: validate-go-version ## Lint all files and apply fixes using golangci-lint
165+ GO111MODULE=on $(GO) run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@$(GOLANGCILINT_VERSION) run --timeout 10m --fix
161166
162167.PHONY: validate-go-version
163168validate-go-version: ## Validate Go environment requirements
README.md+4−4
@@ -12,7 +12,7 @@
1212
1313OAuth2 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.
1414
15−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.
15+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.
1616
1717![Simplified Architecture](docs/static/img/simplified-architecture.svg)
1818
@@ -23,7 +23,7 @@ OAuth2 Proxy's [Installation Docs](https://oauth2-proxy.github.io/oauth2-proxy/i
2323## Releases
2424
2525### Binaries
26−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`.
26+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`.
2727
2828Check out the [latest release](https://github.com/oauth2-proxy/oauth2-proxy/releases/latest).
2929
@@ -49,9 +49,9 @@ SAP Open Source Program
4949Microsoft Azure credits for open source projects
5050
5151## Getting Involved
52−[![Slack](https://img.shields.io/badge/slack-Gopher_%23oauth2--proxy-red?logo=slack)](https://gophers.slack.com/archives/CM2RSS25N)
52+[![Slack](https://img.shields.io/badge/slack-CNCF_%23oauth2--proxy-blue?logo=slack)](https://cloud-native.slack.com/archives/C098Y5URZ2N)
5353
54−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.
54+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://slack.cncf.io/) to get an invite for the CNCF space.
5555
5656OAuth2 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.
5757
contrib/local-environment/Makefile+2−2
@@ -49,8 +49,8 @@ kubernetes-down:
4949
5050.PHONY: traefik-up
5151traefik-up:
52− docker compose -f docker-compose.yaml -f docker-compose-traefik.yaml up -d
52+ docker compose -f docker-compose-traefik.yaml up -d
5353
5454.PHONY: traefik-%
5555traefik-%:
56− docker compose -f docker-compose.yaml -f docker-compose-traefik.yaml $*
56+ docker compose -f docker-compose-traefik.yaml $*
contrib/local-environment/dex-traefik.yamlnew file+25
@@ -0,0 +1,25 @@
1+# This configuration is intended to be used with the Traefik local environment.
2+# Dex uses in-memory storage because this environment is disposable.
3+issuer: http://dex.localtest.me/dex
4+storage:
5+ type: memory
6+web:
7+ http: 0.0.0.0:5556
8+oauth2:
9+ skipApprovalScreen: true
10+expiry:
11+ signingKeys: "4h"
12+ idTokens: "1h"
13+staticClients:
14+ - id: oauth2-proxy
15+ redirectURIs:
16+ - "http://oauth2-proxy.localtest.me/oauth2/callback"
17+ name: "OAuth2 Proxy"
18+ secret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK
19+enablePasswordDB: true
20+staticPasswords:
21+ - email: "admin@example.com"
22+ # bcrypt hash of the string "password"
23+ hash: "$2a$10$2b2cU8CPhOTaGrs1HRQuAueS7JTT5ZHsHSzYiFPm1leZck7Mc8T4W"
24+ username: "admin"
25+ userID: "08a8684b-db88-4b73-90a9-3cd1661f5466"
contrib/local-environment/dex.yaml+13−17
@@ -3,11 +3,7 @@
33# This should configure Dex to run on port 5556 and provides a static login
44issuer: http://dex.localtest.me:5556/dex
55storage:
6− type: etcd
7− config:
8− endpoints:
9− - http://etcd:2379
10− namespace: dex/
6+ type: memory
117web:
128 http: 0.0.0.0:5556
139oauth2:
@@ -16,17 +12,17 @@ expiry:
1612 signingKeys: "4h"
1713 idTokens: "1h"
1814staticClients:
19−- id: oauth2-proxy
20− redirectURIs:
21− # These redirect URIs point to the `--redirect-url` for OAuth2 proxy.
22− - 'http://oauth2-proxy.localtest.me:4180/oauth2/callback' # For basic proxy example.
23− - 'http://oauth2-proxy.oauth2-proxy.localhost/oauth2/callback' # For nginx and traefik example.
24− name: 'OAuth2 Proxy'
25− secret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK
15+ - id: oauth2-proxy
16+ redirectURIs:
17+ # These redirect URIs point to the `--redirect-url` for OAuth2 proxy.
18+ - "http://oauth2-proxy.localtest.me:4180/oauth2/callback" # For basic proxy example.
19+ - "http://oauth2-proxy.localtest.me:8080/oauth2/callback" # For nginx example.
20+ name: "OAuth2 Proxy"
21+ secret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK
2622enablePasswordDB: true
2723staticPasswords:
28−- email: "admin@example.com"
29− # bcrypt hash of the string "password"
30− hash: "$2a$10$2b2cU8CPhOTaGrs1HRQuAueS7JTT5ZHsHSzYiFPm1leZck7Mc8T4W"
31− username: "admin"
32− userID: "08a8684b-db88-4b73-90a9-3cd1661f5466"
24+ - email: "admin@example.com"
25+ # bcrypt hash of the string "password"
26+ hash: "$2a$10$2b2cU8CPhOTaGrs1HRQuAueS7JTT5ZHsHSzYiFPm1leZck7Mc8T4W"
27+ username: "admin"
28+ userID: "08a8684b-db88-4b73-90a9-3cd1661f5466"
contrib/local-environment/docker-compose-alpha-config.yaml+3−16
@@ -1,7 +1,7 @@
11# This docker-compose file can be used to bring up an example instance of oauth2-proxy
22# for manual testing and exploration of features.
33# Alongside OAuth2-Proxy, this file also starts Dex to act as the identity provider,
4−# etcd for storage for Dex and HTTPBin as an example upstream.
4+# HTTPBin as an example upstream.
55# This file also uses alpha configuration when configuring OAuth2 Proxy.
66#
77# This file is an extension of the main compose file and must be used with it
@@ -14,7 +14,7 @@ version: "3.0"
1414services:
1515 oauth2-proxy:
1616 container_name: oauth2-proxy
17− image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0
17+ image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.4
1818 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml
1919 hostname: oauth2-proxy
2020 volumes:
@@ -31,7 +31,7 @@ services:
3131 - httpbin
3232 dex:
3333 container_name: dex
34− image: ghcr.io/dexidp/dex:v2.44.0
34+ image: ghcr.io/dexidp/dex:v2.45.1
3535 command: dex serve /dex.yaml
3636 hostname: dex
3737 volumes:
@@ -43,25 +43,12 @@ services:
4343 dex:
4444 aliases:
4545 - dex.localtest.me
46− etcd: {}
47− depends_on:
48− - etcd
4946 httpbin:
5047 container_name: httpbin
5148 image: kennethreitz/httpbin
5249 ports: []
5350 networks:
5451 httpbin: {}
55− etcd:
56− container_name: etcd
57− image: gcr.io/etcd-development/etcd:v3.6.7
58− entrypoint: /usr/local/bin/etcd
59− command:
60− - --listen-client-urls=http://0.0.0.0:2379
61− - --advertise-client-urls=http://etcd:2379
62− networks:
63− etcd: {}
6452networks:
6553 dex: {}
66− etcd: {}
6754 httpbin: {}
contrib/local-environment/docker-compose-gitea.yaml+2−2
@@ -14,7 +14,7 @@ version: '3.0'
1414services:
1515 oauth2-proxy:
1616 container_name: oauth2-proxy
17− image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0
17+ image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.4
1818 command: --config /oauth2-proxy.cfg
1919 hostname: oauth2-proxy
2020 volumes:
@@ -39,7 +39,7 @@ services:
3939 httpbin: {}
4040
4141 gitea:
42− image: gitea/gitea:1.25.3
42+ image: gitea/gitea:1.27.2
4343 container_name: gitea
4444 environment:
4545 - USER_UID=1000
contrib/local-environment/docker-compose-keycloak.yaml+6−6
@@ -10,11 +10,11 @@
1010#
1111# Access http://oauth2-proxy.localtest.me:4180 to initiate a login cycle using user=admin@example.com, password=password
1212# Access http://keycloak.localtest.me:9080 with the same credentials to check out the settings
13−version: '3.0'
13+version: "3.0"
1414services:
1515 oauth2-proxy:
1616 container_name: oauth2-proxy
17− image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0
17+ image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.4
1818 command: --config /oauth2-proxy.cfg
1919 hostname: oauth2-proxy
2020 volumes:
@@ -40,12 +40,12 @@ services:
4040
4141 keycloak:
4242 container_name: keycloak
43− image: keycloak/keycloak:25.0
43+ image: keycloak/keycloak:26.7
4444 hostname: keycloak
4545 command:
46− - 'start-dev'
47− - '--http-port=9080'
48− - '--import-realm'
46+ - "start-dev"
47+ - "--http-port=9080"
48+ - "--import-realm"
4949 volumes:
5050 - ./keycloak:/opt/keycloak/data/import
5151 environment:
contrib/local-environment/docker-compose-nginx.yaml+9−33
@@ -1,38 +1,28 @@
11# This docker-compose file can be used to bring up an example instance of oauth2-proxy
22# for manual testing and exploration of features.
33# Alongside OAuth2-Proxy, this file also starts Dex to act as the identity provider,
4−# etcd for storage for Dex, nginx as a reverse proxy and other http services for upstreams
4+# nginx as a reverse proxy and other HTTP services for upstreams.
55#
66# This file is an extension of the main compose file and must be used with it
77# docker-compose -f docker-compose.yaml -f docker-compose-nginx.yaml <command>
88# Alternatively:
99# make nginx-<command> (eg make nginx-up, make nginx-down)
1010#
11−# Access one of the following URLs to initiate a login flow:
12−# - http://oauth2-proxy.localhost
13−# - http://httpbin.oauth2-proxy.localhost
14−#
15−# The OAuth2 Proxy itself is hosted at http://oauth2-proxy.oauth2-proxy.localhost
16−#
17−# Note, the above URLs should work with Chrome, but you may need to add hosts
18−# entries for other browsers
19−# 127.0.0.1 oauth2-proxy.localhost
20−# 127.0.0.1 httpbin.oauth2-proxy.localhost
21−# 127.0.0.1 oauth2-proxy.oauth2-proxy.localhost
22−version: '3.0'
11+# Access http://oauth2-proxy.localtest.me:8080 to initiate a login flow.
12+version: "3.0"
2313services:
2414 oauth2-proxy:
25− image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0
15+ image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.4
2616 ports: []
2717 hostname: oauth2-proxy
2818 container_name: oauth2-proxy
2919 command: --config /oauth2-proxy.cfg
20+ restart: unless-stopped
3021 volumes:
3122 - "./oauth2-proxy-nginx.cfg:/oauth2-proxy.cfg"
3223 networks:
3324 oauth2-proxy: {}
3425 dex: {}
35− etcd: {}
3626 httpbin: {}
3727 depends_on:
3828 - dex
@@ -41,52 +31,38 @@ services:
4131 depends_on:
4232 - oauth2-proxy
4333 container_name: nginx
44− image: nginx:1.29
34+ image: nginx:1.31
4535 restart: unless-stopped
4636 ports:
47− - 80:80/tcp
37+ - 8080:8080/tcp
4838 hostname: nginx
4939 volumes:
5040 - "./nginx.conf:/etc/nginx/conf.d/default.conf"
5141 networks:
5242 oauth2-proxy: {}
5343 dex: {}
54− etcd: {}
5544 httpbin: {}
5645 dex:
5746 container_name: dex
58− image: ghcr.io/dexidp/dex:v2.44.0
47+ image: ghcr.io/dexidp/dex:v2.45.1
5948 command: dex serve /dex.yaml
6049 hostname: dex
6150 volumes:
6251 - "./dex.yaml:/dex.yaml"
6352 restart: unless-stopped
6453 ports:
65− - 5556:4181/tcp
54+ - 5556:5556/tcp
6655 networks:
6756 dex:
6857 aliases:
6958 - dex.localtest.me
70− etcd: {}
71− depends_on:
72− - etcd
7359 httpbin:
7460 container_name: httpbin
7561 image: kennethreitz/httpbin
7662 ports: []
7763 networks:
7864 httpbin: {}
79− etcd:
80− container_name: etcd
81− image: gcr.io/etcd-development/etcd:v3.6.7
82− entrypoint: /usr/local/bin/etcd
83− command:
84− - --listen-client-urls=http://0.0.0.0:2379
85− - --advertise-client-urls=http://etcd:2379
86− networks:
87− etcd: {}
8865networks:
8966 dex: {}
90− etcd: {}
9167 httpbin: {}
9268 oauth2-proxy: {}
contrib/local-environment/docker-compose-traefik.yaml+42−18
@@ -1,7 +1,7 @@
11# This docker-compose file can be used to bring up an example instance of oauth2-proxy
22# for manual testing and exploration of features.
3−# Alongside OAuth2-Proxy, this file also starts Dex to act as the identity provider,
4−# HTTPBin as an example upstream.
3+# Alongside OAuth2-Proxy, this file also starts Dex to act as the identity provider
4+# and HTTPBin as an example upstream.
55#
66# This can either be created using docker-compose
77# docker-compose -f docker-compose-traefik.yaml <command>
@@ -9,32 +9,51 @@
99# make traefik-<command> (eg. make traefik-up, make traefik-down)
1010#
1111# Access one of the following URLs to initiate a login flow:
12−# - http://oauth2-proxy.localhost
13−# - http://httpbin.oauth2-proxy.localhost
12+# - http://oauth2-proxy.localtest.me
13+# - http://httpbin.localtest.me
14+# - http://dex.localtest.me/dex
1415#
15−# The OAuth2 Proxy itself is hosted at http://oauth2-proxy.oauth2-proxy.localhost
16−#
17−# Note, the above URLs should work with Chrome, but you may need to add hosts
18−# entries for other browsers
19−# 127.0.0.1 oauth2-proxy.localhost
20−# 127.0.0.1 httpbin.oauth2-proxy.localhost
21−# 127.0.0.1 oauth2-proxy.oauth2-proxy.localhost
22−version: '3.0'
16+# The OAuth2 Proxy itself is hosted at http://oauth2-proxy.localtest.me
2317services:
2418
2519 oauth2-proxy:
26− image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0
20+ container_name: oauth2-proxy
21+ image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.4
22+ command: --config /oauth2-proxy.cfg
2723 ports: []
2824 hostname: oauth2-proxy
2925 volumes:
3026 - "./oauth2-proxy-traefik.cfg:/oauth2-proxy.cfg"
27+ restart: unless-stopped
28+ networks:
29+ oauth2-proxy: {}
30+ dex: {}
31+ depends_on:
32+ - dex
33+ - httpbin
34+
35+ dex:
36+ container_name: dex
37+ image: ghcr.io/dexidp/dex:v2.45.1
38+ command: dex serve /dex.yaml
39+ hostname: dex
40+ volumes:
41+ - "./dex-traefik.yaml:/dex.yaml"
42+ restart: unless-stopped
3143 networks:
32− oauth2-proxy:
44+ dex: {}
45+
46+ httpbin:
47+ container_name: httpbin
48+ image: kennethreitz/httpbin
49+ ports: []
50+ networks:
51+ httpbin: {}
3352
3453 # Reverse proxy
3554 gateway:
3655 container_name: traefik
37− image: traefik:v2.11.35
56+ image: traefik:v3.7.10
3857 volumes:
3958 - "./traefik:/etc/traefik"
4059 ports:
@@ -43,8 +62,13 @@ services:
4362 depends_on:
4463 - oauth2-proxy
4564 networks:
46− oauth2-proxy:
47− httpbin:
65+ oauth2-proxy: {}
66+ httpbin: {}
67+ dex:
68+ aliases:
69+ - dex.localtest.me
4870
4971networks:
50− oauth2-proxy:
72+ dex: {}
73+ httpbin: {}
74+ oauth2-proxy: {}
contrib/local-environment/docker-compose.yaml+3−16
@@ -1,7 +1,7 @@
11# This docker-compose file can be used to bring up an example instance of oauth2-proxy
22# for manual testing and exploration of features.
33# Alongside OAuth2-Proxy, this file also starts Dex to act as the identity provider,
4−# etcd for storage for Dex and HTTPBin as an example upstream.
4+# HTTPBin as an example upstream.
55#
66# This can either be created using docker-compose
77# docker-compose -f docker-compose.yaml <command>
@@ -13,7 +13,7 @@ version: "3.0"
1313services:
1414 oauth2-proxy:
1515 container_name: oauth2-proxy
16− image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0
16+ image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.4
1717 command: --config /oauth2-proxy.cfg
1818 hostname: oauth2-proxy
1919 volumes:
@@ -29,7 +29,7 @@ services:
2929 - httpbin
3030 dex:
3131 container_name: dex
32− image: ghcr.io/dexidp/dex:v2.44.0
32+ image: ghcr.io/dexidp/dex:v2.45.1
3333 command: dex serve /dex.yaml
3434 hostname: dex
3535 volumes:
@@ -41,25 +41,12 @@ services:
4141 dex:
4242 aliases:
4343 - dex.localtest.me
44− etcd: {}
45− depends_on:
46− - etcd
4744 httpbin:
4845 container_name: httpbin
4946 image: kennethreitz/httpbin
5047 ports: []
5148 networks:
5249 httpbin: {}
53− etcd:
54− container_name: etcd
55− image: gcr.io/etcd-development/etcd:v3.6.7
56− entrypoint: /usr/local/bin/etcd
57− command:
58− - --listen-client-urls=http://0.0.0.0:2379
59− - --advertise-client-urls=http://etcd:2379
60− networks:
61− etcd: {}
6250networks:
6351 dex: {}
64− etcd: {}
6552 httpbin: {}
contrib/local-environment/kubernetes/Chart.lock+3−3
@@ -1,7 +1,7 @@
11dependencies:
22- name: dex
33 repository: https://charts.dexidp.io
4− version: 0.24.0
4+ version: 0.24.1
55- name: oauth2-proxy
66 repository: https://oauth2-proxy.github.io/manifests
77 version: 7.18.0
@@ -11,5 +11,5 @@ dependencies:
1111- name: hello-world
1212 repository: https://conservis.github.io/helm-charts
1313 version: 1.1.0
14−digest: sha256:fee913531bfb67e5555e995d8fb040c330e6eb4b5a8c777ceb9841135ea9bb84
15−generated: "2025-10-28T06:46:35.38300324Z"
14+digest: sha256:3fff8bf99cebcd20a73c984423d5f1c2dfa1e5a394f82a5dc60d9aaffe5361b7
15+generated: "2026-08-18T07:33:03.791274914Z"
contrib/local-environment/kubernetes/Chart.yaml+1−1
@@ -3,7 +3,7 @@ description: K8S example based on https://kind.sigs.k8s.io
33name: kubernetes
44dependencies:
55 - name: dex
6− version: 0.24.0
6+ version: 0.24.1
77 repository: https://charts.dexidp.io
88 - name: oauth2-proxy
99 version: &chartVersion 7.18.0
contrib/local-environment/nginx.conf+31−73
@@ -1,86 +1,44 @@
1−# Reverse proxy to oauth2-proxy
2−server {
3− listen 80;
4− server_name oauth2-proxy.oauth2-proxy.localhost;
5−
6− location / {
7− proxy_set_header Host $host;
8− proxy_set_header X-Real-IP $remote_addr;
9−
10− proxy_pass http://oauth2-proxy:4180/;
11− }
12−}
13−
141# Reverse proxy to httpbin
152server {
16− listen 80;
17− server_name httpbin.oauth2-proxy.localhost;
18−
19− auth_request /internal-auth/oauth2/auth;
20−
21− # If the auth_request denies the request (401), redirect to the sign_in page
22− # and include the final rd URL back to the user's original request.
23− error_page 401 =403 http://oauth2-proxy.oauth2-proxy.localhost/oauth2/sign_in?rd=$scheme://$host$request_uri;
24−
25− # Alternatively send the request to `start` to skip the provider button
26− # error_page 401 = http://oauth2-proxy.oauth2-proxy.localhost/oauth2/start?rd=$scheme://$host$request_uri;
27−
28− location / {
29− proxy_pass http://httpbin/;
3+ listen 8080;
4+ server_name oauth2-proxy.localtest.me;
5+
6+ location /oauth2/ {
7+ proxy_pass http://oauth2-proxy:4180;
8+ proxy_set_header Host $host;
9+ proxy_set_header X-Real-IP $remote_addr;
10+ proxy_set_header X-Forwarded-Uri $request_uri;
11+ proxy_set_header X-Auth-Request-Redirect $request_uri;
3012 }
3113
32− # auth_request must be a URI so this allows an internal path to then proxy to
33− # the real auth_request path.
34− # The trailing /'s are required so that nginx strips the prefix before proxying.
35− location /internal-auth/ {
36− internal; # Ensure external users can't access this path
37−
38− # Make sure the OAuth2 Proxy knows where the original request came from.
39− proxy_set_header Host $host;
40− proxy_set_header X-Real-IP $remote_addr;
41− proxy_set_header X-Forwarded-Uri $request_uri;
42−
43− proxy_pass http://oauth2-proxy:4180/;
14+ location = /oauth2/auth {
15+ proxy_pass http://oauth2-proxy:4180;
16+ proxy_set_header Host $host;
17+ proxy_set_header X-Real-IP $remote_addr;
18+ proxy_set_header X-Forwarded-Uri $request_uri;
19+ # nginx auth_request includes headers but not body
20+ proxy_set_header Content-Length "";
21+ proxy_pass_request_body off;
4422 }
45−}
46−
47−# Statically serve the nginx welcome
48−server {
49− listen 80;
50− server_name oauth2-proxy.localhost;
5123
5224 location / {
53− auth_request /internal-auth/oauth2/auth;
54−
55− # If the auth_request denies the request (401), redirect to the sign_in page
56− # and include the final rd URL back to the user's original request.
57− error_page 401 =403 http://oauth2-proxy.oauth2-proxy.localhost/oauth2/sign_in?rd=$scheme://$host$request_uri;
25+ auth_request /oauth2/auth;
26+ error_page 401 = @oauth2_signin;
5827
59− # Alternatively send the request to `start` to skip the provider button
60− # error_page 401 = http://oauth2-proxy.oauth2-proxy.localhost/oauth2/start?rd=$scheme://$host$request_uri;
28+ # pass information via X-User and X-Email headers to backend,
29+ # requires running with --set-xauthrequest flag
30+ auth_request_set $user $upstream_http_x_auth_request_user;
31+ auth_request_set $email $upstream_http_x_auth_request_email;
32+ proxy_set_header X-User $user;
33+ proxy_set_header X-Email $email;
6134
62−
63− root /usr/share/nginx/html;
64− index index.html index.htm;
65− }
66−
67− # redirect server error pages to the static page /50x.html
68− error_page 500 502 503 504 /50x.html;
69− location = /50x.html {
70− root /usr/share/nginx/html;
35+ proxy_pass http://httpbin/;
36+ # or "root /path/to/site;" or "fastcgi_pass ..." etc
7137 }
7238
73− # auth_request must be a URI so this allows an internal path to then proxy to
74− # the real auth_request path.
75− # The trailing /'s are required so that nginx strips the prefix before proxying.
76− location /internal-auth/ {
77− internal; # Ensure external users can't access this path
78−
79− # Make sure the OAuth2 Proxy knows where the original request came from.
80− proxy_set_header Host $host;
81− proxy_set_header X-Real-IP $remote_addr;
82− proxy_set_header X-Forwarded-Uri $request_uri;
83−
84− proxy_pass http://oauth2-proxy:4180/;
39+ # Named location for handling OAuth2 sign-in redirects
40+ # This ensures the browser receives a proper 302 redirect that it will follow
41+ location @oauth2_signin {
42+ return 302 /oauth2/sign_in?rd=$scheme://$http_host$request_uri;
8543 }
8644}
contrib/local-environment/oauth2-proxy-nginx.cfg+11−6
@@ -1,14 +1,19 @@
11http_address="0.0.0.0:4180"
22cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w="
3−provider="oidc"
43email_domains="example.com"
5−oidc_issuer_url="http://dex.localtest.me:5556/dex"
4+cookie_secure="false"
5+upstreams="static://200"
6+cookie_domains=[".localtest.me"] # Required so cookie can be read on all subdomains.
7+whitelist_domains=[".localtest.me"] # Required to allow redirection back to original requested target.
8+
9+# dex provider
610client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK"
711client_id="oauth2-proxy"
8−cookie_secure="false"
12+redirect_url="http://oauth2-proxy.localtest.me:8080/oauth2/callback"
13+
14+oidc_issuer_url="http://dex.localtest.me:5556/dex"
15+provider="oidc"
16+provider_display_name="Dex"
917
10−redirect_url="http://oauth2-proxy.oauth2-proxy.localhost/oauth2/callback"
11−cookie_domains=".oauth2-proxy.localhost" # Required so cookie can be read on all subdomains.
12−whitelist_domains=".oauth2-proxy.localhost" # Required to allow redirection back to original requested target.
1318# Enables the use of `X-Forwarded-*` headers to determine request correctly
1419reverse_proxy="true"
contrib/local-environment/oauth2-proxy-traefik.cfg+4−4
@@ -2,14 +2,14 @@ http_address="0.0.0.0:4180"
22cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w="
33provider="oidc"
44email_domains=["example.com"]
5−oidc_issuer_url="http://dex.localhost:5556/dex"
5+oidc_issuer_url="http://dex.localtest.me/dex"
66client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK"
77client_id="oauth2-proxy"
88cookie_secure="false"
99
10−redirect_url="http://oauth2-proxy.oauth2-proxy.localhost/oauth2/callback"
11−cookie_domains=".oauth2-proxy.localhost" # Required so cookie can be read on all subdomains.
12−whitelist_domains=".oauth2-proxy.localhost" # Required to allow redirection back to original requested target.
10+redirect_url="http://oauth2-proxy.localtest.me/oauth2/callback"
11+cookie_domains=".localtest.me" # Required so cookie can be read on all subdomains.
12+whitelist_domains=".localtest.me" # Required to allow redirection back to original requested target.
1313
1414# Mandatory option when using oauth2-proxy with traefik
1515reverse_proxy="true"
contrib/local-environment/traefik/dynamic.yaml+11−4
@@ -1,22 +1,25 @@
11http:
22 routers:
33 oauth2-proxy-route:
4− rule: "Host(`oauth2-proxy.oauth2-proxy.localhost`)"
4+ rule: "Host(`oauth2-proxy.localtest.me`)"
55 middlewares:
66 - auth-headers
77 service: oauth-backend
8+ dex-route:
9+ rule: "Host(`dex.localtest.me`)"
10+ service: dex-service
811 httpbin-route:
9− rule: "Host(`httpbin.oauth2-proxy.localhost`)"
12+ rule: "Host(`httpbin.localtest.me`)"
1013 service: httpbin-service
1114 middlewares:
1215 - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin
1316 httpbin-route-2:
14− rule: "Host(`httpbin.oauth2-proxy.localhost`) && PathPrefix(`/no-auto-redirect`)"
17+ rule: "Host(`httpbin.localtest.me`) && PathPrefix(`/no-auto-redirect`)"
1518 service: httpbin-service
1619 middlewares:
1720 - oauth-auth-wo-redirect # unauthenticated session will return a 401
1821 services-oauth2-route:
19− rule: "Host(`httpbin.oauth2-proxy.localhost`) && PathPrefix(`/oauth2/`)"
22+ rule: "Host(`httpbin.localtest.me`) && PathPrefix(`/oauth2/`)"
2023 middlewares:
2124 - auth-headers
2225 service: oauth-backend
@@ -30,6 +33,10 @@ http:
3033 loadBalancer:
3134 servers:
3235 - url: http://oauth2-proxy:4180
36+ dex-service:
37+ loadBalancer:
38+ servers:
39+ - url: http://dex:5556
3340
3441 middlewares:
3542 auth-headers:
contrib/local-environment/traefik/traefik.yaml+2
@@ -5,3 +5,5 @@ log:
55providers:
66 file:
77 filename: /etc/traefik/dynamic.yaml
8+ # Routes are static for this example; disabling watch avoids host inotify limits.
9+ watch: false
dist.sh+10−3
@@ -30,16 +30,23 @@ for ARCH in "${ARCHS[@]}"; do
3030 GO_OS=$(echo $ARCH | awk -F- '{print $1}')
3131 GO_ARCH=$(echo $ARCH | awk -F- '{print $2}')
3232
33+ # Determine binary name based on OS
34+ if [[ "${GO_OS}" == "windows" ]]; then
35+ BINARY_NAME="${BINARY}.exe"
36+ else
37+ BINARY_NAME="${BINARY}"
38+ fi
39+
3340 # Create architecture specific binaries
3441 if [[ ${GO_ARCH} == armv* ]]; then
3542 GO_ARM=$(echo $GO_ARCH | awk -Fv '{print $2}')
3643 GO111MODULE=on GOOS=${GO_OS} GOARCH=arm GOARM=${GO_ARM} CGO_ENABLED=0 go build \
3744 -ldflags="-X github.com/oauth2-proxy/oauth2-proxy/v7/pkg/version.VERSION=${VERSION}" \
38− -o release/${BINARY}-${VERSION}.${ARCH}/${BINARY} .
45+ -o release/${BINARY}-${VERSION}.${ARCH}/${BINARY_NAME} .
3946 else
4047 GO111MODULE=on GOOS=${GO_OS} GOARCH=${GO_ARCH} CGO_ENABLED=0 go build \
4148 -ldflags="-X github.com/oauth2-proxy/oauth2-proxy/v7/pkg/version.VERSION=${VERSION}" \
42− -o release/${BINARY}-${VERSION}.${ARCH}/${BINARY} .
49+ -o release/${BINARY}-${VERSION}.${ARCH}/${BINARY_NAME} .
4350 fi
4451
4552 cd release
@@ -51,7 +58,7 @@ for ARCH in "${ARCHS[@]}"; do
5158 sha256sum ${BINARY}-${VERSION}.${ARCH}.tar.gz > ${BINARY}-${VERSION}.${ARCH}.tar.gz-sha256sum.txt
5259
5360 # Create sha256sum for architecture specific binary
54− sha256sum ${BINARY}-${VERSION}.${ARCH}/${BINARY} > ${BINARY}-${VERSION}.${ARCH}-sha256sum.txt
61+ sha256sum ${BINARY}-${VERSION}.${ARCH}/${BINARY_NAME} > ${BINARY}-${VERSION}.${ARCH}-sha256sum.txt
5562
5663 cd ..
5764done
docs/docs/configuration/alpha_config.md+79−3
@@ -106,6 +106,17 @@ the new config.
106106oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg
107107```
108108
109+### Validating Alpha Configuration
110+
111+Use `--config-test` to validate your alpha configuration without starting the proxy:
112+
113+```bash
114+oauth2-proxy --config core.cfg --alpha-config alpha.yaml --config-test
115+```
116+
117+This is useful for CI/CD pipelines to catch configuration errors before deployment.
118+See the [Configuration Validation](./overview.md#configuration-validation) section for more details.
119+
109120### How to use environment variables
110121
111122The 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.
@@ -156,10 +167,73 @@ injectResponseHeaders:
156167* `claimSource` - `claim` (session claims either from id token or from profile URL)
157168* `secretSource` - `value` (base64), `fromFile` (file path)
158169
170+#### Claim value serialization
171+
172+`claimSource` converts the selected claim into one or more string header values. Scalars
173+produce one value, while arrays produce one value per element. Values that cannot be
174+converted directly to strings, such as objects, are JSON-encoded individually.
175+
176+Each non-empty value is added separately under the configured header name. An array of
177+objects therefore produces multiple header values containing one JSON object each, not a
178+single JSON array. HTTP libraries and intermediaries may expose repeated values as a
179+comma-joined string, so consumers should retrieve and parse each header value separately.
180+
159181**Request option:** `preserveRequestValue: true` retains existing header values
160182
161183**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest`
162184
185+### How to utilize arbitrary claims provided by your Identity Provider
186+
187+With the additionalClaims attribute you can specify which claims you want to extract
188+from the ID Token or userinfo (ProfileURL) endpoint.
189+
190+Configure these on the relevant provider entry:
191+
192+```yaml
193+providers:
194+ - id: my-oidc-provider
195+ provider: oidc
196+ clientID: ${OAUTH_CLIENT_ID}
197+ clientSecret: ${OAUTH_CLIENT_SECRET}
198+ oidcConfig:
199+ issuerURL: https://issuer.example.com
200+ profileURL: https://issuer.example.com/oauth2/userinfo
201+ additionalClaims:
202+ - department
203+ - employee_id
204+ - organization.name
205+```
206+
207+OAuth2 Proxy resolves each configured claim using the following order:
208+
209+1. The raw ID token is checked first.
210+2. If the claim is not present there and `profileURL` is configured, the userinfo endpoint is queried.
211+3. If `skipClaimsFromProfileURL: true` is set, only the ID token is used.
212+
213+Claims that are not found are ignored rather than causing authentication to fail.
214+
215+You can use dot-separated paths for nested JSON objects, for example `organization.name`.
216+Array indexes are not supported.
217+
218+Once loaded, these claims are stored in the session as `additionalClaims`. They can then be
219+used anywhere session claims are accepted, including header injection:
220+
221+```yaml
222+injectRequestHeaders:
223+ - name: X-Department
224+ values:
225+ - claimSource:
226+ claim: department
227+ - name: X-Organization
228+ values:
229+ - claimSource:
230+ claim: organization.name
231+```
232+
233+This is useful when your IdP exposes application-specific attributes such as department,
234+tenant, employee ID, entitlement, or other custom claims that are not part of the default
235+OAuth2 Proxy session fields.
236+
163237## Removed options
164238
165239The following flags/options and their respective environment variables are no
@@ -488,6 +562,7 @@ character.
488562| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID<br/>default set to 'email' |
489563| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id<br/>By default `aud` claim is used for verification. |
490564| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed<br/>to pass verification in addition to the client id. |
565+| `enabledSigningAlgs` | _[]string_ | EnabledSigningAlgs is a list of allowed JWT signing algorithms.<br/>When discovery is enabled, the effective set is the intersection<br/>between this list and the provider's discovered supported algorithms.<br/>By default `RS256` is used if nothing has been discovered or specified. |
491566
492567### Provider
493568
@@ -526,6 +601,7 @@ Provider holds all configuration for a single provider
526601| `scope` | _string_ | Scope is the OAuth scope specification |
527602| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group |
528603| `code_challenge_method` | _string_ | The code challenge method |
604+| `additionalClaims` | _[]string_ | Additional claims to be obtained from the upstream IDP, either from the id_token or from the userinfo endpoint if configured. |
529605| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session |
530606
531607### ProviderType
@@ -571,8 +647,8 @@ Server represents the configuration for an HTTP(S) server
571647
572648| Field | Type | Description |
573649| ----- | ---- | ----------- |
574−| `bindAddress` | _string_ | BindAddress is the address on which to serve traffic.<br/>Leave blank or set to "-" to disable. |
575−| `secureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.<br/>Leave blank or set to "-" to disable. |
650+| `bindAddress` | _string_ | BindAddress is the address on which to serve traffic.<br/>Different types of bind addresses are supported:<br/>* `[http://]<addr>:<port>`<br/>* `fd:<int>` (case insensitive)<br/>* `unix://<path>`<br/>Unix sockets are created with default system umask mode, which can be overridden, e.g.: `unix://my-socket,mode=0777`<br/>Square brackets are required for ipv6 address, e.g. `http://[::1]:4180`<br/>Leave blank or set to "-" to disable. |
651+| `secureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.<br/>Secure bind addresses need to respond with valid SSL and use the following format:<br/>* `[https://]<addr>:<port>`<br/>Square brackets are required for ipv6 address, e.g. `https://[::1]:4180`<br/>Leave blank or set to "-" to disable. |
576652| `tls` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the<br/>secure traffic and further configuration for the TLS server. |
577653
578654### TLS
@@ -613,7 +689,7 @@ Requests will be proxied to this upstream if the path matches the request path.
613689| Field | Type | Description |
614690| ----- | ---- | ----------- |
615691| `id` | _string_ | ID should be a unique identifier for the upstream.<br/>This value is required for all upstreams. |
616−| `path` | _string_ | Path is used to map requests to the upstream server.<br/>The closest match will take precedence and all Paths must be unique.<br/>Path can also take a pattern when used with RewriteTarget.<br/>Path segments can be captured and matched using regular experessions.<br/>Eg:<br/>- `^/foo$`: Match only the explicit path `/foo`<br/>- `^/bar/$`: Match any path prefixed with `/bar/`<br/>- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget |
692+| `path` | _string_ | Path is used to map requests to the upstream server.<br/>The closest match will take precedence and all Paths must be unique.<br/>Without RewriteTarget, Path follows gorilla/mux route syntax.<br/>Eg:<br/>- `/foo`: Match only the explicit path `/foo`<br/>- `/bar/`: Match any path prefixed with `/bar/`<br/>- `/baz/{path:.*}`: Match any path prefixed with `/baz/`<br/>When RewriteTarget is set, Path is treated as a regular expression.<br/>Eg: `^/baz/(.*)$` matches any path prefixed with `/baz` and captures the<br/>remaining path for use with RewriteTarget. |
617693| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to<br/>the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem<br/>(for a `file:` upstream).<br/>Use the Path to capture segments for reuse within the rewrite target.<br/>Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite<br/>the request `/baz/abc/123` to `/foo/abc/123` before proxying to the<br/>upstream server. Or if the upstream were `file:///app`, a request for<br/>`/baz/info.html` would return the contents of the file `/app/foo/info.html`. |
618694| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File<br/>based URL. It may include a path, in which case all requests will be served<br/>under that path.<br/>Eg:<br/>- http://localhost:8080<br/>- https://service.localhost<br/>- https://service.localhost/path<br/>- file://host/path<br/>If the URI's path is "/base" and the incoming request was for "/dir",<br/>the upstream request will be for "/base/dir". |
619695| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.<br/>This option is insecure and will allow potential Man-In-The-Middle attacks<br/>between OAuth2 Proxy and the upstream server.<br/>Defaults to false. |
docs/docs/configuration/alpha_config.md.tmpl+74
@@ -106,6 +106,17 @@ the new config.
106106oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg
107107```
108108
109+### Validating Alpha Configuration
110+
111+Use `--config-test` to validate your alpha configuration without starting the proxy:
112+
113+```bash
114+oauth2-proxy --config core.cfg --alpha-config alpha.yaml --config-test
115+```
116+
117+This is useful for CI/CD pipelines to catch configuration errors before deployment.
118+See the [Configuration Validation](./overview.md#configuration-validation) section for more details.
119+
109120### How to use environment variables
110121
111122The 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.
@@ -156,10 +167,73 @@ injectResponseHeaders:
156167* `claimSource` - `claim` (session claims either from id token or from profile URL)
157168* `secretSource` - `value` (base64), `fromFile` (file path)
158169
170+#### Claim value serialization
171+
172+`claimSource` converts the selected claim into one or more string header values. Scalars
173+produce one value, while arrays produce one value per element. Values that cannot be
174+converted directly to strings, such as objects, are JSON-encoded individually.
175+
176+Each non-empty value is added separately under the configured header name. An array of
177+objects therefore produces multiple header values containing one JSON object each, not a
178+single JSON array. HTTP libraries and intermediaries may expose repeated values as a
179+comma-joined string, so consumers should retrieve and parse each header value separately.
180+
159181**Request option:** `preserveRequestValue: true` retains existing header values
160182
161183**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest`
162184
185+### How to utilize arbitrary claims provided by your Identity Provider
186+
187+With the additionalClaims attribute you can specify which claims you want to extract
188+from the ID Token or userinfo (ProfileURL) endpoint.
189+
190+Configure these on the relevant provider entry:
191+
192+```yaml
193+providers:
194+ - id: my-oidc-provider
195+ provider: oidc
196+ clientID: ${OAUTH_CLIENT_ID}
197+ clientSecret: ${OAUTH_CLIENT_SECRET}
198+ oidcConfig:
199+ issuerURL: https://issuer.example.com
200+ profileURL: https://issuer.example.com/oauth2/userinfo
201+ additionalClaims:
202+ - department
203+ - employee_id
204+ - organization.name
205+```
206+
207+OAuth2 Proxy resolves each configured claim using the following order:
208+
209+1. The raw ID token is checked first.
210+2. If the claim is not present there and `profileURL` is configured, the userinfo endpoint is queried.
211+3. If `skipClaimsFromProfileURL: true` is set, only the ID token is used.
212+
213+Claims that are not found are ignored rather than causing authentication to fail.
214+
215+You can use dot-separated paths for nested JSON objects, for example `organization.name`.
216+Array indexes are not supported.
217+
218+Once loaded, these claims are stored in the session as `additionalClaims`. They can then be
219+used anywhere session claims are accepted, including header injection:
220+
221+```yaml
222+injectRequestHeaders:
223+ - name: X-Department
224+ values:
225+ - claimSource:
226+ claim: department
227+ - name: X-Organization
228+ values:
229+ - claimSource:
230+ claim: organization.name
231+```
232+
233+This is useful when your IdP exposes application-specific attributes such as department,
234+tenant, employee ID, entitlement, or other custom claims that are not part of the default
235+OAuth2 Proxy session fields.
236+
163237## Removed options
164238
165239The following flags/options and their respective environment variables are no
docs/docs/configuration/integrations/nginx.md+95−12
@@ -43,7 +43,7 @@ server {
4343
4444 location / {
4545 auth_request /oauth2/auth;
46− error_page 401 =403 /oauth2/sign_in;
46+ error_page 401 = @oauth2_signin;
4747
4848 # pass information via X-User and X-Email headers to backend,
4949 # requires running with --set-xauthrequest flag
@@ -60,31 +60,116 @@ server {
6060 auth_request_set $auth_cookie $upstream_http_set_cookie;
6161 add_header Set-Cookie $auth_cookie;
6262
63− # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb
64− # limit and so the OAuth2 Proxy splits these into multiple parts.
63+ # Large OIDC tokens can make the session cookie exceed the 4KB limit,
64+ # causing OAuth2 Proxy to split the cookie into multiple parts.
6565 # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response,
66− # so if your cookies are larger than 4kb, you will need to extract additional cookies manually.
67− auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1;
66+ # so extract the second part when using the default cookie name, `_oauth2_proxy`.
67+ auth_request_set $auth_cookie_upstream_1 $upstream_cookie__oauth2_proxy_1;
6868
6969 # Extract the Cookie attributes from the first Set-Cookie header and append them
7070 # to the second part ($upstream_cookie_* variables only contain the raw cookie content)
7171 if ($auth_cookie ~* "(; .*)") {
72− set $auth_cookie_name_0 $auth_cookie;
73− set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1";
72+ set $auth_cookie_0 $auth_cookie;
73+ set $auth_cookie_1 "_oauth2_proxy_1=$auth_cookie_upstream_1$1";
7474 }
7575
7676 # Send both Set-Cookie headers now if there was a second part
77− if ($auth_cookie_name_upstream_1) {
78− add_header Set-Cookie $auth_cookie_name_0;
79− add_header Set-Cookie $auth_cookie_name_1;
77+ if ($auth_cookie_upstream_1) {
78+ add_header Set-Cookie $auth_cookie_0;
79+ add_header Set-Cookie $auth_cookie_1;
8080 }
8181
8282 proxy_pass http://backend/;
8383 # or "root /path/to/site;" or "fastcgi_pass ..." etc
8484 }
85+
86+ # Named location for handling OAuth2 sign-in redirects
87+ # This ensures the browser receives a proper 302 redirect that it will follow
88+ location @oauth2_signin {
89+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
90+ }
91+}
92+```
93+
94+### Multi-part session cookies
95+
96+The example above is ready to use with the default `--cookie-name=_oauth2_proxy` setting and handles a session split into two cookies. If you configure a custom cookie name, update both references to the second cookie part:
97+
98+| Cookie configuration | Nginx upstream cookie variable | `Set-Cookie` name |
99+| --- | --- | --- |
100+| Default (`_oauth2_proxy`) | `$upstream_cookie__oauth2_proxy_1` | `_oauth2_proxy_1=` |
101+| `--cookie-name=my_cookie` | `$upstream_cookie_my_cookie_1` | `my_cookie_1=` |
102+
103+For example, with `--cookie-name=my_cookie`, change the relevant lines to:
104+
105+```nginx
106+auth_request_set $auth_cookie_upstream_1 $upstream_cookie_my_cookie_1;
107+set $auth_cookie_1 "my_cookie_1=$auth_cookie_upstream_1$1";
108+```
109+
110+If a session is split into more than two cookies, repeat the extraction for each additional numeric suffix. For consistently large sessions, prefer `--session-store-type=redis` so only a small session ticket is stored in the browser cookie.
111+
112+### Understanding the `error_page` redirect pattern
113+
114+The `auth_request` directive expects the authentication endpoint (`/oauth2/auth`) to return:
115+- **2xx**: Request is authenticated, allow access
116+- **401 or 403**: Request is not authenticated, deny access
117+
118+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**:
119+
120+```nginx
121+error_page 401 = @oauth2_signin;
122+
123+location @oauth2_signin {
124+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
125+}
126+```
127+
128+:::warning Avoid `error_page 401 =403` with sign_in
129+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).
130+
131+The named location pattern above ensures the browser receives a standard **302 redirect** that works correctly with all oauth2-proxy configurations.
132+:::
133+
134+### Browser vs API Routes
135+
136+:::important When to use redirects
137+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.
138+:::
139+
140+#### Browser-facing routes (HTML, UI)
141+
142+For interactive browser routes where users should be redirected to sign in:
143+
144+```nginx
145+location / {
146+ auth_request /oauth2/auth;
147+ error_page 401 = @oauth2_signin;
148+ proxy_pass http://backend/;
149+}
150+
151+location @oauth2_signin {
152+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
153+}
154+```
155+
156+#### API / Machine routes (no redirect)
157+
158+For API endpoints where clients expect a 401/403 status code (not a redirect):
159+
160+```nginx
161+location /api/ {
162+ auth_request /oauth2/auth;
163+ error_page 401 =401; # Pass through the 401 status
164+ proxy_pass http://backend/;
85165}
86166```
87167
168+This ensures:
169+- ✅ Browsers get a redirect and smooth login flow
170+- ✅ API clients fail fast with appropriate HTTP status codes
171+- ✅ `/oauth2/auth` remains a pure boolean oracle (2xx/401)
172+
88173When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
89174
90175```yaml
@@ -100,8 +185,6 @@ It is recommended to use `--session-store-type=redis` when expecting large sessi
100185For 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.
101186:::
102187
103−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=".
104−
105188:::note
106189If 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.
107190:::
docs/docs/configuration/integrations/traefik.md+8
@@ -79,8 +79,16 @@ http:
7979 - "401-403"
8080 service: oauth-backend
8181 query: "/oauth2/sign_in?rd={url}"
82+ statusRewrites:
83+ "401": 302
8284```
8385
86+:::caution Troubleshooting: Browser shows "Found." instead of redirecting
87+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.
88+
89+Adding `statusRewrites` to rewrite `401 -> 302` ensures the browser treats the response as a proper redirect and follows it automatically.
90+:::
91+
8492### ForwardAuth with static upstreams configuration
8593
8694Redirect 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
docs/docs/configuration/overview.md+59−14
@@ -66,11 +66,11 @@ An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/
6666
6767### Command Line Options
6868
69−| Flag | Description |
70−| ----------- | -------------------- |
71−| `--config` | path to config file |
72−| `--version` | print version string |
73−
69+| Flag | Description |
70+| ---------------- | ------------------------------------------------------- |
71+| `--config` | path to config file |
72+| `--config-test` | test configuration and exit (for CI/CD validation) |
73+| `--version` | print version string |
7474
7575### General Provider Options
7676
@@ -83,7 +83,7 @@ Provider specific options can be found on their respective subpages.
8383| flag: `--approval-prompt`<br/>toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` |
8484| flag: `--backend-logout-url`<br/>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 | |
8585| flag: `--client-id`<br/>toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | |
86−| flag: `--client-secret-file`<br/>toml: `client_secret_file` | string | the file with OAuth Client Secret. The file must contain the secret only, with no trailing newline | |
86+| flag: `--client-secret-file`<br/>toml: `client_secret_file` | string | the file with OAuth Client Secret. The file must contain the secret only, with no trailing newline | |
8787| flag: `--client-secret`<br/>toml: `client_secret` | string | the OAuth Client Secret | |
8888| flag: `--code-challenge-method`<br/>toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | |
8989| flag: `--insecure-oidc-allow-unverified-email`<br/>toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false |
@@ -99,10 +99,11 @@ Provider specific options can be found on their respective subpages.
9999| flag: `--oidc-groups-claim`<br/>toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` |
100100| flag: `--oidc-issuer-url`<br/>toml: `oidc_issuer_url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | |
101101| flag: `--oidc-jwks-url`<br/>toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled and public key files are not provided | |
102−| flag: `--oidc-public-key-file`<br/>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 |
102+| flag: `--oidc-public-key-file`<br/>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 | |
103+| flag: `--oidc-enabled-signing-alg`<br/>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. | |
103104| flag: `--profile-url`<br/>toml: `profile_url` | string | Profile access endpoint | |
104105| flag: `--prompt`<br/>toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` |
105−| flag: `--provider-ca-file`<br/>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. |
106+| flag: `--provider-ca-file`<br/>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. | |
106107| flag: `--provider-display-name`<br/>toml: `provider_display_name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) |
107108| flag: `--provider`<br/>toml: `provider` | string | OAuth provider | google |
108109| flag: `--pubjwk-url`<br/>toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | |
@@ -120,6 +121,7 @@ Provider specific options can be found on their respective subpages.
120121| flag: `--cookie-csrf-expire`<br/>toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m |
121122| flag: `--cookie-csrf-per-request`<br/>toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false |
122123| flag: `--cookie-csrf-per-request-limit`<br/>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" |
124+| flag: `--cookie-csrf-samesite`<br/>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. | `""` |
123125| flag: `--cookie-domain`<br/>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). | |
124126| flag: `--cookie-expire`<br/>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 |
125127| flag: `--cookie-httponly`<br/>toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true |
@@ -128,7 +130,7 @@ Provider specific options can be found on their respective subpages.
128130| flag: `--cookie-refresh`<br/>toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers&nbsp;[^1] | |
129131| flag: `--cookie-samesite`<br/>toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` |
130132| flag: `--cookie-secret`<br/>toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | |
131−| flag: `--cookie-secret-file`<br/>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 | |
133+| flag: `--cookie-secret-file`<br/>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 | |
132134| flag: `--cookie-secure`<br/>toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true |
133135
134136[^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)
@@ -174,7 +176,7 @@ Provider specific options can be found on their respective subpages.
174176| Flag / Config Field | Type | Description | Default |
175177| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- |
176178| flag: `--banner`<br/>toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | |
177−| flag: `--custom-sign-in-logo`<br/>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. |
179+| flag: `--custom-sign-in-logo`<br/>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. | |
178180| flag: `--custom-templates-dir`<br/>toml: `custom_templates_dir` | string | path to custom html templates | |
179181| flag: `--display-htpasswd-form`<br/>toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true |
180182| flag: `--footer`<br/>toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | |
@@ -191,6 +193,10 @@ Provider specific options can be found on their respective subpages.
191193
192194### Proxy Options
193195
196+:::warning
197+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.
198+:::
199+
194200| Flag / Config Field | Type | Description | Default |
195201| ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
196202| flag: `--allow-query-semicolons`<br/>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` |
@@ -209,12 +215,13 @@ Provider specific options can be found on their respective subpages.
209215| flag: `--redirect-url`<br/>toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | |
210216| flag: `--relative-redirect-url`<br/>toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false |
211217| flag: `--reverse-proxy`<br/>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 |
218+| flag: `--trusted-proxy-ip`<br/>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"` |
212219| flag: `--signature-key`<br/>toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | |
213220| flag: `--skip-auth-preflight`<br/>toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false |
214−| flag: `--skip-auth-regex`<br/>toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | |
215−| flag: `--skip-auth-route`<br/>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 | |
221+| flag: `--skip-auth-regex`<br/>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. | |
222+| flag: `--skip-auth-route`<br/>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. | |
216223| flag: `--skip-jwt-bearer-tokens`<br/>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 |
217−| flag: `--skip-provider-button`<br/>toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start. When enabled, the `/oauth2/auth` endpoint returns 302 redirects instead of 401, ensuring compatibility with nginx `auth_request` and similar reverse proxy authentication architectures. | false |
224+| flag: `--skip-provider-button`<br/>toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false |
218225| flag: `--ssl-insecure-skip-verify`<br/>toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false |
219226| flag: `--trusted-ip`<br/>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. | |
220227| flag: `--whitelist-domain`<br/>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`)&nbsp;[^2] | |
@@ -225,7 +232,7 @@ Provider specific options can be found on their respective subpages.
225232
226233| Flag / Config Field | Type | Description | Default |
227234| ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
228−| flag: `--http-address`<br/>toml: `http_address` | string | `[http://]<addr>:<port>` or `unix://<path>` or `fd:<int>` (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"` |
235+| flag: `--http-address`<br/>toml: `http_address` | string | `[http://]<addr>:<port>` or `unix://<path>` or `fd:<int>` (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"` |
229236| flag: `--https-address`<br/>toml: `https_address` | string | `[https://]<addr>:<port>` to listen on for HTTPS clients. Square brackets are required for ipv6 address, e.g. `https://[::1]:443` | `":443"` |
230237| flag: `--metrics-address`<br/>toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` |
231238| flag: `--metrics-secure-address`<br/>toml: `metrics_secure_address` | string | the address prometheus metrics will be scraped from if using HTTPS | `""` |
@@ -244,6 +251,7 @@ Provider specific options can be found on their respective subpages.
244251| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
245252| flag: `--redis-cluster-connection-urls`<br/>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` | |
246253| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
254+| flag: `--redis-ca-path`<br/>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. | |
247255| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
248256| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
249257| flag: `--redis-sentinel-password`<br/>toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | |
@@ -265,6 +273,43 @@ Provider specific options can be found on their respective subpages.
265273| flag: `--upstream-timeout`<br/>toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s |
266274| flag: `--upstream`<br/>toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://<status_code>` for static response. Routing is based on the path | |
267275
276+## Configuration Validation
277+
278+The `--config-test` flag validates your configuration file without starting the proxy server. This is useful for:
279+- **CI/CD pipelines**: Pre-deployment validation
280+- **Configuration management**: Testing before applying changes
281+- **Debugging**: Verifying syntax and required fields
282+
283+### Usage
284+
285+```bash
286+# Test legacy config
287+oauth2-proxy --config /etc/oauth2-proxy.cfg --config-test
288+
289+# Test alpha config
290+oauth2-proxy --config /etc/core.cfg --alpha-config /etc/alpha.yaml --config-test
291+
292+# CI/CD pre-deployment check
293+# Returns with exit code 1 if any validation errors occur
294+oauth2-proxy --config new-config.cfg --config-test
295+```
296+
297+### Exit Codes
298+
299+- **0**: Configuration is valid ✅
300+- **1**: Configuration is invalid (errors printed to stderr) ❌
301+
302+### Validation Coverage
303+
304+The `--config-test` flag performs the **same comprehensive validation** as normal startup, including:
305+- Required fields (client ID, client secret, cookie secret, etc.)
306+- Syntax validation (TOML/YAML parsing)
307+- Provider configuration
308+- Upstream server definitions
309+- Session store connectivity (e.g., Redis network checks if configured)
310+
311+**Note**: Cannot be combined with `--convert-config-to-alpha`.
312+
268313## Upstreams Configuration
269314
270315`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.
docs/docs/configuration/providers/atlassian.mdnew file+26
@@ -0,0 +1,26 @@
1+---
2+id: atlassian
3+title: Atlassian Cloud
4+---
5+
6+1. Create an OAuth 2.0 integration in the [Atlassian developer console](https://developer.atlassian.com/console/myapps/).
7+2. Under **Permissions**, add the User identity API with the `read:me` scope.
8+3. Under **Authorization**, set the callback URL to `https://<proxy_host>/oauth2/callback`.
9+4. Copy the client ID and secret from **Settings**.
10+5. Run the proxy with:
11+
12+```shell
13+ --provider=atlassian
14+ --client-id=<client ID>
15+ --client-secret=<secret>
16+ --redirect-url=https://<proxy_host>/oauth2/callback
17+ --cookie-secret=<cookie secret>
18+```
19+
20+A new app works only for the account that created it. Enable sharing under **Distribution** to let other users sign in.
21+Atlassian then admits only accounts with access to the Atlassian site the app is installed on; others are refused at
22+the consent screen.
23+
24+The proxy reads the user's email from `https://api.atlassian.com/me`. Restricting access further is supported by
25+[email](index.md#email-authentication). With `--cookie-refresh` set, the proxy re-validates the token against `/me` on
26+that interval.
docs/docs/configuration/providers/dtt_sso.mdnew file+45
@@ -0,0 +1,45 @@
1+---
2+id: dtt_sso
3+title: DTT SSO
4+---
5+
6+Signs users in with the DTT SSO (auth-server) using the authorization code flow and its HS256 id_token.
7+
8+1. Register a client in the auth-server config, one per protected service, with the proxy's callback as its
9+ only redirect URI:
10+
11+ ```yaml
12+ clients:
13+ redash-gate:
14+ secret: <random secret>
15+ redirect_uri: https://redash.example.com/oauth2/callback
16+ display_name: Redash
17+ ```
18+
19+2. Run the proxy with:
20+
21+ ```shell
22+ --provider=dtt-sso
23+ --client-id=redash-gate
24+ --client-secret-file=/run/secrets/client_secret
25+ --redirect-url=https://redash.example.com/oauth2/callback
26+ --cookie-secret-file=/run/secrets/cookie_secret
27+ --cookie-name=_dtt_sso_redash
28+ --cookie-refresh=5m
29+ ```
30+
31+ Give each instance its own `--cookie-name`: another oauth2-proxy setting its cookie on a parent domain
32+ (the Atlassian proxy uses `_oauth2_proxy` on `.thebestagent.pro`) would otherwise shadow this one.
33+
34+The endpoints default to `https://auth.thebestagent.pro`. For another SSO host set `--login-url`, `--redeem-url`
35+and `--validate-url` to its `/oauth/authorize`, `/oauth/token` and `/oauth/check_token`; the id_token issuer must
36+equal the login URL's origin (the SSO's `site_host`).
37+
38+The scope must stay `openid`, the only scope the SSO accepts.
39+
40+The session carries the SSO `email`, the user UUID as the user, and the SSO `role` as the only group, so
41+`--allowed-group=dtt_admin` restricts access by role. `--authenticated-emails-file` and `--email-domain` restrict
42+by email as usual.
43+
44+With `--cookie-refresh` set, the proxy refreshes the tokens on that interval and re-reads the email and role; a user
45+deleted or signed out in the SSO loses access at the next refresh.
docs/docs/configuration/providers/gitlab.md+1−1
@@ -8,7 +8,7 @@ title: GitLab
88| Flag | Toml Field | Type | Description | Default |
99| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
1010| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
11−| `--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 | |
11+| `--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 | |
1212
1313## Usage
1414
docs/docs/configuration/providers/index.md+2
@@ -9,10 +9,12 @@ with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on.
99Valid providers are :
1010
1111- [ADFS](adfs.md)
12+- [Atlassian Cloud](atlassian.md)
1213- [Bitbucket](bitbucket.md)
1314- [Cidaas](cidaas.md)
1415- [CiscoDuo](cisco_duo.md)
1516- [DigitalOcean](digitalocean.md)
17+- [DTT SSO](dtt_sso.md)
1618- [Facebook](facebook.md)
1719- [Gitea](gitea.md)
1820- [GitHub](github.md)
docs/docs/configuration/systemd_socket.md+8
@@ -40,4 +40,12 @@ the listener it created onto the process, starting with file descriptor 3.
4040 --client-secret=...
4141```
4242
43+## Trusted IPs
44+
45+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.
46+
47+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.
48+
49+## TLS
50+
4351Currently TLS is not supported (but it's doable).
docs/docs/features/endpoints.md+14
@@ -38,6 +38,20 @@ X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page
3838
3939BEWARE 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").
4040
41+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`;
42+
43+```
44+/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
45+```
46+
47+or alternatively in the header:
48+
49+```
50+GET /oauth2/sign_out HTTP/1.1
51+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
52+...
53+```
54+
4155### Auth
4256
4357This endpoint returns 202 Accepted response or a 401 Unauthorized response.
docs/docs/installation.md+1−1
@@ -5,7 +5,7 @@ title: Installation
55
661. Choose how to deploy:
77
8− a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.0`)
8+ a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.15.4`)
99
1010 b. Using Go to install the latest release
1111 ```bash
docs/docusaurus.config.js+1−1
@@ -105,7 +105,7 @@ const config = {
105105 dropdownActiveClassDisabled: true,
106106 },
107107 {
108− href: 'https://gophers.slack.com/messages/CM2RSS25N',
108+ href: 'https://cloud-native.slack.com/archives/C098Y5URZ2N',
109109 label: 'Slack',
110110 position: 'right',
111111 },
docs/package.json+4−1
@@ -17,7 +17,7 @@
1717 "@docusaurus/core": "^3.3.2",
1818 "@docusaurus/preset-classic": "^3.3.2",
1919 "@docusaurus/theme-mermaid": "^3.3.2",
20− "@easyops-cn/docusaurus-search-local": "^0.52.0",
20+ "@easyops-cn/docusaurus-search-local": "^0.55.0",
2121 "@mdx-js/react": "^3.0.0",
2222 "clsx": "^2.0.0",
2323 "prism-react-renderer": "^2.3.0",
@@ -42,5 +42,8 @@
4242 },
4343 "engines": {
4444 "node": ">=18.0"
45+ },
46+ "overrides" : {
47+ "webpackbar" : "^7.0.0"
4548 }
4649}
docs/sidebars.js+2
@@ -46,11 +46,13 @@ const sidebars = {
4646 },
4747 items: [
4848 "configuration/providers/adfs",
49+ "configuration/providers/atlassian",
4950 "configuration/providers/azure",
5051 "configuration/providers/bitbucket",
5152 "configuration/providers/cidaas",
5253 "configuration/providers/cisco_duo",
5354 "configuration/providers/digitalocean",
55+ "configuration/providers/dtt_sso",
5456 "configuration/providers/facebook",
5557 "configuration/providers/gitea",
5658 "configuration/providers/github",
docs/versioned_docs/version-7.10.x/configuration/integration.md+77−1
@@ -33,9 +33,15 @@ server {
3333 proxy_pass_request_body off;
3434 }
3535
36+ # Named location for handling OAuth2 sign-in redirects
37+ # This ensures the browser receives a proper 302 redirect that it will follow
38+ location @oauth2_signin {
39+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
40+ }
41+
3642 location / {
3743 auth_request /oauth2/auth;
38− error_page 401 =403 /oauth2/sign_in;
44+ error_page 401 = @oauth2_signin;
3945
4046 # pass information via X-User and X-Email headers to backend,
4147 # requires running with --set-xauthrequest flag
@@ -77,6 +83,68 @@ server {
7783}
7884```
7985
86+### Understanding the `error_page` redirect pattern
87+
88+The `auth_request` directive expects the authentication endpoint (`/oauth2/auth`) to return:
89+- **2xx**: Request is authenticated, allow access
90+- **401 or 403**: Request is not authenticated, deny access
91+
92+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**:
93+
94+
95+```nginx
96+error_page 401 = @oauth2_signin;
97+
98+location @oauth2_signin {
99+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
100+}
101+```
102+
103+:::warning Avoid `error_page 401 =403` with sign_in
104+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).
105+
106+The named location pattern above ensures the browser receives a standard **302 redirect** that works correctly with all oauth2-proxy configurations.
107+:::
108+
109+### Browser vs API Routes
110+
111+:::important When to use redirects
112+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.
113+:::
114+
115+#### Browser-facing routes (HTML, UI)
116+
117+For interactive browser routes where users should be redirected to sign in:
118+
119+```nginx
120+location / {
121+ auth_request /oauth2/auth;
122+ error_page 401 = @oauth2_signin;
123+ proxy_pass http://backend/;
124+}
125+
126+location @oauth2_signin {
127+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
128+}
129+```
130+
131+#### API / Machine routes (no redirect)
132+
133+For API endpoints where clients expect a 401/403 status code (not a redirect):
134+
135+```nginx
136+location /api/ {
137+ auth_request /oauth2/auth;
138+ error_page 401 =401; # Pass through the 401 status
139+ proxy_pass http://backend/;
140+}
141+```
142+
143+This ensures:
144+- ✅ Browsers get a redirect and smooth login flow
145+- ✅ API clients fail fast with appropriate HTTP status codes
146+- ✅ `/oauth2/auth` remains a pure boolean oracle (2xx/401)
147+
80148When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
81149
82150```yaml
@@ -157,8 +225,16 @@ http:
157225 - "401-403"
158226 service: oauth-backend
159227 query: "/oauth2/sign_in?rd={url}"
228+ statusRewrites:
229+ "401": 302
160230```
161231
232+:::info Troubleshooting: Browser shows "Found." instead of redirecting
233+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.
234+
235+Adding `statusRewrites` to rewrite `401 -> 302` ensures the browser treats the response as a proper redirect and follows it automatically.
236+:::
237+
162238### ForwardAuth with static upstreams configuration
163239
164240Redirect 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
docs/versioned_docs/version-7.10.x/configuration/overview.md+1
@@ -241,6 +241,7 @@ Provider specific options can be found on their respective subpages.
241241| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
242242| flag: `--redis-cluster-connection-urls`<br/>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` | |
243243| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
244+| flag: `--redis-ca-path`<br/>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. |
244245| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
245246| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
246247| flag: `--redis-sentinel-password`<br/>toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | |
docs/versioned_docs/version-7.10.x/configuration/providers/gitlab.md+1−1
@@ -8,7 +8,7 @@ title: GitLab
88| Flag | Toml Field | Type | Description | Default |
99| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
1010| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
11−| `--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 | |
11+| `--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 | |
1212
1313## Usage
1414
docs/versioned_docs/version-7.11.x/configuration/integration.md+77−1
@@ -33,9 +33,15 @@ server {
3333 proxy_pass_request_body off;
3434 }
3535
36+ # Named location for handling OAuth2 sign-in redirects
37+ # This ensures the browser receives a proper 302 redirect that it will follow
38+ location @oauth2_signin {
39+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
40+ }
41+
3642 location / {
3743 auth_request /oauth2/auth;
38− error_page 401 =403 /oauth2/sign_in;
44+ error_page 401 = @oauth2_signin;
3945
4046 # pass information via X-User and X-Email headers to backend,
4147 # requires running with --set-xauthrequest flag
@@ -77,6 +83,68 @@ server {
7783}
7884```
7985
86+### Understanding the `error_page` redirect pattern
87+
88+The `auth_request` directive expects the authentication endpoint (`/oauth2/auth`) to return:
89+- **2xx**: Request is authenticated, allow access
90+- **401 or 403**: Request is not authenticated, deny access
91+
92+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**:
93+
94+
95+```nginx
96+error_page 401 = @oauth2_signin;
97+
98+location @oauth2_signin {
99+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
100+}
101+```
102+
103+:::warning Avoid `error_page 401 =403` with sign_in
104+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).
105+
106+The named location pattern above ensures the browser receives a standard **302 redirect** that works correctly with all oauth2-proxy configurations.
107+:::
108+
109+### Browser vs API Routes
110+
111+:::important When to use redirects
112+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.
113+:::
114+
115+#### Browser-facing routes (HTML, UI)
116+
117+For interactive browser routes where users should be redirected to sign in:
118+
119+```nginx
120+location / {
121+ auth_request /oauth2/auth;
122+ error_page 401 = @oauth2_signin;
123+ proxy_pass http://backend/;
124+}
125+
126+location @oauth2_signin {
127+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
128+}
129+```
130+
131+#### API / Machine routes (no redirect)
132+
133+For API endpoints where clients expect a 401/403 status code (not a redirect):
134+
135+```nginx
136+location /api/ {
137+ auth_request /oauth2/auth;
138+ error_page 401 =401; # Pass through the 401 status
139+ proxy_pass http://backend/;
140+}
141+```
142+
143+This ensures:
144+- ✅ Browsers get a redirect and smooth login flow
145+- ✅ API clients fail fast with appropriate HTTP status codes
146+- ✅ `/oauth2/auth` remains a pure boolean oracle (2xx/401)
147+
80148When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
81149
82150```yaml
@@ -157,8 +225,16 @@ http:
157225 - "401-403"
158226 service: oauth-backend
159227 query: "/oauth2/sign_in?rd={url}"
228+ statusRewrites:
229+ "401": 302
160230```
161231
232+:::info Troubleshooting: Browser shows "Found." instead of redirecting
233+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.
234+
235+Adding `statusRewrites` to rewrite `401 -> 302` ensures the browser treats the response as a proper redirect and follows it automatically.
236+:::
237+
162238### ForwardAuth with static upstreams configuration
163239
164240Redirect 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
docs/versioned_docs/version-7.11.x/configuration/overview.md+1
@@ -244,6 +244,7 @@ Provider specific options can be found on their respective subpages.
244244| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
245245| flag: `--redis-cluster-connection-urls`<br/>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` | |
246246| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
247+| flag: `--redis-ca-path`<br/>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. |
247248| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
248249| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
249250| flag: `--redis-sentinel-password`<br/>toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | |
docs/versioned_docs/version-7.11.x/configuration/providers/gitlab.md+1−1
@@ -8,7 +8,7 @@ title: GitLab
88| Flag | Toml Field | Type | Description | Default |
99| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
1010| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
11−| `--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 | |
11+| `--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 | |
1212
1313## Usage
1414
docs/versioned_docs/version-7.12.x/configuration/integration.md+77−1
@@ -33,9 +33,15 @@ server {
3333 proxy_pass_request_body off;
3434 }
3535
36+ # Named location for handling OAuth2 sign-in redirects
37+ # This ensures the browser receives a proper 302 redirect that it will follow
38+ location @oauth2_signin {
39+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
40+ }
41+
3642 location / {
3743 auth_request /oauth2/auth;
38− error_page 401 =403 /oauth2/sign_in;
44+ error_page 401 = @oauth2_signin;
3945
4046 # pass information via X-User and X-Email headers to backend,
4147 # requires running with --set-xauthrequest flag
@@ -77,6 +83,68 @@ server {
7783}
7884```
7985
86+### Understanding the `error_page` redirect pattern
87+
88+The `auth_request` directive expects the authentication endpoint (`/oauth2/auth`) to return:
89+- **2xx**: Request is authenticated, allow access
90+- **401 or 403**: Request is not authenticated, deny access
91+
92+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**:
93+
94+
95+```nginx
96+error_page 401 = @oauth2_signin;
97+
98+location @oauth2_signin {
99+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
100+}
101+```
102+
103+:::warning Avoid `error_page 401 =403` with sign_in
104+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).
105+
106+The named location pattern above ensures the browser receives a standard **302 redirect** that works correctly with all oauth2-proxy configurations.
107+:::
108+
109+### Browser vs API Routes
110+
111+:::important When to use redirects
112+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.
113+:::
114+
115+#### Browser-facing routes (HTML, UI)
116+
117+For interactive browser routes where users should be redirected to sign in:
118+
119+```nginx
120+location / {
121+ auth_request /oauth2/auth;
122+ error_page 401 = @oauth2_signin;
123+ proxy_pass http://backend/;
124+}
125+
126+location @oauth2_signin {
127+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
128+}
129+```
130+
131+#### API / Machine routes (no redirect)
132+
133+For API endpoints where clients expect a 401/403 status code (not a redirect):
134+
135+```nginx
136+location /api/ {
137+ auth_request /oauth2/auth;
138+ error_page 401 =401; # Pass through the 401 status
139+ proxy_pass http://backend/;
140+}
141+```
142+
143+This ensures:
144+- ✅ Browsers get a redirect and smooth login flow
145+- ✅ API clients fail fast with appropriate HTTP status codes
146+- ✅ `/oauth2/auth` remains a pure boolean oracle (2xx/401)
147+
80148When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
81149
82150```yaml
@@ -157,8 +225,16 @@ http:
157225 - "401-403"
158226 service: oauth-backend
159227 query: "/oauth2/sign_in?rd={url}"
228+ statusRewrites:
229+ "401": 302
160230```
161231
232+:::info Troubleshooting: Browser shows "Found." instead of redirecting
233+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.
234+
235+Adding `statusRewrites` to rewrite `401 -> 302` ensures the browser treats the response as a proper redirect and follows it automatically.
236+:::
237+
162238### ForwardAuth with static upstreams configuration
163239
164240Redirect 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
docs/versioned_docs/version-7.12.x/configuration/overview.md+1
@@ -244,6 +244,7 @@ Provider specific options can be found on their respective subpages.
244244| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
245245| flag: `--redis-cluster-connection-urls`<br/>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` | |
246246| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
247+| flag: `--redis-ca-path`<br/>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. |
247248| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
248249| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
249250| flag: `--redis-sentinel-password`<br/>toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | |
docs/versioned_docs/version-7.12.x/configuration/providers/gitlab.md+1−1
@@ -8,7 +8,7 @@ title: GitLab
88| Flag | Toml Field | Type | Description | Default |
99| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
1010| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
11−| `--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 | |
11+| `--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 | |
1212
1313## Usage
1414
docs/versioned_docs/version-7.13.x/configuration/integrations/nginx.md+68−1
@@ -43,7 +43,7 @@ server {
4343
4444 location / {
4545 auth_request /oauth2/auth;
46− error_page 401 =403 /oauth2/sign_in;
46+ error_page 401 = @oauth2_signin;
4747
4848 # pass information via X-User and X-Email headers to backend,
4949 # requires running with --set-xauthrequest flag
@@ -82,9 +82,76 @@ server {
8282 proxy_pass http://backend/;
8383 # or "root /path/to/site;" or "fastcgi_pass ..." etc
8484 }
85+
86+ # Named location for handling OAuth2 sign-in redirects
87+ # This ensures the browser receives a proper 302 redirect that it will follow
88+ location @oauth2_signin {
89+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
90+ }
91+}
92+```
93+
94+### Understanding the `error_page` redirect pattern
95+
96+The `auth_request` directive expects the authentication endpoint (`/oauth2/auth`) to return:
97+- **2xx**: Request is authenticated, allow access
98+- **401 or 403**: Request is not authenticated, deny access
99+
100+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**:
101+
102+```nginx
103+error_page 401 = @oauth2_signin;
104+
105+location @oauth2_signin {
106+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
85107}
86108```
87109
110+:::warning Avoid `error_page 401 =403` with sign_in
111+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).
112+
113+The named location pattern above ensures the browser receives a standard **302 redirect** that works correctly with all oauth2-proxy configurations.
114+:::
115+
116+### Browser vs API Routes
117+
118+:::important When to use redirects
119+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.
120+:::
121+
122+#### Browser-facing routes (HTML, UI)
123+
124+For interactive browser routes where users should be redirected to sign in:
125+
126+```nginx
127+location / {
128+ auth_request /oauth2/auth;
129+ error_page 401 = @oauth2_signin;
130+ proxy_pass http://backend/;
131+}
132+
133+location @oauth2_signin {
134+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
135+}
136+```
137+
138+#### API / Machine routes (no redirect)
139+
140+For API endpoints where clients expect a 401/403 status code (not a redirect):
141+
142+```nginx
143+location /api/ {
144+ auth_request /oauth2/auth;
145+ error_page 401 =401; # Pass through the 401 status
146+ proxy_pass http://backend/;
147+}
148+```
149+
150+This ensures:
151+- ✅ Browsers get a redirect and smooth login flow
152+- ✅ API clients fail fast with appropriate HTTP status codes
153+- ✅ `/oauth2/auth` remains a pure boolean oracle (2xx/401)
154+
88155When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
89156
90157```yaml
docs/versioned_docs/version-7.13.x/configuration/integrations/traefik.md+8
@@ -79,8 +79,16 @@ http:
7979 - "401-403"
8080 service: oauth-backend
8181 query: "/oauth2/sign_in?rd={url}"
82+ statusRewrites:
83+ "401": 302
8284```
8385
86+:::info Troubleshooting: Browser shows "Found." instead of redirecting
87+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.
88+
89+Adding `statusRewrites` to rewrite `401 -> 302` ensures the browser treats the response as a proper redirect and follows it automatically.
90+:::
91+
8492### ForwardAuth with static upstreams configuration
8593
8694Redirect 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
docs/versioned_docs/version-7.13.x/configuration/overview.md+1
@@ -244,6 +244,7 @@ Provider specific options can be found on their respective subpages.
244244| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
245245| flag: `--redis-cluster-connection-urls`<br/>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` | |
246246| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
247+| flag: `--redis-ca-path`<br/>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. |
247248| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
248249| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
249250| flag: `--redis-sentinel-password`<br/>toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | |
docs/versioned_docs/version-7.13.x/configuration/providers/gitlab.md+1−1
@@ -8,7 +8,7 @@ title: GitLab
88| Flag | Toml Field | Type | Description | Default |
99| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
1010| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
11−| `--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 | |
11+| `--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 | |
1212
1313## Usage
1414
docs/versioned_docs/version-7.14.x/configuration/integrations/nginx.md+68−1
@@ -43,7 +43,7 @@ server {
4343
4444 location / {
4545 auth_request /oauth2/auth;
46− error_page 401 =403 /oauth2/sign_in;
46+ error_page 401 = @oauth2_signin;
4747
4848 # pass information via X-User and X-Email headers to backend,
4949 # requires running with --set-xauthrequest flag
@@ -82,9 +82,76 @@ server {
8282 proxy_pass http://backend/;
8383 # or "root /path/to/site;" or "fastcgi_pass ..." etc
8484 }
85+
86+ # Named location for handling OAuth2 sign-in redirects
87+ # This ensures the browser receives a proper 302 redirect that it will follow
88+ location @oauth2_signin {
89+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
90+ }
91+}
92+```
93+
94+### Understanding the `error_page` redirect pattern
95+
96+The `auth_request` directive expects the authentication endpoint (`/oauth2/auth`) to return:
97+- **2xx**: Request is authenticated, allow access
98+- **401 or 403**: Request is not authenticated, deny access
99+
100+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**:
101+
102+```nginx
103+error_page 401 = @oauth2_signin;
104+
105+location @oauth2_signin {
106+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
85107}
86108```
87109
110+:::warning Avoid `error_page 401 =403` with sign_in
111+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).
112+
113+The named location pattern above ensures the browser receives a standard **302 redirect** that works correctly with all oauth2-proxy configurations.
114+:::
115+
116+### Browser vs API Routes
117+
118+:::important When to use redirects
119+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.
120+:::
121+
122+#### Browser-facing routes (HTML, UI)
123+
124+For interactive browser routes where users should be redirected to sign in:
125+
126+```nginx
127+location / {
128+ auth_request /oauth2/auth;
129+ error_page 401 = @oauth2_signin;
130+ proxy_pass http://backend/;
131+}
132+
133+location @oauth2_signin {
134+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
135+}
136+```
137+
138+#### API / Machine routes (no redirect)
139+
140+For API endpoints where clients expect a 401/403 status code (not a redirect):
141+
142+```nginx
143+location /api/ {
144+ auth_request /oauth2/auth;
145+ error_page 401 =401; # Pass through the 401 status
146+ proxy_pass http://backend/;
147+}
148+```
149+
150+This ensures:
151+- ✅ Browsers get a redirect and smooth login flow
152+- ✅ API clients fail fast with appropriate HTTP status codes
153+- ✅ `/oauth2/auth` remains a pure boolean oracle (2xx/401)
154+
88155When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
89156
90157```yaml
docs/versioned_docs/version-7.14.x/configuration/integrations/traefik.md+8
@@ -79,8 +79,16 @@ http:
7979 - "401-403"
8080 service: oauth-backend
8181 query: "/oauth2/sign_in?rd={url}"
82+ statusRewrites:
83+ "401": 302
8284```
8385
86+:::info Troubleshooting: Browser shows "Found." instead of redirecting
87+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.
88+
89+Adding `statusRewrites` to rewrite `401 -> 302` ensures the browser treats the response as a proper redirect and follows it automatically.
90+:::
91+
8492### ForwardAuth with static upstreams configuration
8593
8694Redirect 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
docs/versioned_docs/version-7.14.x/configuration/overview.md+2−1
@@ -214,7 +214,7 @@ Provider specific options can be found on their respective subpages.
214214| flag: `--skip-auth-regex`<br/>toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | |
215215| flag: `--skip-auth-route`<br/>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 | |
216216| flag: `--skip-jwt-bearer-tokens`<br/>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 |
217−| flag: `--skip-provider-button`<br/>toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start. When enabled, the `/oauth2/auth` endpoint returns 302 redirects instead of 401, ensuring compatibility with nginx `auth_request` and similar reverse proxy authentication architectures. | false |
217+| flag: `--skip-provider-button`<br/>toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false |
218218| flag: `--ssl-insecure-skip-verify`<br/>toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false |
219219| flag: `--trusted-ip`<br/>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. | |
220220| flag: `--whitelist-domain`<br/>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`)&nbsp;[^2] | |
@@ -244,6 +244,7 @@ Provider specific options can be found on their respective subpages.
244244| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
245245| flag: `--redis-cluster-connection-urls`<br/>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` | |
246246| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
247+| flag: `--redis-ca-path`<br/>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. |
247248| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
248249| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
249250| flag: `--redis-sentinel-password`<br/>toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | |
docs/versioned_docs/version-7.14.x/configuration/providers/gitlab.md+1−1
@@ -8,7 +8,7 @@ title: GitLab
88| Flag | Toml Field | Type | Description | Default |
99| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
1010| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
11−| `--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 | |
11+| `--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 | |
1212
1313## Usage
1414
docs/versioned_docs/version-7.14.x/installation.md+1−1
@@ -5,7 +5,7 @@ title: Installation
55
661. Choose how to deploy:
77
8− a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.0`)
8+ a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.3`)
99
1010 b. Using Go to install the latest release
1111 ```bash
docs/versioned_docs/version-7.15.x/behaviour.mdnew file+26
@@ -0,0 +1,26 @@
1+---
2+id: behaviour
3+title: Behaviour
4+---
5+
6+1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints.
7+ - Exception: If the request matches a skipped route (configured via `--skip-auth-route`):
8+ - 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.
9+ - Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds.
10+
11+2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default.
12+ - Ajax Requests: If the request has `Accept: application/json` header:
13+ - Returns `401 Unauthorized`.
14+ - Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT:
15+ - Redirects to the login page by default.
16+ - Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`.
17+
18+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.
19+
20+4. Request Forwarding: The authenticated request is processed based on configuration:
21+ - Forwarded to the configured upstream application with added user info and authentication headers, or
22+ - Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik).
23+
24+---
25+
26+Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management.
docs/versioned_docs/version-7.15.x/community/contribution.mdnew file+91
@@ -0,0 +1,91 @@
1+---
2+id: contribution
3+title: Contribution Guide
4+---
5+
6+We track bugs and issues using Github.
7+
8+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.
9+
10+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.
11+Please mention open bug issue number(s) within your PR if applicable.
12+
13+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.
14+
15+
16+# Go version
17+
18+See the `go.mod` file in the root of this repository for the version of Go used by this project.
19+You can follow [the installation guide for Go](https://go.dev/doc/install),
20+and you can find this specific Go version on [the Go downloads page](https://go.dev/dl/).
21+
22+# Preparing your fork
23+Clone your fork, create a feature branch and update the depedencies to get started.
24+```bash
25+git clone git@github.com:<YOUR_FORK>/oauth2-proxy
26+cd oauth2-proxy
27+git branch feature/<BRANCH_NAME>
28+git push --set-upstream origin feature/<BRANCH_NAME>
29+go mod download
30+```
31+
32+
33+# Testing / Debugging
34+For starting oauth2-proxy locally open the debugging tab and create the `launch.json` and select `Go: Launch Package`.
35+
36+![Debugging Tab](/img/debug-tab.png)
37+```json
38+{
39+ "version": "0.2.0",
40+ "configurations": [
41+ {
42+ "name": "Launch OAuth2 Proxy with Dex",
43+ "type": "go",
44+ "request": "launch",
45+ "mode": "auto",
46+ "program": "${workspaceFolder}",
47+ "args": [
48+ "--config",
49+ // The following configuration contains settings for a locally deployed
50+ // upstream and dex as an idetity provider
51+ "contrib/local-environment/oauth2-proxy.cfg"
52+ ]
53+ },
54+ {
55+ "name": "Launch OAuth2 Proxy with Keycloak",
56+ "type": "go",
57+ "request": "launch",
58+ "mode": "auto",
59+ "program": "${workspaceFolder}",
60+ "args": [
61+ "--config",
62+ // The following configuration contains settings for a locally deployed
63+ // upstream and keycloak as an idetity provider
64+ "contrib/local-environment/oauth2-proxy-keycloak.cfg"
65+ ]
66+ }
67+ ]
68+}
69+```
70+
71+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.
72+
73+Inside the `contrib/local-environment` directory you can use the `Makefile` for
74+starting different example setups:
75+
76+- Dex as your IdP: `make up` or `make down`
77+- Dex as your IdP using the alpha-config: `make alpha-config-up`
78+- Keycloak as your IdP: `make keycloak-up`
79+- Dex as your IdP & nginx reverse proxy: `make nginx-up`
80+- and many more...
81+
82+Check out the `Makefile` to see what is available.
83+
84+The username and password for all setups is usually `admin@example.com` and `password`.
85+
86+The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me
87+
88+- OAuth2 Proxy: http://oauth2-proxy.localtest.me:4180
89+- Upstream: http://httpbin.localtest.me:8080
90+- Dex: http://dex.localtest.me:5556
91+
docs/versioned_docs/version-7.15.x/community/security.mdnew file+49
@@ -0,0 +1,49 @@
1+---
2+id: security
3+title: Security
4+---
5+
6+:::note
7+OAuth2 Proxy is a community project.
8+Maintainers do not work on this project full time, and as such,
9+while we endeavour to respond to disclosures as quickly as possible,
10+this may take longer than in projects with corporate sponsorship.
11+:::
12+
13+## Security Disclosures
14+
15+:::important
16+If you believe you have found a vulnerability within OAuth2 Proxy or any of its
17+dependencies, please do NOT open an issue or PR on GitHub, please do NOT post
18+any details publicly.
19+:::
20+
21+Security disclosures MUST be done in private.
22+If you have found an issue that you would like to bring to the attention of the
23+maintenance team for OAuth2 Proxy, please compose an email and send it to the
24+list of maintainers in our [MAINTAINERS.md](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS.md) file.
25+
26+Please include as much detail as possible.
27+Ideally, your disclosure should include:
28+- A reproducible case that can be used to demonstrate the exploit
29+- How you discovered this vulnerability
30+- A potential fix for the issue (if you have thought of one)
31+- Versions affected (if not present in master)
32+- Your GitHub ID
33+
34+### How will we respond to disclosures?
35+
36+We use [GitHub Security Advisories](https://docs.github.com/en/github/managing-security-vulnerabilities/about-github-security-advisories)
37+to privately discuss fixes for disclosed vulnerabilities.
38+If you include a GitHub ID with your disclosure we will add you as a collaborator
39+for the advisory so that you can join the discussion and validate any fixes
40+we may propose.
41+
42+For minor issues and previously disclosed vulnerabilities (typically for
43+dependencies), we may use regular PRs for fixes and forego the security advisory.
44+
45+Once a fix has been agreed upon, we will merge the fix and create a new release.
46+If we have multiple security issues in flight simultaneously, we may delay
47+merging fixes until all patches are ready.
48+We may also backport the fix to previous releases,
49+but this will be at the discretion of the maintainers.
docs/versioned_docs/version-7.15.x/configuration/alpha_config.mdnew file+702
@@ -0,0 +1,702 @@
1+---
2+id: alpha-config
3+title: Alpha Configuration
4+---
5+
6+:::warning
7+This page contains documentation for alpha features.
8+We reserve the right to make breaking changes to the features detailed within this page with no notice.
9+
10+Options described in this page may be changed, removed, renamed or moved without prior warning.
11+Please beware of this before you use alpha configuration options.
12+:::
13+
14+This page details a set of **alpha** configuration options in a new format.
15+Going forward we are intending to add structured configuration in YAML format to
16+replace the existing TOML based configuration file and flags.
17+
18+Below is a reference for the structure of the configuration, with
19+[AlphaOptions](#alphaoptions) as the root of the configuration.
20+
21+When using alpha configuration, your config file will look something like below:
22+
23+```yaml
24+upstreams:
25+ - id: ...
26+ ...: ...
27+providers:
28+ - id: ...
29+ ...: ...
30+cookie:
31+ secret: ...
32+ ...: ...
33+injectRequestHeaders:
34+ - secretSource:
35+ ...: ...
36+injectResponseHeaders:
37+ - claimSource:
38+ ...: ...
39+```
40+
41+Please browse the [reference](#configuration-reference) below for the structure
42+of the new configuration format.
43+
44+# Migration Guide
45+
46+This section details breaking changes and migration steps for moving to the new
47+alpha configuration format.
48+
49+## Migrating header injections in v7.14.0
50+
51+From v7.14.0 onward, header injection sources must be explicitly nested. If you
52+previously relied on squashed fields, update to the new structure before
53+upgrading:
54+
55+```yaml
56+# before v7.14.0
57+injectRequestHeaders:
58+- name: X-Forwarded-User
59+ values:
60+ - claim: user
61+- name: X-Custom-Secret-header
62+ values:
63+ - value: my-super-secret
64+
65+# v7.14.0 and later
66+injectRequestHeaders:
67+- name: X-Forwarded-User
68+ values:
69+ - claimSource:
70+ claim: user
71+- name: X-Custom-Secret-header
72+ values:
73+ - secretSource:
74+ value: my-super-secret
75+```
76+
77+## Using Alpha Configuration
78+
79+To use the new **alpha** configuration, generate a YAML file based on the format
80+described in the [reference](#configuration-reference) below.
81+
82+Provide the path to this file using the `--alpha-config` flag.
83+
84+:::note
85+When using the `--alpha-config` flag, some options are no longer available.
86+See [removed options](#removed-options) below for more information.
87+:::
88+
89+### Converting configuration to the new structure
90+
91+Before adding the new `--alpha-config` option, start OAuth2 Proxy using the
92+`convert-config-to-alpha` flag to convert existing configuration to the new format.
93+
94+```bash
95+oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg
96+```
97+
98+This will convert any options supported by the new format to YAML and print the
99+new configuration to `STDOUT`.
100+
101+Copy this to a new file, remove any options from your existing configuration
102+noted in [removed options](#removed-options) and then start OAuth2 Proxy using
103+the new config.
104+
105+```bash
106+oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg
107+```
108+
109+### Validating Alpha Configuration
110+
111+Use `--config-test` to validate your alpha configuration without starting the proxy:
112+
113+```bash
114+oauth2-proxy --config core.cfg --alpha-config alpha.yaml --config-test
115+```
116+
117+This is useful for CI/CD pipelines to catch configuration errors before deployment.
118+See the [Configuration Validation](./overview.md#configuration-validation) section for more details.
119+
120+### How to use environment variables
121+
122+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.
123+When using environment variables, your yaml will look like this:
124+
125+```yaml
126+ providers:
127+ - provider: azure
128+ clientSecret: ${CLIENT_SECRET}
129+ ...
130+```
131+Where CLIENT_SECRET is an environment variable.
132+More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs)
133+
134+### How to inject custom headers
135+
136+Configure `injectRequestHeaders` and `injectResponseHeaders` in alpha config YAML.
137+
138+```yaml
139+injectRequestHeaders:
140+ - name: "X-User-Email"
141+ values:
142+ - claimSource:
143+ claim: "email" # extract the email claim contents from the id token
144+ - name: "X-Static-Secret"
145+ values:
146+ # secrets need to be encoded with base64 when directly in the yaml config but will be send decoded
147+ - secretSource:
148+ value: "c3VwZXItc2VjcmV0"
149+ - name: "X-Static-File-Secret"
150+ - secretSource:
151+ fromFile: "/path/to/my/secret"
152+ - name: "X-Static-Env-Secret"
153+ - secretSource:
154+ value: "${MY_SECRET_ENV}" # content still needs to be base64 encoded
155+injectResponseHeaders:
156+ # Following will result in a header "Authorization: Basic <user:password> (encoded)"
157+ - name: "Authorization"
158+ values:
159+ - claimSource:
160+ claim: user
161+ prefix: "Basic "
162+ basicAuthPassword:
163+ value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk # base64 encoded password
164+```
165+
166+**Value sources:**
167+* `claimSource` - `claim` (session claims either from id token or from profile URL)
168+* `secretSource` - `value` (base64), `fromFile` (file path)
169+
170+**Request option:** `preserveRequestValue: true` retains existing header values
171+
172+**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest`
173+
174+### How to utilize arbitrary claims provided by your Identity Provider
175+
176+With the additionalClaims attribute you can specify which claims you want to extract
177+from the ID Token or userinfo (ProfileURL) endpoint.
178+
179+Configure these on the relevant provider entry:
180+
181+```yaml
182+providers:
183+ - id: my-oidc-provider
184+ provider: oidc
185+ clientID: ${OAUTH_CLIENT_ID}
186+ clientSecret: ${OAUTH_CLIENT_SECRET}
187+ oidcConfig:
188+ issuerURL: https://issuer.example.com
189+ profileURL: https://issuer.example.com/oauth2/userinfo
190+ additionalClaims:
191+ - department
192+ - employee_id
193+ - organization.name
194+```
195+
196+OAuth2 Proxy resolves each configured claim using the following order:
197+
198+1. The raw ID token is checked first.
199+2. If the claim is not present there and `profileURL` is configured, the userinfo endpoint is queried.
200+3. If `skipClaimsFromProfileURL: true` is set, only the ID token is used.
201+
202+Claims that are not found are ignored rather than causing authentication to fail.
203+
204+You can use dot-separated paths for nested JSON objects, for example `organization.name`.
205+Array indexes are not supported.
206+
207+Once loaded, these claims are stored in the session as `additionalClaims`. They can then be
208+used anywhere session claims are accepted, including header injection:
209+
210+```yaml
211+injectRequestHeaders:
212+ - name: X-Department
213+ values:
214+ - claimSource:
215+ claim: department
216+ - name: X-Organization
217+ values:
218+ - claimSource:
219+ claim: organization.name
220+```
221+
222+This is useful when your IdP exposes application-specific attributes such as department,
223+tenant, employee ID, entitlement, or other custom claims that are not part of the default
224+OAuth2 Proxy session fields.
225+
226+## Removed options
227+
228+The following flags/options and their respective environment variables are no
229+longer available when using alpha configuration:
230+
231+<!-- Legacy Upstream FlagSet -->
232+- `flush-interval`/`flush_interval`
233+- `pass-host-header`/`pass_host_header`
234+- `proxy-websockets`/`proxy_websockets`
235+- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify`
236+- `upstream`/`upstreams`
237+
238+<!-- Legacy Headers FlagSet -->
239+- `pass-basic-auth`/`pass_basic_auth`
240+- `pass-access-token`/`pass_access_token`
241+- `pass-user-headers`/`pass_user_headers`
242+- `pass-authorization-header`/`pass_authorization_header`
243+- `set-basic-auth`/`set_basic_auth`
244+- `set-xauthrequest`/`set_xauthrequest`
245+- `set-authorization-header`/`set_authorization_header`
246+- `prefer-email-to-user`/`prefer_email_to_user`
247+- `basic-auth-password`/`basic_auth_password`
248+- `skip-auth-strip-headers`/`skip_auth_strip_headers`
249+
250+<!-- Legacy provider FlagSet -->
251+- `client-id`/`client_id`
252+- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file`
253+- `provider`
254+- `provider-display-name`/`provider_display_name`
255+- `provider-ca-file`/`provider_ca_files`
256+- `login-url`/`login_url`
257+- `redeem-url`/`redeem_url`
258+- `profile-url`/`profile_url`
259+- `resource`
260+- `validate-url`/`validate_url`
261+- `scope`
262+- `prompt`
263+- `approval-prompt`/`approval_prompt`
264+- `acr-values`/`acr_values`
265+- `user-id-claim`/`user_id_claim`
266+- `allowed-group`/`allowed_groups`
267+- `allowed-role`/`allowed_roles`
268+- `jwt-key`/`jwt_key`
269+- `jwt-key-file`/`jwt_key_file`
270+- `pubjwk-url`/`pubjwk_url`
271+
272+and all provider-specific options, i.e. any option whose name includes `oidc`,
273+`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to
274+use any of these options via flags or via config when `--alpha-config` is
275+set will result in an error.
276+
277+:::important
278+You must remove these options before starting OAuth2 Proxy with `--alpha-config`
279+:::
280+
281+## Configuration Reference
282+
283+<!--- THIS FILE IS AUTOGENERATED!!! DO NOT EDIT!!! -->
284+
285+### ADFSOptions
286+
287+(**Appears on:** [Provider](#provider))
288+
289+
290+
291+| Field | Type | Description |
292+| ----- | ---- | ----------- |
293+| `skipScope` | _bool_ | Skip adding the scope parameter in login request<br/>Default value is 'false' |
294+
295+### AlphaOptions
296+
297+AlphaOptions contains alpha structured configuration options.
298+Usage of these options allows users to access alpha features that are not
299+available as part of the primary configuration structure for OAuth2 Proxy.
300+
301+:::warning
302+The options within this structure are considered alpha.
303+They may change between releases without notice.
304+:::
305+
306+| Field | Type | Description |
307+| ----- | ---- | ----------- |
308+| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.<br/>Once a user is authenticated, requests to the server will be proxied to<br/>these upstream servers based on the path mappings defined in this list. |
309+| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added<br/>to requests to upstream servers.<br/>Headers may source values from either the authenticated user's session<br/>or from a static secret value. |
310+| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added<br/>to responses from the proxy.<br/>This is typically used when using the proxy as an external authentication<br/>provider in conjunction with another proxy such as NGINX and its<br/>auth_request module.<br/>Headers may source values from either the authenticated user's session<br/>or from a static secret value. |
311+| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.<br/>You may choose to run both HTTP and HTTPS servers simultaneously.<br/>This can be done by setting the BindAddress and the SecureBindAddress simultaneously.<br/>To use the secure server you must configure a TLS certificate and key. |
312+| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.<br/>You may choose to run both HTTP and HTTPS servers simultaneously.<br/>This can be done by setting the BindAddress and the SecureBindAddress simultaneously.<br/>To use the secure server you must configure a TLS certificate and key. |
313+| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not<br/>yet working.** [This feature is tracked in<br/>#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) |
314+
315+### AzureOptions
316+
317+(**Appears on:** [Provider](#provider))
318+
319+
320+
321+| Field | Type | Description |
322+| ----- | ---- | ----------- |
323+| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint<br/>Default value is 'common' |
324+| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph<br/>Default value is 'id' |
325+
326+### BitbucketOptions
327+
328+(**Appears on:** [Provider](#provider))
329+
330+
331+
332+| Field | Type | Description |
333+| ----- | ---- | ----------- |
334+| `team` | _string_ | Team sets restrict logins to members of this team |
335+| `repository` | _string_ | Repository sets restrict logins to user with access to this repository |
336+
337+### ClaimSource
338+
339+(**Appears on:** [HeaderValue](#headervalue))
340+
341+ClaimSource allows loading a header value from a claim within the session
342+
343+| Field | Type | Description |
344+| ----- | ---- | ----------- |
345+| `claim` | _string_ | Claim is the name of the claim in the session that the value should be<br/>loaded from. Available claims: `access_token` `id_token` `created_at`<br/>`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. |
346+| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the<br/>claim if it is non-empty. |
347+| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.<br/>Note the value of claim will become the basic auth username and the<br/>basicAuthPassword will be used as the password value. |
348+
349+### GitHubOptions
350+
351+(**Appears on:** [Provider](#provider))
352+
353+
354+
355+| Field | Type | Description |
356+| ----- | ---- | ----------- |
357+| `org` | _string_ | Org sets restrict logins to members of this organisation |
358+| `team` | _string_ | Team sets restrict logins to members of this team |
359+| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository |
360+| `token` | _string_ | Token is the token to use when verifying repository collaborators<br/>it must have push access to the repository |
361+| `users` | _[]string_ | Users allows users with these usernames to login<br/>even if they do not belong to the specified org and team or collaborators |
362+
363+### GitLabOptions
364+
365+(**Appears on:** [Provider](#provider))
366+
367+
368+
369+| Field | Type | Description |
370+| ----- | ---- | ----------- |
371+| `group` | _[]string_ | Group sets restrict logins to members of this group |
372+| `projects` | _[]string_ | Projects restricts logins to members of these projects |
373+
374+### GoogleOptions
375+
376+(**Appears on:** [Provider](#provider))
377+
378+
379+
380+| Field | Type | Description |
381+| ----- | ---- | ----------- |
382+| `group` | _[]string_ | Groups sets restrict logins to members of this Google group |
383+| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls |
384+| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials |
385+| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON |
386+| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials |
387+| `useOrganizationID` | _bool_ | UseOrganizationId indicates whether to use the organization ID as the UserName claim |
388+| `adminAPIUserScope` | _string_ | admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly |
389+
390+### Header
391+
392+(**Appears on:** [AlphaOptions](#alphaoptions))
393+
394+Header represents an individual header that will be added to a request or
395+response header.
396+
397+| Field | Type | Description |
398+| ----- | ---- | ----------- |
399+| `name` | _string_ | Name is the header name to be used for this set of values.<br/>Names should be unique within a list of Headers. |
400+| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header<br/>should be preserved for the request to the upstream server.<br/>This option only applies to injected request headers.<br/>Defaults to false (headers that match this header will be stripped). |
401+| `InsecureSkipHeaderNormalization` | _bool_ | InsecureSkipHeaderNormalization disables normalizing the header name<br/>According to RFC 7230 Section 3.2 there aren't any rules about<br/>capitalization of header names, but the standard practice is to use<br/>Title-Case (e.g. X-Forwarded-For). By default, header names will be<br/>normalized to Title-Case and any incoming headers that match will be<br/>treated as the same header. Additionally underscores (_) in header names<br/>will be converted to dashes (-) when normalizing.<br/>Defaults to false (header names will be normalized). |
402+| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header |
403+
404+### HeaderValue
405+
406+(**Appears on:** [Header](#header))
407+
408+HeaderValue represents a single header value and the sources that can
409+make up the header value
410+
411+| Field | Type | Description |
412+| ----- | ---- | ----------- |
413+| `value` | _[]byte_ | Value expects a base64 encoded string value. |
414+| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. |
415+| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. |
416+| `claim` | _string_ | Claim is the name of the claim in the session that the value should be<br/>loaded from. Available claims: `access_token` `id_token` `created_at`<br/>`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. |
417+| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the<br/>claim if it is non-empty. |
418+| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.<br/>Note the value of claim will become the basic auth username and the<br/>basicAuthPassword will be used as the password value. |
419+
420+### KeycloakOptions
421+
422+(**Appears on:** [Provider](#provider))
423+
424+
425+
426+| Field | Type | Description |
427+| ----- | ---- | ----------- |
428+| `groups` | _[]string_ | Group enables to restrict login to members of indicated group |
429+| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) |
430+
431+### LoginGovOptions
432+
433+(**Appears on:** [Provider](#provider))
434+
435+
436+
437+| Field | Type | Description |
438+| ----- | ---- | ----------- |
439+| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, |
440+| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT |
441+| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint |
442+
443+### LoginURLParameter
444+
445+(**Appears on:** [Provider](#provider))
446+
447+LoginURLParameter is the configuration for a single query parameter that
448+can be passed through from the `/oauth2/start` endpoint to the IdP login
449+URL. The "default" option specifies the default value or values (if any)
450+that will be passed to the IdP for this parameter, and "allow" is a list
451+of options for ways in which this parameter can be set or overridden via
452+the query string to `/oauth2/start`.
453+If _only_ a default is specified and no "allow" then the parameter is
454+effectively fixed - the default value will always be used and anything
455+passed to the start URL will be ignored. If _only_ "allow" is specified
456+but no default then the parameter will only be passed on to the IdP if
457+the caller provides it, and no value will be sent otherwise.
458+
459+Examples:
460+
461+# A parameter whose value is fixed
462+
463+```
464+name: organization
465+default:
466+- myorg
467+```
468+
469+A parameter that is not passed by default, but may be set to one of a
470+fixed set of values
471+
472+```
473+name: prompt
474+allow:
475+- value: login
476+- value: consent
477+- value: select_account
478+```
479+
480+A parameter that is passed by default but may be overridden by one of
481+a fixed set of values
482+
483+```
484+name: prompt
485+default: ["login"]
486+allow:
487+- value: consent
488+- value: select_account
489+```
490+
491+A parameter that may be overridden, but only by values that match a
492+regular expression. For example to restrict `login_hint` to email
493+addresses in your organization's domain:
494+
495+```
496+name: login_hint
497+allow:
498+- pattern: '^[^@]*@example\.com$'
499+# this allows at most one "@" sign, and requires "example.com" domain.
500+```
501+
502+Note that the YAML rules around exactly which characters are allowed
503+and/or require escaping in different types of string literals are
504+convoluted. For regular expressions the single quoted form is simplest
505+as backslash is not considered to be an escape character. Alternatively
506+use the "chomped block" format `|-`:
507+
508+```
509+ - pattern: |-
510+ ^[^@]*@example\.com$
511+
512+```
513+
514+The hyphen is important, a `|` block would have a trailing newline
515+character.
516+
517+| Field | Type | Description |
518+| ----- | ---- | ----------- |
519+| `name` | _string_ | Name specifies the name of the query parameter. |
520+| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be<br/>passed to the IdP if not overridden. |
521+| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be<br/>overridden via the query string to `/oauth2/start`. Only<br/>values that match one or more of the allow rules will be<br/>forwarded to the IdP. |
522+
523+### MicrosoftEntraIDOptions
524+
525+(**Appears on:** [Provider](#provider))
526+
527+
528+
529+| Field | Type | Description |
530+| ----- | ---- | ----------- |
531+| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are<br/>issued by different issuers and OIDC issuer verification needs to be disabled.<br/>When not specified, all tenants are allowed. Redundant for single-tenant apps<br/>(regular ID token validation matches the issuer). |
532+| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected<br/>by Entra Workload Identity plugin, instead of client secret. |
533+
534+### OIDCOptions
535+
536+(**Appears on:** [Provider](#provider))
537+
538+
539+
540+| Field | Type | Description |
541+| ----- | ---- | ----------- |
542+| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL<br/>eg: https://accounts.google.com |
543+| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified<br/>default set to 'false' |
544+| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL<br/>default set to 'false' |
545+| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match<br/>the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked<br/>after the initial OAuth redeem & subsequent token refreshes.<br/>default set to 'true'<br/>Warning: In a future release, this will change to 'false' by default for enhanced security. |
546+| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints<br/>default set to 'false' |
547+| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL<br/>eg: https://www.googleapis.com/oauth2/v3/certs |
548+| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use<br/>for verifying JWT tokens |
549+| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,<br/>default set to 'email' |
550+| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups<br/>default set to 'groups' |
551+| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID<br/>default set to 'email' |
552+| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id<br/>By default `aud` claim is used for verification. |
553+| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed<br/>to pass verification in addition to the client id. |
554+| `enabledSigningAlgs` | _[]string_ | EnabledSigningAlgs is a list of allowed JWT signing algorithms.<br/>When discovery is enabled, the effective set is the intersection<br/>between this list and the provider's discovered supported algorithms.<br/>By default `RS256` is used if nothing has been discovered or specified. |
555+
556+### Provider
557+
558+(**Appears on:** [Providers](#providers))
559+
560+Provider holds all configuration for a single provider
561+
562+| Field | Type | Description |
563+| ----- | ---- | ----------- |
564+| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider<br/>This value is required for all providers. |
565+| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider<br/>This value is required for all providers. |
566+| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file<br/>containing the OAuth Client Secret, it will be used if ClientSecret is not set. |
567+| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. |
568+| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. |
569+| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. |
570+| `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. |
571+| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. |
572+| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. |
573+| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. |
574+| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. |
575+| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider<br/>or providers utilize OIDC configurations. |
576+| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. |
577+| `id` | _string_ | ID should be a unique identifier for the provider.<br/>This value is required for all providers. |
578+| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider<br/>must be set from the supported providers group,<br/>otherwise 'Google' is set as default |
579+| `name` | _string_ | Name is the providers display name<br/>if set, it will be shown to the users in the login page. |
580+| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.<br/>If not specified, the default Go trust sources are used instead |
581+| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used<br/>If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. |
582+| `loginURL` | _string_ | LoginURL is the authentication endpoint |
583+| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL |
584+| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request |
585+| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint |
586+| `profileURL` | _string_ | ProfileURL is the profile access endpoint |
587+| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token<br/>default set to 'false' |
588+| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) |
589+| `validateURL` | _string_ | ValidateURL is the access token validation endpoint |
590+| `scope` | _string_ | Scope is the OAuth scope specification |
591+| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group |
592+| `code_challenge_method` | _string_ | The code challenge method |
593+| `additionalClaims` | _[]string_ | Additional claims to be obtained from the upstream IDP, either from the id_token or from the userinfo endpoint if configured. |
594+| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session |
595+
596+### ProviderType
597+#### (`string` alias)
598+
599+(**Appears on:** [Provider](#provider))
600+
601+ProviderType is used to enumerate the different provider type options
602+Valid options are: adfs, azure, bitbucket, digitalocean facebook, github,
603+gitlab, google, keycloak, keycloak-oidc, linkedin, login.gov, nextcloud
604+and oidc.
605+
606+### Providers
607+
608+#### ([[]Provider](#provider) alias)
609+
610+(**Appears on:** [AlphaOptions](#alphaoptions))
611+
612+The provider can be selected using the `provider` configuration value, or
613+set in the [`providers` array using
614+AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers).
615+However, [**the feature to implement multiple providers is not
616+complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926).
617+
618+### SecretSource
619+
620+(**Appears on:** [ClaimSource](#claimsource), [HeaderValue](#headervalue), [TLS](#tls))
621+
622+SecretSource references an individual secret value.
623+Only one source within the struct should be defined at any time.
624+
625+| Field | Type | Description |
626+| ----- | ---- | ----------- |
627+| `value` | _[]byte_ | Value expects a base64 encoded string value. |
628+| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. |
629+| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. |
630+
631+### Server
632+
633+(**Appears on:** [AlphaOptions](#alphaoptions))
634+
635+Server represents the configuration for an HTTP(S) server
636+
637+| Field | Type | Description |
638+| ----- | ---- | ----------- |
639+| `bindAddress` | _string_ | BindAddress is the address on which to serve traffic.<br/>Different types of bind addresses are supported:<br/>* `[http://]<addr>:<port>`<br/>* `fd:<int>` (case insensitive)<br/>* `unix://<path>`<br/>Unix sockets are created with default system umask mode, which can be overridden, e.g.: `unix://my-socket,mode=0777`<br/>Square brackets are required for ipv6 address, e.g. `http://[::1]:4180`<br/>Leave blank or set to "-" to disable. |
640+| `secureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.<br/>Secure bind addresses need to respond with valid SSL and use the following format:<br/>* `[https://]<addr>:<port>`<br/>Square brackets are required for ipv6 address, e.g. `https://[::1]:4180`<br/>Leave blank or set to "-" to disable. |
641+| `tls` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the<br/>secure traffic and further configuration for the TLS server. |
642+
643+### TLS
644+
645+(**Appears on:** [Server](#server))
646+
647+TLS contains the information for loading a TLS certificate and key
648+as well as an optional minimal TLS version that is acceptable.
649+
650+| Field | Type | Description |
651+| ----- | ---- | ----------- |
652+| `key` | _[SecretSource](#secretsource)_ | Key is the TLS key data to use.<br/>Typically this will come from a file. |
653+| `cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.<br/>Typically this will come from a file. |
654+| `minVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.<br/>E.g. Set to "TLS1.3" to select TLS version 1.3 |
655+| `cipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.<br/>E.g.:<br/>- TLS_RSA_WITH_RC4_128_SHA<br/>- TLS_RSA_WITH_AES_256_GCM_SHA384<br/>If not specified, the default Go safe cipher list is used.<br/>List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). |
656+
657+### URLParameterRule
658+
659+(**Appears on:** [LoginURLParameter](#loginurlparameter))
660+
661+URLParameterRule represents a rule by which query parameters
662+passed to the `/oauth2/start` endpoint are checked to determine whether
663+they are valid overrides for the given parameter passed to the IdP's
664+login URL. Either Value or Pattern should be supplied, not both.
665+
666+| Field | Type | Description |
667+| ----- | ---- | ----------- |
668+| `value` | _string_ | A Value rule matches just this specific value |
669+| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by<br/>some substring of the value. The expression is _not_ automatically<br/>anchored to the start and end of the value, if you _want_ to restrict<br/>the whole parameter value you must anchor it yourself with `^` and `$`. |
670+
671+### Upstream
672+
673+(**Appears on:** [UpstreamConfig](#upstreamconfig))
674+
675+Upstream represents the configuration for an upstream server.
676+Requests will be proxied to this upstream if the path matches the request path.
677+
678+| Field | Type | Description |
679+| ----- | ---- | ----------- |
680+| `id` | _string_ | ID should be a unique identifier for the upstream.<br/>This value is required for all upstreams. |
681+| `path` | _string_ | Path is used to map requests to the upstream server.<br/>The closest match will take precedence and all Paths must be unique.<br/>Path can also take a pattern when used with RewriteTarget.<br/>Path segments can be captured and matched using regular experessions.<br/>Eg:<br/>- `^/foo$`: Match only the explicit path `/foo`<br/>- `^/bar/$`: Match any path prefixed with `/bar/`<br/>- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget |
682+| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to<br/>the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem<br/>(for a `file:` upstream).<br/>Use the Path to capture segments for reuse within the rewrite target.<br/>Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite<br/>the request `/baz/abc/123` to `/foo/abc/123` before proxying to the<br/>upstream server. Or if the upstream were `file:///app`, a request for<br/>`/baz/info.html` would return the contents of the file `/app/foo/info.html`. |
683+| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File<br/>based URL. It may include a path, in which case all requests will be served<br/>under that path.<br/>Eg:<br/>- http://localhost:8080<br/>- https://service.localhost<br/>- https://service.localhost/path<br/>- file://host/path<br/>If the URI's path is "/base" and the incoming request was for "/dir",<br/>the upstream request will be for "/base/dir". |
684+| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.<br/>This option is insecure and will allow potential Man-In-The-Middle attacks<br/>between OAuth2 Proxy and the upstream server.<br/>Defaults to false. |
685+| `static` | _bool_ | Static will make all requests to this upstream have a static response.<br/>The response will have a body of "Authenticated" and a response code<br/>matching StaticCode.<br/>If StaticCode is not set, the response will return a 200 response. |
686+| `staticCode` | _int_ | StaticCode determines the response code for the Static response.<br/>This option can only be used with Static enabled. |
687+| `flushInterval` | _duration_ | FlushInterval is the period between flushing the response buffer when<br/>streaming response from the upstream.<br/>Defaults to 1 second. |
688+| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied<br/>to the upstream server.<br/>Defaults to true. |
689+| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers<br/>Defaults to true. |
690+| `timeout` | _duration_ | Timeout is the maximum duration the server will wait for a response from the upstream server.<br/>Defaults to 30 seconds. |
691+| `disableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.<br/>Defaults to false. |
692+
693+### UpstreamConfig
694+
695+(**Appears on:** [AlphaOptions](#alphaoptions))
696+
697+UpstreamConfig is a collection of definitions for upstream servers.
698+
699+| Field | Type | Description |
700+| ----- | ---- | ----------- |
701+| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls<br/>like: "/%2F/" which would otherwise be redirected to "/" |
702+| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.<br/>Requests will be proxied to this upstream if the path matches the request path. |
docs/versioned_docs/version-7.15.x/configuration/alpha_config.md.tmplnew file+281
@@ -0,0 +1,281 @@
1+---
2+id: alpha-config
3+title: Alpha Configuration
4+---
5+
6+:::warning
7+This page contains documentation for alpha features.
8+We reserve the right to make breaking changes to the features detailed within this page with no notice.
9+
10+Options described in this page may be changed, removed, renamed or moved without prior warning.
11+Please beware of this before you use alpha configuration options.
12+:::
13+
14+This page details a set of **alpha** configuration options in a new format.
15+Going forward we are intending to add structured configuration in YAML format to
16+replace the existing TOML based configuration file and flags.
17+
18+Below is a reference for the structure of the configuration, with
19+[AlphaOptions](#alphaoptions) as the root of the configuration.
20+
21+When using alpha configuration, your config file will look something like below:
22+
23+```yaml
24+upstreams:
25+ - id: ...
26+ ...: ...
27+providers:
28+ - id: ...
29+ ...: ...
30+cookie:
31+ secret: ...
32+ ...: ...
33+injectRequestHeaders:
34+ - secretSource:
35+ ...: ...
36+injectResponseHeaders:
37+ - claimSource:
38+ ...: ...
39+```
40+
41+Please browse the [reference](#configuration-reference) below for the structure
42+of the new configuration format.
43+
44+# Migration Guide
45+
46+This section details breaking changes and migration steps for moving to the new
47+alpha configuration format.
48+
49+## Migrating header injections in v7.14.0
50+
51+From v7.14.0 onward, header injection sources must be explicitly nested. If you
52+previously relied on squashed fields, update to the new structure before
53+upgrading:
54+
55+```yaml
56+# before v7.14.0
57+injectRequestHeaders:
58+- name: X-Forwarded-User
59+ values:
60+ - claim: user
61+- name: X-Custom-Secret-header
62+ values:
63+ - value: my-super-secret
64+
65+# v7.14.0 and later
66+injectRequestHeaders:
67+- name: X-Forwarded-User
68+ values:
69+ - claimSource:
70+ claim: user
71+- name: X-Custom-Secret-header
72+ values:
73+ - secretSource:
74+ value: my-super-secret
75+```
76+
77+## Using Alpha Configuration
78+
79+To use the new **alpha** configuration, generate a YAML file based on the format
80+described in the [reference](#configuration-reference) below.
81+
82+Provide the path to this file using the `--alpha-config` flag.
83+
84+:::note
85+When using the `--alpha-config` flag, some options are no longer available.
86+See [removed options](#removed-options) below for more information.
87+:::
88+
89+### Converting configuration to the new structure
90+
91+Before adding the new `--alpha-config` option, start OAuth2 Proxy using the
92+`convert-config-to-alpha` flag to convert existing configuration to the new format.
93+
94+```bash
95+oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg
96+```
97+
98+This will convert any options supported by the new format to YAML and print the
99+new configuration to `STDOUT`.
100+
101+Copy this to a new file, remove any options from your existing configuration
102+noted in [removed options](#removed-options) and then start OAuth2 Proxy using
103+the new config.
104+
105+```bash
106+oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg
107+```
108+
109+### Validating Alpha Configuration
110+
111+Use `--config-test` to validate your alpha configuration without starting the proxy:
112+
113+```bash
114+oauth2-proxy --config core.cfg --alpha-config alpha.yaml --config-test
115+```
116+
117+This is useful for CI/CD pipelines to catch configuration errors before deployment.
118+See the [Configuration Validation](./overview.md#configuration-validation) section for more details.
119+
120+### How to use environment variables
121+
122+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.
123+When using environment variables, your yaml will look like this:
124+
125+```yaml
126+ providers:
127+ - provider: azure
128+ clientSecret: ${CLIENT_SECRET}
129+ ...
130+```
131+Where CLIENT_SECRET is an environment variable.
132+More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs)
133+
134+### How to inject custom headers
135+
136+Configure `injectRequestHeaders` and `injectResponseHeaders` in alpha config YAML.
137+
138+```yaml
139+injectRequestHeaders:
140+ - name: "X-User-Email"
141+ values:
142+ - claimSource:
143+ claim: "email" # extract the email claim contents from the id token
144+ - name: "X-Static-Secret"
145+ values:
146+ # secrets need to be encoded with base64 when directly in the yaml config but will be send decoded
147+ - secretSource:
148+ value: "c3VwZXItc2VjcmV0"
149+ - name: "X-Static-File-Secret"
150+ - secretSource:
151+ fromFile: "/path/to/my/secret"
152+ - name: "X-Static-Env-Secret"
153+ - secretSource:
154+ value: "${MY_SECRET_ENV}" # content still needs to be base64 encoded
155+injectResponseHeaders:
156+ # Following will result in a header "Authorization: Basic <user:password> (encoded)"
157+ - name: "Authorization"
158+ values:
159+ - claimSource:
160+ claim: user
161+ prefix: "Basic "
162+ basicAuthPassword:
163+ value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk # base64 encoded password
164+```
165+
166+**Value sources:**
167+* `claimSource` - `claim` (session claims either from id token or from profile URL)
168+* `secretSource` - `value` (base64), `fromFile` (file path)
169+
170+**Request option:** `preserveRequestValue: true` retains existing header values
171+
172+**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest`
173+
174+### How to utilize arbitrary claims provided by your Identity Provider
175+
176+With the additionalClaims attribute you can specify which claims you want to extract
177+from the ID Token or userinfo (ProfileURL) endpoint.
178+
179+Configure these on the relevant provider entry:
180+
181+```yaml
182+providers:
183+ - id: my-oidc-provider
184+ provider: oidc
185+ clientID: ${OAUTH_CLIENT_ID}
186+ clientSecret: ${OAUTH_CLIENT_SECRET}
187+ oidcConfig:
188+ issuerURL: https://issuer.example.com
189+ profileURL: https://issuer.example.com/oauth2/userinfo
190+ additionalClaims:
191+ - department
192+ - employee_id
193+ - organization.name
194+```
195+
196+OAuth2 Proxy resolves each configured claim using the following order:
197+
198+1. The raw ID token is checked first.
199+2. If the claim is not present there and `profileURL` is configured, the userinfo endpoint is queried.
200+3. If `skipClaimsFromProfileURL: true` is set, only the ID token is used.
201+
202+Claims that are not found are ignored rather than causing authentication to fail.
203+
204+You can use dot-separated paths for nested JSON objects, for example `organization.name`.
205+Array indexes are not supported.
206+
207+Once loaded, these claims are stored in the session as `additionalClaims`. They can then be
208+used anywhere session claims are accepted, including header injection:
209+
210+```yaml
211+injectRequestHeaders:
212+ - name: X-Department
213+ values:
214+ - claimSource:
215+ claim: department
216+ - name: X-Organization
217+ values:
218+ - claimSource:
219+ claim: organization.name
220+```
221+
222+This is useful when your IdP exposes application-specific attributes such as department,
223+tenant, employee ID, entitlement, or other custom claims that are not part of the default
224+OAuth2 Proxy session fields.
225+
226+## Removed options
227+
228+The following flags/options and their respective environment variables are no
229+longer available when using alpha configuration:
230+
231+<!-- Legacy Upstream FlagSet -->
232+- `flush-interval`/`flush_interval`
233+- `pass-host-header`/`pass_host_header`
234+- `proxy-websockets`/`proxy_websockets`
235+- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify`
236+- `upstream`/`upstreams`
237+
238+<!-- Legacy Headers FlagSet -->
239+- `pass-basic-auth`/`pass_basic_auth`
240+- `pass-access-token`/`pass_access_token`
241+- `pass-user-headers`/`pass_user_headers`
242+- `pass-authorization-header`/`pass_authorization_header`
243+- `set-basic-auth`/`set_basic_auth`
244+- `set-xauthrequest`/`set_xauthrequest`
245+- `set-authorization-header`/`set_authorization_header`
246+- `prefer-email-to-user`/`prefer_email_to_user`
247+- `basic-auth-password`/`basic_auth_password`
248+- `skip-auth-strip-headers`/`skip_auth_strip_headers`
249+
250+<!-- Legacy provider FlagSet -->
251+- `client-id`/`client_id`
252+- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file`
253+- `provider`
254+- `provider-display-name`/`provider_display_name`
255+- `provider-ca-file`/`provider_ca_files`
256+- `login-url`/`login_url`
257+- `redeem-url`/`redeem_url`
258+- `profile-url`/`profile_url`
259+- `resource`
260+- `validate-url`/`validate_url`
261+- `scope`
262+- `prompt`
263+- `approval-prompt`/`approval_prompt`
264+- `acr-values`/`acr_values`
265+- `user-id-claim`/`user_id_claim`
266+- `allowed-group`/`allowed_groups`
267+- `allowed-role`/`allowed_roles`
268+- `jwt-key`/`jwt_key`
269+- `jwt-key-file`/`jwt_key_file`
270+- `pubjwk-url`/`pubjwk_url`
271+
272+and all provider-specific options, i.e. any option whose name includes `oidc`,
273+`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to
274+use any of these options via flags or via config when `--alpha-config` is
275+set will result in an error.
276+
277+:::important
278+You must remove these options before starting OAuth2 Proxy with `--alpha-config`
279+:::
280+
281+## Configuration Reference
docs/versioned_docs/version-7.15.x/configuration/integrations/caddy.mdnew file+63
@@ -0,0 +1,63 @@
1+---
2+id: caddy
3+title: Caddy
4+---
5+
6+Integrate OAuth2 Proxy with Caddy v2 using the `forward_auth` directive.
7+
8+**Key features:**
9+- Simple forward_auth setup
10+- Automatic header handling
11+- Custom error handling and redirects
12+
13+## Configuring for use with the Caddy (v2) `forward_auth` directive
14+
15+The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`.
16+
17+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.
18+
19+**Following options need to be set on `oauth2-proxy`:**
20+- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly
21+
22+```nginx title="Caddyfile"
23+example.com {
24+ # Requests to /oauth2/* are proxied to oauth2-proxy without authentication.
25+ # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive.
26+ handle /oauth2/* {
27+ reverse_proxy oauth2-proxy.internal:4180 {
28+ # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers.
29+ # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers.
30+ header_up X-Real-IP {remote_host}
31+ header_up X-Forwarded-Uri {uri}
32+ }
33+ }
34+
35+ # Requests to other paths are first processed by oauth2-proxy for authentication.
36+ handle {
37+ forward_auth oauth2-proxy.internal:4180 {
38+ uri /oauth2/auth
39+
40+ # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers.
41+ # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers.
42+ header_up X-Real-IP {remote_host}
43+
44+ # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream.
45+ # Make sure to configure the --set-xauthrequest flag to enable this feature.
46+ #copy_headers X-Auth-Request-User X-Auth-Request-Email
47+
48+ # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page.
49+ @error status 401
50+ handle_response @error {
51+ redir * /oauth2/sign_in?rd={scheme}://{host}{uri}
52+ }
53+ }
54+
55+ # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream.
56+ reverse_proxy upstream.internal:3000
57+ }
58+}
59+```
60+
61+:::note
62+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.
63+:::
docs/versioned_docs/version-7.15.x/configuration/integrations/headlamp.mdnew file+105
@@ -0,0 +1,105 @@
1+---
2+id: headlamp
3+title: Headlamp
4+---
5+
6+Modern, actively maintained Kubernetes web UI with OAuth2 Proxy integration examples.
7+
8+**Key features:**
9+- Active development and maintenance
10+- Modern, intuitive interface
11+- Multi-cluster support
12+- Plugin system
13+- Works with all OAuth2 providers
14+
15+## Configuring for use with Headlamp
16+
17+[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.
18+
19+### Architecture
20+
21+```
22+User → Ingress → OAuth2 Proxy → Authentication Provider (e.g., Azure Entra ID)
23+ ↓
24+ Headlamp
25+```
26+
27+### Prerequisites
28+
29+- Kubernetes cluster (e.g., AKS, EKS, GKE, or self-hosted)
30+- Headlamp installed in the cluster
31+- OAuth2 provider configured (Azure Entra ID, Google, GitHub, etc.)
32+- Ingress controller (Nginx, Traefik, etc.)
33+
34+### Configuration Overview
35+
36+When integrating Headlamp with OAuth2 Proxy, the OAuth2 Proxy acts as a reverse proxy in front of Headlamp:
37+
38+1. User requests access to Headlamp
39+2. Ingress forwards to OAuth2 Proxy
40+3. OAuth2 Proxy authenticates the user via the OAuth2 provider
41+4. After successful authentication, OAuth2 Proxy proxies requests to Headlamp
42+5. Headlamp receives the authenticated user information via headers
43+
44+### OAuth2 Proxy Configuration
45+
46+Configure OAuth2 Proxy to proxy to the Headlamp service:
47+
48+```yaml
49+upstreamConfig:
50+ upstreams:
51+ - id: headlamp
52+ path: /
53+ uri: http://headlamp-service.headlamp-namespace.svc.cluster.local:4466
54+```
55+
56+Enable the necessary headers:
57+
58+```yaml
59+extraArgs:
60+ reverse-proxy: true
61+ pass-authorization-header: true
62+ set-xauthrequest: true
63+ email-domain: "*" # Or restrict to your organization
64+```
65+
66+### Example with Azure Entra ID on AKS
67+
68+For detailed instructions on deploying Headlamp with OAuth2 Proxy on Azure Kubernetes Service using Azure Entra ID, see the official Headlamp documentation:
69+
70+https://headlamp.dev/docs/latest/installation/in-cluster/aks-cluster-oauth/
71+
72+Key steps include:
73+
74+1. **Set up AKS with OIDC**: Enable Microsoft Entra ID authentication with Kubernetes RBAC
75+2. **Create Azure App Registration**: Configure redirect URI and create client secret
76+3. **Deploy Headlamp**: Install Headlamp via Helm in your cluster
77+4. **Deploy OAuth2 Proxy**: Configure OAuth2 Proxy with Entra ID provider settings and upstream pointing to Headlamp
78+5. **Configure Ingress**: Set up Ingress to route traffic through OAuth2 Proxy to Headlamp
79+6. **Set RBAC Policies**: Apply Kubernetes RBAC bindings based on users or groups
80+
81+### Integration with Other Providers
82+
83+The same integration pattern works with other OAuth2 providers supported by OAuth2 Proxy:
84+
85+- **Google**: Use the Google provider configuration
86+- **GitHub**: Use the GitHub provider configuration
87+- **GitLab**: Use the GitLab provider configuration
88+- **Keycloak**: Use the Keycloak OIDC provider configuration
89+- **Any OIDC Provider**: Use the generic OIDC provider configuration
90+
91+For provider-specific configuration examples, see the [OAuth Provider Configuration](../providers/index.md) documentation.
92+
93+### Benefits Over Kubernetes Dashboard
94+
95+Headlamp offers several advantages:
96+
97+- **Active Development**: Headlamp is actively maintained and developed
98+- **Modern UI**: Clean, intuitive interface with better UX
99+- **Plugin System**: Extensible with custom plugins
100+- **Multi-cluster Support**: Built-in support for managing multiple clusters
101+- **Desktop App**: Available as both web UI and desktop application
102+
103+:::note
104+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.
105+:::
docs/versioned_docs/version-7.15.x/configuration/integrations/index.mdnew file+41
@@ -0,0 +1,41 @@
1+---
2+id: index
3+title: Integrations
4+---
5+
6+This section provides configuration examples for integrating OAuth2 Proxy with various reverse proxies, ingress controllers, and Kubernetes web UIs.
7+
8+## Reverse Proxies and Ingress Controllers
9+
10+OAuth2 Proxy can be integrated with popular reverse proxies and ingress controllers to add authentication to your applications:
11+
12+- [Nginx](nginx.md)
13+- [Traefik](traefik.md)
14+- [caddy](caddy.md)
15+
16+## Kubernetes Web UIs
17+
18+OAuth2 Proxy can also be used to add authentication to Kubernetes web user interfaces:
19+
20+- [Headlamp](headlamp.md) ✨ *Recommended*
21+- [Kubernetes Dashboard](kubernetes-dashboard.md) ⚠️ *Deprecated*
22+
23+:::tip
24+When integrating with Kubernetes web UIs, make sure to:
25+1. Configure the Ingress to pass the Authorization header with the bearer token
26+2. Increase buffer sizes for large OIDC tokens (especially with Azure Entra ID)
27+3. Set up appropriate Kubernetes RBAC permissions for your users or groups
28+:::
29+
30+## General Requirements
31+
32+Most integrations require the following OAuth2 Proxy configuration:
33+
34+- `--reverse-proxy=true`: Required to correctly handle `X-Forwarded-*` headers
35+- **Session storage**: For production deployments with large tokens due to a lot of claims like AD groups, use `--session-store-type=redis`
36+
37+For provider-specific configuration, see the [OAuth Provider Configuration](../providers/index.md) documentation.
38+
39+:::note
40+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.
41+:::
docs/versioned_docs/version-7.15.x/configuration/integrations/kubernetes-dashboard.mdnew file+289
@@ -0,0 +1,289 @@
1+---
2+id: kubernetes-dashboard
3+title: Kubernetes Dashboard
4+---
5+
6+:::warning Deprecated Project
7+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.
8+
9+You may want to consider alternative solutions such as [Headlamp](./headlamp.md).
10+:::
11+
12+## Kubernetes Dashboard on AKS with Azure Entra ID
13+
14+Integration guide for the deprecated Kubernetes Dashboard, including comprehensive Azure Entra ID configuration on AKS with detailed troubleshooting and RBAC setup.
15+
16+### Architecture
17+
18+```
19+User → Nginx Ingress → OAuth2 Proxy → Entra ID
20+ ↓
21+ Kubernetes Dashboard
22+```
23+
24+The integration flow:
25+1. Unauthenticated requests to Dashboard are intercepted by Nginx Ingress
26+2. Nginx redirects to OAuth2 Proxy for authentication
27+3. OAuth2 Proxy redirects to Entra ID login
28+4. After successful authentication, OAuth2 Proxy receives ID token from Entra ID
29+5. OAuth2 Proxy sets Authorization header with the bearer token
30+6. Nginx forwards the request with token to Kubernetes Dashboard
31+7. Dashboard validates the token and grants access based on AKS RBAC configuration
32+
33+### Prerequisites
34+
35+- AKS cluster with Entra ID integration enabled
36+- Kubernetes Dashboard installed (version 7.x or later)
37+- NGINX Ingress Controller installed
38+- Entra ID App Registration configured with:
39+ - Redirect URI: `https://your-oauth2-domain.com/oauth2/callback`
40+ - API Permissions: `openid`, `email`, `profile`
41+ - Groups claim enabled (if using group-based RBAC)
42+- Users or groups assigned appropriate Kubernetes RBAC permissions
43+
44+### Alpha Configuration Example
45+
46+Using [Alpha Configuration](../alpha_config.md) with the OAuth2 Proxy Helm chart:
47+
48+```yaml
49+alphaConfig:
50+ enabled: true
51+ configData:
52+ providers:
53+ - id: azure-entra
54+ provider: entra-id
55+ clientID: YOUR_CLIENT_ID
56+ clientSecret: YOUR_CLIENT_SECRET
57+ oidcConfig:
58+ issuerURL: https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0
59+ audienceClaims:
60+ - aud
61+ emailClaim: email
62+ groupsClaim: groups
63+ userIDClaim: oid
64+ scope: openid email profile
65+
66+ upstreamConfig:
67+ upstreams:
68+ - id: static
69+ path: /
70+ static: true
71+ staticCode: 200
72+
73+ # Response headers passed to Dashboard via Nginx
74+ injectResponseHeaders:
75+ - name: Authorization
76+ values:
77+ - claim: id_token
78+ prefix: "Bearer "
79+ - name: X-Auth-Request-User
80+ values:
81+ - claim: email
82+ - name: X-Auth-Request-Email
83+ values:
84+ - claim: email
85+ - name: X-Auth-Request-Groups
86+ values:
87+ - claim: groups
88+
89+ server:
90+ BindAddress: "0.0.0.0:4180"
91+
92+extraArgs:
93+ cookie-domain: ".your-domain.com"
94+ whitelist-domain: ".your-domain.com"
95+ email-domain: "*" # Or restrict to your organization
96+ skip-provider-button: true
97+ reverse-proxy: true
98+ pass-authorization-header: true
99+ set-xauthrequest: true
100+
101+sessionStorage:
102+ type: redis
103+
104+redis:
105+ enabled: true
106+ auth:
107+ enabled: true
108+
109+ingress:
110+ enabled: true
111+ className: nginx
112+ hosts:
113+ - OAuth2 Proxy.your-domain.com
114+ path: /oauth2
115+ pathType: Prefix
116+```
117+
118+### Kubernetes Dashboard Ingress
119+
120+**Critical**: The Ingress must include `Authorization` in the `auth-response-headers` annotation:
121+
122+```yaml
123+apiVersion: networking.k8s.io/v1
124+kind: Ingress
125+metadata:
126+ name: kubernetes-dashboard
127+ namespace: kubernetes-dashboard
128+ annotations:
129+ nginx.ingress.kubernetes.io/backend-protocol: "HTTPS"
130+ nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
131+
132+ # OAuth2 Proxy authentication
133+ nginx.ingress.kubernetes.io/auth-url: "https://OAuth2 Proxy.your-domain.com/oauth2/auth"
134+ nginx.ingress.kubernetes.io/auth-signin: "https://OAuth2 Proxy.your-domain.com/oauth2/start?rd=$scheme://$best_http_host$request_uri"
135+
136+ # Include Authorization header with bearer token
137+ nginx.ingress.kubernetes.io/auth-response-headers: "Authorization, X-Auth-Request-User, X-Auth-Request-Email"
138+
139+ # Buffer sizes for large tokens (Entra tokens can exceed 4KB)
140+ nginx.ingress.kubernetes.io/proxy-buffer-size: "256k"
141+ nginx.ingress.kubernetes.io/proxy-buffers-number: "4"
142+ nginx.ingress.kubernetes.io/proxy-busy-buffers-size: "256k"
143+spec:
144+ ingressClassName: nginx
145+ tls:
146+ - hosts:
147+ - dashboard.your-domain.com
148+ secretName: dashboard-tls
149+ rules:
150+ - host: dashboard.your-domain.com
151+ http:
152+ paths:
153+ - path: /
154+ pathType: Prefix
155+ backend:
156+ service:
157+ name: kubernetes-dashboard-kong-proxy
158+ port:
159+ number: 443
160+```
161+
162+### RBAC Configuration
163+
164+Assign Kubernetes permissions to Entra ID users or groups.
165+
166+**User-based:**
167+```yaml
168+apiVersion: rbac.authorization.k8s.io/v1
169+kind: ClusterRoleBinding
170+metadata:
171+ name: dashboard-user-admin
172+roleRef:
173+ apiGroup: rbac.authorization.k8s.io
174+ kind: ClusterRole
175+ name: cluster-admin
176+subjects:
177+ - kind: User
178+ name: "user@your-domain.com" # Email from Entra ID token
179+ apiGroup: rbac.authorization.k8s.io
180+```
181+
182+**Group-based (recommended):**
183+```yaml
184+apiVersion: rbac.authorization.k8s.io/v1
185+kind: ClusterRoleBinding
186+metadata:
187+ name: dashboard-admins-group
188+roleRef:
189+ apiGroup: rbac.authorization.k8s.io
190+ kind: ClusterRole
191+ name: cluster-admin
192+subjects:
193+ - kind: Group
194+ name: "YOUR_ENTRA_GROUP_OBJECT_ID" # Entra ID Group Object ID
195+ apiGroup: rbac.authorization.k8s.io
196+```
197+
198+For production, create custom roles with limited permissions instead of using `cluster-admin`.
199+
200+### Troubleshooting
201+
202+**Dashboard still asks for token after authentication**
203+
204+Verify that:
205+1. `injectResponseHeaders` in alphaConfig includes Authorization header with id_token claim
206+2. Dashboard Ingress includes `Authorization` in `auth-response-headers` annotation
207+3. Buffer sizes are sufficient for large tokens (set to 256k as shown above)
208+4. Check OAuth2 Proxy logs for successful token generation: `kubectl logs -n OAuth2 Proxy <pod-name>`
209+
210+**"Unauthorized" or "Invalid token" errors**
211+
212+Common causes:
213+1. User/group not configured in Kubernetes RBAC
214+ - Check: `kubectl get clusterrolebindings | grep <user-email>`
215+2. Token validation failed
216+ - Verify AKS Entra ID integration is enabled
217+ - Check Dashboard logs: `kubectl logs -n kubernetes-dashboard <pod-name>`
218+3. Incorrect OAuth2 Proxy configuration
219+ - Ensure `reverse-proxy: true` is set
220+ - Verify issuer URL matches your tenant
221+
222+**Groups not included in token**
223+
224+To include groups in the token:
225+1. In Entra ID App Registration, go to **Token configuration**
226+2. Add **groups claim** and select security groups
227+3. Or edit the manifest and add: `"groupMembershipClaims": "SecurityGroup"`
228+4. For 200+ groups, ensure scope includes `User.Read` for group overage handling
229+5. Verify groups appear in token: check OAuth2 Proxy logs
230+
231+**Session expires too quickly**
232+
233+Configure cookie expiration:
234+```yaml
235+extraArgs:
236+ cookie-expire: "24h"
237+ cookie-refresh: "1h"
238+```
239+
240+### Using Workload Identity (Passwordless)
241+
242+For production environments, use Workload Identity instead of client secrets:
243+
244+```yaml
245+config:
246+ clientID: "YOUR_CLIENT_ID"
247+ secretKeys: # Exclude client-secret
248+ - client-id
249+ - cookie-secret
250+ cookieSecret: "YOUR_COOKIE_SECRET"
251+
252+serviceAccount:
253+ annotations:
254+ azure.workload.identity/client-id: YOUR_CLIENT_ID
255+ azure.workload.identity/tenant-id: YOUR_TENANT_ID
256+
257+podLabels:
258+ azure.workload.identity/use: "true"
259+
260+alphaConfig:
261+ enabled: true
262+ configData:
263+ providers:
264+ - id: azure-entra
265+ provider: entra-id
266+ clientID: YOUR_CLIENT_ID
267+ oidcConfig:
268+ issuerURL: https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0
269+ # ... other config
270+ entraIdConfig:
271+ federatedTokenAuth: true
272+```
273+
274+This requires:
275+- AKS with OIDC issuer and Workload Identity enabled
276+- Federated identity credential configured in Entra ID App Registration
277+- Service account annotated with `azure.workload.identity/client-id`
278+
279+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.
280+
281+## Integration with Other Providers
282+
283+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:
284+
285+1. **Authorization Header**: Pass the bearer token via the `Authorization` header
286+2. **RBAC Configuration**: Configure Kubernetes RBAC for your authentication provider's users/groups
287+3. **Buffer Sizes**: Ensure adequate buffer sizes for tokens (especially important for OIDC providers)
288+
289+For provider-specific configuration examples, see the [OAuth Provider Configuration](../providers/index.md) documentation.
docs/versioned_docs/version-7.15.x/configuration/integrations/nginx.mdnew file+174
@@ -0,0 +1,174 @@
1+---
2+id: nginx
3+title: Nginx
4+---
5+
6+Configure OAuth2 Proxy with Nginx using the `auth_request` directive. Includes examples for both standalone Nginx configurations and Kubernetes ingress-nginx with annotations.
7+
8+**Key features:**
9+- Support for `auth_request` directive
10+- Kubernetes Ingress annotations
11+- Multi-part cookie handling for large tokens
12+- Session refresh support
13+
14+## Configuring for use with the Nginx `auth_request` directive
15+
16+**This option requires `--reverse-proxy` option to be set.**
17+
18+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:
19+
20+```nginx
21+server {
22+ listen 443 ssl;
23+ server_name ...;
24+ include ssl/ssl.conf;
25+
26+ location /oauth2/ {
27+ proxy_pass http://127.0.0.1:4180;
28+ proxy_set_header Host $host;
29+ proxy_set_header X-Real-IP $remote_addr;
30+ proxy_set_header X-Auth-Request-Redirect $request_uri;
31+ # or, if you are handling multiple domains:
32+ # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri;
33+ }
34+ location = /oauth2/auth {
35+ proxy_pass http://127.0.0.1:4180;
36+ proxy_set_header Host $host;
37+ proxy_set_header X-Real-IP $remote_addr;
38+ proxy_set_header X-Forwarded-Uri $request_uri;
39+ # nginx auth_request includes headers but not body
40+ proxy_set_header Content-Length "";
41+ proxy_pass_request_body off;
42+ }
43+
44+ location / {
45+ auth_request /oauth2/auth;
46+ error_page 401 = @oauth2_signin;
47+
48+ # pass information via X-User and X-Email headers to backend,
49+ # requires running with --set-xauthrequest flag
50+ auth_request_set $user $upstream_http_x_auth_request_user;
51+ auth_request_set $email $upstream_http_x_auth_request_email;
52+ proxy_set_header X-User $user;
53+ proxy_set_header X-Email $email;
54+
55+ # if you enabled --pass-access-token, this will pass the token to the backend
56+ auth_request_set $token $upstream_http_x_auth_request_access_token;
57+ proxy_set_header X-Access-Token $token;
58+
59+ # if you enabled --cookie-refresh, this is needed for it to work with auth_request
60+ auth_request_set $auth_cookie $upstream_http_set_cookie;
61+ add_header Set-Cookie $auth_cookie;
62+
63+ # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb
64+ # limit and so the OAuth2 Proxy splits these into multiple parts.
65+ # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response,
66+ # so if your cookies are larger than 4kb, you will need to extract additional cookies manually.
67+ auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1;
68+
69+ # Extract the Cookie attributes from the first Set-Cookie header and append them
70+ # to the second part ($upstream_cookie_* variables only contain the raw cookie content)
71+ if ($auth_cookie ~* "(; .*)") {
72+ set $auth_cookie_name_0 $auth_cookie;
73+ set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1";
74+ }
75+
76+ # Send both Set-Cookie headers now if there was a second part
77+ if ($auth_cookie_name_upstream_1) {
78+ add_header Set-Cookie $auth_cookie_name_0;
79+ add_header Set-Cookie $auth_cookie_name_1;
80+ }
81+
82+ proxy_pass http://backend/;
83+ # or "root /path/to/site;" or "fastcgi_pass ..." etc
84+ }
85+
86+ # Named location for handling OAuth2 sign-in redirects
87+ # This ensures the browser receives a proper 302 redirect that it will follow
88+ location @oauth2_signin {
89+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
90+ }
91+}
92+```
93+
94+### Understanding the `error_page` redirect pattern
95+
96+The `auth_request` directive expects the authentication endpoint (`/oauth2/auth`) to return:
97+- **2xx**: Request is authenticated, allow access
98+- **401 or 403**: Request is not authenticated, deny access
99+
100+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**:
101+
102+```nginx
103+error_page 401 = @oauth2_signin;
104+
105+location @oauth2_signin {
106+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
107+}
108+```
109+
110+:::warning Avoid `error_page 401 =403` with sign_in
111+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).
112+
113+The named location pattern above ensures the browser receives a standard **302 redirect** that works correctly with all oauth2-proxy configurations.
114+:::
115+
116+### Browser vs API Routes
117+
118+:::important When to use redirects
119+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.
120+:::
121+
122+#### Browser-facing routes (HTML, UI)
123+
124+For interactive browser routes where users should be redirected to sign in:
125+
126+```nginx
127+location / {
128+ auth_request /oauth2/auth;
129+ error_page 401 = @oauth2_signin;
130+ proxy_pass http://backend/;
131+}
132+
133+location @oauth2_signin {
134+ return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri;
135+}
136+```
137+
138+#### API / Machine routes (no redirect)
139+
140+For API endpoints where clients expect a 401/403 status code (not a redirect):
141+
142+```nginx
143+location /api/ {
144+ auth_request /oauth2/auth;
145+ error_page 401 =401; # Pass through the 401 status
146+ proxy_pass http://backend/;
147+}
148+```
149+
150+This ensures:
151+- ✅ Browsers get a redirect and smooth login flow
152+- ✅ API clients fail fast with appropriate HTTP status codes
153+- ✅ `/oauth2/auth` remains a pure boolean oracle (2xx/401)
154+
155+When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
156+
157+```yaml
158+nginx.ingress.kubernetes.io/auth-url: "https://<oauth2-proxy-fqdn>/oauth2/auth"
159+nginx.ingress.kubernetes.io/auth-signin: "https://<oauth2-proxy-fqdn>/oauth2/start?rd=$escaped_request_uri"
160+```
161+
162+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/.
163+
164+It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure).
165+
166+:::tip Kubernetes Dashboard with Azure Entra ID
167+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.
168+:::
169+
170+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=".
171+
172+:::note
173+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.
174+:::
docs/versioned_docs/version-7.15.x/configuration/integrations/traefik.mdnew file+192
@@ -0,0 +1,192 @@
1+---
2+id: traefik
3+title: Traefik
4+---
5+
6+Set up OAuth2 Proxy with Traefik v2 using the `ForwardAuth` middleware. Includes examples for both error-based redirects and static upstream configurations.
7+
8+**Key features:**
9+- ForwardAuth middleware integration
10+- Error middleware for 401 redirects
11+- Static upstream configuration (202 responses)
12+- Dynamic file configuration examples
13+
14+
15+## Configuring for use with the Traefik (v2) `ForwardAuth` middleware
16+
17+**This option requires `--reverse-proxy` option to be set.**
18+
19+### ForwardAuth with 401 errors middleware
20+
21+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:
22+
23+```yaml
24+http:
25+ routers:
26+ a-service:
27+ rule: "Host(`a-service.example.com`)"
28+ service: a-service-backend
29+ middlewares:
30+ - oauth-errors
31+ - oauth-auth
32+ tls:
33+ certResolver: default
34+ domains:
35+ - main: "example.com"
36+ sans:
37+ - "*.example.com"
38+ oauth:
39+ rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)"
40+ middlewares:
41+ - auth-headers
42+ service: oauth-backend
43+ tls:
44+ certResolver: default
45+ domains:
46+ - main: "example.com"
47+ sans:
48+ - "*.example.com"
49+
50+ services:
51+ a-service-backend:
52+ loadBalancer:
53+ servers:
54+ - url: http://172.16.0.2:7555
55+ oauth-backend:
56+ loadBalancer:
57+ servers:
58+ - url: http://172.16.0.1:4180
59+
60+ middlewares:
61+ auth-headers:
62+ headers:
63+ sslRedirect: true
64+ stsSeconds: 315360000
65+ browserXssFilter: true
66+ contentTypeNosniff: true
67+ forceSTSHeader: true
68+ sslHost: example.com
69+ stsIncludeSubdomains: true
70+ stsPreload: true
71+ frameDeny: true
72+ oauth-auth:
73+ forwardAuth:
74+ address: https://oauth.example.com/oauth2/auth
75+ trustForwardHeader: true
76+ oauth-errors:
77+ errors:
78+ status:
79+ - "401-403"
80+ service: oauth-backend
81+ query: "/oauth2/sign_in?rd={url}"
82+ statusRewrites:
83+ "401": 302
84+```
85+
86+:::caution Troubleshooting: Browser shows "Found." instead of redirecting
87+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.
88+
89+Adding `statusRewrites` to rewrite `401 -> 302` ensures the browser treats the response as a proper redirect and follows it automatically.
90+:::
91+
92+### ForwardAuth with static upstreams configuration
93+
94+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
95+
96+**Following options need to be set on `oauth2-proxy`:**
97+- `--upstream=static://202`: Configures a static response for authenticated sessions
98+- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly
99+
100+```yaml
101+http:
102+ routers:
103+ a-service-route-1:
104+ rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)"
105+ service: a-service-backend
106+ middlewares:
107+ - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin
108+ tls:
109+ certResolver: default
110+ domains:
111+ - main: "example.com"
112+ sans:
113+ - "*.example.com"
114+ a-service-route-2:
115+ rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)"
116+ service: a-service-backend
117+ middlewares:
118+ - oauth-auth-wo-redirect # unauthenticated session will return a 401
119+ tls:
120+ certResolver: default
121+ domains:
122+ - main: "example.com"
123+ sans:
124+ - "*.example.com"
125+ services-oauth2-route:
126+ rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)"
127+ middlewares:
128+ - auth-headers
129+ service: oauth-backend
130+ tls:
131+ certResolver: default
132+ domains:
133+ - main: "example.com"
134+ sans:
135+ - "*.example.com"
136+ oauth2-proxy-route:
137+ rule: "Host(`oauth.example.com`) && PathPrefix(`/`)"
138+ middlewares:
139+ - auth-headers
140+ service: oauth-backend
141+ tls:
142+ certResolver: default
143+ domains:
144+ - main: "example.com"
145+ sans:
146+ - "*.example.com"
147+
148+ services:
149+ a-service-backend:
150+ loadBalancer:
151+ servers:
152+ - url: http://172.16.0.2:7555
153+ b-service-backend:
154+ loadBalancer:
155+ servers:
156+ - url: http://172.16.0.3:7555
157+ oauth-backend:
158+ loadBalancer:
159+ servers:
160+ - url: http://172.16.0.1:4180
161+
162+ middlewares:
163+ auth-headers:
164+ headers:
165+ sslRedirect: true
166+ stsSeconds: 315360000
167+ browserXssFilter: true
168+ contentTypeNosniff: true
169+ forceSTSHeader: true
170+ sslHost: example.com
171+ stsIncludeSubdomains: true
172+ stsPreload: true
173+ frameDeny: true
174+ oauth-auth-redirect:
175+ forwardAuth:
176+ address: https://oauth.example.com/
177+ trustForwardHeader: true
178+ authResponseHeaders:
179+ - X-Auth-Request-Access-Token
180+ - Authorization
181+ oauth-auth-wo-redirect:
182+ forwardAuth:
183+ address: https://oauth.example.com/oauth2/auth
184+ trustForwardHeader: true
185+ authResponseHeaders:
186+ - X-Auth-Request-Access-Token
187+ - Authorization
188+```
189+
190+:::note
191+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.
192+:::
docs/versioned_docs/version-7.15.x/configuration/overview.mdnew file+451
@@ -0,0 +1,451 @@
1+---
2+id: overview
3+title: Overview
4+---
5+
6+`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).
7+
8+## Generating a Cookie Secret
9+
10+To generate a strong cookie secret use one of the below commands:
11+
12+import Tabs from '@theme/Tabs';
13+import TabItem from '@theme/TabItem';
14+
15+<Tabs defaultValue="python">
16+ <TabItem value="python" label="Python">
17+
18+```shell
19+python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())'
20+```
21+
22+ </TabItem>
23+ <TabItem value="bash" label="Bash">
24+
25+```shell
26+dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64 | tr -d -- '\n' | tr -- '+/' '-_' ; echo
27+```
28+
29+ </TabItem>
30+ <TabItem value="openssl" label="OpenSSL">
31+
32+```shell
33+openssl rand -base64 32 | tr -- '+/' '-_'
34+```
35+
36+ </TabItem>
37+ <TabItem value="powershell" label="PowerShell">
38+
39+```powershell
40+# Add System.Web assembly to session, just in case
41+Add-Type -AssemblyName System.Web
42+[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([System.Web.Security.Membership]::GeneratePassword(32,4))).Replace("+","-").Replace("/","_")
43+```
44+
45+ </TabItem>
46+ <TabItem value="terraform" label="Terraform">
47+
48+```hcl
49+# Valid 32 Byte Base64 URL encoding set that will decode to 24 []byte AES-192 secret
50+resource "random_password" "cookie_secret" {
51+ length = 32
52+ override_special = "-_"
53+}
54+```
55+
56+ </TabItem>
57+</Tabs>
58+
59+## Config File
60+
61+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).
62+
63+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`
64+
65+## Config Options
66+
67+### Command Line Options
68+
69+| Flag | Description |
70+| ---------------- | ------------------------------------------------------- |
71+| `--config` | path to config file |
72+| `--config-test` | test configuration and exit (for CI/CD validation) |
73+| `--version` | print version string |
74+
75+### General Provider Options
76+
77+Provider specific options can be found on their respective subpages.
78+
79+| Flag / Config Field | Type | Description | Default |
80+| --------------------------------------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |
81+| flag: `--acr-values`<br/>toml: `acr_values` | string | optional, see [docs](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues) | `""` |
82+| flag: `--allowed-group`<br/>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. | |
83+| flag: `--approval-prompt`<br/>toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` |
84+| flag: `--backend-logout-url`<br/>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 | |
85+| flag: `--client-id`<br/>toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | |
86+| flag: `--client-secret-file`<br/>toml: `client_secret_file` | string | the file with OAuth Client Secret. The file must contain the secret only, with no trailing newline | |
87+| flag: `--client-secret`<br/>toml: `client_secret` | string | the OAuth Client Secret | |
88+| flag: `--code-challenge-method`<br/>toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | |
89+| flag: `--insecure-oidc-allow-unverified-email`<br/>toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false |
90+| flag: `--insecure-oidc-skip-issuer-verification`<br/>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 |
91+| flag: `--insecure-oidc-skip-nonce`<br/>toml: `insecure_oidc_skip_nonce` | bool | skip verifying the OIDC ID Token's nonce claim | true |
92+| flag: `--jwt-key-file`<br/>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 | |
93+| flag: `--jwt-key`<br/>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 | |
94+| flag: `--login-url`<br/>toml: `login_url` | string | Authentication endpoint | |
95+| flag: `--auth-request-response-mode`<br/>toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | |
96+| flag: `--oidc-audience-claim`<br/>toml: `oidc_audience_claims` | string | which OIDC claim contains the audience | `"aud"` |
97+| flag: `--oidc-email-claim`<br/>toml: `oidc_email_claim` | string | which OIDC claim contains the user's email | `"email"` |
98+| flag: `--oidc-extra-audience`<br/>toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` |
99+| flag: `--oidc-groups-claim`<br/>toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` |
100+| flag: `--oidc-issuer-url`<br/>toml: `oidc_issuer_url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | |
101+| flag: `--oidc-jwks-url`<br/>toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled and public key files are not provided | |
102+| flag: `--oidc-public-key-file`<br/>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 | |
103+| flag: `--oidc-enabled-signing-alg`<br/>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. | |
104+| flag: `--profile-url`<br/>toml: `profile_url` | string | Profile access endpoint | |
105+| flag: `--prompt`<br/>toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` |
106+| flag: `--provider-ca-file`<br/>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. | |
107+| flag: `--provider-display-name`<br/>toml: `provider_display_name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) |
108+| flag: `--provider`<br/>toml: `provider` | string | OAuth provider | google |
109+| flag: `--pubjwk-url`<br/>toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | |
110+| flag: `--redeem-url`<br/>toml: `redeem_url` | string | Token redemption endpoint | |
111+| flag: `--scope`<br/>toml:`scope` | string | OAuth scope specification. Every provider has a default list of scopes which will be used in case no scope is configured. | |
112+| flag: `--skip-claims-from-profile-url`<br/>toml: `skip_claims_from_profile_url` | bool | skip request to Profile URL for resolving claims not present in id_token | false |
113+| flag: `--skip-oidc-discovery`<br/>toml: `skip_oidc_discovery` | bool | bypass OIDC endpoint discovery. `--login-url`, `--redeem-url` and `--oidc-jwks-url` must be configured in this case | false |
114+| flag: `--use-system-trust-store`<br/>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 |
115+| flag: `--validate-url`<br/>toml: `validate_url` | string | Access token validation endpoint | |
116+
117+### Cookie Options
118+
119+| Flag / Config Field | Type | Description | Default |
120+| --------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- |
121+| flag: `--cookie-csrf-expire`<br/>toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m |
122+| flag: `--cookie-csrf-per-request`<br/>toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false |
123+| flag: `--cookie-csrf-per-request-limit`<br/>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" |
124+| flag: `--cookie-csrf-samesite`<br/>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. | `""` |
125+| flag: `--cookie-domain`<br/>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). | |
126+| flag: `--cookie-expire`<br/>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 |
127+| flag: `--cookie-httponly`<br/>toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true |
128+| flag: `--cookie-name`<br/>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"` |
129+| flag: `--cookie-path`<br/>toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` |
130+| flag: `--cookie-refresh`<br/>toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers&nbsp;[^1] | |
131+| flag: `--cookie-samesite`<br/>toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` |
132+| flag: `--cookie-secret`<br/>toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | |
133+| flag: `--cookie-secret-file`<br/>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 | |
134+| flag: `--cookie-secure`<br/>toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true |
135+
136+[^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)
137+
138+### Header Options
139+
140+| Flag / Config Field | Type | Description | Default |
141+| ------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
142+| flag: `--basic-auth-password`<br/>toml: `basic_auth_password` | string | the password to set when passing the HTTP Basic Auth header | |
143+| flag: `--set-xauthrequest`<br/>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 |
144+| flag: `--set-authorization-header`<br/>toml: `set_authorization_header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false |
145+| flag: `--set-basic-auth`<br/>toml: `set_basic_auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false |
146+| flag: `--skip-auth-strip-headers`<br/>toml: `skip_auth_strip_headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy | true |
147+| flag: `--pass-access-token`<br/>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 |
148+| flag: `--pass-authorization-header`<br/>toml: `pass_authorization_header` | bool | pass OIDC IDToken to upstream via Authorization Bearer header | false |
149+| flag: `--pass-basic-auth`<br/>toml: `pass_basic_auth` | bool | pass HTTP Basic Auth, X-Forwarded-User, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true |
150+| flag: `--prefer-email-to-user`<br/>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 |
151+| flag: `--pass-user-headers`<br/>toml: `pass_user_headers` | bool | pass X-Forwarded-User, X-Forwarded-Groups, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true |
152+
153+### Logging Options
154+
155+| Flag / Config Field | Type | Description | Default |
156+| --------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------- | --------------------------------------------------- |
157+| flag: `--auth-logging-format`<br/>toml: `auth_logging_format` | string | Template for authentication log lines | see [Logging Configuration](#logging-configuration) |
158+| flag: `--auth-logging`<br/>toml: `auth_logging` | bool | Log authentication attempts | true |
159+| flag: `--errors-to-info-log`<br/>toml: `errors_to_info_log` | bool | redirects error-level logging to default log channel instead of stderr | false |
160+| flag: `--exclude-logging-path`<br/>toml: `exclude_logging_paths` | string | comma separated list of paths to exclude from logging, e.g. `"/ping,/path2"` | `""` (no paths excluded) |
161+| flag: `--logging-compress`<br/>toml: `logging_compress` | bool | Should rotated log files be compressed using gzip | false |
162+| flag: `--logging-filename`<br/>toml: `logging_filename` | string | File to log requests to, empty for `stdout` | `""` (stdout) |
163+| flag: `--logging-local-time`<br/>toml: `logging_local_time` | bool | Use local time in log files and backup filenames instead of UTC | true (local time) |
164+| flag: `--logging-max-age`<br/>toml: `logging_max_age` | int | Maximum number of days to retain old log files | 7 |
165+| flag: `--logging-max-backups`<br/>toml: `logging_max_backups` | int | Maximum number of old log files to retain; 0 to disable | 0 |
166+| flag: `--logging-max-size`<br/>toml: `logging_max_size` | int | Maximum size in megabytes of the log file before rotation | 100 |
167+| flag: `--request-id-header`<br/>toml: `request_id_header` | string | Request header to use as the request ID in logging | X-Request-Id |
168+| flag: `--request-logging-format`<br/>toml: `request_logging_format` | string | Template for request log lines | see [Logging Configuration](#logging-configuration) |
169+| flag: `--request-logging`<br/>toml: `request_logging` | bool | Log requests | true |
170+| flag: `--silence-ping-logging`<br/>toml: `silence_ping_logging` | bool | disable logging of requests to ping & ready endpoints | false |
171+| flag: `--standard-logging-format`<br/>toml: `standard_logging_format` | string | Template for standard log lines | see [Logging Configuration](#logging-configuration) |
172+| flag: `--standard-logging`<br/>toml: `standard_logging` | bool | Log standard runtime information | true |
173+
174+### Page Template Options
175+
176+| Flag / Config Field | Type | Description | Default |
177+| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- |
178+| flag: `--banner`<br/>toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | |
179+| flag: `--custom-sign-in-logo`<br/>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. | |
180+| flag: `--custom-templates-dir`<br/>toml: `custom_templates_dir` | string | path to custom html templates | |
181+| flag: `--display-htpasswd-form`<br/>toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true |
182+| flag: `--footer`<br/>toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | |
183+| flag: `--show-debug-on-error`<br/>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 |
184+
185+### Probe Options
186+
187+| Flag / Config Field | Type | Description | Default |
188+| ------------------------------------------------------- | ------ | ---------------------------------------------------------- | ----------------------------- |
189+| flag: `--ping-path`<br/>toml: `ping_path` | string | the ping endpoint that can be used for basic health checks | `"/ping"` |
190+| flag: `--ping-user-agent`<br/>toml: `ping_user_agent` | string | a User-Agent that can be used for basic health checks | `""` (don't check user agent) |
191+| flag: `--ready-path`<br/>toml: `ready_path` | string | the ready endpoint that can be used for deep health checks | `"/ready"` |
192+| flag: `--gcp-healthchecks`<br/>toml: `gcp_healthchecks` | bool | Enable GCP/GKE healthcheck endpoints (deprecated) | false |
193+
194+### Proxy Options
195+
196+:::warning
197+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.
198+:::
199+
200+| Flag / Config Field | Type | Description | Default |
201+| ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
202+| flag: `--allow-query-semicolons`<br/>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` |
203+| flag: `--api-route`<br/>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 | |
204+| flag: `--authenticated-emails-file`<br/>toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | |
205+| flag: `--bearer-token-login-fallback`<br/>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 |
206+| flag: `--email-domain`<br/>toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | |
207+| flag: `--encode-state`<br/>toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false |
208+| flag: `--extra-jwt-issuers`<br/>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`) | |
209+| flag: `--force-https`<br/>toml: `force_https` | bool | enforce https redirect | `false` |
210+| flag: `--force-json-errors`<br/>toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` |
211+| flag: `--htpasswd-file`<br/>toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | |
212+| flag: `--htpasswd-user-group`<br/>toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | |
213+| flag: `--proxy-prefix`<br/>toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`<oauth2>/sign_in`) | `"/oauth2"` |
214+| flag: `--real-client-ip-header`<br/>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 |
215+| flag: `--redirect-url`<br/>toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | |
216+| flag: `--relative-redirect-url`<br/>toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false |
217+| flag: `--reverse-proxy`<br/>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 |
218+| flag: `--trusted-proxy-ip`<br/>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"` |
219+| flag: `--signature-key`<br/>toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | |
220+| flag: `--skip-auth-preflight`<br/>toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false |
221+| flag: `--skip-auth-regex`<br/>toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | |
222+| flag: `--skip-auth-route`<br/>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 | |
223+| flag: `--skip-jwt-bearer-tokens`<br/>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 |
224+| flag: `--skip-provider-button`<br/>toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false |
225+| flag: `--ssl-insecure-skip-verify`<br/>toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false |
226+| flag: `--trusted-ip`<br/>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. | |
227+| flag: `--whitelist-domain`<br/>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`)&nbsp;[^2] | |
228+
229+[^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:*`.
230+
231+### Server Options
232+
233+| Flag / Config Field | Type | Description | Default |
234+| ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
235+| flag: `--http-address`<br/>toml: `http_address` | string | `[http://]<addr>:<port>` or `unix://<path>` or `fd:<int>` (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"` |
236+| flag: `--https-address`<br/>toml: `https_address` | string | `[https://]<addr>:<port>` to listen on for HTTPS clients. Square brackets are required for ipv6 address, e.g. `https://[::1]:443` | `":443"` |
237+| flag: `--metrics-address`<br/>toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` |
238+| flag: `--metrics-secure-address`<br/>toml: `metrics_secure_address` | string | the address prometheus metrics will be scraped from if using HTTPS | `""` |
239+| flag: `--metrics-tls-cert-file`<br/>toml: `metrics_tls_cert_file` | string | path to certificate file for secure metrics server | `""` |
240+| flag: `--metrics-tls-key-file`<br/>toml: `metrics_tls_key_file` | string | path to private key file for secure metrics server | `""` |
241+| flag: `--tls-cert-file`<br/>toml: `tls_cert_file` | string | path to certificate file | |
242+| flag: `--tls-key-file`<br/>toml: `tls_key_file` | string | path to private key file | |
243+| flag: `--tls-cipher-suite`<br/>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). | |
244+| flag: `--tls-min-version`<br/>toml: `tls_min_version` | string | minimum TLS version that is acceptable, either `"TLS1.2"` or `"TLS1.3"` | `"TLS1.2"` |
245+
246+### Session Options
247+
248+| Flag / Config Field | Type | Description | Default |
249+| ----------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
250+| flag: `--session-cookie-minimal`<br/>toml: `session_cookie_minimal` | bool | strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only) | false |
251+| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
252+| flag: `--redis-cluster-connection-urls`<br/>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` | |
253+| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
254+| flag: `--redis-ca-path`<br/>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. | |
255+| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
256+| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
257+| flag: `--redis-sentinel-password`<br/>toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | |
258+| flag: `--redis-sentinel-master-name`<br/>toml: `redis_sentinel_master_name` | string | Redis sentinel master name. Used in conjunction with `--redis-use-sentinel` | |
259+| flag: `--redis-sentinel-connection-urls`<br/>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` | |
260+| flag: `--redis-use-cluster`<br/>toml: `redis_use_cluster` | bool | Connect to redis cluster. Must set `--redis-cluster-connection-urls` to use this feature | false |
261+| flag: `--redis-use-sentinel`<br/>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 |
262+| flag: `--redis-connection-idle-timeout`<br/>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 |
263+
264+### Upstream Options
265+
266+| Flag / Config Field | Type | Description | Default |
267+| ----------------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- |
268+| flag: `--flush-interval`<br/>toml: `flush_interval` | duration | period between flushing response buffers when streaming responses | `"1s"` |
269+| flag: `--pass-host-header`<br/>toml: `pass_host_header` | bool | pass the request Host Header to upstream | true |
270+| flag: `--proxy-websockets`<br/>toml: `proxy_websockets` | bool | enables WebSocket proxying | true |
271+| flag: `--ssl-upstream-insecure-skip-verify`<br/>toml: `ssl_upstream_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false |
272+| flag: `--disable-keep-alives`<br/>toml: `disable_keep_alives` | bool | disable HTTP keep-alive connections to the upstream server | false |
273+| flag: `--upstream-timeout`<br/>toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s |
274+| flag: `--upstream`<br/>toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://<status_code>` for static response. Routing is based on the path | |
275+
276+## Configuration Validation
277+
278+The `--config-test` flag validates your configuration file without starting the proxy server. This is useful for:
279+- **CI/CD pipelines**: Pre-deployment validation
280+- **Configuration management**: Testing before applying changes
281+- **Debugging**: Verifying syntax and required fields
282+
283+### Usage
284+
285+```bash
286+# Test legacy config
287+oauth2-proxy --config /etc/oauth2-proxy.cfg --config-test
288+
289+# Test alpha config
290+oauth2-proxy --config /etc/core.cfg --alpha-config /etc/alpha.yaml --config-test
291+
292+# CI/CD pre-deployment check
293+# Returns with exit code 1 if any validation errors occur
294+oauth2-proxy --config new-config.cfg --config-test
295+```
296+
297+### Exit Codes
298+
299+- **0**: Configuration is valid ✅
300+- **1**: Configuration is invalid (errors printed to stderr) ❌
301+
302+### Validation Coverage
303+
304+The `--config-test` flag performs the **same comprehensive validation** as normal startup, including:
305+- Required fields (client ID, client secret, cookie secret, etc.)
306+- Syntax validation (TOML/YAML parsing)
307+- Provider configuration
308+- Upstream server definitions
309+- Session store connectivity (e.g., Redis network checks if configured)
310+
311+**Note**: Cannot be combined with `--convert-config-to-alpha`.
312+
313+## Upstreams Configuration
314+
315+`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.
316+
317+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.
318+
319+* 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`.
320+* 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`.
321+
322+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.
323+
324+**Unix socket upstreams** are configured as `unix:///path/to/unix.sock`.
325+
326+**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/`.
327+
328+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.
329+
330+## Environment variables
331+
332+Every command line argument can be specified as an environment variable by
333+prefixing it with `OAUTH2_PROXY_`, capitalising it, and replacing hyphens (`-`)
334+with underscores (`_`). If the argument can be specified multiple times, the
335+environment variable should be plural (trailing `S`).
336+
337+This is particularly useful for storing secrets outside a configuration file
338+or the command line.
339+
340+For example, the `--cookie-secret` flag becomes `OAUTH2_PROXY_COOKIE_SECRET`.
341+If a flag has the type `string | list` like the `--email-domain` flag it is
342+available as an environment variable in plural form e.g. `OAUTH2_PROXY_EMAIL_DOMAINS`
343+
344+Values for type `string | list` usually have a plural environment variable name
345+and need to be seperated by `,` e.g.
346+`OAUTH2_PROXY_SKIP_AUTH_ROUTES="GET=^/api/status,POST=^/api/saved_objects/_import"`
347+
348+Please check the type for each [config option](#config-options) first.
349+
350+## Logging Configuration
351+
352+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.
353+
354+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`).
355+
356+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`.
357+
358+Each type of logging has its own configurable format and variables. By default, these formats are similar to the Apache Combined Log.
359+
360+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.
361+
362+## Auth Log Format
363+
364+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:
365+
366+```
367+<REMOTE_ADDRESS> - <REQUEST ID> - <user@domain.com> [2015/03/19 17:20:19] [<STATUS>] <MESSAGE>
368+```
369+
370+The status block will contain one of the below strings:
371+
372+- `AuthSuccess` If a user has authenticated successfully by any method
373+- `AuthFailure` If the user failed to authenticate explicitly
374+- `AuthError` If there was an unexpected error during authentication
375+
376+If you require a different format than that, you can configure it with the `--auth-logging-format` flag.
377+The default format is configured as follows:
378+
379+```
380+{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}}
381+```
382+
383+Available variables for auth logging:
384+
385+| Variable | Example | Description |
386+| ------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- |
387+| 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. |
388+| Host | domain.com | The value of the Host header. |
389+| Message | Authenticated via OAuth2 | The details of the auth attempt. |
390+| Protocol | HTTP/1.0 | The request protocol. |
391+| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty |
392+| RequestMethod | GET | The request method. |
393+| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. |
394+| UserAgent | - | The full user agent as reported by the requesting client. |
395+| Username | username@email.com | The email or username of the auth request. |
396+| Status | AuthSuccess | The status of the auth request. See above for details. |
397+
398+## Request Log Format
399+
400+HTTP request logs will output by default in the below format:
401+
402+```
403+<REMOTE_ADDRESS> - <REQUEST ID> - <user@domain.com> [2015/03/19 17:20:19] <HOST_HEADER> GET <UPSTREAM_HOST> "/path/" HTTP/1.1 "<USER_AGENT>" <RESPONSE_CODE> <RESPONSE_BYTES> <REQUEST_DURATION>
404+```
405+
406+If you require a different format than that, you can configure it with the `--request-logging-format` flag.
407+The default format is configured as follows:
408+
409+```
410+{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}}
411+```
412+
413+Available variables for request logging:
414+
415+| Variable | Example | Description |
416+| --------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- |
417+| 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. |
418+| Host | domain.com | The value of the Host header. |
419+| Protocol | HTTP/1.0 | The request protocol. |
420+| RequestDuration | 0.001 | The time in seconds that a request took to process. |
421+| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty |
422+| RequestMethod | GET | The request method. |
423+| RequestURI | "/oauth2/auth" | The URI path of the request. |
424+| ResponseSize | 12 | The size in bytes of the response. |
425+| StatusCode | 200 | The HTTP status code of the response. |
426+| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. |
427+| Upstream | - | The upstream data of the HTTP request. |
428+| UserAgent | - | The full user agent as reported by the requesting client. |
429+| Username | username@email.com | The email or username of the auth request. |
430+
431+## Standard Log Format
432+
433+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:
434+
435+```
436+[2015/03/19 17:20:19] [main.go:40] <MESSAGE>
437+```
438+
439+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:
440+
441+```
442+[{{.Timestamp}}] [{{.File}}] {{.Message}}
443+```
444+
445+Available variables for standard logging:
446+
447+| Variable | Example | Description |
448+| --------- | --------------------------------- | -------------------------------------------------- |
449+| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. |
450+| File | main.go:40 | The file and line number of the logging statement. |
451+| Message | HTTP: listening on 127.0.0.1:4180 | The details of the log statement. |
docs/versioned_docs/version-7.15.x/configuration/providers/adfs.mdnew file+19
@@ -0,0 +1,19 @@
1+---
2+id: adfs
3+title: ADFS
4+---
5+
6+1. Open the ADFS administration console on your Windows Server and add a new Application Group
7+2. Provide a name for the integration, select Server Application from the Standalone applications section and click Next
8+3. Follow the wizard to get the client-id, client-secret and configure the application credentials
9+4. Configure the proxy with
10+
11+```
12+ --provider=adfs
13+ --client-id=<application ID from step 3>
14+ --client-secret=<value from step 3>
15+```
16+
17+Note: When using the ADFS Auth provider with nginx and the cookie session store you may find the cookie is too large and
18+doesn't get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the
19+[redis session storage](../sessions.md#redis-storage) should resolve this.
docs/versioned_docs/version-7.15.x/configuration/providers/bitbucket.mdnew file+25
@@ -0,0 +1,25 @@
1+---
2+id: bitbucket
3+title: BitBucket
4+---
5+
6+1. [Add a new OAuth consumer](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html)
7+ * In "Callback URL" use `https://<oauth2-proxy>/oauth2/callback`, substituting `<oauth2-proxy>` with the actual
8+ hostname that oauth2-proxy is running on.
9+ * In Permissions section select:
10+ * Account -> Email
11+ * Team membership -> Read
12+ * Repositories -> Read
13+2. Note the Client ID and Client Secret.
14+
15+To use the provider, pass the following options:
16+
17+```
18+ --provider=bitbucket
19+ --client-id=<Client ID>
20+ --client-secret=<Client Secret>
21+```
22+
23+The default configuration allows everyone with Bitbucket account to authenticate. To restrict the access to the team
24+members use additional configuration option: `--bitbucket-team=<Team name>`. To restrict the access to only these users
25+who have access to one selected repository use `--bitbucket-repository=<Repository name>`.
docs/versioned_docs/version-7.15.x/configuration/providers/cidaas.mdnew file+37
@@ -0,0 +1,37 @@
1+---
2+id: cidaas
3+title: Cidaas
4+---
5+
6+[Cidaas](https://www.cidaas.com/) is an Identity as a Service (IDaaS) solution that provides authentication and authorization services.
7+It supports various protocols including OpenID Connect, OAuth 2.0, and SAML.
8+
9+However, Cidaas provides groups and their roles as hierarchical claims, which are not supported by oauth2-proxy yet.
10+The Cidaas provider transforms the hierarchical claims into a flat list of groups, which can be used by oauth2-proxy.
11+
12+Example of groups and roles in Cidaas:
13+
14+```json
15+{
16+ "groups": [
17+ {
18+ "groupId": "group1",
19+ "roles": ["role1", "role2"]
20+ },
21+ {
22+ "groupId": "group2",
23+ "roles": ["role3"]
24+ }
25+ ]
26+}
27+```
28+
29+This will be transformed into a flat list of groups:
30+
31+```json
32+{
33+ "groups": ["group1:role1", "group2:role2", "group2:role3"]
34+}
35+```
36+
37+Apart from that the Cidaas provider inherits all the features of the [OpenID Connect provider](openid_connect.md).
docs/versioned_docs/version-7.15.x/configuration/providers/cisco_duo.mdnew file+44
@@ -0,0 +1,44 @@
1+---
2+id: cisco_duo
3+title: Cisco Duo
4+---
5+
6+Cisco Duo SSO can be configured with OAuth2 Proxy using the OIDC provider.
7+
8+1. Create a new **Generic OIDC Relying Party - Single Sign-On** application in the Duo Admin Portal
9+2. Configure OAuth2 Proxy with the following options:
10+
11+```
12+provider = "oidc"
13+provider_display_name = "Duo SSO"
14+scope = "openid email profile"
15+pass_access_token = true
16+code_challenge_method = "S256"
17+```
18+
19+3. Configure Provider endpoints. Copy the following values from the corresponding fields in the Duo Admin Portal:
20+
21+```
22+# Copy from "Client ID" field
23+client_id = "XXXXXXXX"
24+
25+# Copy from "Client Secret" field
26+client_secret = "XXXXXXXX"
27+
28+# Copy from "Issuer" field
29+oidc_issuer_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx"
30+
31+# Copy from "JWKS URL" field
32+oidc_jwks_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/jwks"
33+
34+# Copy from "Token Introspection URL" field
35+validate_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/token_introspection"
36+
37+# Copy from "UserInfo" field
38+profile_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/userinfo"
39+
40+# Copy from "Token URL" field
41+redeem_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/token"
42+```
43+
44+4. Complete Configuration by filling in any remaining required fields and save your configuration.
docs/versioned_docs/version-7.15.x/configuration/providers/digitalocean.mdnew file+21
@@ -0,0 +1,21 @@
1+---
2+id: digitalocean
3+title: DigitalOcean
4+---
5+
6+1. [Create a new OAuth application](https://cloud.digitalocean.com/account/api/applications)
7+ * You can fill in the name, homepage, and description however you wish.
8+ * In the "Application callback URL" field, enter: `https://oauth-proxy/oauth2/callback`, substituting `oauth2-proxy`
9+ with the actual hostname that oauth2-proxy is running on. The URL must match oauth2-proxy's configured redirect URL.
10+2. Note the Client ID and Client Secret.
11+
12+To use the provider, pass the following options:
13+
14+```
15+ --provider=digitalocean
16+ --client-id=<Client ID>
17+ --client-secret=<Client Secret>
18+```
19+
20+Alternatively, set the equivalent options in the config file. The redirect URL defaults to
21+`https://<requested host header>/oauth2/callback`. If you need to change it, you can use the `--redirect-url` command-line option.
docs/versioned_docs/version-7.15.x/configuration/providers/facebook.mdnew file+7
@@ -0,0 +1,7 @@
1+---
2+id: facebook
3+title: Facebook
4+---
5+
6+1. Create a new FB App from https://developers.facebook.com/
7+2. Under FB Login, set your Valid OAuth redirect URIs to `https://internal.yourcompany.com/oauth2/callback`
docs/versioned_docs/version-7.15.x/configuration/providers/gitea.mdnew file+24
@@ -0,0 +1,24 @@
1+---
2+id: gitea
3+title: Gitea / Forgejo
4+---
5+
6+:::note
7+This is not actually a fully serparate provider. For more details and options please refer to the [GitHub Provider Options](github.md)
8+:::
9+
10+1. Create a new application: `https://< your gitea host >/user/settings/applications`
11+2. Under `Redirect URI` enter the correct URL i.e. `https://<proxied host>/oauth2/callback`
12+3. Note the Client ID and Client Secret.
13+4. Pass the following options to the proxy:
14+
15+```
16+ --provider="github"
17+ --redirect-url="https://<proxied host>/oauth2/callback"
18+ --provider-display-name="Gitea"
19+ --client-id="< client_id as generated by Gitea >"
20+ --client-secret="< client_secret as generated by Gitea >"
21+ --login-url="https://< your gitea host >/login/oauth/authorize"
22+ --redeem-url="https://< your gitea host >/login/oauth/access_token"
23+ --validate-url="https://< your gitea host >/api/v1/user/emails"
24+```
docs/versioned_docs/version-7.15.x/configuration/providers/github.mdnew file+81
@@ -0,0 +1,81 @@
1+---
2+id: github
3+title: GitHub
4+---
5+
6+## Config Options
7+
8+| Flag | Toml Field | Type | Description | Default |
9+| ---------------- | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------- | ------- |
10+| `--github-org` | `github_org` | string | restrict logins to members of this organisation | |
11+| `--github-team` | `github_team` | string | restrict logins to members of any of these teams (slug) or (org:team), comma separated | |
12+| `--github-repo` | `github_repo` | string | restrict logins to collaborators of this repository formatted as `orgname/repo` | |
13+| `--github-token` | `github_token` | string | the token to use when verifying repository collaborators (must have push access to the repository) | |
14+| `--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 | |
15+
16+## Usage
17+
18+1. Create a new project: https://github.com/settings/developers
19+2. Under `Authorization callback URL` enter the correct url ie `https://internal.yourcompany.com/oauth2/callback`
20+
21+The GitHub auth provider supports two additional ways to restrict authentication to either organization and optional
22+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`
23+
24+NOTE: When `--github-user` is set, the specified users are allowed to log in even if they do not belong to the specified
25+org and team or collaborators.
26+
27+To restrict access to your organization:
28+
29+```shell
30+ # restrict logins to members of this organisation
31+ --github-org="your-org"
32+```
33+
34+To restrict access to specific teams within an organization:
35+
36+```shell
37+ --github-org="your-org"
38+ # restrict logins to members of any of these teams (slug), comma separated
39+ --github-team="team1,team2,team3"
40+```
41+
42+To restrict to teams within different organizations, keep the organization flag empty and use `--github-team` like so:
43+
44+```shell
45+ # keep empty
46+ --github-org=""
47+ # restrict logins to members to any of the following teams (format <org>:<slug>, like octo:team1), comma separated
48+ --github-team="org1:team1,org2:team1,org3:team42,octo:cat"
49+```
50+
51+If you would rather restrict access to collaborators of a repository, those users must either have push access to a
52+public repository or any access to a private repository:
53+
54+```shell
55+ # restrict logins to collaborators of this repository formatted as orgname/repo
56+ --github-repo=""
57+```
58+
59+If you'd like to allow access to users with **read only** access to a **public** repository you will need to provide a
60+[token](https://github.com/settings/tokens) for a user that has write access to the repository. The token must be
61+created with at least the `public_repo` scope:
62+
63+```shell
64+ # the token to use when verifying repository collaborators
65+ --github-token=""
66+```
67+
68+To allow a user to log in with their username even if they do not belong to the specified org and team or collaborators:
69+
70+```shell
71+ # allow logins by username, comma separated
72+ --github-user=""
73+```
74+
75+If you are using GitHub enterprise, make sure you set the following to the appropriate url:
76+
77+```shell
78+ --login-url="http(s)://<enterprise github host>/login/oauth/authorize"
79+ --redeem-url="http(s)://<enterprise github host>/login/oauth/access_token"
80+ --validate-url="http(s)://<enterprise github host>/api/v3"
81+```
docs/versioned_docs/version-7.15.x/configuration/providers/gitlab.mdnew file+49
@@ -0,0 +1,49 @@
1+---
2+id: gitlab
3+title: GitLab
4+---
5+
6+## Config Options
7+
8+| Flag | Toml Field | Type | Description | Default |
9+| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
10+| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
11+| `--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 | |
12+
13+## Usage
14+
15+This auth provider has been tested against Gitlab version 12.X. Due to Gitlab API changes, it may not work for version
16+prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)).
17+
18+Whether you are using GitLab.com or self-hosting GitLab, follow
19+[these steps to add an application](https://docs.gitlab.com/integration/oauth_provider/). Make sure to enable at
20+least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g.
21+https://myapp.com/oauth2/callback.
22+
23+If you need projects filtering, add the extra `read_api` scope to your application.
24+
25+The following config should be set to ensure that the oauth will work properly. To get a cookie secret follow
26+[these steps](../overview.md#generating-a-cookie-secret)
27+
28+```
29+ --provider="gitlab"
30+ --redirect-url="https://myapp.com/oauth2/callback" // Should be the same as the redirect url for the application in gitlab
31+ --client-id=GITLAB_CLIENT_ID
32+ --client-secret=GITLAB_CLIENT_SECRET
33+ --cookie-secret=COOKIE_SECRET
34+```
35+
36+Restricting by group membership is possible with the following option:
37+
38+```shell
39+ --gitlab-group="mygroup,myothergroup" # restrict logins to members of any of these groups (slug), separated by a comma
40+```
41+
42+If you are using self-hosted GitLab, make sure you set the following to the appropriate URL:
43+
44+```shell
45+ --oidc-issuer-url="<your gitlab url>"
46+```
47+
48+If your self-hosted GitLab is on a subdirectory (e.g. domain.tld/gitlab), as opposed to its own subdomain
49+(e.g. gitlab.domain.tld), you may need to add a redirect from domain.tld/oauth pointing at e.g. domain.tld/gitlab/oauth.
docs/versioned_docs/version-7.15.x/configuration/providers/google.mdnew file+84
@@ -0,0 +1,84 @@
1+---
2+id: google
3+title: Google (default)
4+---
5+
6+## Config Options
7+
8+| Flag | Toml Field | Type | Description | Default |
9+|-------------------------------------------------|----------------------------------------------| ------ |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------|
10+| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | |
11+| `--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. | |
12+| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | |
13+| `--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) | |
14+| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC |
15+| `--google-use-organization-id` | `google_use_organization_id` | bool | use organization id as preferred username | false |
16+| `--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'<br/> | `readonly` |
17+
18+## Usage
19+
20+For Google, the registration steps are:
21+
22+1. Create a new project: https://console.developers.google.com/project
23+2. Choose the new project from the top right project dropdown (only if another project is selected)
24+3. In the project Dashboard center pane, choose **"APIs & Services"**
25+4. In the left Nav pane, choose **"Credentials"**
26+5. In the center pane, choose **"OAuth consent screen"** tab. Fill in **"Product name shown to users"** and hit save.
27+6. In the center pane, choose **"Credentials"** tab.
28+ - Open the **"New credentials"** drop down
29+ - Choose **"OAuth client ID"**
30+ - Choose **"Web application"**
31+ - Application name is freeform, choose something appropriate
32+ - Authorized JavaScript origins is your domain ex: `https://internal.yourcompany.com`
33+ - Authorized redirect URIs is the location of oauth2/callback ex: `https://internal.yourcompany.com/oauth2/callback`
34+ - Choose **"Create"**
35+7. Take note of the **Client ID** and **Client Secret**
36+
37+It's recommended to refresh sessions on a short interval (1h) with `cookie-refresh` setting which validates that the
38+account is still authorized.
39+
40+#### Restrict auth to specific Google groups on your domain. (optional)
41+
42+1. Create a [service account](https://developers.google.com/identity/protocols/oauth2/service-account) and configure it
43+ to use [Application Default Credentials / Workload Identity / Workload Identity Federation (recommended)](#using-application-default-credentials-adc--workload-identity--workload-identity-federation-recommended) or,
44+ alternatively download the JSON.
45+2. Make note of the Client ID for a future step.
46+3. Under "APIs & Auth", choose APIs.
47+4. Click on Admin SDK and then Enable API.
48+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)
49+ and give the client id from step 2 the following oauth scopes:
50+
51+ ```
52+ https://www.googleapis.com/auth/admin.directory.group.member.readonly
53+ ```
54+
55+6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access.
56+7. Create or choose an existing administrative email address on the Gmail domain to assign to the `google-admin-email`
57+ flag. This email will be impersonated by this client to make calls to the Admin SDK. See the note on the link from
58+ step 5 for the reason why.
59+8. Create or choose an existing email group and set that email to the `google-group` flag. You can pass multiple instances
60+ of this flag with different groups and the user will be checked against all the provided groups.
61+
62+(Only if using a JSON file (see step 1))
63+
64+9. Lock down the permissions on the json file downloaded from step 1 so only oauth2-proxy is able to read the file and
65+ set the path to the file in the `google-service-account-json` flag.
66+10. Restart oauth2-proxy.
67+
68+Note: The user is checked against the group members list on initial authentication and every time the token is
69+refreshed ( about once an hour ).
70+
71+##### Using Application Default Credentials (ADC) / Workload Identity / Workload Identity Federation (recommended)
72+oauth2-proxy can make use of [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials).
73+When deployed within GCP, this means that it can automatically use the service account attached to the resource. When deployed to GKE, ADC
74+can be leveraged through a feature called Workload Identity. Follow Google's [guide](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity)
75+to set up Workload Identity.
76+
77+When deployed outside of GCP, [Workload Identity Federation](https://cloud.google.com/docs/authentication/provide-credentials-adc#wlif) might be an option.
78+
79+##### Using Organization ID as Preferred Username (optional)
80+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.
81+This requires that the service account used to query the Google Admin SDK has one of the following scopes granted in step 5 above:
82+- `https://www.googleapis.com/auth/admin.directory.user.readonly`,
83+- `https://www.googleapis.com/auth/admin.directory.user`
84+- `https://www.googleapis.com/auth/cloud-platform`
docs/versioned_docs/version-7.15.x/configuration/providers/index.mdnew file+46
@@ -0,0 +1,46 @@
1+---
2+id: index
3+title: OAuth Provider Configuration
4+---
5+
6+You will need to register an OAuth application with a Provider (Google, GitHub or another provider), and configure it
7+with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on.
8+
9+Valid providers are :
10+
11+- [ADFS](adfs.md)
12+- [Bitbucket](bitbucket.md)
13+- [Cidaas](cidaas.md)
14+- [CiscoDuo](cisco_duo.md)
15+- [DigitalOcean](digitalocean.md)
16+- [Facebook](facebook.md)
17+- [Gitea](gitea.md)
18+- [GitHub](github.md)
19+- [GitLab](gitlab.md)
20+- [Google](google.md) _default_
21+- [Keycloak](keycloak.md) (Deprecated)
22+- [Keycloak OIDC](keycloak_oidc.md)
23+- [LinkedIn](linkedin.md)
24+- [login.gov](login_gov.md)
25+- [Microsoft Azure](ms_azure_ad.md) (Deprecated)
26+- [Microsoft Entra ID](ms_entra_id.md)
27+- [Nextcloud](nextcloud.md)
28+- [OpenID Connect](openid_connect.md)
29+- [SourceHut](sourcehut.md)
30+
31+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).
32+
33+Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the
34+OpenID Connect provider.
35+
36+## Email Authentication
37+
38+To authorize a specific email-domain use `--email-domain=yourcompany.com`. To authorize individual email addresses use
39+`--authenticated-emails-file=/path/to/file` with one email per line. To authorize all email addresses use `--email-domain=*`.
40+
41+## Adding a new Provider
42+
43+Follow the examples in the [`providers` package](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/) to define a new
44+`Provider` instance. Add a new `case` to
45+[`providers.New()`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/providers.go) to allow `oauth2-proxy` to use the
46+new `Provider`.
docs/versioned_docs/version-7.15.x/configuration/providers/keycloak.mdnew file+36
@@ -0,0 +1,36 @@
1+---
2+id: keycloak
3+title: Keycloak (Deprecated)
4+---
5+
6+:::note
7+This is the legacy and deprecated provider for Keycloak, use [Keycloak OIDC Auth Provider](keycloak_oidc.md) if possible.
8+:::
9+
10+1. Create new client in your Keycloak realm with **Access Type** 'confidential' and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback'
11+2. Take note of the Secret in the credential tab of the client
12+3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'.
13+
14+Make sure you set the following to the appropriate url:
15+
16+```
17+ --provider=keycloak
18+ --client-id=<client you have created>
19+ --client-secret=<your client's secret>
20+ --login-url="http(s)://<keycloak host>/auth/realms/<your realm>/protocol/openid-connect/auth"
21+ --redeem-url="http(s)://<keycloak host>/auth/realms/<your realm>/protocol/openid-connect/token"
22+ --profile-url="http(s)://<keycloak host>/auth/realms/<your realm>/protocol/openid-connect/userinfo"
23+ --validate-url="http(s)://<keycloak host>/auth/realms/<your realm>/protocol/openid-connect/userinfo"
24+ --keycloak-group=<first_allowed_user_group>
25+ --keycloak-group=<second_allowed_user_group>
26+```
27+
28+For group based authorization, the optional `--keycloak-group` (legacy) or `--allowed-group` (global standard)
29+flags can be used to specify which groups to limit access to.
30+
31+If these are unset but a `groups` mapper is set up above in step (3), the provider will still
32+populate the `X-Forwarded-Groups` header to your upstream server with the `groups` data in the
33+Keycloak userinfo endpoint response.
34+
35+The group management in keycloak is using a tree. If you create a group named admin in keycloak
36+you should define the 'keycloak-group' value to /admin.
docs/versioned_docs/version-7.15.x/configuration/providers/keycloak_oidc.mdnew file+151
@@ -0,0 +1,151 @@
1+---
2+id: keycloak_oidc
3+title: Keycloak OIDC
4+---
5+
6+## Config Options
7+
8+| Flag | Toml Field | Type | Description | Default |
9+| ---------------- | --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------ | ------- |
10+| `--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. | |
11+
12+## Usage
13+
14+```
15+ --provider=keycloak-oidc
16+ --client-id=<your client's id>
17+ --client-secret=<your client's secret>
18+ --redirect-url=https://internal.yourcompany.com/oauth2/callback
19+ --oidc-issuer-url=https://<keycloak host>/realms/<your realm> // For Keycloak versions <17: --oidc-issuer-url=https://<keycloak host>/auth/realms/<your realm>
20+ --email-domain=<yourcompany.com> // Validate email domain for users, see option documentation
21+ --allowed-role=<realm role name> // Optional, required realm role
22+ --allowed-role=<client id>:<client role name> // Optional, required client role
23+ --allowed-group=</group name> // Optional, requires group client scope
24+ --code-challenge-method=S256 // PKCE
25+```
26+
27+:::note
28+Keycloak has updated its admin console and as of version 19.0.0, the new admin console is enabled by default. The
29+legacy admin console has been announced for removal with the release of version 21.0.0.
30+:::
31+
32+**Keycloak legacy admin console**
33+
34+1. Create new client in your Keycloak realm with **Access Type** 'confidential', **Client protocol** 'openid-connect'
35+ and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback'
36+2. Take note of the Secret in the credential tab of the client
37+3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'.
38+4. Create a mapper with **Mapper Type** 'Audience' and **Included Client Audience** and **Included Custom Audience** set
39+ to your client name.
40+
41+**Keycloak new admin console (default as of v19.0.0)**
42+
43+The following example shows how to create a simple OIDC client using the new Keycloak admin2 console. However, for best
44+practices, it is recommended to consult the Keycloak documentation.
45+
46+The OIDC client must be configured with an _audience mapper_ to include the client's name in the `aud` claim of the JWT token.
47+The `aud` claim specifies the intended recipient of the token, and OAuth2 Proxy expects a match against the values of
48+either `--client-id` or `--oidc-extra-audience`.
49+
50+_In Keycloak, claims are added to JWT tokens through the use of mappers at either the realm level using "client scopes" or
51+through "dedicated" client mappers._
52+
53+**Creating the client**
54+
55+1. Create a new OIDC client in your Keycloak realm by navigating to:
56+ **Clients** -> **Create client**
57+ * **Client Type** 'OpenID Connect'
58+ * **Client ID** `<your client's id>`, please complete the remaining fields as appropriate and click **Next**.
59+ * **Client authentication** 'On'
60+ * **Authentication flow**
61+ * **Standard flow** 'selected'
62+ * **Direct access grants** 'deselect'
63+ * _Save the configuration._
64+ * **Settings / Access settings**:
65+ * **Valid redirect URIs** `https://internal.yourcompany.com/oauth2/callback`
66+ * _Save the configuration._
67+ * Under the **Credentials** tab you will now be able to locate `<your client's secret>`.
68+2. Configure a dedicated *audience mapper* for your client by navigating to **Clients** -> **\<your client's id\>** -> **Client scopes**.
69+* Access the dedicated mappers pane by clicking **\<your client's id\>-dedicated**, located under *Assigned client scope*.
70+ _(It should have a description of "Dedicated scope and mappers for this client")_
71+ * Click **Configure a new mapper** and select **Audience**
72+ * **Name** 'aud-mapper-\<your client's id\>'
73+ * **Included Client Audience** select `<your client's id>` from the dropdown.
74+ * _OAuth2 proxy can be set up to pass both the access and ID JWT tokens to your upstream services.
75+ If you require additional audience entries, you can use the **Included Custom Audience** field in addition
76+ to the "Included Client Audience" dropdown. Note that the "aud" claim of a JWT token should be limited and
77+ only specify its intended recipients._
78+ * **Add to ID token** 'On'
79+ * **Add to access token** 'On' - [#1916](https://github.com/oauth2-proxy/oauth2-proxy/pull/1916)
80+ * _Save the configuration._
81+* Any subsequent dedicated client mappers can be defined by clicking **Dedicated scopes** -> **Add mapper** ->
82+ **By configuration** -> *Select mapper*
83+
84+You should now be able to create a test user in Keycloak and get access to the OAuth2 Proxy instance, make sure to set
85+an email address matching `<yourcompany.com>` and select _Email verified_.
86+
87+**Authorization**
88+
89+_OAuth2 Proxy will perform authorization by requiring a valid user, this authorization can be extended to take into
90+account a user's membership in Keycloak `groups`, `realm roles`, and `client roles` using the keycloak-oidc provider options
91+`--allowed-role` or `--allowed-group`_
92+
93+**Roles**
94+
95+_A standard Keycloak installation comes with the required mappers for **realm roles** and **client roles** through the
96+pre-defined client scope "roles". This ensures that any roles assigned to a user are included in the `JWT` tokens when
97+using an OIDC client that has the "Full scope allowed" feature activated, the feature is enabled by default._
98+
99+_Creating a realm role_
100+* Navigate to **Realm roles** -> **Create role**
101+ * **Role name**, *`<realm role name>`* -> **save**
102+
103+_Creating a client role_
104+* Navigate to **Clients** -> `<your client's id>` -> **Roles** -> **Create role**
105+ * **Role name**, *`<client role name>`* -> **save**
106+
107+
108+_Assign a role to a user_
109+
110+**Users** -> _Username_ -> **Role mapping** -> **Assign role** -> _filter by roles or clients and select_ -> **Assign**.
111+
112+Keycloak "realm roles" can be authorized using the `--allowed-role=<realm role name>` option, while "client roles" can be
113+evaluated using `--allowed-role=<your client's id>:<client role name>`.
114+
115+You may limit the _realm roles_ included in the JWT tokens for any given client by navigating to:
116+**Clients** -> `<your client's id>` -> **Client scopes** -> _\<your client's id\>-dedicated_ -> **Scope**
117+Disabling **Full scope allowed** activates the **Assign role** option, allowing you to select which roles, if assigned
118+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
119+want to reduce the size and impact of the JWT token.
120+
121+
122+**Groups**
123+
124+You may also do authorization on group memberships by using the OAuth2 Proxy option `--allowed-group`.
125+We will only do a brief description of creating the required _client scope_ **groups** and refer you to read the Keycloak
126+documentation.
127+
128+To summarize, the steps required to authorize Keycloak group membership with OAuth2 Proxy are as follows:
129+
130+* Create a new Client Scope with the name **groups** in Keycloak.
131+ * Include a mapper of type **Group Membership**.
132+ * Set the "Token Claim Name" to **groups** or customize by matching it to the `--oidc-groups-claim` option of OAuth2 Proxy.
133+ * If the "Full group path" option is selected, you need to include a "/" separator in the group names defined in the
134+ `--allowed-group` option of OAuth2 Proxy. Example: "/groupname" or "/groupname/child_group".
135+
136+After creating the _Client Scope_ named _groups_ you will need to attach it to your client.
137+**Clients** -> `<your client's id>` -> **Client scopes** -> **Add client scope** -> Select **groups** and choose Optional
138+and you should now have a client that maps group memberships into the JWT tokens so that Oauth2 Proxy may evaluate them.
139+
140+Create a group by navigating to **Groups** -> **Create group** and _add_ your test user as a member.
141+
142+The OAuth2 Proxy option `--allowed-group=/groupname` will now allow you to filter on group membership
143+
144+Keycloak also has the option of attaching roles to groups, please refer to the Keycloak documentation for more information.
145+
146+**Tip**
147+
148+To check if roles or groups are added to JWT tokens, you can preview a users token in the Keycloak console by following
149+these steps: **Clients** -> `<your client's id>` -> **Client scopes** -> **Evaluate**.
150+Select a _realm user_ and optional _scope parameters_ such as groups, and generate the JSON representation of an access
151+or id token to examine its contents.
docs/versioned_docs/version-7.15.x/configuration/providers/linkedin.mdnew file+13
@@ -0,0 +1,13 @@
1+---
2+id: linkedin
3+title: LinkedIn
4+---
5+
6+For LinkedIn, the registration steps are:
7+
8+1. Create a new project: https://www.linkedin.com/secure/developer
9+2. In the OAuth User Agreement section:
10+ - In default scope, select r_basicprofile and r_emailaddress.
11+ - In "OAuth 2.0 Redirect URLs", enter `https://internal.yourcompany.com/oauth2/callback`
12+3. Fill in the remaining required fields and Save.
13+4. Take note of the **Consumer Key / API Key** and **Consumer Secret / Secret Key**
docs/versioned_docs/version-7.15.x/configuration/providers/login_gov.mdnew file+79
@@ -0,0 +1,79 @@
1+---
2+id: login_gov
3+title: Login.gov
4+---
5+
6+login.gov is an OIDC provider for the US Government.
7+If you are a US Government agency, you can contact the login.gov team through the contact information
8+that you can find on https://login.gov/developers/ and work with them to understand how to get login.gov
9+accounts for integration/test and production access.
10+
11+A developer guide is available here: https://developers.login.gov/, though this proxy handles everything
12+but the data you need to create to register your application in the login.gov dashboard.
13+
14+As a demo, we will assume that you are running your application that you want to secure locally on
15+http://localhost:3000/, that you will be starting your proxy up on http://localhost:4180/, and that
16+you have an agency integration account for testing.
17+
18+First, register your application in the dashboard. The important bits are:
19+* Identity protocol: make this `Openid connect`
20+* Issuer: do what they say for OpenID Connect. We will refer to this string as `${LOGINGOV_ISSUER}`.
21+* Public key: This is a self-signed certificate in .pem format generated from a 2048-bit RSA private key.
22+ A quick way to do this is
23+ `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'`.
24+ The contents of the `key.pem` shall be referred to as `${OAUTH2_PROXY_JWT_KEY}`.
25+* Return to App URL: Make this be `http://localhost:4180/`
26+* Redirect URIs: Make this be `http://localhost:4180/oauth2/callback`.
27+* Attribute Bundle: Make sure that email is selected.
28+
29+Now start the proxy up with the following options:
30+```
31+./oauth2-proxy -provider login.gov \
32+ -client-id=${LOGINGOV_ISSUER} \
33+ -redirect-url=http://localhost:4180/oauth2/callback \
34+ -oidc-issuer-url=https://idp.int.identitysandbox.gov/ \
35+ -cookie-secure=false \
36+ -email-domain=gsa.gov \
37+ -upstream=http://localhost:3000/ \
38+ -cookie-secret=somerandomstring12341234567890AB \
39+ -cookie-domain=localhost \
40+ -skip-provider-button=true \
41+ -pubjwk-url=https://idp.int.identitysandbox.gov/api/openid_connect/certs \
42+ -profile-url=https://idp.int.identitysandbox.gov/api/openid_connect/userinfo \
43+ -jwt-key="${OAUTH2_PROXY_JWT_KEY}"
44+```
45+You can also set all these options with environment variables, for use in cloud/docker environments.
46+One tricky thing that you may encounter is that some cloud environments will pass in environment
47+variables in a docker env-file, which does not allow multiline variables like a PEM file.
48+If you encounter this, then you can create a `jwt_signing_key.pem` file in the top level
49+directory of the repo which contains the key in PEM format and then do your docker build.
50+The docker build process will copy that file into your image which you can then access by
51+setting the `OAUTH2_PROXY_JWT_KEY_FILE=/etc/ssl/private/jwt_signing_key.pem`
52+environment variable, or by setting `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem` on the commandline.
53+
54+Once it is running, you should be able to go to `http://localhost:4180/` in your browser,
55+get authenticated by the login.gov integration server, and then get proxied on to your
56+application running on `http://localhost:3000/`. In a real deployment, you would secure
57+your application with a firewall or something so that it was only accessible from the
58+proxy, and you would use real hostnames everywhere.
59+
60+#### Skip OIDC discovery
61+
62+Some providers do not support OIDC discovery via their issuer URL, so oauth2-proxy cannot simply grab the authorization,
63+token and jwks URI endpoints from the provider's metadata.
64+
65+In this case, you can set the `--skip-oidc-discovery` option, and supply those required endpoints manually:
66+
67+```
68+ -provider oidc
69+ -client-id oauth2-proxy
70+ -client-secret proxy
71+ -redirect-url http://127.0.0.1:4180/oauth2/callback
72+ -oidc-issuer-url http://127.0.0.1:5556
73+ -skip-oidc-discovery
74+ -login-url http://127.0.0.1:5556/authorize
75+ -redeem-url http://127.0.0.1:5556/token
76+ -oidc-jwks-url http://127.0.0.1:5556/keys
77+ -cookie-secure=false
78+ -email-domain example.com
79+```
docs/versioned_docs/version-7.15.x/configuration/providers/ms_azure_ad.mdnew file+59
@@ -0,0 +1,59 @@
1+---
2+id: azure
3+title: Azure (Deprecated)
4+---
5+
6+:::note
7+This is the legacy and deprecated provider for Azure, use [Microsoft Entra ID](ms_entra_id.md) if possible.
8+:::
9+
10+## Config Options
11+
12+| Flag | Toml Field | Type | Description | Default |
13+| ---------------- | -------------- | ------ | ---------------------------------------------------------------- | ---------- |
14+| `--azure-tenant` | `azure_tenant` | string | go to a tenant-specific or common (tenant-independent) endpoint. | `"common"` |
15+| `--resource` | `resource` | string | The resource that is protected (Azure AD only) | |
16+
17+## Usage
18+
19+1. Add an application: go to [https://portal.azure.com](https://portal.azure.com), choose **Azure Active Directory**, select
20+ **App registrations** and then click on **New registration**.
21+2. Pick a name, check the supported account type(single-tenant, multi-tenant, etc). In the **Redirect URI** section create a new
22+ **Web** platform entry for each app that you want to protect by the oauth2 proxy(e.g.
23+ https://internal.yourcompanycom/oauth2/callback). Click **Register**.
24+3. Next we need to add group read permissions for the app registration, on the **API Permissions** page of the app, click on
25+ **Add a permission**, select **Microsoft Graph**, then select **Application permissions**, then click on **Group** and select
26+ **Group.Read.All**. Hit **Add permissions** and then on **Grant admin consent** (you might need an admin to do this).
27+ <br/>**IMPORTANT**: Even if this permission is listed with **"Admin consent required=No"** the consent might actually
28+ be required, due to AAD policies you won't be able to see. If you get a **"Need admin approval"** during login,
29+ most likely this is what you're missing!
30+4. Next, if you are planning to use v2.0 Azure Auth endpoint, go to the **Manifest** page and set `"accessTokenAcceptedVersion": 2`
31+ in the App registration manifest file.
32+5. On the **Certificates & secrets** page of the app, add a new client secret and note down the value after hitting **Add**.
33+6. Configure the proxy with:
34+- for V1 Azure Auth endpoint (Azure Active Directory Endpoints - https://login.microsoftonline.com/common/oauth2/authorize)
35+
36+```
37+ --provider=azure
38+ --client-id=<application ID from step 3>
39+ --client-secret=<value from step 5>
40+ --azure-tenant={tenant-id}
41+ --oidc-issuer-url=https://sts.windows.net/{tenant-id}/
42+```
43+
44+- for V2 Azure Auth endpoint (Microsoft Identity Platform Endpoints - https://login.microsoftonline.com/common/oauth2/v2.0/authorize)
45+```
46+ --provider=azure
47+ --client-id=<application ID from step 3>
48+ --client-secret=<value from step 5>
49+ --azure-tenant={tenant-id}
50+ --oidc-issuer-url=https://login.microsoftonline.com/{tenant-id}/v2.0
51+```
52+
53+***Notes***:
54+- When using v2.0 Azure Auth endpoint (`https://login.microsoftonline.com/{tenant-id}/v2.0`) as `--oidc_issuer_url`, in conjunction
55+ with `--resource` flag, be sure to append `/.default` at the end of the resource name. See
56+ https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope for more details.
57+- When using the Azure Auth provider with nginx and the cookie session store you may find the cookie is too large and doesn't
58+ get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the
59+ [redis session storage](../sessions.md#redis-storage) should resolve this.
docs/versioned_docs/version-7.15.x/configuration/providers/ms_entra_id.mdnew file+201
@@ -0,0 +1,201 @@
1+---
2+id: ms_entra_id
3+title: Microsoft Entra ID
4+---
5+
6+Provider for Microsoft Entra ID. Fully compliant with OIDC, with support for group overage and multi-tenant apps.
7+
8+## Config Options
9+
10+The provider is OIDC-compliant, so all the OIDC parameters are honored. Additional provider-specific configuration parameters are:
11+
12+| Flag | Toml Field | Type | Description | Default |
13+| --------------------------- | -------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
14+| `--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). | |
15+| `--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 |
16+
17+## Configure App registration
18+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.
19+
20+<details>
21+ <summary>See Azure Portal example</summary>
22+ <div class="videoBlock">
23+ <iframe src="https://www.youtube.com/embed/IUNfxhOzr4E"></iframe>
24+ </div>
25+</details>
26+
27+<details>
28+ <summary>See Terraform example</summary>
29+```
30+ resource "azuread_application" "auth" {
31+ display_name = "oauth2-proxy"
32+ sign_in_audience = "AzureADMyOrg" # Others are also supported
33+
34+ web {
35+ redirect_uris = [
36+ "https://podinfo.lakis.tech/oauth2/callback",
37+ ]
38+ }
39+ // We don't specify any required API permissions - we allow user consent only
40+ }
41+
42+ resource "azuread_service_principal" "sp" {
43+ client_id = azuread_application.auth.client_id
44+ app_role_assignment_required = false
45+ }
46+
47+ resource "azuread_service_principal_password" "pass" {
48+ service_principal_id = azuread_service_principal.sp.id
49+ }
50+
51+```
52+</details>
53+
54+### Configure groups
55+If you want to make use of groups, you can configure *groups claim* to be present in ID Tokens issued by the App registration.
56+<details>
57+ <summary>See Azure Portal example</summary>
58+ <div class="videoBlock">
59+ <div class="videoBlock">
60+ <iframe src="https://www.youtube.com/embed/QZmP5MKEJis"></iframe>
61+ </div>
62+ </div>
63+</details>
64+<details>
65+ <summary>See Terraform example</summary>
66+```
67+ resource "azuread_application" "auth" {
68+ display_name = "oauth2-proxy"
69+ sign_in_audience = "AzureADMyOrg"
70+
71+ group_membership_claims = [
72+ "SecurityGroup"
73+ ]
74+
75+ web {
76+ redirect_uris = [
77+ "https://podinfo.lakis.tech/oauth2/callback",
78+ ]
79+ }
80+ }
81+
82+ resource "azuread_service_principal" "sp" {
83+ client_id = azuread_application.auth.client_id
84+ app_role_assignment_required = false
85+ }
86+
87+ resource "azuread_service_principal_password" "pass" {
88+ service_principal_id = azuread_service_principal.sp.id
89+ }
90+
91+```
92+</details>
93+
94+### Scopes and claims
95+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)).
96+
97+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.
98+
99+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).
100+
101+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.
102+
103+For personal microsoft accounts, required scope is `openid profile email`.
104+
105+See: [Overview of permissions and consent in the Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview).
106+
107+### Multi-tenant apps
108+To authenticate apps from multiple tenants (including personal Microsoft accounts), set the common OIDC issuer url and disable verification:
109+```toml
110+oidc_issuer_url=https://login.microsoftonline.com/common/v2.0
111+insecure_oidc_skip_issuer_verification=true
112+```
113+`insecure_oidc_skip_issuer_verification` setting is required to disable following checks:
114+* 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).
115+* 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).
116+
117+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.
118+
119+### Workload Identity
120+Provider supports authentication with federated token, without need of using client secret. Following conditions have to be met:
121+
122+* 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`.
123+* 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).
124+* Appropriate federated credential is added to application registration.
125+<details>
126+ <summary>See federated credential terraform example</summary>
127+```
128+ resource "azuread_application_federated_identity_credential" "fedcred" {
129+ application_id = azuread_application.application.id # ID of your application
130+ display_name = "federation-cred"
131+ description = "Workload identity for oauth2-proxy"
132+ audiences = ["api://AzureADTokenExchange"] # Fixed value
133+ issuer = "https://cluster-oidc-issuer-url..."
134+ subject = "system:serviceaccount:oauth2-proxy-namespace-name:oauth2-proxy-sa-name" # set proper NS and SA name
135+ }
136+```
137+</details>
138+
139+* Kubernetes service account associated with oauth2-proxy deployment, is annotated with `azure.workload.identity/client-id: <app-registration-client-id>`
140+* oauth2-proxy pod is labeled with `azure.workload.identity/use: "true"`
141+* oauth2-proxy is configured with `entra_id_federated_token_auth` set to `true`.
142+
143+`client_secret` setting can be omitted when using federated token authentication.
144+
145+See: [Azure Workload Identity documentation](https://azure.github.io/azure-workload-identity/docs/).
146+
147+### Example configurations
148+Single-tenant app without groups (*groups claim* not enabled). Consider using generic OIDC provider:
149+```toml
150+provider="entra-id"
151+oidc_issuer_url="https://login.microsoftonline.com/<tenant-id>/v2.0"
152+client_id="<client-id>"
153+client_secret="<client-secret>"
154+scope="openid"
155+```
156+
157+Single-tenant app with up to 200 groups (*groups claim* enabled). Consider using generic OIDC provider:
158+```toml
159+provider="entra-id"
160+oidc_issuer_url="https://login.microsoftonline.com/<tenant-id>/v2.0"
161+client_id="<client-id>"
162+client_secret="<client-secret>"
163+scope="openid"
164+allowed_groups=["ac51800c-2679-4ecb-8130-636380a3b491"]
165+```
166+
167+Single-tenant app with more than 200 groups:
168+```toml
169+provider="entra-id"
170+oidc_issuer_url="https://login.microsoftonline.com/<tenant-id>/v2.0"
171+client_id="<client-id>"
172+client_secret="<client-secret>"
173+scope="openid User.Read"
174+allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"]
175+```
176+
177+Single-tenant app with more than 200 groups and workload identity enabled:
178+```toml
179+provider="entra-id"
180+oidc_issuer_url="https://login.microsoftonline.com/<tenant-id>/v2.0"
181+client_id="<client-id>"
182+scope="openid User.Read"
183+allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"]
184+entra_id_federated_token_auth=true
185+```
186+
187+Multi-tenant app with Microsoft personal accounts & one Entra tenant allowed, with group overage considered:
188+```toml
189+provider="entra-id"
190+oidc_issuer_url="https://login.microsoftonline.com/common/v2.0"
191+client_id="<client-id>"
192+client_secret="<client-secret>"
193+insecure_oidc_skip_issuer_verification=true
194+scope="openid profile email User.Read"
195+entra_id_allowed_tenants=["9188040d-6c67-4c5b-b112-36a304b66dad","<my-tenant-id>"] # Allow only <my-tenant-id> and Personal MS Accounts tenant
196+email_domains="*"
197+```
198+
199+## Kubernetes Dashboard Integration
200+
201+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).
docs/versioned_docs/version-7.15.x/configuration/providers/nextcloud.mdnew file+28
@@ -0,0 +1,28 @@
1+---
2+id: nextcloud
3+title: NextCloud
4+---
5+
6+The Nextcloud provider allows you to authenticate against users in your
7+Nextcloud instance.
8+
9+When you are using the Nextcloud provider, you must specify the urls via
10+configuration, environment variable, or command line argument. Depending
11+on whether your Nextcloud instance is using pretty urls your urls may be of the
12+form `/index.php/apps/oauth2/*` or `/apps/oauth2/*`.
13+
14+Refer to the [OAuth2
15+documentation](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/oauth2.html)
16+to set up the client id and client secret. Your "Redirection URI" will be
17+`https://internalapp.yourcompany.com/oauth2/callback`.
18+
19+```
20+ -provider nextcloud
21+ -client-id <from nextcloud admin>
22+ -client-secret <from nextcloud admin>
23+ -login-url="<your nextcloud url>/index.php/apps/oauth2/authorize"
24+ -redeem-url="<your nextcloud url>/index.php/apps/oauth2/api/v1/token"
25+ -validate-url="<your nextcloud url>/ocs/v2.php/cloud/user?format=json"
26+```
27+
28+Note: in *all* cases the validate-url will *not* have the `index.php`.
docs/versioned_docs/version-7.15.x/configuration/providers/openid_connect.mdnew file+146
@@ -0,0 +1,146 @@
1+---
2+id: openid_connect
3+title: OpenID Connect
4+---
5+
6+OpenID Connect is a spec for OAUTH 2.0 + identity that is implemented by many major providers and several open source projects.
7+
8+This provider was originally built against CoreOS Dex, and we will use it as an example.
9+The OpenID Connect Provider (OIDC) can also be used to connect to other Identity Providers such as Okta, an example can be found below.
10+
11+#### Dex
12+
13+To configure the OIDC provider for Dex, perform the following steps:
14+
15+1. Download Dex:
16+
17+ ```
18+ go get github.com/dexidp/dex
19+ ```
20+
21+ See the [getting started guide](https://dexidp.io/docs/getting-started/) for more details.
22+
23+2. Setup oauth2-proxy with the correct provider and using the default ports and callbacks. Add a configuration block to
24+ the `staticClients` section of `examples/config-dev.yaml`:
25+
26+ ```
27+ - id: oauth2-proxy
28+ redirectURIs:
29+ - 'http://127.0.0.1:4180/oauth2/callback'
30+ name: 'oauth2-proxy'
31+ secret: proxy
32+ ```
33+
34+3. Launch Dex: from `$GOPATH/github.com/dexidp/dex`, run:
35+
36+ ```
37+ bin/dex serve examples/config-dev.yaml
38+ ```
39+
40+4. In a second terminal, run the oauth2-proxy with the following args:
41+
42+ ```shell
43+ --provider oidc
44+ --provider-display-name "My OIDC Provider"
45+ --client-id oauth2-proxy
46+ --client-secret proxy
47+ --redirect-url http://127.0.0.1:4180/oauth2/callback
48+ --oidc-issuer-url http://127.0.0.1:5556/dex
49+ --cookie-secure=false
50+ --cookie-secret=secret
51+ --email-domain kilgore.trout
52+ ```
53+
54+ To serve the current working directory as a website under the `/static` endpoint, add:
55+
56+ ```shell
57+ --upstream file://$PWD/#/static/
58+ ```
59+
60+5. Test the setup by visiting http://127.0.0.1:4180 or http://127.0.0.1:4180/static .
61+
62+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.
63+
64+#### Okta
65+
66+To configure the OIDC provider for Okta, perform the following steps:
67+
68+1. Log in to Okta using an administrative account. It is suggested you try this in preview first, `example.oktapreview.com`
69+2. (OPTIONAL) If you want to configure authorization scopes and claims to be passed on to multiple applications,
70+ you may wish to configure an authorization server for each application. Otherwise, the provided `default` will work.
71+ * Navigate to **Security** then select **API**
72+ * Click **Add Authorization Server**, if this option is not available you may require an additional license for a custom
73+ authorization server.
74+ * Fill out the **Name** with something to describe the application you are protecting. e.g. 'Example App'.
75+ * For **Audience**, pick the URL of the application you wish to protect: https://example.corp.com
76+ * Fill out a **Description**
77+ * Add any **Access Policies** you wish to configure to limit application access.
78+ * The default settings will work for other options.
79+ [See Okta documentation for more information on Authorization Servers](https://developer.okta.com/docs/guides/customize-authz-server/overview/)
80+3. Navigate to **Applications** then select **Add Application**.
81+ * Select **Web** for the **Platform** setting.
82+ * Select **OpenID Connect** and click **Create**
83+ * Pick an **Application Name** such as `Example App`.
84+ * Set the **Login redirect URI** to `https://example.corp.com`.
85+ * Under **General** set the **Allowed grant types** to `Authorization Code` and `Refresh Token`.
86+ * Leave the rest as default, taking note of the `Client ID` and `Client Secret`.
87+ * Under **Assignments** select the users or groups you wish to access your application.
88+4. Create a configuration file like the following:
89+
90+ ```
91+ provider = "oidc"
92+ redirect_url = "https://example.corp.com/oauth2/callback"
93+ oidc_issuer_url = "https://corp.okta.com/oauth2/abCd1234"
94+ upstreams = [
95+ "https://example.corp.com"
96+ ]
97+ email_domains = [
98+ "corp.com"
99+ ]
100+ client_id = "XXXXX"
101+ client_secret = "YYYYY"
102+ pass_access_token = true
103+ cookie_secret = "ZZZZZ"
104+ skip_provider_button = true
105+ ```
106+
107+The `oidc_issuer_url` is based on URL from your **Authorization Server**'s **Issuer** field in step 2, or simply
108+https://corp.okta.com. The `client_id` and `client_secret` are configured in the application settings.
109+Generate a unique `cookie_secret` to encrypt the cookie.
110+
111+Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/example.cfg`
112+
113+#### Okta - localhost
114+
115+1. Signup for developer account: https://developer.okta.com/signup/
116+2. Create New `Web` Application: https://$\{your-okta-domain\}/dev/console/apps/new
117+3. Example Application Settings for localhost:
118+ * **Name:** My Web App
119+ * **Base URIs:** http://localhost:4180/
120+ * **Login redirect URIs:** http://localhost:4180/oauth2/callback
121+ * **Logout redirect URIs:** http://localhost:4180/
122+ * **Group assignments:** `Everyone`
123+ * **Grant type allowed:** `Authorization Code` and `Refresh Token`
124+4. Make note of the `Client ID` and `Client secret`, they are needed in a future step
125+5. Make note of the **default** Authorization Server Issuer URI from: https://$\{your-okta-domain\}/admin/oauth2/as
126+6. Example config file `/etc/localhost.cfg`
127+ ```shell
128+ provider = "oidc"
129+ redirect_url = "http://localhost:4180/oauth2/callback"
130+ oidc_issuer_url = "https://$\{your-okta-domain\}/oauth2/default"
131+ upstreams = [
132+ "http://0.0.0.0:8080"
133+ ]
134+ email_domains = [
135+ "*"
136+ ]
137+ client_id = "XXX"
138+ client_secret = "YYY"
139+ pass_access_token = true
140+ cookie_secret = "ZZZ"
141+ cookie_secure = false
142+ skip_provider_button = true
143+ # Note: use the following for testing within a container
144+ # http_address = "0.0.0.0:4180"
145+ ```
146+7. Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/localhost.cfg`
docs/versioned_docs/version-7.15.x/configuration/providers/sourcehut.mdnew file+25
@@ -0,0 +1,25 @@
1+---
2+id: sourcehut
3+title: SourceHut
4+---
5+
6+1. Create a new OAuth client: https://meta.sr.ht/oauth2
7+2. Under `Redirection URI` enter the correct URL, i.e.
8+ `https://internal.yourcompany.com/oauth2/callback`
9+
10+To use the provider, start with `--provider=sourcehut`.
11+
12+If you are hosting your own SourceHut instance, make sure you set the following
13+to the appropriate URLs:
14+
15+```shell
16+ --login-url="https://<meta.your.instance>/oauth2/authorize"
17+ --redeem-url="https://<meta.your.instance>/oauth2/access-token"
18+ --profile-url="https://<meta.your.instance>/query"
19+ --validate-url="https://<meta.your.instance>/profile"
20+```
21+
22+The default configuration allows everyone with an account to authenticate.
23+Restricting access is currently only supported by
24+[email](index.md#email-authentication).
25+
docs/versioned_docs/version-7.15.x/configuration/sessions.mdnew file+99
@@ -0,0 +1,99 @@
1+---
2+id: session_storage
3+title: Session Storage
4+---
5+
6+Sessions allow a user's authentication to be tracked between multiple HTTP
7+requests to a service.
8+
9+The OAuth2 Proxy uses a Cookie to track user sessions and will store the session
10+data in one of the available session storage backends.
11+
12+At present the available backends are (as passed to `--session-store-type`):
13+- [cookie](#cookie-storage) (default)
14+- [redis](#redis-storage)
15+
16+### Cookie Storage
17+
18+The Cookie storage backend is the default backend implementation and has
19+been used in the OAuth2 Proxy historically.
20+
21+With the Cookie storage backend, all session information is stored in client
22+side cookies and transferred with each and every request.
23+
24+The following should be known when using this implementation:
25+- Since all state is stored client side, this storage backend means that the OAuth2 Proxy is completely stateless
26+- Cookies are signed server side to prevent modification client-side
27+- It is mandatory to set a `cookie-secret` which will ensure data is encrypted within the cookie data.
28+- Since multiple requests can be made concurrently to the OAuth2 Proxy, this session implementation
29+cannot lock sessions and while updating and refreshing sessions, there can be conflicts which force
30+users to re-authenticate
31+
32+
33+### Redis Storage
34+
35+The Redis Storage backend stores encrypted sessions in redis. Instead of sending all the information
36+back the client for storage, as in the [Cookie storage](#cookie-storage), a ticket is sent back
37+to the user as the cookie value instead.
38+
39+A ticket is composed as the following:
40+
41+`{CookieName}-{ticketID}.{secret}`
42+
43+Where:
44+
45+- The `CookieName` is the OAuth2 cookie name (_oauth2_proxy by default)
46+- The `ticketID` is a 128-bit random number, hex-encoded
47+- The `secret` is a 128-bit random number, base64url encoded (no padding). The secret is unique for every session.
48+- The pair of `{CookieName}-{ticketID}` comprises a ticket handle, and thus, the redis key
49+to which the session is stored. The encoded session is encrypted with the secret and stored
50+in redis via the `SETEX` command.
51+
52+Encrypting every session uniquely protects the refresh/access/id tokens stored in the session from
53+disclosure. Additionally, the browser only has to send a short Cookie with every request and not the whole JWT,
54+which can get quite big.
55+
56+Two settings are used to configure the OAuth2 Proxy cookie lifetime:
57+
58+ --cookie-refresh duration refresh the cookie after this duration; 0 to disable
59+ --cookie-expire duration expire timeframe for cookie 168h0m0s
60+
61+The "cookie-expire" value should be equal to the lifetime of the Refresh-Token that is issued by the OAuth2 authorization server.
62+If it expires earlier and is deleted by the browser, OAuth2 Proxy cannot find the stored Refresh-Tokens in Redis and thus cannot start
63+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
64+expired.
65+
66+The "cookie-refresh" value controls when OAuth2 Proxy tries to refresh an Access-Token. If it is set to "0", the
67+Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2 Proxy will
68+refresh the Access-Token after this many seconds whether it is still valid or not. According to the official OAuth2.0 specification
69+Access-Tokens are not required to follow a specific format. Therefore OAuth2 Proxy cannot check for any expiry date without an
70+introspection endpoint. If an Access-Token expires and you have not set a corresponding "cookie-refresh" value, you will likely
71+encounter expiry issues.
72+
73+Caveat: It can happen that the Access-Token is valid for e.g. "1m" and a request happens after exactly "59s".
74+It would pass OAuth2 Proxy and be forwarded to the backend but is just expired when the backend tries to validate
75+it. This is especially relevant if the backend uses the JWT to make requests to other backends.
76+For this reason, it's advised to set the cookie-refresh a couple of seconds less than the Access-Token lifespan.
77+
78+Recommended settings:
79+
80+* cookie_refresh := Access-Token lifespan - 1m
81+* cookie_expire := Refresh-Token lifespan (i.e. Keycloak client_session_idle)
82+
83+#### Usage
84+
85+When using the redis store, specify `--session-store-type=redis` as well as the Redis connection URL, via
86+`--redis-connection-url=redis://host[:port][/db-number]`.
87+
88+You may also configure the store for Redis Sentinel. In this case, you will want to use the
89+`--redis-use-sentinel=true` flag, as well as configure the flags `--redis-sentinel-master-name`
90+and `--redis-sentinel-connection-urls` appropriately.
91+
92+Redis Cluster is available to be the backend store as well. To leverage it, you will need to set the
93+`--redis-use-cluster=true` flag, and configure the flags `--redis-cluster-connection-urls` appropriately.
94+
95+Note that flags `--redis-use-sentinel=true` and `--redis-use-cluster=true` are mutually exclusive.
96+
97+Note, if Redis timeout option is set to non-zero, the `--redis-connection-idle-timeout`
98+must be less than [Redis timeout option](https://redis.io/docs/reference/clients/#client-timeouts). For example: if either redis.conf includes
99+`timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14`
docs/versioned_docs/version-7.15.x/configuration/systemd_socket.mdnew file+51
@@ -0,0 +1,51 @@
1+---
2+id: systemd_socket
3+title: Systemd Socket Activation
4+---
5+
6+Pass an existing listener created by systemd.socket to oauth2-proxy.
7+
8+To do this create a socket:
9+
10+oauth2-proxy.socket
11+```
12+[Socket]
13+ListenStream=%t/oauth2.sock
14+SocketGroup=www-data
15+SocketMode=0660
16+```
17+
18+Now it's possible to call this socket from e.g. nginx:
19+```
20+server {
21+ location /oauth2/ {
22+ proxy_pass http://unix:/run/oauth2-proxy/oauth2.sock;
23+}
24+```
25+
26+The oauth2-proxy should have `--http-address=fd:3` as a parameter.
27+Here fd is case insensitive and means file descriptor. The number 3 refers to the first non-stdin/stdout/stderr file descriptor,
28+systemd-socket-activate (which is what systemd.socket uses), listens to what it is told and passes
29+the listener it created onto the process, starting with file descriptor 3.
30+
31+```
32+./oauth2-proxy \
33+ --http-address="fd:3" \
34+ --email-domain="yourcompany.com" \
35+ --upstream=http://127.0.0.1:8080/ \
36+ --cookie-secret=... \
37+ --cookie-secure=true \
38+ --provider=... \
39+ --client-id=... \
40+ --client-secret=...
41+```
42+
43+## Trusted IPs
44+
45+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.
46+
47+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.
48+
49+## TLS
50+
51+Currently TLS is not supported (but it's doable).
docs/versioned_docs/version-7.15.x/configuration/tls.mdnew file+85
@@ -0,0 +1,85 @@
1+---
2+id: tls
3+title: TLS Configuration
4+---
5+
6+There are two recommended configurations:
7+- [At OAuth2 Proxy](#terminate-tls-at-oauth2-proxy)
8+- [At Reverse Proxy](#terminate-tls-at-reverse-proxy-eg-nginx)
9+
10+### Terminate TLS at OAuth2 Proxy
11+
12+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`.
13+
14+ The command line to run `oauth2-proxy` in this configuration would look like this:
15+
16+ ```bash
17+ ./oauth2-proxy \
18+ --email-domain="yourcompany.com" \
19+ --upstream=http://127.0.0.1:8080/ \
20+ --tls-cert-file=/path/to/cert.pem \
21+ --tls-key-file=/path/to/cert.key \
22+ --cookie-secret=... \
23+ --cookie-secure=true \
24+ --provider=... \
25+ --client-id=... \
26+ --client-secret=...
27+ ```
28+
29+2. With this configuration approach the customization of the TLS settings is limited.
30+
31+ The minimal acceptable TLS version can be set with `--tls-min-version=TLS1.3`.
32+ The defaults set `TLS1.2` as the minimal version.
33+ Regardless of the minimum version configured, `TLS1.3` is currently always used as the maximal version.
34+
35+ TLS server side cipher suites can be specified with `--tls-cipher-suite=TLS_RSA_WITH_RC4_128_SHA`.
36+ 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.
37+ A complete list of valid TLS cipher suite names can be found in [`crypto/tls`](https://pkg.go.dev/crypto/tls#pkg-constants).
38+
39+### Terminate TLS at Reverse Proxy, e.g. Nginx
40+
41+1. Configure SSL Termination with [Nginx](http://nginx.org/) (example config below), Amazon ELB, Google Cloud Platform Load Balancing, or ...
42+
43+ Because `oauth2-proxy` listens on `127.0.0.1:4180` by default, to listen on all interfaces (needed when using an
44+ external load balancer like Amazon ELB or Google Platform Load Balancing) use `--http-address="0.0.0.0:4180"` or
45+ `--http-address="http://:4180"`.
46+
47+ Nginx will listen on port `443` and handle SSL connections while proxying to `oauth2-proxy` on port `4180`.
48+ `oauth2-proxy` will then authenticate requests for an upstream application. The external endpoint for this example
49+ would be `https://internal.yourcompany.com/`.
50+
51+ An example Nginx config follows. Note the use of `Strict-Transport-Security` header to pin requests to SSL
52+ via [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security):
53+
54+ ```
55+ server {
56+ listen 443 default ssl;
57+ server_name internal.yourcompany.com;
58+ ssl_certificate /path/to/cert.pem;
59+ ssl_certificate_key /path/to/cert.key;
60+ add_header Strict-Transport-Security max-age=2592000;
61+
62+ location / {
63+ proxy_pass http://127.0.0.1:4180;
64+ proxy_set_header Host $host;
65+ proxy_set_header X-Real-IP $remote_addr;
66+ proxy_connect_timeout 1;
67+ proxy_send_timeout 30;
68+ proxy_read_timeout 30;
69+ }
70+ }
71+ ```
72+
73+2. The command line to run `oauth2-proxy` in this configuration would look like this:
74+
75+ ```bash
76+ ./oauth2-proxy \
77+ --email-domain="yourcompany.com" \
78+ --upstream=http://127.0.0.1:8080/ \
79+ --cookie-secret=... \
80+ --cookie-secure=true \
81+ --provider=... \
82+ --reverse-proxy=true \
83+ --client-id=... \
84+ --client-secret=...
85+ ```
docs/versioned_docs/version-7.15.x/features/endpoints.mdnew file+73
@@ -0,0 +1,73 @@
1+---
2+id: endpoints
3+title: Endpoints
4+---
5+
6+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.
7+
8+- / - the proxy endpoint provides authentication and returns the appropriate 40x error if not authenticated or authorized then passes the request upstream.
9+- /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
10+- /ping - returns a 200 OK response, which is intended for use with health checks
11+- /ready - returns a 200 OK response if all the underlying connections (e.g., Redis store) are connected
12+- /metrics - Metrics endpoint for Prometheus to scrape, serve on the address specified by `--metrics-address`, disabled by default
13+- /oauth2/sign_in - the login page, which also doubles as a sign-out page (it clears cookies)
14+- /oauth2/sign_out - this URL is used to clear the session cookie
15+- /oauth2/start - a URL that will redirect to start the OAuth cycle
16+- /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url.
17+- /oauth2/userinfo - the URL is used to return user's email from the session in JSON format.
18+- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integrations/nginx)
19+- /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages
20+
21+### Sign out
22+
23+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!):
24+
25+```
26+/oauth2/sign_out?rd=https%3A%2F%2Fmy-oidc-provider.example.com%2Fsign_out_page
27+```
28+
29+Alternatively, include the redirect URL in the `X-Auth-Request-Redirect` header:
30+
31+```
32+GET /oauth2/sign_out HTTP/1.1
33+X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page
34+...
35+```
36+
37+(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.)
38+
39+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").
40+
41+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`;
42+
43+```
44+/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
45+```
46+
47+or alternatively in the header:
48+
49+```
50+GET /oauth2/sign_out HTTP/1.1
51+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
52+...
53+```
54+
55+### Auth
56+
57+This endpoint returns 202 Accepted response or a 401 Unauthorized response.
58+
59+It can be configured using the following query parameters:
60+- `allowed_groups`: comma separated list of allowed groups
61+- `allowed_email_domains`: comma separated list of allowed email domains
62+- `allowed_emails`: comma separated list of allowed emails
63+
64+### Proxy (/)
65+
66+This endpoint returns the upstream response if authenticated.
67+If unauthenticated it returns a 401 Unauthorized. If the authenticatd user
68+is not in one of the allowed groups, or emails then it returns a 403 forbidden
69+
70+It can be configured using the following query parameters:
71+- `allowed_groups`: comma separated list of allowed groups
72+- `allowed_email_domains`: comma separated list of allowed email domains
73+- `allowed_emails`: comma separated list of allowed emails
docs/versioned_docs/version-7.15.x/installation.mdnew file+32
@@ -0,0 +1,32 @@
1+---
2+id: installation
3+title: Installation
4+---
5+
6+1. Choose how to deploy:
7+
8+ a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.15.4`)
9+
10+ b. Using Go to install the latest release
11+ ```bash
12+ $ go install github.com/oauth2-proxy/oauth2-proxy/v7@latest
13+ ```
14+ 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`
15+
16+ c. Using a [Prebuilt Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy) (AMD64, PPC64LE, S390x, ARMv6, ARMv7, and ARM64 available)
17+
18+ d. Using a [Pre-Release Nightly Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy-nightly) (AMD64, PPC64LE, ARMv6, ARMv7, and ARM64 available)
19+
20+ e. Using the official [Kubernetes manifest](https://github.com/oauth2-proxy/manifests) (Helm)
21+
22+ 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`.
23+
24+ ```
25+ $ sha256sum -c sha256sum.txt
26+ oauth2-proxy-x.y.z.linux-amd64: OK
27+ ```
28+
29+2. [Select a Provider and Register an OAuth Application with a Provider](configuration/providers/index.md)
30+3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration/overview.md)
31+4. [Configure SSL or Deploy behind an SSL endpoint](configuration/tls.md) (example provided for Nginx)
32+5. [Configure OAuth2 Proxy using systemd.socket](configuration/systemd_socket.md) (example provided for Nginx/Systemd)
docs/versioned_docs/version-7.15.x/welcome.mdnew file+33
@@ -0,0 +1,33 @@
1+---
2+id: welcome
3+title: Welcome
4+hide_table_of_contents: true
5+slug: /
6+---
7+
8+![OAuth2 Proxy](/img/logos/OAuth2_Proxy_horizontal.svg)
9+
10+A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others)
11+to validate accounts by email, domain or group.
12+
13+:::note
14+This repository was forked from [bitly/OAuth2_Proxy](https://github.com/bitly/oauth2_proxy) on 27/11/2018.
15+Versions v3.0.0 and up are from this fork and will have diverged from any changes in the original fork.
16+A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/CHANGELOG.md).
17+:::
18+
19+![Sign In Page](/img/sign-in-page.png)
20+
21+## Architecture
22+
23+![OAuth2 Proxy Architecture](/img/simplified-architecture.svg)
24+
25+
26+## Cloud Native Computing Foundation
27+
28+OAuth2 Proxy is a [Cloud Native Computing Foundation](https://cncf.io) Sandbox project.
29+
30+![CNCF](https://www.cncf.io/wp-content/uploads/2023/04/cncf-main-site-logo.svg)
31+
32+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).
33+
docs/versioned_docs/version-7.6.x/configuration/overview.md+1
@@ -237,6 +237,7 @@ Provider specific options can be found on their respective subpages.
237237| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
238238| flag: `--redis-cluster-connection-urls`<br/>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` | |
239239| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
240+| flag: `--redis-ca-path`<br/>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. |
240241| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
241242| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
242243| flag: `--redis-sentinel-password`<br/>toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | |
docs/versioned_docs/version-7.6.x/configuration/providers/gitlab.md+1−1
@@ -8,7 +8,7 @@ title: GitLab
88| Flag | Toml Field | Type | Description | Default |
99| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
1010| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
11−| `--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 | |
11+| `--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 | |
1212
1313## Usage
1414
docs/versioned_docs/version-7.7.x/configuration/overview.md+1
@@ -237,6 +237,7 @@ Provider specific options can be found on their respective subpages.
237237| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
238238| flag: `--redis-cluster-connection-urls`<br/>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` | |
239239| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
240+| flag: `--redis-ca-path`<br/>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. |
240241| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
241242| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
242243| flag: `--redis-sentinel-password`<br/>toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | |
docs/versioned_docs/version-7.7.x/configuration/providers/gitlab.md+1−1
@@ -8,7 +8,7 @@ title: GitLab
88| Flag | Toml Field | Type | Description | Default |
99| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
1010| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
11−| `--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 | |
11+| `--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 | |
1212
1313## Usage
1414
docs/versioned_docs/version-7.8.x/configuration/overview.md+1
@@ -239,6 +239,7 @@ Provider specific options can be found on their respective subpages.
239239| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
240240| flag: `--redis-cluster-connection-urls`<br/>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` | |
241241| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
242+| flag: `--redis-ca-path`<br/>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. |
242243| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
243244| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
244245| flag: `--redis-sentinel-password`<br/>toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | |
docs/versioned_docs/version-7.8.x/configuration/providers/gitlab.md+1−1
@@ -8,7 +8,7 @@ title: GitLab
88| Flag | Toml Field | Type | Description | Default |
99| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
1010| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
11−| `--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 | |
11+| `--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 | |
1212
1313## Usage
1414
docs/versioned_docs/version-7.9.x/configuration/overview.md+1
@@ -241,6 +241,7 @@ Provider specific options can be found on their respective subpages.
241241| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
242242| flag: `--redis-cluster-connection-urls`<br/>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` | |
243243| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
244+| flag: `--redis-ca-path`<br/>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. |
244245| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
245246| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
246247| flag: `--redis-sentinel-password`<br/>toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | |
docs/versioned_docs/version-7.9.x/configuration/providers/gitlab.md+1−1
@@ -8,7 +8,7 @@ title: GitLab
88| Flag | Toml Field | Type | Description | Default |
99| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
1010| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
11−| `--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 | |
11+| `--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 | |
1212
1313## Usage
1414
docs/versioned_sidebars/version-7.15.x-sidebars.jsonnew file+100
@@ -0,0 +1,100 @@
1+{
2+ "docs": [
3+ {
4+ "type": "doc",
5+ "id": "welcome"
6+ },
7+ {
8+ "type": "doc",
9+ "id": "installation"
10+ },
11+ {
12+ "type": "doc",
13+ "id": "behaviour"
14+ },
15+ {
16+ "type": "category",
17+ "label": "Configuration",
18+ "link": {
19+ "type": "doc",
20+ "id": "configuration/overview"
21+ },
22+ "collapsed": false,
23+ "items": [
24+ "configuration/overview",
25+ {
26+ "type": "category",
27+ "label": "Integration Guides",
28+ "link": {
29+ "type": "doc",
30+ "id": "configuration/integrations/index"
31+ },
32+ "items": [
33+ "configuration/integrations/nginx",
34+ "configuration/integrations/traefik",
35+ "configuration/integrations/caddy",
36+ "configuration/integrations/headlamp",
37+ "configuration/integrations/kubernetes-dashboard"
38+ ]
39+ },
40+ {
41+ "type": "category",
42+ "label": "OAuth Provider Configuration",
43+ "link": {
44+ "type": "doc",
45+ "id": "configuration/providers/index"
46+ },
47+ "items": [
48+ "configuration/providers/adfs",
49+ "configuration/providers/azure",
50+ "configuration/providers/bitbucket",
51+ "configuration/providers/cidaas",
52+ "configuration/providers/cisco_duo",
53+ "configuration/providers/digitalocean",
54+ "configuration/providers/facebook",
55+ "configuration/providers/gitea",
56+ "configuration/providers/github",
57+ "configuration/providers/gitlab",
58+ "configuration/providers/google",
59+ "configuration/providers/keycloak",
60+ "configuration/providers/keycloak_oidc",
61+ "configuration/providers/linkedin",
62+ "configuration/providers/login_gov",
63+ "configuration/providers/ms_entra_id",
64+ "configuration/providers/nextcloud",
65+ "configuration/providers/openid_connect",
66+ "configuration/providers/sourcehut"
67+ ]
68+ },
69+ "configuration/session_storage",
70+ "configuration/tls",
71+ "configuration/alpha-config"
72+ ]
73+ },
74+ {
75+ "type": "category",
76+ "label": "Features",
77+ "link": {
78+ "type": "doc",
79+ "id": "features/endpoints"
80+ },
81+ "collapsed": false,
82+ "items": [
83+ "features/endpoints"
84+ ]
85+ },
86+ {
87+ "type": "category",
88+ "label": "Community",
89+ "link": {
90+ "type": "doc",
91+ "id": "community/security"
92+ },
93+ "collapsed": false,
94+ "items": [
95+ "community/contribution",
96+ "community/security"
97+ ]
98+ }
99+ ]
100+}
docs/versions.json+1
@@ -1,4 +1,5 @@
11[
2+ "7.15.x",
23 "7.14.x",
34 "7.13.x",
45 "7.12.x",
go.mod+45−48
@@ -1,86 +1,83 @@
11module github.com/oauth2-proxy/oauth2-proxy/v7
22
3−go 1.25.5
3+go 1.26.0
44
55require (
66 cloud.google.com/go/compute/metadata v0.9.0
77 github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb
88 github.com/a8m/envsubst v1.4.3
9− github.com/alicebob/miniredis/v2 v2.35.0
9+ github.com/alicebob/miniredis/v2 v2.38.0
1010 github.com/bitly/go-simplejson v0.5.1
11− github.com/bsm/redislock v0.9.4
12− github.com/coreos/go-oidc/v3 v3.17.0
11+ github.com/bsm/redislock v0.10.0
12+ github.com/coreos/go-oidc/v3 v3.20.0
1313 github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf
14− github.com/fsnotify/fsnotify v1.9.0
15− github.com/go-jose/go-jose/v3 v3.0.4
16− github.com/go-viper/mapstructure/v2 v2.4.0
17− github.com/golang-jwt/jwt/v5 v5.3.0
14+ github.com/fsnotify/fsnotify v1.10.1
15+ github.com/go-jose/go-jose/v3 v3.0.5
16+ github.com/go-jose/go-jose/v4 v4.1.4
17+ github.com/go-viper/mapstructure/v2 v2.5.0
18+ github.com/golang-jwt/jwt/v5 v5.3.1
1819 github.com/google/go-cmp v0.7.0
1920 github.com/google/uuid v1.6.0
2021 github.com/gorilla/mux v1.8.1
2122 github.com/justinas/alice v1.2.0
2223 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25
23− github.com/onsi/ginkgo/v2 v2.27.3
24− github.com/onsi/gomega v1.38.3
25− github.com/pierrec/lz4/v4 v4.1.23
26− github.com/prometheus/client_golang v1.23.2
27− github.com/redis/go-redis/v9 v9.17.2
24+ github.com/onsi/ginkgo/v2 v2.32.1
25+ github.com/onsi/gomega v1.42.1
26+ github.com/pierrec/lz4/v4 v4.1.28
27+ github.com/prometheus/client_golang v1.24.1
28+ github.com/redis/go-redis/v9 v9.22.0
2829 github.com/spf13/cast v1.10.0
2930 github.com/spf13/pflag v1.0.10
3031 github.com/spf13/viper v1.21.0
31− github.com/stretchr/testify v1.11.1
32+ github.com/stretchr/testify v1.12.0
3233 github.com/vmihailenco/msgpack/v5 v5.4.1
33− go.yaml.in/yaml/v3 v3.0.4
34− golang.org/x/crypto v0.46.0
35− golang.org/x/net v0.48.0
36− golang.org/x/oauth2 v0.34.0
37− golang.org/x/sync v0.19.0
38− google.golang.org/api v0.258.0
34+ go.yaml.in/yaml/v3 v3.0.5
35+ golang.org/x/crypto v0.55.0
36+ golang.org/x/net v0.58.0
37+ golang.org/x/oauth2 v0.36.0
38+ golang.org/x/sync v0.22.0
39+ google.golang.org/api v0.293.0
3940 gopkg.in/natefinch/lumberjack.v2 v2.2.1
40− k8s.io/apimachinery v0.35.0
41+ k8s.io/apimachinery v0.36.3
4142)
4243
4344require (
44− cloud.google.com/go/auth v0.18.0 // indirect
45+ cloud.google.com/go/auth v0.23.1 // indirect
4546 cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
46− github.com/Masterminds/semver/v3 v3.4.0 // indirect
47+ github.com/Masterminds/semver/v3 v3.5.0 // indirect
4748 github.com/beorn7/perks v1.0.1 // indirect
4849 github.com/cespare/xxhash/v2 v2.3.0 // indirect
49− github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
50− github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
51− github.com/felixge/httpsnoop v1.0.4 // indirect
52− github.com/go-jose/go-jose/v4 v4.1.3 // indirect
53− github.com/go-logr/logr v1.4.3 // indirect
50+ github.com/felixge/httpsnoop v1.1.0 // indirect
51+ github.com/go-logr/logr v1.4.4 // indirect
5452 github.com/go-logr/stdr v1.2.2 // indirect
5553 github.com/go-task/slim-sprig/v3 v3.0.0 // indirect
56− github.com/google/pprof v0.0.0-20251213031049-b05bdaca462f // indirect
54+ github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 // indirect
5755 github.com/google/s2a-go v0.1.9 // indirect
58− github.com/googleapis/enterprise-certificate-proxy v0.3.7 // indirect
59− github.com/googleapis/gax-go/v2 v2.16.0 // indirect
56+ github.com/googleapis/enterprise-certificate-proxy v0.3.21 // indirect
57+ github.com/googleapis/gax-go/v2 v2.23.0 // indirect
6058 github.com/kylelemons/godebug v1.1.0 // indirect
6159 github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
62− github.com/pelletier/go-toml/v2 v2.2.4 // indirect
63− github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
60+ github.com/pelletier/go-toml/v2 v2.4.3 // indirect
6461 github.com/prometheus/client_model v0.6.2 // indirect
65− github.com/prometheus/common v0.67.4 // indirect
66− github.com/prometheus/procfs v0.19.2 // indirect
62+ github.com/prometheus/common v0.70.1 // indirect
63+ github.com/prometheus/procfs v0.21.1 // indirect
6764 github.com/sagikazarmark/locafero v0.12.0 // indirect
6865 github.com/spf13/afero v1.15.0 // indirect
6966 github.com/subosito/gotenv v1.6.0 // indirect
7067 github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
71− github.com/yuin/gopher-lua v1.1.1 // indirect
68+ github.com/yuin/gopher-lua v1.1.2 // indirect
7269 go.opentelemetry.io/auto/sdk v1.2.1 // indirect
73− go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0 // indirect
74− go.opentelemetry.io/otel v1.39.0 // indirect
75− go.opentelemetry.io/otel/metric v1.39.0 // indirect
76− go.opentelemetry.io/otel/trace v1.39.0 // indirect
77− go.yaml.in/yaml/v2 v2.4.3 // indirect
78− golang.org/x/mod v0.31.0 // indirect
79− golang.org/x/sys v0.39.0 // indirect
80− golang.org/x/text v0.32.0 // indirect
81− golang.org/x/tools v0.40.0 // indirect
82− google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect
83− google.golang.org/grpc v1.78.0 // indirect
84− google.golang.org/protobuf v1.36.11 // indirect
70+ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 // indirect
71+ go.opentelemetry.io/otel v1.45.0 // indirect
72+ go.opentelemetry.io/otel/metric v1.45.0 // indirect
73+ go.opentelemetry.io/otel/trace v1.45.0 // indirect
74+ go.uber.org/atomic v1.11.0 // indirect
75+ golang.org/x/mod v0.40.0 // indirect
76+ golang.org/x/sys v0.47.0 // indirect
77+ golang.org/x/text v0.41.0 // indirect
78+ golang.org/x/tools v0.49.0 // indirect
79+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260817212433-ac3dfec99bb1 // indirect
80+ google.golang.org/grpc v1.83.0 // indirect
81+ google.golang.org/protobuf v1.36.12 // indirect
8582 gopkg.in/yaml.v3 v3.0.1 // indirect
8683)
go.sum+110−110
@@ -1,5 +1,5 @@
1−cloud.google.com/go/auth v0.18.0 h1:wnqy5hrv7p3k7cShwAU/Br3nzod7fxoqG+k0VZ+/Pk0=
2−cloud.google.com/go/auth v0.18.0/go.mod h1:wwkPM1AgE1f2u6dG443MiWoD8C3BtOywNsUMcUTVDRo=
1+cloud.google.com/go/auth v0.23.1 h1:1tPpBPG02lQHmoiAvs9egyCASqXP0xgobptjZzov/Jg=
2+cloud.google.com/go/auth v0.23.1/go.mod h1:4DhBRcqvtljQN3dJ57qtqbib5ZGCYE5f2crfiiC2EM0=
33cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc=
44cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c=
55cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
@@ -8,14 +8,14 @@ github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb h1:ZVN4Iat3runWO
88github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb/go.mod h1:WsAABbY4HQBgd3mGuG4KMNTbHJCPvx9IVBHzysbknss=
99github.com/FZambia/sentinel v1.0.0 h1:KJ0ryjKTZk5WMp0dXvSdNqp3lFaW1fNFuEYfrkLOYIc=
1010github.com/FZambia/sentinel v1.0.0/go.mod h1:ytL1Am/RLlAoAXG6Kj5LNuw/TRRQrv2rt2FT26vP5gI=
11−github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
12−github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
11+github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE=
12+github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
1313github.com/a8m/envsubst v1.4.3 h1:kDF7paGK8QACWYaQo6KtyYBozY2jhQrTuNNuUxQkhJY=
1414github.com/a8m/envsubst v1.4.3/go.mod h1:4jjHWQlZoaXPoLQUb7H2qT4iLkZDdmEQiOUogdUmqVU=
1515github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
1616github.com/alicebob/miniredis/v2 v2.11.1/go.mod h1:UA48pmi7aSazcGAvcdKcBB49z521IC9VjTTRz2nIaJE=
17−github.com/alicebob/miniredis/v2 v2.35.0 h1:QwLphYqCEAo1eu1TqPRN2jgVMPBweeQcR21jeqDCONI=
18−github.com/alicebob/miniredis/v2 v2.35.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM=
17+github.com/alicebob/miniredis/v2 v2.38.0 h1:nZAzCR+Lj+Vxk4ZXzm2NuKq2O33RXj1XxJ2e2uP9jiw=
18+github.com/alicebob/miniredis/v2 v2.38.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM=
1919github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
2020github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
2121github.com/bitly/go-simplejson v0.5.1 h1:xgwPbetQScXt1gh9BmoJ6j9JMr3TElvuIyjR8pgdoow=
@@ -24,51 +24,47 @@ github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
2424github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
2525github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
2626github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
27−github.com/bsm/redislock v0.9.4 h1:X/Wse1DPpiQgHbVYRE9zv6m070UcKoOGekgvpNhiSvw=
28−github.com/bsm/redislock v0.9.4/go.mod h1:Epf7AJLiSFwLCiZcfi6pWFO/8eAYrYpQXFxEDPoDeAk=
27+github.com/bsm/redislock v0.10.0 h1:NAe1OHDnwPmWEzD+LpWBZXAdZrWld/xj/wmqEcQednQ=
28+github.com/bsm/redislock v0.10.0/go.mod h1:M05WZGjPbX/8ne7LmB7AbOsa2kv7Jzx4fqkLpDFZvJs=
2929github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
3030github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
3131github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
3232github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
3333github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
34−github.com/coreos/go-oidc/v3 v3.17.0 h1:hWBGaQfbi0iVviX4ibC7bk8OKT5qNr4klBaCHVNvehc=
35−github.com/coreos/go-oidc/v3 v3.17.0/go.mod h1:wqPbKFrVnE90vty060SB40FCJ8fTHTxSwyXJqZH+sI8=
34+github.com/coreos/go-oidc/v3 v3.20.0 h1:EtE0WIBHk03N+DqGkY4+UONzzZHk7amKt6IyNd7OsZE=
35+github.com/coreos/go-oidc/v3 v3.20.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
3636github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf h1:iW4rZ826su+pqaw19uhpSCzhj44qo35pNgKFGqzDKkU=
3737github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
3838github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
39−github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
40−github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
41−github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
42−github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
43−github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
44−github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
39+github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
40+github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
4541github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
4642github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
47−github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
48−github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
43+github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
44+github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
4945github.com/gkampitakis/ciinfo v0.3.2 h1:JcuOPk8ZU7nZQjdUhctuhQofk7BGHuIy0c9Ez8BNhXs=
5046github.com/gkampitakis/ciinfo v0.3.2/go.mod h1:1NIwaOcFChN4fa/B0hEBdAb6npDlFL8Bwx4dfRLRqAo=
5147github.com/gkampitakis/go-diff v1.3.2 h1:Qyn0J9XJSDTgnsgHRdz9Zp24RaJeKMUHg2+PDZZdC4M=
5248github.com/gkampitakis/go-diff v1.3.2/go.mod h1:LLgOrpqleQe26cte8s36HTWcTmMEur6OPYerdAAS9tk=
5349github.com/gkampitakis/go-snaps v0.5.15 h1:amyJrvM1D33cPHwVrjo9jQxX8g/7E2wYdZ+01KS3zGE=
5450github.com/gkampitakis/go-snaps v0.5.15/go.mod h1:HNpx/9GoKisdhw9AFOBT1N7DBs9DiHo/hGheFGBZ+mc=
55−github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY=
56−github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ=
57−github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs=
58−github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
51+github.com/go-jose/go-jose/v3 v3.0.5 h1:BLLJWbC4nMZOfuPVxoZIxeYsn6Nl2r1fITaJ78UQlVQ=
52+github.com/go-jose/go-jose/v3 v3.0.5/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ=
53+github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
54+github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
5955github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
60−github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
61−github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
56+github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
57+github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
6258github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
6359github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
6460github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=
6561github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=
66−github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
67−github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
62+github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
63+github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
6864github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
6965github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
70−github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
71−github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
66+github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
67+github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
7268github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
7369github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
7470github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3 h1:6amM4HsNPOvMLVc2ZnyqrjeQ92YAVWn7T4WBKK87inY=
@@ -76,25 +72,27 @@ github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3/go.mod h1:B4C85q
7672github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
7773github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
7874github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
79−github.com/google/pprof v0.0.0-20251213031049-b05bdaca462f h1:HU1RgM6NALf/KW9HEY6zry3ADbDKcmpQ+hJedoNGQYQ=
80−github.com/google/pprof v0.0.0-20251213031049-b05bdaca462f/go.mod h1:67FPmZWbr+KDT/VlpWtw6sO9XSjpJmLuHpoLmWiTGgY=
75+github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
76+github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
8177github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
8278github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
8379github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
8480github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
8581github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
86−github.com/googleapis/enterprise-certificate-proxy v0.3.7 h1:zrn2Ee/nWmHulBx5sAVrGgAa0f2/R35S4DJwfFaUPFQ=
87−github.com/googleapis/enterprise-certificate-proxy v0.3.7/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA=
88−github.com/googleapis/gax-go/v2 v2.16.0 h1:iHbQmKLLZrexmb0OSsNGTeSTS0HO4YvFOG8g5E4Zd0Y=
89−github.com/googleapis/gax-go/v2 v2.16.0/go.mod h1:o1vfQjjNZn4+dPnRdl/4ZD7S9414Y4xA+a/6Icj6l14=
82+github.com/googleapis/enterprise-certificate-proxy v0.3.21 h1:OFdQ3tnCX/zaQ0Cedur3D3z7kI6HiLX9g3TiAN4/DFU=
83+github.com/googleapis/enterprise-certificate-proxy v0.3.21/go.mod h1:L3D/IQExI6LqEjBdXcZQ1WluSgigQmSwBboFstVPM4w=
84+github.com/googleapis/gax-go/v2 v2.23.0 h1:Tchl7qkvE7Ip3y+ztvNufYFvkfqTe7NfLTYGIdJRLuE=
85+github.com/googleapis/gax-go/v2 v2.23.0/go.mod h1:rBQKOVJCdb8IFEzg+FCwlt1LP/xMDGuqUXhUG+XMXEg=
9086github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
9187github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
9288github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE=
9389github.com/joshdk/go-junit v1.0.0/go.mod h1:TiiV0PqkaNfFXjEiyjWM3XXrhVyCa1K4Zfga6W52ung=
9490github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo=
9591github.com/justinas/alice v1.2.0/go.mod h1:fN5HRH/reO/zrUflLfTN43t3vXvKzvZIENsNEe7i7qA=
96−github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
97−github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
92+github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
93+github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
94+github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
95+github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
9896github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
9997github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
10098github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
@@ -111,27 +109,25 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq
111109github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
112110github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk=
113111github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw=
114−github.com/onsi/ginkgo/v2 v2.27.3 h1:ICsZJ8JoYafeXFFlFAG75a7CxMsJHwgKwtO+82SE9L8=
115−github.com/onsi/ginkgo/v2 v2.27.3/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo=
116−github.com/onsi/gomega v1.38.3 h1:eTX+W6dobAYfFeGC2PV6RwXRu/MyT+cQguijutvkpSM=
117−github.com/onsi/gomega v1.38.3/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4=
118−github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
119−github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
120−github.com/pierrec/lz4/v4 v4.1.23 h1:oJE7T90aYBGtFNrI8+KbETnPymobAhzRrR8Mu8n1yfU=
121−github.com/pierrec/lz4/v4 v4.1.23/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
112+github.com/onsi/ginkgo/v2 v2.32.1 h1:6tlvcDm/3sE8lGJbZ4+d4mO3RLy24/tQWOFzVSQNIfw=
113+github.com/onsi/ginkgo/v2 v2.32.1/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44=
114+github.com/onsi/gomega v1.42.1 h1:iN1rCUX+44NZ1Dc97MPoeFYbFR0vh8zxoxMFwKdyZ6I=
115+github.com/onsi/gomega v1.42.1/go.mod h1:REff/hsDsodHoKlWsP2mAPhu1+5/6hVYNf9rIEBpeSg=
116+github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
117+github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
118+github.com/pierrec/lz4/v4 v4.1.28 h1:pPEPwRJ4kybBTfGt28q7lQsRJQHhC08axprdLD5Ppio=
119+github.com/pierrec/lz4/v4 v4.1.28/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
122120github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
123−github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
124−github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
125−github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
126−github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
121+github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
122+github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
127123github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
128124github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
129−github.com/prometheus/common v0.67.4 h1:yR3NqWO1/UyO1w2PhUvXlGQs/PtFmoveVO0KZ4+Lvsc=
130−github.com/prometheus/common v0.67.4/go.mod h1:gP0fq6YjjNCLssJCQp0yk4M8W6ikLURwkdd/YKtTbyI=
131−github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws=
132−github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw=
133−github.com/redis/go-redis/v9 v9.17.2 h1:P2EGsA4qVIM3Pp+aPocCJ7DguDHhqrXNhVcEp4ViluI=
134−github.com/redis/go-redis/v9 v9.17.2/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
125+github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
126+github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
127+github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
128+github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
129+github.com/redis/go-redis/v9 v9.22.0 h1:laDvpYXTJtZLloinw1fA5Kqd6HAEH2XKxOkG/PDq2F0=
130+github.com/redis/go-redis/v9 v9.22.0/go.mod h1:y2g0Wj8rQvuK0ELM+oxSudcLtC09JScs98I/X9gRWY4=
135131github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
136132github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
137133github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4=
@@ -146,8 +142,8 @@ github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
146142github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
147143github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
148144github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
149−github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
150−github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
145+github.com/stretchr/testify v1.12.0 h1:K6Mr6jO9JICuend/5xzTM03ydSV3vdNRYAdPSukj8uI=
146+github.com/stretchr/testify v1.12.0/go.mod h1:bOYBZb5qJ00vPzWfIqBUZPaxK8jWiXc6d3ErP4Ca9Gw=
151147github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
152148github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
153149github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
@@ -165,53 +161,57 @@ github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV
165161github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
166162github.com/yuin/gopher-lua v0.0.0-20190206043414-8bfc7677f583/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ=
167163github.com/yuin/gopher-lua v0.0.0-20191213034115-f46add6fdb5c/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ=
168−github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
169−github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
164+github.com/yuin/gopher-lua v1.1.2 h1:yF/FjE3hD65tBbt0VXLE13HWS9h34fdzJmrWRXwobGA=
165+github.com/yuin/gopher-lua v1.1.2/go.mod h1:7aRmXIWl37SqRf0koeyylBEzJ+aPt8A+mmkQ4f1ntR8=
166+github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
167+github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
170168go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
171169go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
172−go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ=
173−go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo=
174−go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0 h1:ssfIgGNANqpVFCndZvcuyKbl0g+UAVcbBcqGkG28H0Y=
175−go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0/go.mod h1:GQ/474YrbE4Jx8gZ4q5I4hrhUzM6UPzyrqJYV2AqPoQ=
176−go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48=
177−go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8=
178−go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0=
179−go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs=
180−go.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18=
181−go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE=
182−go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8=
183−go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=
184−go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI=
185−go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA=
170+go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04=
171+go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc=
172+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 h1:LMuyCAyfalSjDyjdC65nK6N0zoTT63+E/u95X0JovZI=
173+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0/go.mod h1:085m8qbm4hgc8rZWGDEa4vmyyo2c3nPxUslYUKUIU04=
174+go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU=
175+go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ=
176+go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M=
177+go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s=
178+go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw=
179+go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA=
180+go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o=
181+go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA=
182+go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag=
183+go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc=
184+go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
185+go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
186186go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
187187go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
188−go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
189−go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
190−go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
191−go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
188+go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
189+go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
190+go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
191+go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
192192golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
193193golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
194194golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
195−golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
196−golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
195+golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
196+golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
197197golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
198198golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
199−golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
200−golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
199+golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs=
200+golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE=
201201golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
202202golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
203203golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
204204golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
205205golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
206−golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
207−golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
208−golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
209−golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
206+golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
207+golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
208+golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
209+golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
210210golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
211211golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
212212golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
213−golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
214−golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
213+golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
214+golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
215215golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
216216golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
217217golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -221,8 +221,8 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
221221golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
222222golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
223223golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
224−golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
225−golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
224+golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
225+golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
226226golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
227227golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
228228golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
@@ -234,31 +234,31 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
234234golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
235235golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
236236golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
237−golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
238−golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
239−golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
240−golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
237+golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
238+golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
239+golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
240+golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
241241golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
242242golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
243243golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
244244golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
245−golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
246−golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
245+golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
246+golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
247247golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
248−gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
249−gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
250−google.golang.org/api v0.258.0 h1:IKo1j5FBlN74fe5isA2PVozN3Y5pwNKriEgAXPOkDAc=
251−google.golang.org/api v0.258.0/go.mod h1:qhOMTQEZ6lUps63ZNq9jhODswwjkjYYguA7fA3TBFww=
252−google.golang.org/genproto v0.0.0-20251202230838-ff82c1b0f217 h1:GvESR9BIyHUahIb0NcTum6itIWtdoglGX+rnGxm2934=
253−google.golang.org/genproto v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:yJ2HH4EHEDTd3JiLmhds6NkJ17ITVYOdV3m3VKOnws0=
254−google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls=
255−google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:+rXWjjaukWZun3mLfjmVnQi18E1AsFbDN9QdJ5YXLto=
256−google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=
257−google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
258−google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc=
259−google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U=
260−google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
261−google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
248+gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
249+gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
250+google.golang.org/api v0.293.0 h1:p9XIWOf63U4OgYx120ZwVU8+vl4XTPmWfgVPnmOAS9w=
251+google.golang.org/api v0.293.0/go.mod h1:6n5tjEB1gzwniZTepZ0g5u+wM7Bof5GeULCx/zh8ZE0=
252+google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0=
253+google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:L43LFes82YgSonw6iTXTxXUX1OlULt4AQtkik4ULL/I=
254+google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7 h1:jQ9p21COKWjP3VwuFrNRiiOTMh3mPpN45R7SLrH/HUU=
255+google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7/go.mod h1:KqHwBx2upmfa1XSi1WuRvC+2VGCLtooKkfmyvRbUmqA=
256+google.golang.org/genproto/googleapis/rpc v0.0.0-20260817212433-ac3dfec99bb1 h1:utmqiUzZAEINbLmRyAt1QjVkMyLQ+lvIwCpLaB1rZfw=
257+google.golang.org/genproto/googleapis/rpc v0.0.0-20260817212433-ac3dfec99bb1/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
258+google.golang.org/grpc v1.83.0 h1:JeNZEKJFbQxArAMl+hiytHauacDNqJUllNfmIMmpqnQ=
259+google.golang.org/grpc v1.83.0/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ=
260+google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
261+google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
262262gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
263263gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
264264gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
@@ -267,5 +267,5 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYs
267267gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
268268gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
269269gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
270−k8s.io/apimachinery v0.35.0 h1:Z2L3IHvPVv/MJ7xRxHEtk6GoJElaAqDCCU0S6ncYok8=
271−k8s.io/apimachinery v0.35.0/go.mod h1:jQCgFZFR1F4Ik7hvr2g84RTJSZegBc8yHgFWKn//hns=
270+k8s.io/apimachinery v0.36.3 h1:PkzMRBRG8joFD8EhCuQAtNPvJlxb82FwplP26HIzvAM=
271+k8s.io/apimachinery v0.36.3/go.mod h1:cTSjBWgPe/6CQyBKzY/hDIRWCQQQeK0mfLbml0UYFHE=
main.go+14
@@ -26,6 +26,7 @@ func main() {
2626 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)")
2727 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")
2828 showVersion := configFlagSet.Bool("version", false, "print version string")
29+ configTest := configFlagSet.Bool("config-test", false, "test the configuration and exit")
2930 configFlagSet.Parse(os.Args[1:])
3031
3132 if *showVersion {
@@ -37,11 +38,24 @@ func main() {
3738 logger.Fatal("cannot use alpha-config and convert-config-to-alpha together")
3839 }
3940
41+ if *configTest && *convertConfig {
42+ logger.Fatal("cannot use config-test and convert-config-to-alpha together")
43+ }
44+
4045 opts, err := loadConfiguration(*config, *alphaConfig, configFlagSet, os.Args[1:])
4146 if err != nil {
4247 logger.Fatalf("ERROR: %v", err)
4348 }
4449
50+ if *configTest {
51+ if err = validation.Validate(opts); err != nil {
52+ logger.Errorf("%s", err)
53+ os.Exit(1)
54+ }
55+ fmt.Println("configuration is valid")
56+ return
57+ }
58+
4559 if *convertConfig {
4660 if err := printConvertedConfig(opts); err != nil {
4761 logger.Fatalf("ERROR: could not convert config: %v", err)
main_test.go+78−2
@@ -7,6 +7,7 @@ import (
77 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
88 . "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options/testutil"
99 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
10+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/validation"
1011 . "github.com/onsi/ginkgo/v2"
1112 . "github.com/onsi/gomega"
1213 "github.com/onsi/gomega/format"
@@ -186,6 +187,7 @@ redirect_url="http://localhost:4180/oauth2/callback"
186187 InsecureAllowUnverifiedEmail: ptr.To(false),
187188 InsecureSkipIssuerVerification: ptr.To(false),
188189 SkipDiscovery: ptr.To(false),
190+ EnabledSigningAlgs: []string{},
189191 },
190192 MicrosoftEntraIDConfig: options.MicrosoftEntraIDOptions{
191193 FederatedTokenAuth: ptr.To(false),
@@ -276,7 +278,7 @@ redirect_url="http://localhost:4180/oauth2/callback"
276278 Entry("with bad legacy configuration", loadConfigurationTableInput{
277279 configContent: testCoreConfig + "unknown_field=\"something\"",
278280 expectedOptions: func() *options.Options { return nil },
279− 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"),
281+ 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"),
280282 }),
281283 Entry("with bad alpha configuration", loadConfigurationTableInput{
282284 configContent: testCoreConfig,
@@ -288,7 +290,81 @@ redirect_url="http://localhost:4180/oauth2/callback"
288290 configContent: testCoreConfig + "unknown_field=\"something\"",
289291 alphaConfigContent: testAlphaConfig,
290292 expectedOptions: func() *options.Options { return nil },
291− 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"),
293+ 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"),
292294 }),
293295 )
296+
297+ Describe("Config Test Mode", func() {
298+ const validConfig = `
299+http_address="127.0.0.1:4180"
300+upstreams="http://httpbin"
301+client_id="oauth2-proxy"
302+client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK"
303+cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w="
304+email_domains="example.com"
305+cookie_secure="false"
306+redirect_url="http://localhost:4180/oauth2/callback"
307+`
308+
309+ const invalidConfig = `
310+http_address="127.0.0.1:4180"
311+upstreams="http://httpbin"
312+email_domains="example.com"
313+cookie_secure="false"
314+redirect_url="http://localhost:4180/oauth2/callback"
315+`
316+
317+ writeTempConfig := func(content string) string {
318+ file, err := os.CreateTemp("", "oauth2-proxy-test-config-XXXX.cfg")
319+ Expect(err).ToNot(HaveOccurred())
320+ defer file.Close()
321+
322+ _, err = file.WriteString(content)
323+ Expect(err).ToNot(HaveOccurred())
324+ return file.Name()
325+ }
326+
327+ It("should pass validation with a valid configuration", func() {
328+ configFile := writeTempConfig(validConfig)
329+ defer os.Remove(configFile)
330+
331+ flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
332+ opts, err := loadConfiguration(configFile, "", flagSet, []string{})
333+ Expect(err).ToNot(HaveOccurred())
334+
335+ err = validation.Validate(opts)
336+ Expect(err).ToNot(HaveOccurred())
337+ })
338+
339+ It("should fail validation with an invalid configuration (missing required fields)", func() {
340+ configFile := writeTempConfig(invalidConfig)
341+ defer os.Remove(configFile)
342+
343+ flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
344+ opts, err := loadConfiguration(configFile, "", flagSet, []string{})
345+ Expect(err).ToNot(HaveOccurred())
346+
347+ err = validation.Validate(opts)
348+ Expect(err).To(HaveOccurred())
349+ Expect(err.Error()).To(ContainSubstring("invalid configuration"))
350+ })
351+
352+ It("should fail to load a configuration file with syntax errors", func() {
353+ configFile := writeTempConfig("this is not valid toml ===")
354+ defer os.Remove(configFile)
355+
356+ flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
357+ _, err := loadConfiguration(configFile, "", flagSet, []string{})
358+ Expect(err).To(HaveOccurred())
359+ })
360+
361+ It("should register the config-test flag", func() {
362+ flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
363+ flagSet.ParseErrorsAllowlist.UnknownFlags = true
364+ configTest := flagSet.Bool("config-test", false, "test the configuration and exit")
365+ err := flagSet.Parse([]string{"--config-test"})
366+ Expect(err).ToNot(HaveOccurred())
367+ Expect(*configTest).To(BeTrue())
368+ })
369+ })
294370})
oauthproxy.go+61−39
@@ -54,9 +54,13 @@ const (
5454 authOnlyPath = "/auth"
5555 userInfoPath = "/userinfo"
5656 staticPathPrefix = "/static/"
57+
58+ idTokenPlaceholder = "{id_token}"
5759)
5860
5961var (
62+ defaultTrustedProxyIPs = []string{"0.0.0.0/0", "::/0"}
63+
6064 // ErrNeedsLogin means the user should be redirected to the login page
6165 ErrNeedsLogin = errors.New("redirect to login page")
6266
@@ -181,13 +185,14 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
181185
182186 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)
183187
184− trustedIPs := ip.NewNetSet()
185− for _, ipStr := range opts.TrustedIPs {
186− if ipNet := ip.ParseIPNet(ipStr); ipNet != nil {
187− trustedIPs.AddIPNet(*ipNet)
188− } else {
189− return nil, fmt.Errorf("could not parse IP network (%s)", ipStr)
190− }
188+ trustedIPs, err := ip.ParseNetSet(opts.TrustedIPs)
189+ if err != nil {
190+ return nil, err
191+ }
192+
193+ trustedProxies, err := buildTrustedProxyNetSet(opts)
194+ if err != nil {
195+ return nil, err
191196 }
192197
193198 allowedRoutes, err := buildRoutesAllowlist(opts)
@@ -200,7 +205,7 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
200205 return nil, err
201206 }
202207
203− preAuthChain, err := buildPreAuthChain(opts, sessionStore)
208+ preAuthChain, err := buildPreAuthChain(opts, sessionStore, trustedProxies)
204209 if err != nil {
205210 return nil, fmt.Errorf("could not build pre-auth chain: %v", err)
206211 }
@@ -353,8 +358,8 @@ func (p *OAuthProxy) buildProxySubrouter(s *mux.Router) {
353358// buildPreAuthChain constructs a chain that should process every request before
354359// the OAuth2 Proxy authentication logic kicks in.
355360// For example forcing HTTPS or health checks.
356−func buildPreAuthChain(opts *options.Options, sessionStore sessionsapi.SessionStore) (alice.Chain, error) {
357− chain := alice.New(middleware.NewScope(opts.ReverseProxy, opts.Logging.RequestIDHeader))
361+func buildPreAuthChain(opts *options.Options, sessionStore sessionsapi.SessionStore, trustedProxies *ip.NetSet) (alice.Chain, error) {
362+ chain := alice.New(middleware.NewScope(opts.ReverseProxy, opts.Logging.RequestIDHeader, trustedProxies))
358363
359364 if opts.ForceHTTPS {
360365 _, httpsPort, err := net.SplitHostPort(opts.Server.SecureBindAddress)
@@ -393,13 +398,24 @@ func buildPreAuthChain(opts *options.Options, sessionStore sessionsapi.SessionSt
393398 return chain, nil
394399}
395400
401+func buildTrustedProxyNetSet(opts *options.Options) (*ip.NetSet, error) {
402+ trustedProxyIPs := opts.TrustedProxyIPs
403+ if opts.ReverseProxy && len(trustedProxyIPs) == 0 {
404+ 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.")
405+ trustedProxyIPs = defaultTrustedProxyIPs
406+ }
407+
408+ return ip.ParseNetSet(trustedProxyIPs)
409+}
410+
396411func buildSessionChain(opts *options.Options, provider providers.Provider, sessionStore sessionsapi.SessionStore, validator basic.Validator) alice.Chain {
397412 chain := alice.New()
398413
399414 if opts.SkipJwtBearerTokens {
400− sessionLoaders := []middlewareapi.TokenToSessionFunc{
401− provider.CreateSessionFromToken,
402− }
415+ verifiers := opts.GetJWTBearerVerifiers()
416+
417+ sessionLoaders := make([]middlewareapi.TokenToSessionFunc, 0, len(verifiers)+1)
418+ sessionLoaders = append(sessionLoaders, provider.CreateSessionFromToken)
403419
404420 for _, verifier := range opts.GetJWTBearerVerifiers() {
405421 sessionLoaders = append(sessionLoaders,
@@ -571,7 +587,7 @@ func (p *OAuthProxy) ErrorPage(rw http.ResponseWriter, req *http.Request, code i
571587
572588// IsAllowedRequest is used to check if auth should be skipped for this request
573589func (p *OAuthProxy) IsAllowedRequest(req *http.Request) bool {
574− isPreflightRequestAllowed := p.skipAuthPreflight && req.Method == "OPTIONS"
590+ isPreflightRequestAllowed := p.skipAuthPreflight && req.Method == http.MethodOptions
575591 return isPreflightRequestAllowed || p.isAllowedRoute(req) || p.isTrustedIP(req)
576592}
577593
@@ -610,9 +626,7 @@ func (p *OAuthProxy) isAPIPath(req *http.Request) bool {
610626
611627// isTrustedIP is used to check if a request comes from a trusted client IP address.
612628func (p *OAuthProxy) isTrustedIP(req *http.Request) bool {
613− // RemoteAddr @ means unix socket
614− // https://github.com/golang/go/blob/0fa53e41f122b1661d0678a6d36d71b7b5ad031d/src/syscall/syscall_linux.go#L506-L511
615− if p.trustedIPs == nil && req.RemoteAddr != "@" {
629+ if p.trustedIPs == nil {
616630 return false
617631 }
618632
@@ -633,6 +647,10 @@ func (p *OAuthProxy) isTrustedIP(req *http.Request) bool {
633647// SignInPage writes the sign in template to the response
634648func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code int) {
635649 prepareNoCache(rw)
650+
651+ if err := p.ClearSessionCookie(rw, req); err != nil {
652+ logger.Printf("Error clearing session cookie: %v", err)
653+ }
636654 rw.WriteHeader(code)
637655
638656 redirectURL, err := p.appDirector.GetRedirect(req)
@@ -646,16 +664,12 @@ func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code
646664 redirectURL = "/"
647665 }
648666
649− if err := p.ClearSessionCookie(rw, req); err != nil {
650− logger.Printf("Error clearing session cookie: %v", err)
651− }
652−
653667 p.pageWriter.WriteSignInPage(rw, req, redirectURL, code)
654668}
655669
656670// ManualSignIn handles basic auth logins to the proxy
657671func (p *OAuthProxy) ManualSignIn(req *http.Request) (string, bool, int) {
658− if req.Method != "POST" || p.basicAuthValidator == nil {
672+ if req.Method != http.MethodPost || p.basicAuthValidator == nil {
659673 return "", false, http.StatusOK
660674 }
661675 user := req.FormValue("username")
@@ -720,15 +734,17 @@ func (p *OAuthProxy) UserInfo(rw http.ResponseWriter, req *http.Request) {
720734 }
721735
722736 userInfo := struct {
723− User string `json:"user"`
724− Email string `json:"email"`
725− Groups []string `json:"groups,omitempty"`
726− PreferredUsername string `json:"preferredUsername,omitempty"`
737+ User string `json:"user"`
738+ Email string `json:"email"`
739+ Groups []string `json:"groups,omitempty"`
740+ PreferredUsername string `json:"preferredUsername,omitempty"`
741+ AdditionalClaims map[string]interface{} `json:"additionalClaims,omitempty"`
727742 }{
728743 User: session.User,
729744 Email: session.Email,
730745 Groups: session.Groups,
731746 PreferredUsername: session.PreferredUsername,
747+ AdditionalClaims: session.AdditionalClaims,
732748 }
733749
734750 if err := json.NewEncoder(rw).Encode(userInfo); err != nil {
@@ -745,6 +761,20 @@ func (p *OAuthProxy) SignOut(rw http.ResponseWriter, req *http.Request) {
745761 p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
746762 return
747763 }
764+
765+ if strings.Contains(redirect, idTokenPlaceholder) {
766+ session, err := p.getAuthenticatedSession(rw, req)
767+ if err != nil {
768+ logger.Errorf("error getting authenticated session during SignOut, won't replace id_token placeholder in redirect URL: %v", err)
769+ } else {
770+ redirect = strings.ReplaceAll(redirect, idTokenPlaceholder, session.IDToken)
771+ }
772+ }
773+
774+ // Call backend logout before clearing the session so we still have the session
775+ // (and id_token) available to invoke the provider's logout endpoint
776+ p.backendLogout(rw, req)
777+
748778 err = p.ClearSessionCookie(rw, req)
749779 if err != nil {
750780 logger.Errorf("Error clearing session cookie: %v", err)
@@ -752,8 +782,6 @@ func (p *OAuthProxy) SignOut(rw http.ResponseWriter, req *http.Request) {
752782 return
753783 }
754784
755− p.backendLogout(rw, req)
756−
757785 http.Redirect(rw, req, redirect, http.StatusFound)
758786}
759787
@@ -773,7 +801,7 @@ func (p *OAuthProxy) backendLogout(rw http.ResponseWriter, req *http.Request) {
773801 return
774802 }
775803
776− backendLogoutURL := strings.ReplaceAll(providerData.BackendLogoutURL, "{id_token}", session.IDToken)
804+ backendLogoutURL := strings.ReplaceAll(providerData.BackendLogoutURL, idTokenPlaceholder, session.IDToken)
777805 // security exception because URL is dynamic ({id_token} replacement) but
778806 // base is not end-user provided but comes from configuration somewhat secure
779807 resp, err := http.Get(backendLogoutURL) // #nosec G107
@@ -783,7 +811,7 @@ func (p *OAuthProxy) backendLogout(rw http.ResponseWriter, req *http.Request) {
783811 }
784812
785813 defer resp.Body.Close()
786− if resp.StatusCode != 200 {
814+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
787815 logger.Errorf("error while calling backend logout url, returned error code %v", resp.StatusCode)
788816 }
789817}
@@ -858,6 +886,8 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
858886 remoteAddr := ip.GetClientString(p.realClientIPParser, req, true)
859887
860888 // finish the oauth cycle
889+ // #nosec G120 -- The default max size in Go is already capped at 10MB so this would be the absolute max and is
890+ // unlikely to be hit in practice.
861891 err := req.ParseForm()
862892 if err != nil {
863893 logger.Errorf("Error while parsing OAuth2 callback: %v", err)
@@ -987,15 +1017,7 @@ func (p *OAuthProxy) enrichSessionState(ctx context.Context, s *sessionsapi.Sess
9871017// and optional authorization).
9881018func (p *OAuthProxy) AuthOnly(rw http.ResponseWriter, req *http.Request) {
9891019 session, err := p.getAuthenticatedSession(rw, req)
990− // If SkipProviderButton is enabled and user needs login, redirect directly
991− // to OAuth provider instead of returning 401. This allows nginx auth_request
992− // to pass through the 302 redirect to the browser, bypassing error_page
993− // handling which can break redirect flows.
994− // See: https://github.com/oauth2-proxy/oauth2-proxy/issues/334
995− if p.SkipProviderButton && err == ErrNeedsLogin {
996− p.doOAuthStart(rw, req, nil)
997− return
998− } else if err != nil {
1020+ if err != nil {
9991021 http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
10001022 return
10011023 }
oauthproxy_test.go+342−106
@@ -15,6 +15,7 @@ import (
1515 "time"
1616
1717 "github.com/coreos/go-oidc/v3/oidc"
18+ middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
1819 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
1920 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
2021 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/hmacauth"
@@ -53,7 +54,7 @@ func TestRobotsTxt(t *testing.T) {
5354 t.Fatal(err)
5455 }
5556 rw := httptest.NewRecorder()
56− req, _ := http.NewRequest("GET", "/robots.txt", nil)
57+ req, _ := http.NewRequest(http.MethodGet, "/robots.txt", nil)
5758 proxy.ServeHTTP(rw, req)
5859 assert.Equal(t, 200, rw.Code)
5960 assert.Equal(t, "User-agent: *\nDisallow: /\n", rw.Body.String())
@@ -240,7 +241,7 @@ func TestBasicAuthPassword(t *testing.T) {
240241
241242 // Save the required session
242243 rw := httptest.NewRecorder()
243− req, _ := http.NewRequest("GET", "/", nil)
244+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
244245 err = proxy.sessionStore.Save(rw, req, &sessions.SessionState{
245246 Email: emailAddress,
246247 })
@@ -249,7 +250,7 @@ func TestBasicAuthPassword(t *testing.T) {
249250 // Extract the cookie value to inject into the test request
250251 cookie := rw.Header().Values("Set-Cookie")[0]
251252
252− req, _ = http.NewRequest("GET", "/", nil)
253+ req, _ = http.NewRequest(http.MethodGet, "/", nil)
253254 req.Header.Set("Cookie", cookie)
254255 rw = httptest.NewRecorder()
255256 proxy.ServeHTTP(rw, req)
@@ -299,14 +300,14 @@ func TestPassGroupsHeadersWithGroups(t *testing.T) {
299300
300301 // Save the required session
301302 rw := httptest.NewRecorder()
302− req, _ := http.NewRequest("GET", "/", nil)
303+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
303304 err = proxy.sessionStore.Save(rw, req, session)
304305 assert.NoError(t, err)
305306
306307 // Extract the cookie value to inject into the test request
307308 cookie := rw.Header().Values("Set-Cookie")[0]
308309
309− req, _ = http.NewRequest("GET", "/", nil)
310+ req, _ = http.NewRequest(http.MethodGet, "/", nil)
310311 req.Header.Set("Cookie", cookie)
311312 rw = httptest.NewRecorder()
312313 proxy.ServeHTTP(rw, req)
@@ -456,7 +457,7 @@ func (patTest *PassAccessTokenTest) getEndpointWithCookie(cookie string, endpoin
456457 return 0, ""
457458 }
458459
459− req, err := http.NewRequest("GET", endpoint, strings.NewReader(""))
460+ req, err := http.NewRequest(http.MethodGet, endpoint, strings.NewReader(""))
460461 if err != nil {
461462 return 0, ""
462463 }
@@ -607,7 +608,7 @@ func NewSignInPageTest(skipProvider bool) (*SignInPageTest, error) {
607608
608609func (sipTest *SignInPageTest) GetEndpoint(endpoint string) (int, string) {
609610 rw := httptest.NewRecorder()
610− req, _ := http.NewRequest("GET", endpoint, strings.NewReader(""))
611+ req, _ := http.NewRequest(http.MethodGet, endpoint, strings.NewReader(""))
611612 sipTest.proxy.ServeHTTP(rw, req)
612613 return rw.Code, rw.Body.String()
613614}
@@ -712,6 +713,50 @@ func TestManualSignInCorrectCredentials(t *testing.T) {
712713 assert.Equal(t, http.StatusFound, statusCode)
713714}
714715
716+func TestSignInPageClearsExistingSessionCookie(t *testing.T) {
717+ opts := baseTestOptions()
718+ err := validation.Validate(opts)
719+ require.NoError(t, err)
720+
721+ proxy, err := NewOAuthProxy(opts, func(string) bool {
722+ return true
723+ })
724+ require.NoError(t, err)
725+
726+ // Create a real session cookie using the actual session store.
727+ saveRW := httptest.NewRecorder()
728+ saveReq := httptest.NewRequest(http.MethodGet, "/", nil)
729+ err = proxy.sessionStore.Save(saveRW, saveReq, &sessions.SessionState{
730+ Email: "john.doe@example.com",
731+ })
732+ require.NoError(t, err)
733+
734+ cookies := saveRW.Result().Cookies()
735+ require.NotEmpty(t, cookies)
736+
737+ // Send that cookie to the sign-in page.
738+ req := httptest.NewRequest(http.MethodGet, "/oauth2/sign_in", nil)
739+ for _, c := range cookies {
740+ req.AddCookie(c)
741+ }
742+
743+ rw := httptest.NewRecorder()
744+ proxy.ServeHTTP(rw, req)
745+
746+ assert.Equal(t, http.StatusOK, rw.Code)
747+
748+ cleared := false
749+ for _, c := range rw.Result().Cookies() {
750+ if c.Name == proxy.CookieOptions.Name {
751+ cleared = true
752+ assert.Equal(t, "", c.Value)
753+ assert.Less(t, c.MaxAge, 0)
754+ }
755+ }
756+
757+ assert.True(t, cleared, "expected sign-in page to clear existing session cookie")
758+}
759+
715760func TestSignInPageIncludesTargetRedirect(t *testing.T) {
716761 sipTest, err := NewSignInPageTest(false)
717762 if err != nil {
@@ -834,20 +879,8 @@ func NewProcessCookieTest(opts ProcessCookieTestOpts, modifiers ...OptionsModifi
834879 return nil, err
835880 }
836881 testProvider := &TestProvider{
837− ProviderData: &providers.ProviderData{
838− ProviderName: "Test Provider",
839− LoginURL: &url.URL{
840− Scheme: "http",
841− Host: "localhost",
842− Path: "/oauth/authorize",
843− },
844− RedeemURL: &url.URL{
845− Scheme: "http",
846− Host: "localhost",
847− Path: "/oauth/token",
848− },
849− },
850− ValidToken: opts.providerValidateCookieResponse,
882+ ProviderData: &providers.ProviderData{},
883+ ValidToken: opts.providerValidateCookieResponse,
851884 }
852885
853886 groups := pcTest.opts.Providers[0].AllowedGroups
@@ -861,7 +894,7 @@ func NewProcessCookieTest(opts ProcessCookieTestOpts, modifiers ...OptionsModifi
861894 // access_token validation.
862895 pcTest.proxy.CookieOptions.Refresh = time.Duration(0)
863896 pcTest.rw = httptest.NewRecorder()
864− pcTest.req, _ = http.NewRequest("GET", "/", strings.NewReader(""))
897+ pcTest.req, _ = http.NewRequest(http.MethodGet, "/", strings.NewReader(""))
865898 pcTest.validateUser = true
866899 return &pcTest, nil
867900}
@@ -994,7 +1027,7 @@ func NewUserInfoEndpointTest() (*ProcessCookieTest, error) {
9941027 if err != nil {
9951028 return nil, err
9961029 }
997− pcTest.req, _ = http.NewRequest("GET",
1030+ pcTest.req, _ = http.NewRequest(http.MethodGet,
9981031 pcTest.opts.ProxyPrefix+"/userinfo", nil)
9991032 return pcTest, nil
10001033}
@@ -1044,6 +1077,20 @@ func TestUserInfoEndpointAccepted(t *testing.T) {
10441077 },
10451078 expectedResponse: "{\"user\":\"john.doe\",\"email\":\"john.doe@example.com\",\"groups\":[\"example\",\"groups\"],\"preferredUsername\":\"john\"}\n",
10461079 },
1080+ {
1081+ name: "With Additional Claim",
1082+ session: &sessions.SessionState{
1083+ User: "john.doe",
1084+ PreferredUsername: "john",
1085+ Email: "john.doe@example.com",
1086+ Groups: []string{"example", "groups"},
1087+ AccessToken: "my_access_token",
1088+ AdditionalClaims: map[string]interface{}{
1089+ "foo": "bar",
1090+ },
1091+ },
1092+ expectedResponse: "{\"user\":\"john.doe\",\"email\":\"john.doe@example.com\",\"groups\":[\"example\",\"groups\"],\"preferredUsername\":\"john\",\"additionalClaims\":{\"foo\":\"bar\"}}\n",
1093+ },
10471094 }
10481095
10491096 for _, tc := range testCases {
@@ -1088,7 +1135,7 @@ func NewAuthOnlyEndpointTest(querystring string, modifiers ...OptionsModifier) (
10881135 return nil, err
10891136 }
10901137 pcTest.req, _ = http.NewRequest(
1091− "GET",
1138+ http.MethodGet,
10921139 fmt.Sprintf("%s/auth%s", pcTest.opts.ProxyPrefix, querystring),
10931140 nil)
10941141 return pcTest, nil
@@ -1124,35 +1171,6 @@ func TestAuthOnlyEndpointUnauthorizedOnNoCookieSetError(t *testing.T) {
11241171 assert.Equal(t, "Unauthorized\n", string(bodyBytes))
11251172}
11261173
1127−// TestAuthOnlyEndpointRedirectWithSkipProviderButton tests that when SkipProviderButton
1128−// is true and no session exists, the /auth endpoint should return a 302 redirect
1129−// to the OAuth provider instead of 401. This is important for nginx auth_request
1130−// architecture where 401 triggers error_page handling which can break the redirect flow.
1131−// See: https://github.com/oauth2-proxy/oauth2-proxy/issues/334
1132−func TestAuthOnlyEndpointRedirectWithSkipProviderButton(t *testing.T) {
1133− test, err := NewAuthOnlyEndpointTest("", func(opts *options.Options) {
1134− opts.SkipProviderButton = true
1135− })
1136− if err != nil {
1137− t.Fatal(err)
1138− }
1139−
1140− test.proxy.ServeHTTP(test.rw, test.req)
1141−
1142− // With SkipProviderButton=true and no session, should return 302 redirect
1143− // to OAuth provider, NOT 401 Unauthorized
1144− assert.Equal(t, http.StatusFound, test.rw.Code)
1145− location := test.rw.Header().Get("Location")
1146− assert.NotEmpty(t, location, "Expected Location header for redirect")
1147−
1148− // Verify the redirect points to the OAuth provider's authorize endpoint
1149− // and contains key OAuth parameters
1150− assert.Contains(t, location, "/oauth/authorize", "Expected redirect to OAuth authorize endpoint")
1151− assert.Contains(t, location, "client_id=", "Expected client_id in redirect URL")
1152− assert.Contains(t, location, "redirect_uri=", "Expected redirect_uri in redirect URL")
1153− assert.Contains(t, location, "state=", "Expected state parameter in redirect URL")
1154−}
1155−
11561174func TestAuthOnlyEndpointUnauthorizedOnExpiration(t *testing.T) {
11571175 test, err := NewAuthOnlyEndpointTest("", func(opts *options.Options) {
11581176 opts.Cookie.Expire = time.Duration(24) * time.Hour
@@ -1256,7 +1274,7 @@ func TestAuthOnlyEndpointSetXAuthRequestHeaders(t *testing.T) {
12561274 pcTest.validateUser = true
12571275
12581276 pcTest.rw = httptest.NewRecorder()
1259− pcTest.req, _ = http.NewRequest("GET",
1277+ pcTest.req, _ = http.NewRequest(http.MethodGet,
12601278 pcTest.opts.ProxyPrefix+authOnlyPath, nil)
12611279
12621280 created := time.Now()
@@ -1349,7 +1367,7 @@ func TestAuthOnlyEndpointSetBasicAuthTrueRequestHeaders(t *testing.T) {
13491367 pcTest.validateUser = true
13501368
13511369 pcTest.rw = httptest.NewRecorder()
1352− pcTest.req, _ = http.NewRequest("GET",
1370+ pcTest.req, _ = http.NewRequest(http.MethodGet,
13531371 pcTest.opts.ProxyPrefix+authOnlyPath, nil)
13541372
13551373 created := time.Now()
@@ -1429,7 +1447,7 @@ func TestAuthOnlyEndpointSetBasicAuthFalseRequestHeaders(t *testing.T) {
14291447 pcTest.validateUser = true
14301448
14311449 pcTest.rw = httptest.NewRecorder()
1432− pcTest.req, _ = http.NewRequest("GET",
1450+ pcTest.req, _ = http.NewRequest(http.MethodGet,
14331451 pcTest.opts.ProxyPrefix+authOnlyPath, nil)
14341452
14351453 created := time.Now()
@@ -1477,7 +1495,7 @@ func TestAuthSkippedForPreflightRequests(t *testing.T) {
14771495 }
14781496 proxy.provider = NewTestProvider(upstreamURL, "")
14791497 rw := httptest.NewRecorder()
1480− req, _ := http.NewRequest("OPTIONS", "/preflight-request", nil)
1498+ req, _ := http.NewRequest(http.MethodOptions, "/preflight-request", nil)
14811499 proxy.ServeHTTP(rw, req)
14821500
14831501 assert.Equal(t, 200, rw.Code)
@@ -1634,19 +1652,19 @@ func TestRequestSignature(t *testing.T) {
16341652 resp string
16351653 }{
16361654 "No request signature": {
1637− method: "GET",
1655+ method: http.MethodGet,
16381656 body: "",
16391657 key: "",
16401658 resp: "no signature received",
16411659 },
16421660 "Get request": {
1643− method: "GET",
1661+ method: http.MethodGet,
16441662 body: "",
16451663 key: "7d9e1aa87a5954e6f9fc59266b3af9d7c35fda2d",
16461664 resp: "signatures match",
16471665 },
16481666 "Post request": {
1649− method: "POST",
1667+ method: http.MethodPost,
16501668 body: `{ "hello": "world!" }`,
16511669 key: "d90df39e2d19282840252612dd7c81421a372f61",
16521670 resp: "signatures match",
@@ -2069,6 +2087,44 @@ func Test_noCacheHeaders(t *testing.T) {
20692087 })
20702088}
20712089
2090+func TestSignOutCallsBackendLogoutURL(t *testing.T) {
2091+ const testIDToken = "test-id-token-12345"
2092+ var receivedURL string
2093+ backendLogoutServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
2094+ receivedURL = req.URL.String()
2095+ rw.WriteHeader(http.StatusOK)
2096+ }))
2097+ defer backendLogoutServer.Close()
2098+
2099+ opts := baseTestOptions()
2100+ opts.Providers[0].BackendLogoutURL = backendLogoutServer.URL + "/logout?id_token_hint={id_token}"
2101+ err := validation.Validate(opts)
2102+ require.NoError(t, err)
2103+
2104+ proxy, err := NewOAuthProxy(opts, func(string) bool { return true })
2105+ require.NoError(t, err)
2106+
2107+ // Save a session with IDToken so backend logout can use it
2108+ rw := httptest.NewRecorder()
2109+ req := httptest.NewRequest(http.MethodGet, "/", nil)
2110+ err = proxy.sessionStore.Save(rw, req, &sessions.SessionState{
2111+ Email: "user@example.com",
2112+ IDToken: testIDToken,
2113+ })
2114+ require.NoError(t, err)
2115+ cookie := rw.Header().Values("Set-Cookie")[0]
2116+
2117+ // Hit sign_out with the session cookie; backend logout should be called before session is cleared
2118+ signOutReq := httptest.NewRequest(http.MethodGet, "/oauth2/sign_out", nil)
2119+ signOutReq.Header.Set("Cookie", cookie)
2120+ rec := httptest.NewRecorder()
2121+ proxy.ServeHTTP(rec, signOutReq)
2122+
2123+ assert.Equal(t, http.StatusFound, rec.Code, "sign_out should redirect")
2124+ assert.Contains(t, receivedURL, "id_token_hint="+testIDToken,
2125+ "backend logout URL should have been called with id_token from session")
2126+}
2127+
20722128func baseTestOptions() *options.Options {
20732129 opts := options.NewOptions()
20742130 opts.Cookie.Secret = rawCookieSecret
@@ -2133,7 +2189,33 @@ func TestTrustedIPs(t *testing.T) {
21332189 reverseProxy: false,
21342190 realClientIPHeader: "X-Real-IP", // Default value
21352191 req: func() *http.Request {
2136− req, _ := http.NewRequest("GET", "/", nil)
2192+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
2193+ return req
2194+ }(),
2195+ expectTrusted: false,
2196+ },
2197+ // Check Unix socket with no trusted IPs configured does not error.
2198+ {
2199+ name: "UnixSocketWithoutTrustedIPs",
2200+ trustedIPs: nil,
2201+ reverseProxy: false,
2202+ realClientIPHeader: "X-Real-IP",
2203+ req: func() *http.Request {
2204+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
2205+ req.RemoteAddr = "@"
2206+ return req
2207+ }(),
2208+ expectTrusted: false,
2209+ },
2210+ // Check Unix socket with trusted IPs configured returns false (no IP to match).
2211+ {
2212+ name: "UnixSocketWithTrustedIPs",
2213+ trustedIPs: []string{"127.0.0.1"},
2214+ reverseProxy: false,
2215+ realClientIPHeader: "X-Real-IP",
2216+ req: func() *http.Request {
2217+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
2218+ req.RemoteAddr = "@"
21372219 return req
21382220 }(),
21392221 expectTrusted: false,
@@ -2145,7 +2227,7 @@ func TestTrustedIPs(t *testing.T) {
21452227 reverseProxy: false,
21462228 realClientIPHeader: "X-Real-IP", // Default value
21472229 req: func() *http.Request {
2148− req, _ := http.NewRequest("GET", "/", nil)
2230+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
21492231 req.RemoteAddr = "127.0.0.1:43670"
21502232 return req
21512233 }(),
@@ -2158,7 +2240,7 @@ func TestTrustedIPs(t *testing.T) {
21582240 reverseProxy: true,
21592241 realClientIPHeader: "X-Real-IP", // Default value
21602242 req: func() *http.Request {
2161− req, _ := http.NewRequest("GET", "/", nil)
2243+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
21622244 req.RemoteAddr = "127.0.0.1:44324"
21632245 return req
21642246 }(),
@@ -2171,7 +2253,7 @@ func TestTrustedIPs(t *testing.T) {
21712253 reverseProxy: true,
21722254 realClientIPHeader: "X-Forwarded-For",
21732255 req: func() *http.Request {
2174− req, _ := http.NewRequest("GET", "/", nil)
2256+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
21752257 req.Header.Add("X-Forwarded-For", "127.0.0.1")
21762258 return req
21772259 }(),
@@ -2184,7 +2266,7 @@ func TestTrustedIPs(t *testing.T) {
21842266 reverseProxy: true,
21852267 realClientIPHeader: "X-Forwarded-For",
21862268 req: func() *http.Request {
2187− req, _ := http.NewRequest("GET", "/", nil)
2269+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
21882270 req.Header.Add("X-Forwarded-For", "::1")
21892271 return req
21902272 }(),
@@ -2197,7 +2279,7 @@ func TestTrustedIPs(t *testing.T) {
21972279 reverseProxy: true,
21982280 realClientIPHeader: "X-Forwarded-For",
21992281 req: func() *http.Request {
2200− req, _ := http.NewRequest("GET", "/", nil)
2282+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
22012283 req.Header.Add("X-Forwarded-For", "12.34.56.78")
22022284 return req
22032285 }(),
@@ -2210,7 +2292,7 @@ func TestTrustedIPs(t *testing.T) {
22102292 reverseProxy: true,
22112293 realClientIPHeader: "X-Forwarded-For",
22122294 req: func() *http.Request {
2213− req, _ := http.NewRequest("GET", "/", nil)
2295+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
22142296 req.Header.Add("X-Forwarded-For", "::2")
22152297 return req
22162298 }(),
@@ -2223,7 +2305,7 @@ func TestTrustedIPs(t *testing.T) {
22232305 reverseProxy: true,
22242306 realClientIPHeader: "X-Forwarded-For",
22252307 req: func() *http.Request {
2226− req, _ := http.NewRequest("GET", "/", nil)
2308+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
22272309 req.Header.Add("X-Real-IP", "::1")
22282310 return req
22292311 }(),
@@ -2236,7 +2318,7 @@ func TestTrustedIPs(t *testing.T) {
22362318 reverseProxy: true,
22372319 realClientIPHeader: "X-Forwarded-For",
22382320 req: func() *http.Request {
2239− req, _ := http.NewRequest("GET", "/", nil)
2321+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
22402322 req.Header.Add("X-Forwarded-For", "adsfljk29242as!!")
22412323 return req
22422324 }(),
@@ -2249,7 +2331,7 @@ func TestTrustedIPs(t *testing.T) {
22492331 reverseProxy: false,
22502332 realClientIPHeader: "X-Real-IP",
22512333 req: func() *http.Request {
2252− req, _ := http.NewRequest("GET", "/", nil)
2334+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
22532335 req.RemoteAddr = "adsfljk29242as!!"
22542336 return req
22552337 }(),
@@ -2345,12 +2427,12 @@ func Test_buildRoutesAllowlist(t *testing.T) {
23452427 },
23462428 expectedRoutes: []expectedAllowedRoute{
23472429 {
2348− method: "GET",
2430+ method: http.MethodGet,
23492431 negate: false,
23502432 regexString: "^/foo/bar",
23512433 },
23522434 {
2353− method: "POST",
2435+ method: http.MethodPost,
23542436 negate: false,
23552437 regexString: "^/baz/[0-9]+/thing",
23562438 },
@@ -2403,11 +2485,11 @@ func Test_buildRoutesAllowlist(t *testing.T) {
24032485 regexString: "^/baz/[0-9]+/thing/regex",
24042486 },
24052487 {
2406− method: "GET",
2488+ method: http.MethodGet,
24072489 regexString: "^/foo/bar",
24082490 },
24092491 {
2410− method: "POST",
2492+ method: http.MethodPost,
24112493 regexString: "^/baz/[0-9]+/thing",
24122494 },
24132495 {
@@ -2559,7 +2641,7 @@ func TestApiRoutes(t *testing.T) {
25592641
25602642 for _, tc := range testCases {
25612643 t.Run(tc.name, func(t *testing.T) {
2562− req, err := http.NewRequest("GET", tc.url, nil)
2644+ req, err := http.NewRequest(http.MethodGet, tc.url, nil)
25632645 req.Header.Set("Accept", tc.contentType)
25642646 assert.NoError(t, err)
25652647
@@ -2597,9 +2679,11 @@ func TestAllowedRequest(t *testing.T) {
25972679 }
25982680 opts.SkipAuthRegex = []string{
25992681 "^/skip/auth/regex$",
2682+ "^/public/.*/endpoint$",
26002683 }
26012684 opts.SkipAuthRoutes = []string{
26022685 "GET=^/skip/auth/routes/get",
2686+ "^/foo/.*/bar$",
26032687 }
26042688 err := validation.Validate(opts)
26052689 assert.NoError(t, err)
@@ -2616,25 +2700,37 @@ func TestAllowedRequest(t *testing.T) {
26162700 }{
26172701 {
26182702 name: "Regex GET allowed",
2619− method: "GET",
2703+ method: http.MethodGet,
26202704 url: "/skip/auth/regex",
26212705 allowed: true,
26222706 },
26232707 {
26242708 name: "Regex POST allowed ",
2625− method: "POST",
2709+ method: http.MethodPost,
26262710 url: "/skip/auth/regex",
26272711 allowed: true,
26282712 },
26292713 {
26302714 name: "Regex denied",
2631− method: "GET",
2715+ method: http.MethodGet,
26322716 url: "/wrong/denied",
26332717 allowed: false,
26342718 },
2719+ {
2720+ name: "Regex allowed with fragment-free path",
2721+ method: http.MethodGet,
2722+ url: "/public/legit/endpoint",
2723+ allowed: true,
2724+ },
2725+ {
2726+ name: "Regex denied when path contains encoded fragment suffix",
2727+ method: http.MethodGet,
2728+ url: "/public/secret%23/endpoint",
2729+ allowed: false,
2730+ },
26352731 {
26362732 name: "Route allowed",
2637− method: "GET",
2733+ method: http.MethodGet,
26382734 url: "/skip/auth/routes/get",
26392735 allowed: true,
26402736 },
@@ -2646,16 +2742,28 @@ func TestAllowedRequest(t *testing.T) {
26462742 },
26472743 {
26482744 name: "Route denied with wrong path",
2649− method: "GET",
2745+ method: http.MethodGet,
26502746 url: "/skip/auth/routes/wrong/path",
26512747 allowed: false,
26522748 },
26532749 {
26542750 name: "Route denied with wrong path and method",
2655− method: "POST",
2751+ method: http.MethodPost,
26562752 url: "/skip/auth/routes/wrong/path",
26572753 allowed: false,
26582754 },
2755+ {
2756+ name: "Route allowed with fragment-free path",
2757+ method: http.MethodGet,
2758+ url: "/foo/public/bar",
2759+ allowed: true,
2760+ },
2761+ {
2762+ name: "Route denied when path contains encoded fragment suffix",
2763+ method: http.MethodGet,
2764+ url: "/foo/secret%23/bar",
2765+ allowed: false,
2766+ },
26592767 }
26602768
26612769 for _, tc := range testCases {
@@ -2696,9 +2804,11 @@ func TestAllowedRequestWithForwardedUriHeader(t *testing.T) {
26962804 }
26972805 opts.SkipAuthRegex = []string{
26982806 "^/skip/auth/regex$",
2807+ "^/public/.*/endpoint$",
26992808 }
27002809 opts.SkipAuthRoutes = []string{
27012810 "GET=^/skip/auth/routes/get",
2811+ "^/foo/.*/bar$",
27022812 }
27032813 err := validation.Validate(opts)
27042814 assert.NoError(t, err)
@@ -2715,25 +2825,37 @@ func TestAllowedRequestWithForwardedUriHeader(t *testing.T) {
27152825 }{
27162826 {
27172827 name: "Regex GET allowed",
2718− method: "GET",
2828+ method: http.MethodGet,
27192829 url: "/skip/auth/regex",
27202830 allowed: true,
27212831 },
27222832 {
27232833 name: "Regex POST allowed ",
2724− method: "POST",
2834+ method: http.MethodPost,
27252835 url: "/skip/auth/regex",
27262836 allowed: true,
27272837 },
27282838 {
27292839 name: "Regex denied",
2730− method: "GET",
2840+ method: http.MethodGet,
27312841 url: "/wrong/denied",
27322842 allowed: false,
27332843 },
2844+ {
2845+ name: "Regex allowed with fragment-free path",
2846+ method: http.MethodGet,
2847+ url: "/public/legit/endpoint",
2848+ allowed: true,
2849+ },
2850+ {
2851+ name: "Regex denied when X-Forwarded-Uri contains an encoded fragment suffix",
2852+ method: http.MethodGet,
2853+ url: "/public/secret%23/endpoint",
2854+ allowed: false,
2855+ },
27342856 {
27352857 name: "Route allowed",
2736− method: "GET",
2858+ method: http.MethodGet,
27372859 url: "/skip/auth/routes/get",
27382860 allowed: true,
27392861 },
@@ -2745,22 +2867,35 @@ func TestAllowedRequestWithForwardedUriHeader(t *testing.T) {
27452867 },
27462868 {
27472869 name: "Route denied with wrong path",
2748− method: "GET",
2870+ method: http.MethodGet,
27492871 url: "/skip/auth/routes/wrong/path",
27502872 allowed: false,
27512873 },
27522874 {
27532875 name: "Route denied with wrong path and method",
2754− method: "POST",
2876+ method: http.MethodPost,
27552877 url: "/skip/auth/routes/wrong/path",
27562878 allowed: false,
27572879 },
2880+ {
2881+ name: "Route allowed with fragment-free path",
2882+ method: http.MethodGet,
2883+ url: "/foo/public/bar",
2884+ allowed: true,
2885+ },
2886+ {
2887+ name: "Route denied when X-Forwarded-Uri contains an encoded fragment suffix",
2888+ method: http.MethodGet,
2889+ url: "/foo/secret%23/bar",
2890+ allowed: false,
2891+ },
27582892 }
27592893
27602894 for _, tc := range testCases {
27612895 t.Run(tc.name, func(t *testing.T) {
27622896 req, err := http.NewRequest(tc.method, opts.ProxyPrefix+authOnlyPath, nil)
27632897 req.Header.Set("X-Forwarded-Uri", tc.url)
2898+ req.RemoteAddr = "127.0.0.1:4180"
27642899 assert.NoError(t, err)
27652900
27662901 rw := httptest.NewRecorder()
@@ -2775,6 +2910,43 @@ func TestAllowedRequestWithForwardedUriHeader(t *testing.T) {
27752910 }
27762911}
27772912
2913+func TestAllowedRequestWithForwardedUriHeaderRequiresTrustedProxy(t *testing.T) {
2914+ upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2915+ w.WriteHeader(200)
2916+ }))
2917+ t.Cleanup(upstreamServer.Close)
2918+
2919+ opts := baseTestOptions()
2920+ opts.ReverseProxy = true
2921+ opts.TrustedProxyIPs = []string{"127.0.0.1/32"}
2922+ opts.UpstreamServers = options.UpstreamConfig{
2923+ Upstreams: []options.Upstream{
2924+ {
2925+ ID: upstreamServer.URL,
2926+ Path: "/",
2927+ URI: upstreamServer.URL,
2928+ },
2929+ },
2930+ }
2931+ opts.SkipAuthRegex = []string{"^/skip/auth/regex$"}
2932+
2933+ err := validation.Validate(opts)
2934+ assert.NoError(t, err)
2935+
2936+ proxy, err := NewOAuthProxy(opts, func(_ string) bool { return true })
2937+ assert.NoError(t, err)
2938+
2939+ req, err := http.NewRequest(http.MethodGet, opts.ProxyPrefix+authOnlyPath, nil)
2940+ assert.NoError(t, err)
2941+ req.RemoteAddr = "192.0.2.10:4180"
2942+ req.Header.Set("X-Forwarded-Uri", "/skip/auth/regex")
2943+
2944+ rw := httptest.NewRecorder()
2945+ proxy.ServeHTTP(rw, req)
2946+
2947+ assert.Equal(t, 401, rw.Code)
2948+}
2949+
27782950func TestAllowedRequestNegateWithoutMethod(t *testing.T) {
27792951 upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
27802952 w.WriteHeader(200)
@@ -2814,37 +2986,37 @@ func TestAllowedRequestNegateWithoutMethod(t *testing.T) {
28142986 }{
28152987 {
28162988 name: "Some static file allowed",
2817− method: "GET",
2989+ method: http.MethodGet,
28182990 url: "/static/file.txt",
28192991 allowed: true,
28202992 },
28212993 {
28222994 name: "POST to contact form allowed",
2823− method: "POST",
2995+ method: http.MethodPost,
28242996 url: "/contact",
28252997 allowed: true,
28262998 },
28272999 {
28283000 name: "Regex POST allowed",
2829− method: "POST",
3001+ method: http.MethodPost,
28303002 url: "/api/public-entity",
28313003 allowed: true,
28323004 },
28333005 {
28343006 name: "Regex POST with trailing slash allowed",
2835− method: "POST",
3007+ method: http.MethodPost,
28363008 url: "/api/public-entity/",
28373009 allowed: true,
28383010 },
28393011 {
28403012 name: "Regex GET api route denied",
2841− method: "GET",
3013+ method: http.MethodGet,
28423014 url: "/api/users",
28433015 allowed: false,
28443016 },
28453017 {
28463018 name: "Regex POST api route denied",
2847− method: "POST",
3019+ method: http.MethodPost,
28483020 url: "/api/users",
28493021 allowed: false,
28503022 },
@@ -2914,37 +3086,37 @@ func TestAllowedRequestNegateWithMethod(t *testing.T) {
29143086 }{
29153087 {
29163088 name: "Some static file allowed",
2917− method: "GET",
3089+ method: http.MethodGet,
29183090 url: "/static/file.txt",
29193091 allowed: true,
29203092 },
29213093 {
29223094 name: "POST to contact form not allowed",
2923− method: "POST",
3095+ method: http.MethodPost,
29243096 url: "/contact",
29253097 allowed: false,
29263098 },
29273099 {
29283100 name: "Regex POST allowed",
2929− method: "POST",
3101+ method: http.MethodPost,
29303102 url: "/api/public-entity",
29313103 allowed: true,
29323104 },
29333105 {
29343106 name: "Regex POST with trailing slash allowed",
2935− method: "POST",
3107+ method: http.MethodPost,
29363108 url: "/api/public-entity/",
29373109 allowed: true,
29383110 },
29393111 {
29403112 name: "Regex GET api route denied",
2941− method: "GET",
3113+ method: http.MethodGet,
29423114 url: "/api/users",
29433115 allowed: false,
29443116 },
29453117 {
29463118 name: "Regex POST api route denied",
2947− method: "POST",
3119+ method: http.MethodPost,
29483120 url: "/api/users",
29493121 allowed: false,
29503122 },
@@ -3084,7 +3256,7 @@ func TestProxyAllowedGroups(t *testing.T) {
30843256 t.Fatal(err)
30853257 }
30863258
3087− test.req, _ = http.NewRequest("GET", fmt.Sprintf("/%s", tt.querystring), nil)
3259+ test.req, _ = http.NewRequest(http.MethodGet, fmt.Sprintf("/%s", tt.querystring), nil)
30883260
30893261 test.req.Header.Add("accept", applicationJSON)
30903262 err = test.SaveSession(session)
@@ -3228,7 +3400,7 @@ func TestAuthOnlyAllowedGroupsWithSkipMethods(t *testing.T) {
32283400 {
32293401 name: "UserWithGroupSkipAuthPreflight",
32303402 groups: []string{"a", "c"},
3231− method: "OPTIONS",
3403+ method: http.MethodOptions,
32323404 ip: "1.2.3.5:43670",
32333405 withSession: true,
32343406 expectedStatusCode: http.StatusAccepted,
@@ -3236,7 +3408,7 @@ func TestAuthOnlyAllowedGroupsWithSkipMethods(t *testing.T) {
32363408 {
32373409 name: "UserWithGroupTrustedIp",
32383410 groups: []string{"a", "c"},
3239− method: "GET",
3411+ method: http.MethodGet,
32403412 ip: "1.2.3.4:43670",
32413413 withSession: true,
32423414 expectedStatusCode: http.StatusAccepted,
@@ -3244,7 +3416,7 @@ func TestAuthOnlyAllowedGroupsWithSkipMethods(t *testing.T) {
32443416 {
32453417 name: "UserWithoutGroupSkipAuthPreflight",
32463418 groups: []string{"c"},
3247− method: "OPTIONS",
3419+ method: http.MethodOptions,
32483420 ip: "1.2.3.5:43670",
32493421 withSession: true,
32503422 expectedStatusCode: http.StatusForbidden,
@@ -3252,21 +3424,21 @@ func TestAuthOnlyAllowedGroupsWithSkipMethods(t *testing.T) {
32523424 {
32533425 name: "UserWithoutGroupTrustedIp",
32543426 groups: []string{"c"},
3255− method: "GET",
3427+ method: http.MethodGet,
32563428 ip: "1.2.3.4:43670",
32573429 withSession: true,
32583430 expectedStatusCode: http.StatusForbidden,
32593431 },
32603432 {
32613433 name: "UserWithoutSessionSkipAuthPreflight",
3262− method: "OPTIONS",
3434+ method: http.MethodOptions,
32633435 ip: "1.2.3.5:43670",
32643436 withSession: false,
32653437 expectedStatusCode: http.StatusAccepted,
32663438 },
32673439 {
32683440 name: "UserWithoutSessionTrustedIp",
3269− method: "GET",
3441+ method: http.MethodGet,
32703442 ip: "1.2.3.4:43670",
32713443 withSession: false,
32723444 expectedStatusCode: http.StatusAccepted,
@@ -3366,6 +3538,24 @@ func TestAuthOnlyAllowedEmailDomains(t *testing.T) {
33663538 querystring: "?allowed_email_domains=a.b.c.example.com,*.c.example.com",
33673539 expectedStatusCode: http.StatusAccepted,
33683540 },
3541+ {
3542+ name: "UserWithMultipleAtSignsExactDomain",
3543+ email: "attacker@evil.com@example.com",
3544+ querystring: "?allowed_email_domains=example.com",
3545+ expectedStatusCode: http.StatusForbidden,
3546+ },
3547+ {
3548+ name: "UserWithMultipleAtSignsWildcardDomain",
3549+ email: "attacker@evil.com@foo.example.com",
3550+ querystring: "?allowed_email_domains=*.example.com",
3551+ expectedStatusCode: http.StatusForbidden,
3552+ },
3553+ {
3554+ name: "UserWithMultipleAtSignsDotPrefixedDomain",
3555+ email: "attacker@evil.com@foo.example.com",
3556+ querystring: "?allowed_email_domains=.example.com",
3557+ expectedStatusCode: http.StatusForbidden,
3558+ },
33693559 }
33703560
33713561 for _, tc := range testCases {
@@ -3572,3 +3762,49 @@ func TestGetOAuthRedirectURI(t *testing.T) {
35723762 })
35733763 }
35743764}
3765+
3766+func TestIdTokenPlaceholderInSignOut(t *testing.T) {
3767+ opts := baseTestOptions()
3768+ opts.WhitelistDomains = []string{"my-oidc-provider.example.com"}
3769+
3770+ err := validation.Validate(opts)
3771+ assert.NoError(t, err)
3772+
3773+ const emailAddress = "john.doe@example.com"
3774+ const userName = "9fcab5c9b889a557"
3775+ created := time.Now()
3776+
3777+ session := &sessions.SessionState{
3778+ User: userName,
3779+ Groups: []string{"a", "b"},
3780+ Email: emailAddress,
3781+ IDToken: "eYjjjjjj.vvvv.ddd",
3782+ AccessToken: "oauth_token",
3783+ CreatedAt: &created,
3784+ }
3785+
3786+ proxy, err := NewOAuthProxy(opts, func(email string) bool {
3787+ return true
3788+ })
3789+ assert.NoError(t, err)
3790+
3791+ // Save the required session
3792+ rw := httptest.NewRecorder()
3793+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
3794+ err = proxy.sessionStore.Save(rw, req, session)
3795+ assert.NoError(t, err)
3796+
3797+ rw = httptest.NewRecorder()
3798+
3799+ 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/")
3800+ req, _ = http.NewRequest(http.MethodGet, "/oauth2/sign_out?rd="+rdUrl, nil)
3801+ req = middlewareapi.AddRequestScope(req, &middlewareapi.RequestScope{
3802+ RequestID: "11111111-2222-4333-8444-555555555555",
3803+ Session: session,
3804+ })
3805+
3806+ proxy.SignOut(rw, req)
3807+ newLocation := rw.Header().Values("Location")[0]
3808+
3809+ 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)
3810+}
pkg/apis/middleware/scope.go+48−1
@@ -2,9 +2,12 @@ package middleware
22
33import (
44 "context"
5+ "net"
56 "net/http"
7+ "strings"
68
79 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
10+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
811)
912
1013type scopeKey string
@@ -18,9 +21,13 @@ const RequestScopeKey scopeKey = "request-scope"
1821// within the chain.
1922type RequestScope struct {
2023 // ReverseProxy tracks whether OAuth2-Proxy is operating in reverse proxy
21− // mode and if request `X-Forwarded-*` headers should be trusted
24+ // mode and if request `X-Forwarded-*` headers may be trusted
2225 ReverseProxy bool
2326
27+ // TrustedProxies tracks which direct callers are allowed to supply
28+ // forwarded headers when ReverseProxy mode is enabled.
29+ TrustedProxies *ip.NetSet
30+
2431 // RequestID is set to the request's `X-Request-Id` header if set.
2532 // Otherwise a random UUID is set.
2633 RequestID string
@@ -58,3 +65,43 @@ func AddRequestScope(req *http.Request, scope *RequestScope) *http.Request {
5865 ctx := context.WithValue(req.Context(), RequestScopeKey, scope)
5966 return req.WithContext(ctx)
6067}
68+
69+// CanTrustForwardedHeaders returns whether forwarded headers should be
70+// processed for this request.
71+func (s *RequestScope) CanTrustForwardedHeaders(req *http.Request) bool {
72+ if s == nil || req == nil || !s.ReverseProxy || s.TrustedProxies == nil {
73+ return false
74+ }
75+
76+ if isUnixSocketRemoteAddr(req.RemoteAddr) {
77+ return true
78+ }
79+
80+ remoteIP := parseRemoteAddrIP(req.RemoteAddr)
81+ if remoteIP == nil {
82+ return false
83+ }
84+
85+ return s.TrustedProxies.Has(remoteIP)
86+}
87+
88+func parseRemoteAddrIP(remoteAddr string) net.IP {
89+ if remoteAddr == "" {
90+ return nil
91+ }
92+
93+ if ip := net.ParseIP(remoteAddr); ip != nil {
94+ return ip
95+ }
96+
97+ host, _, err := net.SplitHostPort(remoteAddr)
98+ if err != nil {
99+ return nil
100+ }
101+
102+ return net.ParseIP(host)
103+}
104+
105+func isUnixSocketRemoteAddr(remoteAddr string) bool {
106+ return remoteAddr == "@" || strings.HasPrefix(remoteAddr, "/")
107+}
pkg/apis/middleware/scope_test.go+34
@@ -4,6 +4,7 @@ import (
44 "net/http"
55
66 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
7+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
78 . "github.com/onsi/ginkgo/v2"
89 . "github.com/onsi/gomega"
910)
@@ -53,4 +54,37 @@ var _ = Describe("Scope Suite", func() {
5354 })
5455 })
5556 })
57+
58+ Context("CanTrustForwardedHeaders", func() {
59+ var request *http.Request
60+ var scope *middleware.RequestScope
61+
62+ BeforeEach(func() {
63+ var err error
64+ request, err = http.NewRequest("", "http://127.0.0.1/", nil)
65+ Expect(err).ToNot(HaveOccurred())
66+
67+ trustedProxies, err := ip.ParseNetSet([]string{"127.0.0.1"})
68+ Expect(err).ToNot(HaveOccurred())
69+ scope = &middleware.RequestScope{
70+ ReverseProxy: true,
71+ TrustedProxies: trustedProxies,
72+ }
73+ })
74+
75+ It("returns true for a trusted remote address", func() {
76+ request.RemoteAddr = "127.0.0.1:4180"
77+ Expect(scope.CanTrustForwardedHeaders(request)).To(BeTrue())
78+ })
79+
80+ It("returns false for an untrusted remote address", func() {
81+ request.RemoteAddr = "192.0.2.10:4180"
82+ Expect(scope.CanTrustForwardedHeaders(request)).To(BeFalse())
83+ })
84+
85+ It("returns true for unix socket callers", func() {
86+ request.RemoteAddr = "@"
87+ Expect(scope.CanTrustForwardedHeaders(request)).To(BeTrue())
88+ })
89+ })
5690})
pkg/apis/options/cookie.go+3
@@ -24,6 +24,7 @@ type Cookie struct {
2424 CSRFPerRequest bool `flag:"cookie-csrf-per-request" cfg:"cookie_csrf_per_request"`
2525 CSRFPerRequestLimit int `flag:"cookie-csrf-per-request-limit" cfg:"cookie_csrf_per_request_limit"`
2626 CSRFExpire time.Duration `flag:"cookie-csrf-expire" cfg:"cookie_csrf_expire"`
27+ CSRFSameSite string `flag:"cookie-csrf-samesite" cfg:"cookie_csrf_samesite"`
2728}
2829
2930func cookieFlagSet() *pflag.FlagSet {
@@ -42,6 +43,7 @@ func cookieFlagSet() *pflag.FlagSet {
4243 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.")
4344 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.")
4445 flagSet.Duration("cookie-csrf-expire", time.Duration(15)*time.Minute, "expire timeframe for CSRF cookie")
46+ 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.")
4547 return flagSet
4648}
4749
@@ -61,6 +63,7 @@ func cookieDefaults() Cookie {
6163 CSRFPerRequest: false,
6264 CSRFPerRequestLimit: 0,
6365 CSRFExpire: time.Duration(15) * time.Minute,
66+ CSRFSameSite: "",
6467 }
6568}
6669
pkg/apis/options/legacy_options.go+18−14
@@ -51,15 +51,16 @@ func NewLegacyOptions() *LegacyOptions {
5151 },
5252
5353 LegacyProvider: LegacyProvider{
54− ProviderType: "google",
55− AzureTenant: "common",
56− ApprovalPrompt: "force",
57− UserIDClaim: "email",
58− OIDCEmailClaim: "email",
59− OIDCGroupsClaim: "groups",
60− OIDCAudienceClaims: []string{"aud"},
61− OIDCExtraAudiences: []string{},
62− InsecureOIDCSkipNonce: true,
54+ ProviderType: "google",
55+ AzureTenant: "common",
56+ ApprovalPrompt: "force",
57+ UserIDClaim: "email",
58+ OIDCEmailClaim: "email",
59+ OIDCGroupsClaim: "groups",
60+ OIDCAudienceClaims: []string{"aud"},
61+ OIDCExtraAudiences: []string{},
62+ OIDCEnabledSigningAlgs: []string{},
63+ InsecureOIDCSkipNonce: true,
6364 },
6465
6566 Options: *NewOptions(),
@@ -179,10 +180,10 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) {
179180 upstream.URI = ""
180181 upstream.InsecureSkipTLSVerify = ptr.To(false)
181182 upstream.DisableKeepAlives = ptr.To(false)
182− upstream.PassHostHeader = nil
183− upstream.ProxyWebSockets = nil
184− upstream.FlushInterval = nil
185− upstream.Timeout = nil
183+ upstream.PassHostHeader = ptr.To(false)
184+ upstream.ProxyWebSockets = ptr.To(false)
185+ upstream.FlushInterval = ptr.To(DefaultUpstreamFlushInterval)
186+ upstream.Timeout = ptr.To(DefaultUpstreamTimeout)
186187 case "unix":
187188 upstream.Path = "/"
188189 }
@@ -545,6 +546,7 @@ type LegacyProvider struct {
545546 OIDCAudienceClaims []string `flag:"oidc-audience-claim" cfg:"oidc_audience_claims"`
546547 OIDCExtraAudiences []string `flag:"oidc-extra-audience" cfg:"oidc_extra_audiences"`
547548 OIDCPublicKeyFiles []string `flag:"oidc-public-key-file" cfg:"oidc_public_key_files"`
549+ OIDCEnabledSigningAlgs []string `flag:"oidc-enabled-signing-alg" cfg:"oidc_enabled_signing_algs"`
548550 LoginURL string `flag:"login-url" cfg:"login_url"`
549551 AuthRequestResponseMode string `flag:"auth-request-response-mode" cfg:"auth_request_response_mode"`
550552 RedeemURL string `flag:"redeem-url" cfg:"redeem_url"`
@@ -606,6 +608,7 @@ func legacyProviderFlagSet() *pflag.FlagSet {
606608 flagSet.StringSlice("oidc-audience-claim", OIDCAudienceClaims, "which OIDC claims are used as audience to verify against client id")
607609 flagSet.StringSlice("oidc-extra-audience", []string{}, "additional audiences allowed to pass audience verification")
608610 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)")
611+ flagSet.StringSlice("oidc-enabled-signing-alg", []string{}, "accepted signing algorithms for provider to use")
609612 flagSet.String("login-url", "", "Authentication endpoint")
610613 flagSet.String("redeem-url", "", "Token redemption endpoint")
611614 flagSet.String("profile-url", "", "Profile access endpoint")
@@ -691,7 +694,7 @@ func (l LegacyServer) convert() (Server, Server) {
691694}
692695
693696func (l *LegacyProvider) convert() (Providers, error) {
694− providers := Providers{}
697+ providers := make(Providers, 0, 1)
695698
696699 provider := Provider{
697700 ClientID: l.ClientID,
@@ -727,6 +730,7 @@ func (l *LegacyProvider) convert() (Providers, error) {
727730 AudienceClaims: l.OIDCAudienceClaims,
728731 ExtraAudiences: l.OIDCExtraAudiences,
729732 PublicKeyFiles: l.OIDCPublicKeyFiles,
733+ EnabledSigningAlgs: l.OIDCEnabledSigningAlgs,
730734 }
731735
732736 // Support for legacy configuration option
pkg/apis/options/legacy_options_test.go+14−12
@@ -27,6 +27,7 @@ var _ = Describe("Legacy Options", func() {
2727 legacyOpts.LegacyUpstreams.Upstreams = []string{"http://foo.bar/baz", "file:///var/lib/website#/bar", "static://204"}
2828 legacyOpts.LegacyProvider.ClientID = "oauth-proxy"
2929 legacyOpts.LegacyUpstreams.DisableKeepAlives = false
30+ legacyOpts.LegacyProvider.OIDCEnabledSigningAlgs = []string{"RS256", "EdDSA"}
3031
3132 staticCode := 204
3233 opts.UpstreamServers = UpstreamConfig{
@@ -128,6 +129,7 @@ var _ = Describe("Legacy Options", func() {
128129 opts.Providers[0].OIDCConfig.ExtraAudiences = []string{}
129130 opts.Providers[0].OIDCConfig.InsecureSkipNonce = ptr.To(true)
130131 opts.Providers[0].OIDCConfig.InsecureSkipIssuerVerification = ptr.To(false)
132+ opts.Providers[0].OIDCConfig.EnabledSigningAlgs = []string{"RS256", "EdDSA"}
131133 opts.Providers[0].LoginURLParameters = []LoginURLParameter{
132134 {Name: "approval_prompt", Default: []string{"force"}},
133135 }
@@ -204,12 +206,12 @@ var _ = Describe("Legacy Options", func() {
204206 URI: "",
205207 Static: ptr.To(true),
206208 StaticCode: &validStaticCode,
207− InsecureSkipTLSVerify: ptr.To(false),
208− PassHostHeader: nil,
209− ProxyWebSockets: nil,
210− FlushInterval: nil,
211− Timeout: nil,
212− DisableKeepAlives: ptr.To(false),
209+ InsecureSkipTLSVerify: ptr.To(DefaultUpsteamInsecureSkipTLSVerify),
210+ PassHostHeader: ptr.To(DefaultStaticPassHostHeader),
211+ ProxyWebSockets: ptr.To(DefaultStaticProxyWebSockets),
212+ FlushInterval: ptr.To(DefaultUpstreamFlushInterval),
213+ Timeout: ptr.To(DefaultUpstreamTimeout),
214+ DisableKeepAlives: ptr.To(DefaultUpstreamDisableKeepAlives),
213215 }
214216
215217 invalidStatic := "static://abc"
@@ -220,12 +222,12 @@ var _ = Describe("Legacy Options", func() {
220222 URI: "",
221223 Static: ptr.To(true),
222224 StaticCode: &invalidStaticCode,
223− InsecureSkipTLSVerify: ptr.To(false),
224− PassHostHeader: nil,
225− ProxyWebSockets: nil,
226− FlushInterval: nil,
227− Timeout: nil,
228− DisableKeepAlives: ptr.To(false),
225+ InsecureSkipTLSVerify: ptr.To(DefaultUpsteamInsecureSkipTLSVerify),
226+ PassHostHeader: ptr.To(DefaultStaticPassHostHeader),
227+ ProxyWebSockets: ptr.To(DefaultStaticProxyWebSockets),
228+ FlushInterval: ptr.To(DefaultUpstreamFlushInterval),
229+ Timeout: ptr.To(DefaultUpstreamTimeout),
230+ DisableKeepAlives: ptr.To(DefaultUpstreamDisableKeepAlives),
229231 }
230232
231233 invalidHTTP := ":foo"
pkg/apis/options/load.go+1−1
@@ -145,7 +145,7 @@ func loadAndSubstituteEnvs(configFileName string) ([]byte, error) {
145145func registerFlags(v *viper.Viper, prefix string, flagSet *pflag.FlagSet, options interface{}) error {
146146 val := reflect.ValueOf(options)
147147 var typ reflect.Type
148− if val.Kind() == reflect.Ptr {
148+ if val.Kind() == reflect.Pointer {
149149 typ = val.Elem().Type()
150150 } else {
151151 typ = val.Type()
pkg/apis/options/load_test.go+2−2
@@ -282,7 +282,7 @@ var _ = Describe("Load", func() {
282282 Entry("with an invalid config file", &testOptionsTableInput{
283283 configFile: []byte(`slice_option = foo`),
284284 flagSet: func() *pflag.FlagSet { return testOptionsFlagSet },
285− expectedErr: fmt.Errorf("unable to load config file: While parsing config: toml: expected 'false'"),
285+ expectedErr: fmt.Errorf("unable to load config file: While parsing config: toml: expected keyword \"false\""),
286286 expectedOutput: &TestOptions{},
287287 }),
288288 Entry("with an invalid flagset", &testOptionsTableInput{
@@ -329,7 +329,7 @@ var _ = Describe("Load", func() {
329329 Entry("with an unknown option in the config file", &testOptionsTableInput{
330330 configFile: []byte(`unknown_option="foo"`),
331331 flagSet: func() *pflag.FlagSet { return testOptionsFlagSet },
332− expectedErr: fmt.Errorf("error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_option"),
332+ expectedErr: fmt.Errorf("error unmarshalling config: decoding failed due to the following error(s):\n\n'options.TestOptions' has invalid keys: unknown_option"),
333333 // Viper will unmarshal before returning the error, so this is the default output
334334 expectedOutput: &TestOptions{
335335 StringOption: "default",
pkg/apis/options/options.go+2
@@ -24,6 +24,7 @@ type Options struct {
2424 ReadyPath string `flag:"ready-path" cfg:"ready_path"`
2525 ReverseProxy bool `flag:"reverse-proxy" cfg:"reverse_proxy"`
2626 RealClientIPHeader string `flag:"real-client-ip-header" cfg:"real_client_ip_header"`
27+ TrustedProxyIPs []string `flag:"trusted-proxy-ip" cfg:"trusted_proxy_ips"`
2728 TrustedIPs []string `flag:"trusted-ip" cfg:"trusted_ips"`
2829 ForceHTTPS bool `flag:"force-https" cfg:"force_https"`
2930 RawRedirectURL string `flag:"redirect-url" cfg:"redirect_url"`
@@ -119,6 +120,7 @@ func NewFlagSet() *pflag.FlagSet {
119120
120121 flagSet.Bool("reverse-proxy", false, "are we running behind a reverse proxy, controls whether headers like X-Real-Ip are accepted")
121122 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)")
123+ 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.")
122124 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.")
123125 flagSet.Bool("force-https", false, "force HTTPS redirect for HTTP requests")
124126 flagSet.String("redirect-url", "", "the OAuth Redirect URL. ie: \"https://internalapp.yourcompany.com/oauth2/callback\"")
pkg/apis/options/providers.go+14
@@ -134,6 +134,9 @@ type Provider struct {
134134 // The code challenge method
135135 CodeChallengeMethod string `yaml:"code_challenge_method,omitempty"`
136136
137+ // Additional claims to be obtained from the upstream IDP, either from the id_token or from the userinfo endpoint if configured.
138+ AdditionalClaims []string `yaml:"additionalClaims,omitempty"`
139+
137140 // URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session
138141 BackendLogoutURL string `yaml:"backendLogoutURL"`
139142}
@@ -148,6 +151,9 @@ const (
148151 // ADFSProvider is the provider type for ADFS
149152 ADFSProvider ProviderType = "adfs"
150153
154+ // AtlassianProvider is the provider type for Atlassian Cloud
155+ AtlassianProvider ProviderType = "atlassian"
156+
151157 // AzureProvider is the provider type for Azure
152158 AzureProvider ProviderType = "azure"
153159
@@ -163,6 +169,9 @@ const (
163169 // DigitalOceanProvider is the provider type for DigitalOcean
164170 DigitalOceanProvider ProviderType = "digitalocean"
165171
172+ // DTTSSOProvider is the provider type for the DTT SSO
173+ DTTSSOProvider ProviderType = "dtt-sso"
174+
166175 // FacebookProvider is the provider type for Facebook
167176 FacebookProvider ProviderType = "facebook"
168177
@@ -318,6 +327,11 @@ type OIDCOptions struct {
318327 // ExtraAudiences is a list of additional audiences that are allowed
319328 // to pass verification in addition to the client id.
320329 ExtraAudiences []string `yaml:"extraAudiences,omitempty"`
330+ // EnabledSigningAlgs is a list of allowed JWT signing algorithms.
331+ // When discovery is enabled, the effective set is the intersection
332+ // between this list and the provider's discovered supported algorithms.
333+ // By default `RS256` is used if nothing has been discovered or specified.
334+ EnabledSigningAlgs []string `yaml:"enabledSigningAlgs,omitempty"`
321335}
322336
323337type LoginGovOptions struct {
pkg/apis/options/server.go+9
@@ -3,10 +3,19 @@ package options
33// Server represents the configuration for an HTTP(S) server
44type Server struct {
55 // BindAddress is the address on which to serve traffic.
6+ // Different types of bind addresses are supported:
7+ // * `[http://]<addr>:<port>`
8+ // * `fd:<int>` (case insensitive)
9+ // * `unix://<path>`
10+ // Unix sockets are created with default system umask mode, which can be overridden, e.g.: `unix://my-socket,mode=0777`
11+ // Square brackets are required for ipv6 address, e.g. `http://[::1]:4180`
612 // Leave blank or set to "-" to disable.
713 BindAddress string `yaml:"bindAddress,omitempty"`
814
915 // SecureBindAddress is the address on which to serve secure traffic.
16+ // Secure bind addresses need to respond with valid SSL and use the following format:
17+ // * `[https://]<addr>:<port>`
18+ // Square brackets are required for ipv6 address, e.g. `https://[::1]:4180`
1019 // Leave blank or set to "-" to disable.
1120 SecureBindAddress string `yaml:"secureBindAddress,omitempty"`
1221
pkg/apis/options/upstreams.go+28−8
@@ -29,9 +29,15 @@ const (
2929 // DefaultUpstreamPassHostHeader determines if upstreams will pass the host header by default.
3030 DefaultUpstreamPassHostHeader bool = true
3131
32+ // Static upstreams cannot pass the host header.
33+ DefaultStaticPassHostHeader bool = false
34+
3235 // DefaultUpstreamProxyWebSockets determines if upstreams will proxy websockets by default.
3336 DefaultUpstreamProxyWebSockets bool = true
3437
38+ // Static upstreams cannot proxy websockets.
39+ DefaultStaticProxyWebSockets bool = false
40+
3541 // DefaultUpstreamDisableKeepAlives determines if upstreams will disable keep-alives by default.
3642 DefaultUpstreamDisableKeepAlives bool = false
3743)
@@ -56,12 +62,14 @@ type Upstream struct {
5662
5763 // Path is used to map requests to the upstream server.
5864 // The closest match will take precedence and all Paths must be unique.
59− // Path can also take a pattern when used with RewriteTarget.
60− // Path segments can be captured and matched using regular experessions.
65+ // Without RewriteTarget, Path follows gorilla/mux route syntax.
6166 // Eg:
62− // - `^/foo$`: Match only the explicit path `/foo`
63− // - `^/bar/$`: Match any path prefixed with `/bar/`
64− // - `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget
67+ // - `/foo`: Match only the explicit path `/foo`
68+ // - `/bar/`: Match any path prefixed with `/bar/`
69+ // - `/baz/{path:.*}`: Match any path prefixed with `/baz/`
70+ // When RewriteTarget is set, Path is treated as a regular expression.
71+ // Eg: `^/baz/(.*)$` matches any path prefixed with `/baz` and captures the
72+ // remaining path for use with RewriteTarget.
6573 Path string `yaml:"path,omitempty"`
6674
6775 // RewriteTarget allows users to rewrite the request path before it is sent to
@@ -143,19 +151,31 @@ func (u *Upstream) EnsureDefaults() {
143151 if u.Static == nil {
144152 u.Static = ptr.To(DefaultUpstreamStatic)
145153 }
146− if u.FlushInterval == nil {
147− u.FlushInterval = ptr.To(DefaultUpstreamFlushInterval)
148− }
149154 if u.PassHostHeader == nil {
150155 u.PassHostHeader = ptr.To(DefaultUpstreamPassHostHeader)
151156 }
152157 if u.ProxyWebSockets == nil {
153158 u.ProxyWebSockets = ptr.To(DefaultUpstreamProxyWebSockets)
154159 }
160+ if u.FlushInterval == nil {
161+ u.FlushInterval = ptr.To(DefaultUpstreamFlushInterval)
162+ }
155163 if u.Timeout == nil {
156164 u.Timeout = ptr.To(DefaultUpstreamTimeout)
157165 }
158166 if u.DisableKeepAlives == nil {
159167 u.DisableKeepAlives = ptr.To(DefaultUpstreamDisableKeepAlives)
160168 }
169+
170+ // Force defaults compatible with static upstreams.
171+ // This overrides any user provided values to ensure static upstreams behave correctly.
172+ if ptr.Deref(u.Static, DefaultUpstreamStatic) {
173+ u.URI = ""
174+ u.InsecureSkipTLSVerify = ptr.To(DefaultUpsteamInsecureSkipTLSVerify)
175+ u.DisableKeepAlives = ptr.To(DefaultUpstreamDisableKeepAlives)
176+ u.PassHostHeader = ptr.To(DefaultStaticPassHostHeader)
177+ u.ProxyWebSockets = ptr.To(DefaultStaticProxyWebSockets)
178+ u.FlushInterval = ptr.To(DefaultUpstreamFlushInterval)
179+ u.Timeout = ptr.To(DefaultUpstreamTimeout)
180+ }
161181}
pkg/apis/sessions/session_state.go+17−1
@@ -8,6 +8,7 @@ import (
88 "time"
99
1010 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption"
11+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util"
1112 "github.com/pierrec/lz4/v4"
1213 "github.com/vmihailenco/msgpack/v5"
1314)
@@ -28,6 +29,9 @@ type SessionState struct {
2829 Groups []string `msgpack:"g,omitempty"`
2930 PreferredUsername string `msgpack:"pu,omitempty"`
3031
32+ // Additional claims
33+ AdditionalClaims map[string]interface{} `msgpack:"ac,omitempty"`
34+
3135 // Internal helpers, not serialized
3236 Clock func() time.Time `msgpack:"-"` // override for time.Now, for testing
3337 Lock Lock `msgpack:"-"`
@@ -123,6 +127,8 @@ func (s *SessionState) String() string {
123127 }
124128 if s.RefreshToken != "" {
125129 o += " refresh_token:true"
130+ } else {
131+ o += " refresh_token:false"
126132 }
127133 if len(s.Groups) > 0 {
128134 o += fmt.Sprintf(" groups:%v", s.Groups)
@@ -156,8 +162,18 @@ func (s *SessionState) GetClaim(claim string) []string {
156162 case "preferred_username":
157163 return []string{s.PreferredUsername}
158164 default:
159− return []string{}
165+ return s.getAdditionalClaim(claim)
166+ }
167+}
168+
169+func (s *SessionState) getAdditionalClaim(claim string) []string {
170+ if value, ok := s.AdditionalClaims[claim]; ok {
171+ var result []string
172+ if err := util.CoerceClaim(value, &result); err == nil {
173+ return result
174+ }
160175 }
176+ return []string{}
161177}
162178
163179// CheckNonce compares the Nonce against a potential hash of it
pkg/apis/sessions/session_state_test.go+98−5
@@ -4,6 +4,7 @@ import (
44 "crypto/rand"
55 "fmt"
66 "io"
7+ "strings"
78 "testing"
89 "time"
910
@@ -57,7 +58,7 @@ func TestString(t *testing.T) {
5758 User: "some.user",
5859 PreferredUsername: "preferred.user",
5960 },
60− expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user}",
61+ expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user refresh_token:false}",
6162 },
6263 {
6364 name: "Full Session",
@@ -81,7 +82,7 @@ func TestString(t *testing.T) {
8182 PreferredUsername: "preferred.user",
8283 CreatedAt: &created,
8384 },
84− expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user created:2000-01-01 00:00:00 +0000 UTC}",
85+ expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user created:2000-01-01 00:00:00 +0000 UTC refresh_token:false}",
8586 },
8687 {
8788 name: "With an ExpiresOn",
@@ -91,7 +92,7 @@ func TestString(t *testing.T) {
9192 PreferredUsername: "preferred.user",
9293 ExpiresOn: &expires,
9394 },
94− expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user expires:2000-01-01 01:00:00 +0000 UTC}",
95+ expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user expires:2000-01-01 01:00:00 +0000 UTC refresh_token:false}",
9596 },
9697 {
9798 name: "With an AccessToken",
@@ -101,7 +102,7 @@ func TestString(t *testing.T) {
101102 PreferredUsername: "preferred.user",
102103 AccessToken: "access.token",
103104 },
104− expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user token:true}",
105+ expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user token:true refresh_token:false}",
105106 },
106107 {
107108 name: "With an IDToken",
@@ -111,7 +112,7 @@ func TestString(t *testing.T) {
111112 PreferredUsername: "preferred.user",
112113 IDToken: "id.token",
113114 },
114− expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user id_token:true}",
115+ expected: "Session{email:email@email.email user:some.user PreferredUsername:preferred.user id_token:true refresh_token:false}",
115116 },
116117 {
117118 name: "With a RefreshToken",
@@ -222,6 +223,23 @@ func TestEncodeAndDecodeSessionState(t *testing.T) {
222223 Nonce: []byte("abcdef1234567890abcdef1234567890"),
223224 Groups: []string{"group-a", "group-b"},
224225 },
226+ "With additional claims": {
227+ Email: "username@example.com",
228+ User: "username",
229+ PreferredUsername: "preferred.username",
230+ AccessToken: "AccessToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7",
231+ IDToken: "IDToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7",
232+ CreatedAt: &created,
233+ ExpiresOn: &expires,
234+ RefreshToken: "RefreshToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7",
235+ Nonce: []byte("abcdef1234567890abcdef1234567890"),
236+ Groups: []string{"group-a", "group-b"},
237+ AdditionalClaims: map[string]interface{}{
238+ "custom_claim_1": "value1",
239+ "custom_claim_2": true,
240+ "custom_claim_3": []interface{}{"item1", "item2"},
241+ },
242+ },
225243 }
226244
227245 for _, secretSize := range []int{16, 24, 32} {
@@ -289,3 +307,78 @@ func compareSessionStates(t *testing.T, expected *SessionState, actual *SessionS
289307 act.ExpiresOn = nil
290308 assert.Equal(t, exp, act)
291309}
310+
311+func TestGetClaim(t *testing.T) {
312+ createdAt := time.Now()
313+ expiresOn := createdAt.Add(1 * time.Hour)
314+
315+ ss := &SessionState{
316+ CreatedAt: &createdAt,
317+ ExpiresOn: &expiresOn,
318+ AccessToken: "AccessToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7",
319+ IDToken: "IDToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7",
320+ RefreshToken: "RefreshToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7",
321+ Email: "user@example.com",
322+ User: "user123",
323+ Groups: []string{"group1", "group2"},
324+ PreferredUsername: "preferred_user",
325+ AdditionalClaims: map[string]interface{}{
326+ "custom_claim_1": "value1",
327+ "custom_claim_2": true,
328+ "custom_claim_3": []string{"item1", "item2"},
329+ },
330+ }
331+
332+ tests := []struct {
333+ claim string
334+ want []string
335+ }{
336+ {"access_token", []string{"AccessToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7"}},
337+ {"id_token", []string{"IDToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7"}},
338+ {"refresh_token", []string{"RefreshToken.12349871293847fdsaihf9238h4f91h8fr.1349f831y98fd7"}},
339+ {"created_at", []string{createdAt.String()}},
340+ {"expires_on", []string{expiresOn.String()}},
341+ {"email", []string{"user@example.com"}},
342+ {"user", []string{"user123"}},
343+ {"groups", []string{"group1", "group2"}},
344+ {"preferred_username", []string{"preferred_user"}},
345+ {"custom_claim_1", []string{"value1"}},
346+ {"custom_claim_2", []string{"true"}},
347+ {"custom_claim_3", []string{"[\"item1\",\"item2\"]"}},
348+ }
349+
350+ for _, tt := range tests {
351+ t.Run(tt.claim, func(t *testing.T) {
352+ gs := NewWithT(t)
353+ gs.Expect(ss.GetClaim(tt.claim)).To(Equal(tt.want))
354+ })
355+ }
356+}
357+
358+func TestSessionState_String_RefreshTokenFalse(t *testing.T) {
359+ session := &SessionState{
360+ Email: "test@example.com",
361+ User: "testuser",
362+ // No RefreshToken set
363+ }
364+
365+ result := session.String()
366+
367+ if !strings.Contains(result, "refresh_token:false") {
368+ t.Errorf("Expected 'refresh_token:false' in output, got: %s", result)
369+ }
370+}
371+
372+func TestSessionState_String_RefreshTokenTrue(t *testing.T) {
373+ session := &SessionState{
374+ Email: "test@example.com",
375+ User: "testuser",
376+ RefreshToken: "some-token",
377+ }
378+
379+ result := session.String()
380+
381+ if !strings.Contains(result, "refresh_token:true") {
382+ t.Errorf("Expected 'refresh_token:true' in output, got: %s", result)
383+ }
384+}
pkg/app/redirect/director_test.go+33−2
@@ -4,6 +4,7 @@ import (
44 "net/http"
55
66 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
7+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
78 . "github.com/onsi/ginkgo/v2"
89 . "github.com/onsi/gomega"
910)
@@ -33,9 +34,16 @@ var _ = Describe("Director Suite", func() {
3334 req.Header.Add(header, value)
3435 }
3536 }
36− req = middleware.AddRequestScope(req, &middleware.RequestScope{
37+ scope := &middleware.RequestScope{
3738 ReverseProxy: in.reverseProxy,
38− })
39+ }
40+ if in.reverseProxy {
41+ req.RemoteAddr = "127.0.0.1:4180"
42+ trustedProxies, err := ip.ParseNetSet([]string{"127.0.0.1"})
43+ Expect(err).ToNot(HaveOccurred())
44+ scope.TrustedProxies = trustedProxies
45+ }
46+ req = middleware.AddRequestScope(req, scope)
3947
4048 redirect, err := appDirector.GetRedirect(req)
4149 Expect(err).ToNot(HaveOccurred())
@@ -174,4 +182,27 @@ var _ = Describe("Director Suite", func() {
174182 expectedRedirect: "https://a-service.example.com/foo/bar",
175183 }),
176184 )
185+
186+ It("ignores forwarded headers from an untrusted remote address", func() {
187+ appDirector := NewAppDirector(AppDirectorOpts{
188+ ProxyPrefix: testProxyPrefix,
189+ Validator: testValidator(true),
190+ })
191+
192+ req, _ := http.NewRequest("GET", "https://oauth.example.com/foo?bar", nil)
193+ req.RemoteAddr = "192.0.2.10:4180"
194+ req.Header.Add("X-Forwarded-Proto", "https")
195+ req.Header.Add("X-Forwarded-Host", "a-service.example.com")
196+ req.Header.Add("X-Forwarded-Uri", fooBar)
197+ trustedProxies, err := ip.ParseNetSet([]string{"127.0.0.1"})
198+ Expect(err).ToNot(HaveOccurred())
199+ req = middleware.AddRequestScope(req, &middleware.RequestScope{
200+ ReverseProxy: true,
201+ TrustedProxies: trustedProxies,
202+ })
203+
204+ redirect, err := appDirector.GetRedirect(req)
205+ Expect(err).ToNot(HaveOccurred())
206+ Expect(redirect).To(Equal("/foo?bar"))
207+ })
177208})
pkg/authentication/hmacauth/hmacauth_test.go+1−1
@@ -286,7 +286,7 @@ func TestSendAuthenticatedPostRequestToServer(t *testing.T) {
286286 upstream := httptest.NewServer(
287287 http.HandlerFunc(authenticator.Authenticate))
288288
289− req, err := http.NewRequest("POST", upstream.URL+"/foo/bar",
289+ req, err := http.NewRequest(http.MethodPost, upstream.URL+"/foo/bar",
290290 io.NopCloser(&fakeNetConn{reqBody: payload}))
291291 if err != nil {
292292 panic(err)
pkg/cookies/cookies.go+18−8
@@ -7,14 +7,24 @@ import (
77 "strings"
88 "time"
99
10− "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
1110 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
1211 requestutil "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests/util"
1312)
1413
14+type CookieOptions struct {
15+ Name string
16+ Value string
17+ Domains []string
18+ Expiration time.Duration
19+ SameSite string
20+ Path string
21+ HTTPOnly bool
22+ Secure bool
23+}
24+
1525// MakeCookieFromOptions constructs a cookie based on the given *options.CookieOptions,
1626// value and creation time
17−func MakeCookieFromOptions(req *http.Request, name string, value string, opts *options.Cookie, expiration time.Duration) *http.Cookie {
27+func MakeCookieFromOptions(req *http.Request, opts *CookieOptions) *http.Cookie {
1828 domain := GetCookieDomain(req, opts.Domains)
1929 // If nothing matches, create the cookie with the shortest domain
2030 if domain == "" && len(opts.Domains) > 0 {
@@ -26,8 +36,8 @@ func MakeCookieFromOptions(req *http.Request, name string, value string, opts *o
2636 }
2737
2838 c := &http.Cookie{
29− Name: name,
30− Value: value,
39+ Name: opts.Name,
40+ Value: opts.Value,
3141 Path: opts.Path,
3242 Domain: domain,
3343 HttpOnly: opts.HTTPOnly,
@@ -35,9 +45,9 @@ func MakeCookieFromOptions(req *http.Request, name string, value string, opts *o
3545 SameSite: ParseSameSite(opts.SameSite),
3646 }
3747
38− if expiration > time.Duration(0) {
39− c.MaxAge = int(expiration.Seconds())
40− } else if expiration < time.Duration(0) {
48+ if opts.Expiration > time.Duration(0) {
49+ c.MaxAge = int(opts.Expiration.Seconds())
50+ } else if opts.Expiration < time.Duration(0) {
4151 c.MaxAge = -1
4252 }
4353
@@ -58,7 +68,7 @@ func GetCookieDomain(req *http.Request, cookieDomains []string) string {
5868 return ""
5969}
6070
61−// Parse a valid http.SameSite value from a user supplied string for use of making cookies.
71+// ParseSameSite a valid http.SameSite value from a user supplied string for use of making cookies.
6272func ParseSameSite(v string) http.SameSite {
6373 switch v {
6474 case "lax":
pkg/cookies/cookies_suite_test.go+4
@@ -17,6 +17,10 @@ const (
1717 cookieDomain = "o2p.cookies.test"
1818 cookiePath = "/cookie-tests"
1919
20+ sameSiteLax = "lax"
21+ sameSiteStrict = "strict"
22+ sameSiteNone = "none"
23+
2024 nowEpoch = 1609366421
2125)
2226
pkg/cookies/cookies_test.go+39−51
@@ -5,9 +5,8 @@ import (
55 "net/http"
66 "time"
77
8− "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
9−
108 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
9+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
1110 . "github.com/onsi/ginkgo/v2"
1211 . "github.com/onsi/gomega"
1312)
@@ -32,8 +31,13 @@ var _ = Describe("Cookie Tests", func() {
3231
3332 if in.xForwardedHost != "" {
3433 req.Header.Add("X-Forwarded-Host", in.xForwardedHost)
34+ req.RemoteAddr = "127.0.0.1:4180"
35+ trustedProxies, err := ip.ParseNetSet([]string{"127.0.0.1"})
36+ Expect(err).ToNot(HaveOccurred())
37+
3538 req = middlewareapi.AddRequestScope(req, &middlewareapi.RequestScope{
36− ReverseProxy: true,
39+ ReverseProxy: true,
40+ TrustedProxies: trustedProxies,
3741 })
3842 }
3943
@@ -82,16 +86,12 @@ var _ = Describe("Cookie Tests", func() {
8286 Context("MakeCookieFromOptions", func() {
8387 type makeCookieFromOptionsTableInput struct {
8488 host string
85− name string
86− value string
87− opts options.Cookie
88− expiration time.Duration
89+ opts CookieOptions
8990 now time.Time
9091 expectedOutput int
9192 }
9293
9394 validName := "_oauth2_proxy"
94− validSecret := "secretthirtytwobytes+abcdefghijk"
9595 domains := []string{"www.cookies.test"}
9696
9797 now := time.Now()
@@ -106,62 +106,50 @@ var _ = Describe("Cookie Tests", func() {
106106 )
107107 Expect(err).ToNot(HaveOccurred())
108108
109− Expect(MakeCookieFromOptions(req, in.name, in.value, &in.opts, in.expiration).MaxAge).To(Equal(in.expectedOutput))
109+ Expect(MakeCookieFromOptions(req, &in.opts).MaxAge).To(Equal(in.expectedOutput))
110110 },
111111 Entry("persistent cookie", makeCookieFromOptionsTableInput{
112− host: "www.cookies.test",
113− name: validName,
114− value: "1",
115− opts: options.Cookie{
116− Name: validName,
117− Secret: validSecret,
118− Domains: domains,
119− Path: "",
120− Expire: time.Hour,
121− Refresh: 15 * time.Minute,
122− Secure: true,
123− HTTPOnly: false,
124− SameSite: "",
112+ host: "www.cookies.test",
113+ opts: CookieOptions{
114+ Name: validName,
115+ Value: "1",
116+ Domains: domains,
117+ Expiration: 15 * time.Minute,
118+ SameSite: "",
119+ Path: "",
120+ HTTPOnly: false,
121+ Secure: true,
125122 },
126− expiration: 15 * time.Minute,
127123 now: now,
128124 expectedOutput: int((15 * time.Minute).Seconds()),
129125 }),
130126 Entry("persistent cookie to be cleared", makeCookieFromOptionsTableInput{
131− host: "www.cookies.test",
132− name: validName,
133− value: "1",
134− opts: options.Cookie{
135− Name: validName,
136− Secret: validSecret,
137− Domains: domains,
138− Path: "",
139− Expire: time.Hour * -1,
140− Refresh: 15 * time.Minute,
141− Secure: true,
142− HTTPOnly: false,
143− SameSite: "",
127+ host: "www.cookies.test",
128+ opts: CookieOptions{
129+ Name: validName,
130+ Value: "1",
131+ Domains: domains,
132+ Expiration: time.Hour * -1,
133+ SameSite: "",
134+ Path: "",
135+ HTTPOnly: false,
136+ Secure: true,
144137 },
145− expiration: time.Hour * -1,
146138 now: now,
147139 expectedOutput: -1,
148140 }),
149141 Entry("session cookie", makeCookieFromOptionsTableInput{
150− host: "www.cookies.test",
151− name: validName,
152− value: "1",
153− opts: options.Cookie{
154− Name: validName,
155− Secret: validSecret,
156− Domains: domains,
157− Path: "",
158− Expire: 0,
159− Refresh: 15 * time.Minute,
160− Secure: true,
161− HTTPOnly: false,
162− SameSite: "",
142+ host: "www.cookies.test",
143+ opts: CookieOptions{
144+ Name: validName,
145+ Value: "1",
146+ Domains: domains,
147+ Expiration: 0,
148+ SameSite: "",
149+ Path: "",
150+ HTTPOnly: false,
151+ Secure: true,
163152 },
164− expiration: 0,
165153 now: now,
166154 expectedOutput: expectedMaxAge,
167155 }),
pkg/cookies/csrf.go+34−15
@@ -134,6 +134,15 @@ func (c *csrf) SetSessionNonce(s *sessions.SessionState) {
134134 s.Nonce = c.OIDCNonce
135135}
136136
137+// getCSRFSameSite get the CSRF same site
138+func getCSRFSameSite(opts *options.Cookie) string {
139+ sameSite := opts.CSRFSameSite
140+ if sameSite == "" {
141+ sameSite = opts.SameSite
142+ }
143+ return sameSite
144+}
145+
137146// SetCookie encodes the CSRF to a signed cookie and sets it on the ResponseWriter
138147func (c *csrf) SetCookie(rw http.ResponseWriter, req *http.Request) (*http.Cookie, error) {
139148 encoded, err := c.encodeCookie()
@@ -141,13 +150,18 @@ func (c *csrf) SetCookie(rw http.ResponseWriter, req *http.Request) (*http.Cooki
141150 return nil, err
142151 }
143152
144− cookie := MakeCookieFromOptions(
145− req,
146− c.cookieName(),
147− encoded,
148− c.cookieOpts,
149− c.cookieOpts.CSRFExpire,
150− )
153+ csrfCookieOptions := &CookieOptions{
154+ Name: c.cookieName(),
155+ Value: encoded,
156+ Domains: c.cookieOpts.Domains,
157+ Expiration: c.cookieOpts.CSRFExpire,
158+ SameSite: getCSRFSameSite(c.cookieOpts),
159+ Path: c.cookieOpts.Path,
160+ HTTPOnly: c.cookieOpts.HTTPOnly,
161+ Secure: c.cookieOpts.Secure,
162+ }
163+
164+ cookie := MakeCookieFromOptions(req, csrfCookieOptions)
151165 http.SetCookie(rw, cookie)
152166
153167 return cookie, nil
@@ -197,13 +211,18 @@ func ClearExtraCsrfCookies(opts *options.Cookie, rw http.ResponseWriter, req *ht
197211
198212// ClearCookie removes the CSRF cookie
199213func (c *csrf) ClearCookie(rw http.ResponseWriter, req *http.Request) {
200− http.SetCookie(rw, MakeCookieFromOptions(
201− req,
202− c.cookieName(),
203− "",
204− c.cookieOpts,
205− time.Hour*-1,
206− ))
214+ csrfCookieOptions := &CookieOptions{
215+ Name: c.cookieName(),
216+ Value: "",
217+ Domains: c.cookieOpts.Domains,
218+ Expiration: time.Hour * -1,
219+ SameSite: getCSRFSameSite(c.cookieOpts),
220+ Path: c.cookieOpts.Path,
221+ HTTPOnly: c.cookieOpts.HTTPOnly,
222+ Secure: c.cookieOpts.Secure,
223+ }
224+
225+ http.SetCookie(rw, MakeCookieFromOptions(req, csrfCookieOptions))
207226}
208227
209228// encodeCookie MessagePack encodes and encrypts the CSRF and then creates a
@@ -234,7 +253,7 @@ func decodeCSRFCookie(cookie *http.Cookie, opts *options.Cookie) (*csrf, error)
234253 return nil, fmt.Errorf("error getting cookie secret: %v", err)
235254 }
236255
237− val, t, ok := encryption.Validate(cookie, secret, opts.Expire)
256+ val, t, ok := encryption.Validate(cookie, secret, opts.CSRFExpire)
238257 if !ok {
239258 return nil, errors.New("CSRF cookie failed validation")
240259 }
pkg/cookies/csrf_per_request_test.go+12−7
@@ -216,13 +216,18 @@ var _ = Describe("CSRF Cookie with non-fixed name Tests", func() {
216216 for _, csrf := range []*csrf{privateCSRF1, privateCSRF2, privateCSRF3} {
217217 encoded, err := csrf.encodeCookie()
218218 Expect(err).ToNot(HaveOccurred())
219− cookie := MakeCookieFromOptions(
220− req,
221− csrf.cookieName(),
222− encoded,
223− csrf.cookieOpts,
224− csrf.cookieOpts.CSRFExpire,
225− )
219+ csrfCookieOptions := &CookieOptions{
220+ Name: csrf.cookieName(),
221+ Value: encoded,
222+ Domains: csrf.cookieOpts.Domains,
223+ Expiration: csrf.cookieOpts.CSRFExpire,
224+ SameSite: getCSRFSameSite(csrf.cookieOpts),
225+ Path: csrf.cookieOpts.Path,
226+ HTTPOnly: csrf.cookieOpts.HTTPOnly,
227+ Secure: csrf.cookieOpts.Secure,
228+ }
229+
230+ cookie := MakeCookieFromOptions(req, csrfCookieOptions)
226231 cookies = append(cookies, fmt.Sprintf("%v=%v", cookie.Name, cookie.Value))
227232 }
228233
pkg/cookies/csrf_test.go+284−1
@@ -119,9 +119,33 @@ var _ = Describe("CSRF Cookie Tests", func() {
119119 Value: encoded,
120120 }
121121
122− _, _, valid := encryption.Validate(cookie, cookieOpts.Secret, cookieOpts.Expire)
122+ _, _, valid := encryption.Validate(cookie, cookieOpts.Secret, cookieOpts.CSRFExpire)
123123 Expect(valid).To(BeTrue())
124124 })
125+
126+ It("validates CSRF token using CSRFExpire when Expire is lower", func() {
127+ // Set Expire to be much lower than CSRFExpire
128+ cookieOpts.Expire = time.Second
129+ cookieOpts.CSRFExpire = time.Hour
130+
131+ privateCSRF.OAuthState = []byte(csrfState)
132+ privateCSRF.OIDCNonce = []byte(csrfNonce)
133+
134+ encoded, err := privateCSRF.encodeCookie()
135+ Expect(err).ToNot(HaveOccurred())
136+
137+ cookie := &http.Cookie{
138+ Name: privateCSRF.cookieName(),
139+ Value: encoded,
140+ }
141+
142+ // The cookie should still be valid even though Expire is only 1 second
143+ decoded, err := decodeCSRFCookie(cookie, cookieOpts)
144+ Expect(err).ToNot(HaveOccurred())
145+ Expect(decoded).ToNot(BeNil())
146+ Expect(decoded.OAuthState).To(Equal([]byte(csrfState)))
147+ Expect(decoded.OIDCNonce).To(Equal([]byte(csrfNonce)))
148+ })
125149 })
126150
127151 Context("Cookie Management", func() {
@@ -254,4 +278,263 @@ var _ = Describe("CSRF Cookie Tests", func() {
254278 })
255279 })
256280 })
281+
282+ Context("Test Cookie SameSite", func() {
283+ var req *http.Request
284+ var cookieOpts *options.Cookie
285+
286+ testNow := time.Unix(nowEpoch, 0)
287+
288+ BeforeEach(func() {
289+ // we need to reset the time to ensure the cookie is valid
290+ privateCSRF.clock = time.Now
291+
292+ req = &http.Request{
293+ Method: http.MethodGet,
294+ Proto: "HTTP/1.1",
295+ Host: cookieDomain,
296+
297+ URL: &url.URL{
298+ Scheme: "https",
299+ Host: cookieDomain,
300+ Path: cookiePath,
301+ },
302+ }
303+
304+ cookieOpts = &options.Cookie{
305+ Name: cookieName,
306+ Secret: cookieSecret,
307+ Domains: []string{cookieDomain},
308+ Path: cookiePath,
309+ Expire: time.Hour,
310+ Secure: true,
311+ HTTPOnly: true,
312+ CSRFPerRequest: false,
313+ CSRFExpire: time.Hour,
314+ }
315+ })
316+
317+ It("Call SetCookie when CSRF SameSite is not defined. Expected result: CSRF cookie SameSite is the same as session cookie.", func() {
318+ // prepare
319+ cookieOpts.SameSite = sameSiteLax
320+ CSRF, _ := NewCSRF(cookieOpts, "verifier")
321+ rw := httptest.NewRecorder()
322+ CSRF.(*csrf).clock = func() time.Time { return testNow }
323+
324+ // test
325+ _, err := CSRF.SetCookie(rw, req)
326+
327+ // validate
328+ Expect(err).ToNot(HaveOccurred())
329+ Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring(
330+ fmt.Sprintf(
331+ "; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure; SameSite=Lax",
332+ cookiePath,
333+ cookieDomain,
334+ int(cookieOpts.CSRFExpire.Seconds()),
335+ ),
336+ ))
337+ })
338+
339+ It("Call SetCookie when CSRF SameSite is an empty string. Expected result: CSRF cookie SameSite is the same as session cookie.", func() {
340+ // prepare
341+ cookieOpts.SameSite = sameSiteLax
342+ cookieOpts.CSRFSameSite = ""
343+ CSRF, _ := NewCSRF(cookieOpts, "verifier")
344+ rw := httptest.NewRecorder()
345+ CSRF.(*csrf).clock = func() time.Time { return testNow }
346+
347+ // test
348+ _, err := CSRF.SetCookie(rw, req)
349+
350+ // validate
351+ Expect(err).ToNot(HaveOccurred())
352+ Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring(
353+ fmt.Sprintf(
354+ "; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure; SameSite=Lax",
355+ cookiePath,
356+ cookieDomain,
357+ int(cookieOpts.CSRFExpire.Seconds()),
358+ ),
359+ ))
360+ })
361+
362+ It("Call SetCookie when CSRF SameSite is 'none'. Expected result: CSRF cookie SameSite is None.", func() {
363+ // prepare
364+ cookieOpts.SameSite = sameSiteLax
365+ cookieOpts.CSRFSameSite = sameSiteNone
366+ CSRF, _ := NewCSRF(cookieOpts, "verifier")
367+ rw := httptest.NewRecorder()
368+ CSRF.(*csrf).clock = func() time.Time { return testNow }
369+
370+ // test
371+ _, err := CSRF.SetCookie(rw, req)
372+
373+ // validate
374+ Expect(err).ToNot(HaveOccurred())
375+ Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring(
376+ fmt.Sprintf(
377+ "; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure; SameSite=None",
378+ cookiePath,
379+ cookieDomain,
380+ int(cookieOpts.CSRFExpire.Seconds()),
381+ ),
382+ ))
383+ })
384+
385+ It("Call SetCookie when CSRF SameSite is 'strict'. Expected result: CSRF cookie SameSite is Strict.", func() {
386+ // prepare
387+ cookieOpts.SameSite = sameSiteLax
388+ cookieOpts.CSRFSameSite = sameSiteStrict
389+ CSRF, _ := NewCSRF(cookieOpts, "verifier")
390+ rw := httptest.NewRecorder()
391+ CSRF.(*csrf).clock = func() time.Time { return testNow }
392+
393+ // test
394+ _, err := CSRF.SetCookie(rw, req)
395+
396+ // validate
397+ Expect(err).ToNot(HaveOccurred())
398+ Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring(
399+ fmt.Sprintf(
400+ "; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure; SameSite=Strict",
401+ cookiePath,
402+ cookieDomain,
403+ int(cookieOpts.CSRFExpire.Seconds()),
404+ ),
405+ ))
406+ })
407+
408+ It("Call SetCookie when CSRF SameSite is 'lax'. Expected result: CSRF cookie SameSite is Lax.", func() {
409+ // prepare
410+ cookieOpts.SameSite = sameSiteStrict
411+ cookieOpts.CSRFSameSite = sameSiteLax
412+ CSRF, _ := NewCSRF(cookieOpts, "verifier")
413+ rw := httptest.NewRecorder()
414+ CSRF.(*csrf).clock = func() time.Time { return testNow }
415+
416+ // test
417+ _, err := CSRF.SetCookie(rw, req)
418+
419+ // validate
420+ Expect(err).ToNot(HaveOccurred())
421+ Expect(rw.Header().Get("Set-Cookie")).To(ContainSubstring(
422+ fmt.Sprintf(
423+ "; Path=%s; Domain=%s; Max-Age=%d; HttpOnly; Secure; SameSite=Lax",
424+ cookiePath,
425+ cookieDomain,
426+ int(cookieOpts.CSRFExpire.Seconds()),
427+ ),
428+ ))
429+ })
430+
431+ It("Call ClearCookie when CSRF SameSite is not defined. Expected result: CSRF cookie SameSite is the same as session cookie.", func() {
432+ // prepare
433+ cookieOpts.SameSite = sameSiteLax
434+ CSRF, _ := NewCSRF(cookieOpts, "verifier")
435+ rw := httptest.NewRecorder()
436+ CSRF.(*csrf).clock = func() time.Time { return testNow }
437+
438+ // test
439+ CSRF.ClearCookie(rw, req)
440+
441+ // validate
442+ Expect(rw.Header().Get("Set-Cookie")).To(Equal(
443+ fmt.Sprintf(
444+ "%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure; SameSite=Lax",
445+ CSRF.(*csrf).cookieName(),
446+ cookiePath,
447+ cookieDomain,
448+ ),
449+ ))
450+ })
451+
452+ It("Call ClearCookie when CSRF SameSite is an empty string. Expected result: CSRF cookie SameSite is the same as session cookie.", func() {
453+ // prepare
454+ cookieOpts.SameSite = sameSiteLax
455+ cookieOpts.CSRFSameSite = ""
456+ CSRF, _ := NewCSRF(cookieOpts, "verifier")
457+ rw := httptest.NewRecorder()
458+ CSRF.(*csrf).clock = func() time.Time { return testNow }
459+
460+ // test
461+ CSRF.ClearCookie(rw, req)
462+
463+ // validate
464+ Expect(rw.Header().Get("Set-Cookie")).To(Equal(
465+ fmt.Sprintf(
466+ "%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure; SameSite=Lax",
467+ CSRF.(*csrf).cookieName(),
468+ cookiePath,
469+ cookieDomain,
470+ ),
471+ ))
472+ })
473+
474+ It("Call ClearCookie when CSRF SameSite is 'none'. Expected result: CSRF cookie SameSite is None.", func() {
475+ // prepare
476+ cookieOpts.SameSite = sameSiteLax
477+ cookieOpts.CSRFSameSite = sameSiteNone
478+ CSRF, _ := NewCSRF(cookieOpts, "verifier")
479+ rw := httptest.NewRecorder()
480+ CSRF.(*csrf).clock = func() time.Time { return testNow }
481+
482+ // test
483+ CSRF.ClearCookie(rw, req)
484+
485+ // validate
486+ Expect(rw.Header().Get("Set-Cookie")).To(Equal(
487+ fmt.Sprintf(
488+ "%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure; SameSite=None",
489+ CSRF.(*csrf).cookieName(),
490+ cookiePath,
491+ cookieDomain,
492+ ),
493+ ))
494+ })
495+
496+ It("Call ClearCookie when CSRF SameSite is 'strict'. Expected result: CSRF cookie SameSite is Strict.", func() {
497+ // prepare
498+ cookieOpts.SameSite = sameSiteLax
499+ cookieOpts.CSRFSameSite = sameSiteStrict
500+ CSRF, _ := NewCSRF(cookieOpts, "verifier")
501+ rw := httptest.NewRecorder()
502+ CSRF.(*csrf).clock = func() time.Time { return testNow }
503+
504+ // test
505+ CSRF.ClearCookie(rw, req)
506+
507+ // validate
508+ Expect(rw.Header().Get("Set-Cookie")).To(Equal(
509+ fmt.Sprintf(
510+ "%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure; SameSite=Strict",
511+ CSRF.(*csrf).cookieName(),
512+ cookiePath,
513+ cookieDomain,
514+ ),
515+ ))
516+ })
517+
518+ It("Call ClearCookie when CSRF SameSite is 'lax'. Expected result: CSRF cookie SameSite is Lax.", func() {
519+ // prepare
520+ cookieOpts.SameSite = sameSiteStrict
521+ cookieOpts.CSRFSameSite = sameSiteLax
522+ CSRF, _ := NewCSRF(cookieOpts, "verifier")
523+ rw := httptest.NewRecorder()
524+ CSRF.(*csrf).clock = func() time.Time { return testNow }
525+
526+ // test
527+ CSRF.ClearCookie(rw, req)
528+
529+ // validate
530+ Expect(rw.Header().Get("Set-Cookie")).To(Equal(
531+ fmt.Sprintf(
532+ "%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure; SameSite=Lax",
533+ CSRF.(*csrf).cookieName(),
534+ cookiePath,
535+ cookieDomain,
536+ ),
537+ ))
538+ })
539+ })
257540})
pkg/ip/parse_ip_net.go+16
@@ -1,6 +1,7 @@
11package ip
22
33import (
4+ "fmt"
45 "net"
56 "strings"
67)
@@ -37,3 +38,18 @@ func ParseIPNet(s string) *net.IPNet {
3738 return ipNet
3839 }
3940}
41+
42+func ParseNetSet(ipStrs []string) (*NetSet, error) {
43+ netSet := NewNetSet()
44+
45+ for _, ipStr := range ipStrs {
46+ ipNet := ParseIPNet(ipStr)
47+ if ipNet == nil {
48+ return nil, fmt.Errorf("could not parse IP network (%s)", ipStr)
49+ }
50+
51+ netSet.AddIPNet(*ipNet)
52+ }
53+
54+ return netSet, nil
55+}
pkg/ip/parse_ip_net_test.gonew file+118
@@ -0,0 +1,118 @@
1+package ip
2+
3+import (
4+ "net"
5+ "testing"
6+
7+ "github.com/stretchr/testify/assert"
8+)
9+
10+func TestParseIPNet(t *testing.T) {
11+ tests := []struct {
12+ name string
13+ input string
14+ expectedIP net.IP
15+ expectedMask net.IPMask
16+ }{
17+ {
18+ name: "ipv4 address",
19+ input: "127.0.0.1",
20+ expectedIP: net.ParseIP("127.0.0.1"),
21+ expectedMask: net.CIDRMask(32, 32),
22+ },
23+ {
24+ name: "ipv6 address",
25+ input: "::1",
26+ expectedIP: net.ParseIP("::1"),
27+ expectedMask: net.CIDRMask(128, 128),
28+ },
29+ {
30+ name: "ipv4 cidr",
31+ input: "10.0.0.0/24",
32+ expectedIP: net.ParseIP("10.0.0.0"),
33+ expectedMask: net.CIDRMask(24, 32),
34+ },
35+ {
36+ name: "ipv6 cidr",
37+ input: "2001:db8::/64",
38+ expectedIP: net.ParseIP("2001:db8::"),
39+ expectedMask: net.CIDRMask(64, 128),
40+ },
41+ }
42+
43+ for _, test := range tests {
44+ t.Run(test.name, func(t *testing.T) {
45+ ipNet := ParseIPNet(test.input)
46+
47+ assert.NotNil(t, ipNet)
48+ if ipNet == nil {
49+ return
50+ }
51+
52+ assert.True(t, test.expectedIP.Equal(ipNet.IP))
53+ assert.Equal(t, test.expectedMask, ipNet.Mask)
54+ })
55+ }
56+}
57+
58+func TestParseIPNetRejectsInvalidNetworks(t *testing.T) {
59+ tests := []struct {
60+ name string
61+ input string
62+ }{
63+ {
64+ name: "invalid ip",
65+ input: "not-an-ip",
66+ },
67+ {
68+ name: "ipv4 cidr with host bits set",
69+ input: "10.0.0.1/24",
70+ },
71+ {
72+ name: "ipv6 cidr with host bits set",
73+ input: "2001:db8::1/64",
74+ },
75+ {
76+ name: "invalid cidr mask",
77+ input: "10.0.0.0/33",
78+ },
79+ }
80+
81+ for _, test := range tests {
82+ t.Run(test.name, func(t *testing.T) {
83+ assert.Nil(t, ParseIPNet(test.input))
84+ })
85+ }
86+}
87+
88+func TestParseNetSet(t *testing.T) {
89+ netSet, err := ParseNetSet([]string{
90+ "127.0.0.1",
91+ "10.0.0.0/24",
92+ "::1",
93+ "2001:db8::/64",
94+ })
95+
96+ assert.NoError(t, err)
97+ assert.NotNil(t, netSet)
98+ if netSet == nil {
99+ return
100+ }
101+
102+ assert.True(t, netSet.Has(net.ParseIP("127.0.0.1")))
103+ assert.True(t, netSet.Has(net.ParseIP("10.0.0.55")))
104+ assert.True(t, netSet.Has(net.ParseIP("::1")))
105+ assert.True(t, netSet.Has(net.ParseIP("2001:db8::abcd")))
106+
107+ assert.False(t, netSet.Has(net.ParseIP("127.0.0.2")))
108+ assert.False(t, netSet.Has(net.ParseIP("10.0.1.1")))
109+ assert.False(t, netSet.Has(net.ParseIP("::2")))
110+ assert.False(t, netSet.Has(net.ParseIP("2001:db9::1")))
111+}
112+
113+func TestParseNetSetReturnsErrorForInvalidNetwork(t *testing.T) {
114+ netSet, err := ParseNetSet([]string{"127.0.0.1", "10.0.0.1/24"})
115+
116+ assert.Nil(t, netSet)
117+ assert.EqualError(t, err, "could not parse IP network (10.0.0.1/24)")
118+}
pkg/ip/realclientip.go+7−1
@@ -73,6 +73,12 @@ func GetClientIP(p ipapi.RealClientIPParser, req *http.Request) (net.IP, error)
7373
7474// getRemoteIP obtains the IP of the low-level connected network host
7575func getRemoteIP(req *http.Request) (net.IP, error) {
76+ // Unix domain sockets set RemoteAddr to "@" which has no meaningful IP.
77+ // https://github.com/golang/go/blob/0fa53e41f122b1661d0678a6d36d71b7b5ad031d/src/syscall/syscall_linux.go#L506-L511
78+ if req.RemoteAddr == "@" {
79+ return nil, nil
80+ }
81+
7682 //revive:disable:indent-error-flow
7783 if ipStr, _, err := net.SplitHostPort(req.RemoteAddr); err != nil {
7884 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) (
94100 }
95101
96102 var remoteIPStr string
97− if remoteIP, err := getRemoteIP(req); err == nil {
103+ if remoteIP, err := getRemoteIP(req); err == nil && remoteIP != nil {
98104 remoteIPStr = remoteIP.String()
99105 }
100106
pkg/ip/realclientip_test.go+4
@@ -112,6 +112,8 @@ func TestGetRemoteIP(t *testing.T) {
112112 errString string
113113 expectedIP net.IP
114114 }{
115+ // Unix domain sockets set RemoteAddr to "@"
116+ {"@", "", nil},
115117 {"", "unable to get ip and port from http.RemoteAddr ()", nil},
116118 {"nil", "unable to get ip and port from http.RemoteAddr (nil)", nil},
117119 {"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) {
155157 }{
156158 // Should fail quietly, only printing warnings to the log
157159 {nil, "", "", "", ""},
160+ // Unix domain socket — no IP available
161+ {nil, "@", "", "", ""},
158162 {p, "127.0.0.1:11950", "", "127.0.0.1", "127.0.0.1"},
159163 {p, "[::1]:28660", "99.103.56.12", "99.103.56.12", "::1 (99.103.56.12)"},
160164 {nil, "10.254.244.165:62750", "", "10.254.244.165", "10.254.244.165"},
pkg/middleware/healthcheck.go+7−4
@@ -43,10 +43,13 @@ func healthCheck(paths, userAgents []string, next http.Handler) http.Handler {
4343
4444func isHealthCheckRequest(paths, userAgents map[string]struct{}, req *http.Request) bool {
4545 if _, ok := paths[req.URL.EscapedPath()]; ok {
46− return true
47− }
48− if _, ok := userAgents[req.Header.Get("User-Agent")]; ok {
49− return true
46+ if len(userAgents) == 0 {
47+ return true
48+ }
49+
50+ if _, ok := userAgents[req.Header.Get("User-Agent")]; ok {
51+ return true
52+ }
5053 }
5154 return false
5255}
pkg/middleware/healthcheck_test.go+31−9
@@ -45,6 +45,16 @@ var _ = Describe("HealthCheck suite", func() {
4545 healthCheckPaths: []string{"/ping"},
4646 healthCheckUserAgents: []string{"hc/1.0"},
4747 requestString: "http://example.com/ping",
48+ headers: map[string]string{
49+ "User-Agent": "hc/1.0",
50+ },
51+ expectedStatus: 200,
52+ expectedBody: "OK",
53+ }),
54+ Entry("when requesting the healthcheck path with no health check user agents configured", &requestTableInput{
55+ healthCheckPaths: []string{"/ping"},
56+ healthCheckUserAgents: []string{},
57+ requestString: "http://example.com/ping",
4858 headers: map[string]string{},
4959 expectedStatus: 200,
5060 expectedBody: "OK",
@@ -85,15 +95,25 @@ var _ = Describe("HealthCheck suite", func() {
8595 expectedStatus: 404,
8696 expectedBody: "404 page not found\n",
8797 }),
88− Entry("with a request from the health check user agent", &requestTableInput{
98+ Entry("with a request from the health check user agent on a non-healthcheck path", &requestTableInput{
8999 healthCheckPaths: []string{"/ping"},
90100 healthCheckUserAgents: []string{"hc/1.0"},
91101 requestString: "http://example.com/abc",
92102 headers: map[string]string{
93103 "User-Agent": "hc/1.0",
94104 },
95− expectedStatus: 200,
96− expectedBody: "OK",
105+ expectedStatus: 404,
106+ expectedBody: "404 page not found\n",
107+ }),
108+ Entry("when an auth_request endpoint receives the configured health check user agent", &requestTableInput{
109+ healthCheckPaths: []string{"/ping"},
110+ healthCheckUserAgents: []string{"GoogleHC/1.0"},
111+ requestString: "http://example.com/oauth2/auth",
112+ headers: map[string]string{
113+ "User-Agent": "GoogleHC/1.0",
114+ },
115+ expectedStatus: 404,
116+ expectedBody: "404 page not found\n",
97117 }),
98118 Entry("when a blank string is configured as a health check agent and a request has no user agent", &requestTableInput{
99119 healthCheckPaths: []string{"/ping"},
@@ -107,9 +127,11 @@ var _ = Describe("HealthCheck suite", func() {
107127 healthCheckPaths: []string{"/ping", "/liveness_check", "/readiness_check"},
108128 healthCheckUserAgents: []string{"hc/1.0"},
109129 requestString: "http://example.com/readiness_check",
110− headers: map[string]string{},
111− expectedStatus: 200,
112− expectedBody: "OK",
130+ headers: map[string]string{
131+ "User-Agent": "hc/1.0",
132+ },
133+ expectedStatus: 200,
134+ expectedBody: "OK",
113135 }),
114136 Entry("with multiple paths, request none of the healthcheck paths", &requestTableInput{
115137 healthCheckPaths: []string{"/ping", "/liveness_check", "/readiness_check"},
@@ -121,15 +143,15 @@ var _ = Describe("HealthCheck suite", func() {
121143 expectedStatus: 404,
122144 expectedBody: "404 page not found\n",
123145 }),
124− Entry("with multiple user agents, request from a health check user agent", &requestTableInput{
146+ Entry("with multiple user agents, request from a health check user agent on a non-healthcheck path", &requestTableInput{
125147 healthCheckPaths: []string{"/ping"},
126148 healthCheckUserAgents: []string{"hc/1.0", "GoogleHC/1.0"},
127149 requestString: "http://example.com/abc",
128150 headers: map[string]string{
129151 "User-Agent": "GoogleHC/1.0",
130152 },
131− expectedStatus: 200,
132− expectedBody: "OK",
153+ expectedStatus: 404,
154+ expectedBody: "404 page not found\n",
133155 }),
134156 Entry("with multiple user agents, request from none of the health check user agents", &requestTableInput{
135157 healthCheckPaths: []string{"/ping"},
pkg/middleware/redirect_to_https_test.go+15
@@ -6,6 +6,7 @@ import (
66 "net/http/httptest"
77
88 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
9+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
910 . "github.com/onsi/ginkgo/v2"
1011 . "github.com/onsi/gomega"
1112)
@@ -39,6 +40,10 @@ var _ = Describe("RedirectToHTTPS suite", func() {
3940 scope := &middlewareapi.RequestScope{
4041 ReverseProxy: in.reverseProxy,
4142 }
43+ if in.reverseProxy {
44+ req.RemoteAddr = "127.0.0.1:4180"
45+ scope.TrustedProxies = newRedirectTrustedProxySet("127.0.0.1")
46+ }
4247 req = middlewareapi.AddRequestScope(req, scope)
4348
4449 rw := httptest.NewRecorder()
@@ -207,3 +212,13 @@ var _ = Describe("RedirectToHTTPS suite", func() {
207212 }),
208213 )
209214})
215+
216+func newRedirectTrustedProxySet(cidrs ...string) *ip.NetSet {
217+ set := ip.NewNetSet()
218+ for _, cidr := range cidrs {
219+ ipNet := ip.ParseIPNet(cidr)
220+ Expect(ipNet).ToNot(BeNil())
221+ set.AddIPNet(*ipNet)
222+ }
223+ return set
224+}
pkg/middleware/scope.go+5−3
@@ -6,14 +6,16 @@ import (
66 "github.com/google/uuid"
77 "github.com/justinas/alice"
88 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
9+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
910)
1011
11−func NewScope(reverseProxy bool, idHeader string) alice.Constructor {
12+func NewScope(reverseProxy bool, idHeader string, trustedProxies *ip.NetSet) alice.Constructor {
1213 return func(next http.Handler) http.Handler {
1314 return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
1415 scope := &middlewareapi.RequestScope{
15− ReverseProxy: reverseProxy,
16− RequestID: genRequestID(req, idHeader),
16+ ReverseProxy: reverseProxy,
17+ TrustedProxies: trustedProxies,
18+ RequestID: genRequestID(req, idHeader),
1719 }
1820 req = middlewareapi.AddRequestScope(req, scope)
1921 next.ServeHTTP(rw, req)
pkg/middleware/scope_test.go+18−4
@@ -6,6 +6,7 @@ import (
66
77 "github.com/google/uuid"
88 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
9+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
910 . "github.com/onsi/ginkgo/v2"
1011 . "github.com/onsi/gomega"
1112)
@@ -32,7 +33,7 @@ var _ = Describe("Scope Suite", func() {
3233
3334 Context("ReverseProxy is false", func() {
3435 BeforeEach(func() {
35− handler := NewScope(false, testRequestHeader)(
36+ handler := NewScope(false, testRequestHeader, nil)(
3637 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
3738 nextRequest = r
3839 w.WriteHeader(200)
@@ -60,8 +61,15 @@ var _ = Describe("Scope Suite", func() {
6061 })
6162
6263 Context("ReverseProxy is true", func() {
64+ var trustedProxies *ip.NetSet
65+
6366 BeforeEach(func() {
64− handler := NewScope(true, testRequestHeader)(
67+ var err error
68+
69+ trustedProxies, err = ip.ParseNetSet([]string{"127.0.0.1"})
70+ Expect(err).ToNot(HaveOccurred())
71+
72+ handler := NewScope(true, testRequestHeader, trustedProxies)(
6573 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
6674 nextRequest = r
6775 w.WriteHeader(200)
@@ -74,12 +82,18 @@ var _ = Describe("Scope Suite", func() {
7482 Expect(scope).ToNot(BeNil())
7583 Expect(scope.ReverseProxy).To(BeTrue())
7684 })
85+
86+ It("stores the trusted proxies on the scope", func() {
87+ scope := middlewareapi.GetRequestScope(nextRequest)
88+ Expect(scope).ToNot(BeNil())
89+ Expect(scope.TrustedProxies).To(BeIdenticalTo(trustedProxies))
90+ })
7791 })
7892
7993 Context("Request ID header is present", func() {
8094 BeforeEach(func() {
8195 request.Header.Add(testRequestHeader, testRequestID)
82− handler := NewScope(false, testRequestHeader)(
96+ handler := NewScope(false, testRequestHeader, nil)(
8397 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
8498 nextRequest = r
8599 w.WriteHeader(200)
@@ -97,7 +111,7 @@ var _ = Describe("Scope Suite", func() {
97111 BeforeEach(func() {
98112 uuid.SetRand(mockRand{})
99113
100− handler := NewScope(true, testRequestHeader)(
114+ handler := NewScope(true, testRequestHeader, nil)(
101115 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
102116 nextRequest = r
103117 w.WriteHeader(200)
pkg/middleware/stored_session.go+46−2
@@ -5,6 +5,7 @@ import (
55 "errors"
66 "fmt"
77 "net/http"
8+ "strings"
89 "time"
910
1011 "github.com/justinas/alice"
@@ -31,6 +32,33 @@ const (
3132 sessionRefreshRetryPeriod = 10 * time.Millisecond
3233)
3334
35+// isFatalRefreshError checks if a refresh error indicates a revoked or
36+// non-existent session that should be immediately invalidated.
37+// Fatal errors indicate the session is no longer valid at the provider level.
38+// Non-fatal errors (network issues, timeouts) should not invalidate the session.
39+//
40+// Only checks standard OAuth2 error codes (RFC 6749 Section 5.2).
41+// Does NOT check error_description strings as they are optional and provider-specific.
42+func isFatalRefreshError(err error) bool {
43+ if err == nil {
44+ return false
45+ }
46+
47+ // Only check standard OAuth2 error codes (RFC 6749 Section 5.2)
48+ // Do NOT check error_description strings as they are optional and provider-specific
49+ fatalErrors := []string{
50+ "invalid_grant", // refresh token revoked, expired, or session terminated
51+ "invalid_client", // client credentials no longer valid
52+ }
53+
54+ for _, fe := range fatalErrors {
55+ if strings.Contains(err.Error(), fe) {
56+ return true
57+ }
58+ }
59+ return false
60+}
61+
3462// StoredSessionLoaderOptions contains all of the requirements to construct
3563// a stored session loader.
3664// All options must be provided.
@@ -188,9 +216,24 @@ func (s *storedSessionLoader) refreshSessionIfNeeded(rw http.ResponseWriter, req
188216 // We are holding the lock and the session needs a refresh
189217 logger.Printf("Refreshing session - User: %s; SessionAge: %s", session.User, session.Age())
190218 if err := s.refreshSession(rw, req, session); err != nil {
191− // If a preemptive refresh fails, we still keep the session
192− // if validateSession succeeds.
193219 logger.Errorf("Unable to refresh session: %v", err)
220+
221+ // Check if this is a fatal error that indicates the session is revoked
222+ // or no longer valid at the provider level
223+ if isFatalRefreshError(err) {
224+ logger.Printf("Fatal refresh error detected (session revoked or invalid), clearing session for user: %s", session.User)
225+
226+ // Clear the session from storage (Redis) and remove the cookie
227+ if err := s.store.Clear(rw, req); err != nil {
228+ logger.Errorf("failed clearing session: %v", err)
229+ }
230+
231+ // Return error immediately to force re-authentication
232+ return fmt.Errorf("session invalidated due to fatal refresh error: %w", err)
233+ }
234+
235+ // For non-fatal errors (network issues, timeouts), keep the session
236+ // and let validateSession determine if it's still usable
194237 }
195238
196239 // Validate all sessions after any Redeem/Refresh operation (fail or success)
@@ -222,6 +265,7 @@ func (s *storedSessionLoader) refreshSession(rw http.ResponseWriter, req *http.R
222265
223266 // Session not refreshed, nothing to persist.
224267 if !refreshed {
268+ logger.Printf("Session not refreshed - User: %s; no refresh token available or provider returned false", session.User)
225269 return nil
226270 }
227271
pkg/middleware/stored_session_test.go+51
@@ -7,6 +7,7 @@ import (
77 "net/http"
88 "net/http/httptest"
99 "sync"
10+ "testing"
1011 "time"
1112
1213 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
801802func (f *fakeSessionStore) VerifyConnection(_ context.Context) error {
802803 return nil
803804}
805+
806+// TestIsFatalRefreshError tests the isFatalRefreshError function to ensure
807+// it correctly identifies fatal OAuth2 errors that should invalidate a session.
808+func TestIsFatalRefreshError(t *testing.T) {
809+ tests := []struct {
810+ name string
811+ err error
812+ expected bool
813+ }{
814+ {
815+ name: "nil error",
816+ err: nil,
817+ expected: false,
818+ },
819+ {
820+ name: "invalid_grant error",
821+ err: fmt.Errorf("failed to get token: oauth2: \"invalid_grant\" \"Session not active\""),
822+ expected: true,
823+ },
824+ {
825+ name: "invalid_client error",
826+ err: fmt.Errorf("invalid_client: client not found"),
827+ expected: true,
828+ },
829+ {
830+ name: "network timeout - not fatal",
831+ err: fmt.Errorf("Post \"https://keycloak/token\": dial tcp: connect: connection refused"),
832+ expected: false,
833+ },
834+ {
835+ name: "server error - not fatal",
836+ err: fmt.Errorf("unexpected status code 500"),
837+ expected: false,
838+ },
839+ {
840+ name: "generic refresh error - not fatal",
841+ err: fmt.Errorf("error refreshing tokens: context deadline exceeded"),
842+ expected: false,
843+ },
844+ }
845+
846+ for _, tt := range tests {
847+ t.Run(tt.name, func(t *testing.T) {
848+ result := isFatalRefreshError(tt.err)
849+ if result != tt.expected {
850+ t.Errorf("isFatalRefreshError(%v) = %v, want %v", tt.err, result, tt.expected)
851+ }
852+ })
853+ }
854+}
pkg/providers/oidc/provider_verifier.go+36−1
@@ -155,13 +155,48 @@ func getVerifierBuilder(ctx context.Context, opts ProviderVerifierOptions) (veri
155155 return nil, nil, fmt.Errorf("error while discovery OIDC configuration: %w", err)
156156 }
157157
158+ supportedSigningAlgs, err := intersectSigningAlgs(provider.SupportedSigningAlgs(), opts.SupportedSigningAlgs)
159+ if err != nil {
160+ return nil, nil, fmt.Errorf("error while determining supported signing algorithms: %w", err)
161+ }
162+
158163 return newVerifierBuilder(
159164 opts.IssuerURL,
160165 oidc.NewRemoteKeySet(ctx, provider.Endpoints().JWKsURL),
161− provider.SupportedSigningAlgs(),
166+ supportedSigningAlgs,
162167 ), provider, nil
163168}
164169
170+// intersectSigningAlgs returns the intersecting list of signing algorithms from the oidc discovery
171+// and the signing algorithms provided through the options.
172+func intersectSigningAlgs(discoveredSigningAlgs, configuredSigningAlgs []string) ([]string, error) {
173+ if len(configuredSigningAlgs) == 0 {
174+ return discoveredSigningAlgs, nil
175+ }
176+
177+ if len(discoveredSigningAlgs) == 0 {
178+ return configuredSigningAlgs, nil
179+ }
180+
181+ discovered := make(map[string]struct{}, len(discoveredSigningAlgs))
182+ for _, signingAlg := range discoveredSigningAlgs {
183+ discovered[signingAlg] = struct{}{}
184+ }
185+
186+ intersection := make([]string, 0, len(configuredSigningAlgs))
187+ for _, signingAlg := range configuredSigningAlgs {
188+ if _, ok := discovered[signingAlg]; ok {
189+ intersection = append(intersection, signingAlg)
190+ }
191+ }
192+
193+ if len(intersection) == 0 {
194+ return nil, fmt.Errorf("no supported signing algorithms in common between provider and configuration: discovered=%v, configured=%v", discoveredSigningAlgs, configuredSigningAlgs)
195+ }
196+
197+ return intersection, nil
198+}
199+
165200// GetPublicKeyFromBytes parses a PEM-encoded public key from a byte array
166201// and returns a crypto.PublicKey object.
167202func getPublicKeyFromBytes(bytes []byte) (crypto.PublicKey, error) {
pkg/providers/oidc/provider_verifier_test.go+92
@@ -2,6 +2,9 @@ package oidc
22
33import (
44 "context"
5+ "encoding/json"
6+ "net"
7+ "net/http"
58 "os"
69 "path/filepath"
710 "time"
@@ -195,6 +198,21 @@ var _ = Describe("ProviderVerifier", func() {
195198 Expect(idToken.Subject).To(Equal(claims.Subject))
196199 },
197200 Entry("with the default opts and claims", &verifierTableInput{}),
201+ Entry("with skip discovery and an allowed signing algorithm", &verifierTableInput{
202+ modifyOpts: func(p *ProviderVerifierOptions) {
203+ p.SkipDiscovery = true
204+ p.JWKsURL = m.JWKSEndpoint()
205+ p.SupportedSigningAlgs = []string{"RS256"}
206+ },
207+ }),
208+ Entry("with skip discovery and a disallowed signing algorithm", &verifierTableInput{
209+ modifyOpts: func(p *ProviderVerifierOptions) {
210+ p.SkipDiscovery = true
211+ p.JWKsURL = m.JWKSEndpoint()
212+ p.SupportedSigningAlgs = []string{"HS256"}
213+ },
214+ expectedError: "failed to verify token: oidc: malformed jwt: unexpected signature algorithm \"RS256\"; expected [\"HS256\"]",
215+ }),
198216 Entry("when the audience is mismatched", &verifierTableInput{
199217 modifyClaims: func(j *jwt.RegisteredClaims) {
200218 j.Audience = jwt.ClaimStrings{"OtherClient"}
@@ -230,4 +248,78 @@ var _ = Describe("ProviderVerifier", func() {
230248 expectedError: "failed to verify token: oidc: token is expired",
231249 }),
232250 )
251+
252+ Describe("intersectSigningAlgs", func() {
253+ DescribeTable("when determining allowed signing algorithms", func(discoveredSigningAlgs, configuredSigningAlgs, expected []string, expectedError string) {
254+ actual, err := intersectSigningAlgs(discoveredSigningAlgs, configuredSigningAlgs)
255+ Expect(actual).To(Equal(expected))
256+ if len(expectedError) > 0 {
257+ Expect(err).To(HaveOccurred())
258+ Expect(err.Error()).To(Equal(expectedError))
259+ }
260+ },
261+ Entry("returns discovered values when no configured values are provided", []string{"RS256", "HS256"}, []string(nil), []string{"RS256", "HS256"}, ""),
262+ Entry("returns configured values when no discovered values are provided", []string(nil), []string{"RS256"}, []string{"RS256"}, ""),
263+ Entry("returns the configured order of the intersection", []string{"RS256", "HS256", "EdDSA"}, []string{"EdDSA", "RS256"}, []string{"EdDSA", "RS256"}, ""),
264+ 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]"),
265+ )
266+ })
267+
268+ It("uses the intersection between discovered and configured signing algorithms", func() {
269+ customServer, err := mockoidc.NewServer(nil)
270+ Expect(err).ToNot(HaveOccurred())
271+ customServer.AddMiddleware(newConfiguredSigningAlgsIssuerMiddleware(customServer, []string{"RS256", "HS256"}))
272+
273+ listener, err := net.Listen("tcp", "127.0.0.1:0")
274+ Expect(err).ToNot(HaveOccurred())
275+
276+ Expect(customServer.Start(listener, nil)).To(Succeed())
277+ defer func() {
278+ Expect(customServer.Shutdown()).To(Succeed())
279+ }()
280+
281+ pv, err := NewProviderVerifier(context.Background(), ProviderVerifierOptions{
282+ AudienceClaims: []string{"aud"},
283+ ClientID: customServer.Config().ClientID,
284+ ExtraAudiences: []string{},
285+ IssuerURL: customServer.Issuer(),
286+ SupportedSigningAlgs: []string{"HS256"},
287+ })
288+ Expect(err).ToNot(HaveOccurred())
289+
290+ rawIDToken, err := customServer.Keypair.SignJWT(jwt.RegisteredClaims{
291+ Audience: jwt.ClaimStrings{customServer.Config().ClientID},
292+ Issuer: customServer.Issuer(),
293+ ExpiresAt: jwt.NewNumericDate(time.Now().Add(1 * time.Hour)),
294+ IssuedAt: jwt.NewNumericDate(time.Now()),
295+ Subject: "user",
296+ })
297+ Expect(err).ToNot(HaveOccurred())
298+
299+ _, err = pv.Verifier().Verify(context.Background(), rawIDToken)
300+ Expect(err).To(MatchError(HavePrefix("failed to verify token: oidc: malformed jwt: unexpected signature algorithm \"RS256\"; expected [\"HS256\"]")))
301+ })
233302})
303+
304+func newConfiguredSigningAlgsIssuerMiddleware(m *mockoidc.MockOIDC, supportedSigningAlgs []string) func(http.Handler) http.Handler {
305+ return func(next http.Handler) http.Handler {
306+ return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
307+ provider := providerJSON{
308+ Issuer: m.Issuer(),
309+ AuthURL: m.AuthorizationEndpoint(),
310+ TokenURL: m.TokenEndpoint(),
311+ JWKsURL: m.JWKSEndpoint(),
312+ UserInfoURL: m.UserinfoEndpoint(),
313+ SupportedSigningAlgs: supportedSigningAlgs,
314+ }
315+
316+ data, err := json.Marshal(provider)
317+ if err != nil {
318+ rw.WriteHeader(http.StatusInternalServerError)
319+ return
320+ }
321+
322+ _, _ = rw.Write(data)
323+ })
324+ }
325+}
pkg/providers/util/claim_extractor.go+10−74
@@ -3,7 +3,6 @@ package util
33import (
44 "context"
55 "encoding/base64"
6− "encoding/json"
76 "fmt"
87 "mime"
98 "net/http"
@@ -12,17 +11,17 @@ import (
1211
1312 "github.com/bitly/go-simplejson"
1413 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests"
15− "github.com/spf13/cast"
14+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util"
1615)
1716
1817// ClaimExtractor is used to extract claim values from an ID Token, or, if not
1918// present, from the profile URL.
2019type ClaimExtractor interface {
2120 // GetClaim fetches a named claim and returns the value.
22− GetClaim(claim string) (interface{}, bool, error)
21+ GetClaim(claim string) (any, bool, error)
2322
2423 // GetClaimInto fetches a named claim and puts the value into the destination.
25− GetClaimInto(claim string, dst interface{}) (bool, error)
24+ GetClaimInto(claim string, dst any) (bool, error)
2625}
2726
2827// NewClaimExtractor constructs a new ClaimExtractor from the raw ID Token.
@@ -31,12 +30,12 @@ type ClaimExtractor interface {
3130func NewClaimExtractor(ctx context.Context, idToken string, profileURL *url.URL, profileRequestHeaders http.Header) (ClaimExtractor, error) {
3231 payload, err := parseJWT(idToken)
3332 if err != nil {
34− return nil, fmt.Errorf("failed to parse ID Token: %v", err)
33+ return nil, fmt.Errorf("failed to parse ID Token: %w", err)
3534 }
3635
3736 tokenClaims, err := simplejson.NewJson(payload)
3837 if err != nil {
39− return nil, fmt.Errorf("failed to parse ID Token payload: %v", err)
38+ return nil, fmt.Errorf("failed to parse ID Token payload: %w", err)
4039 }
4140
4241 return &claimExtractor{
@@ -59,7 +58,7 @@ type claimExtractor struct {
5958// GetClaim will return the value claim if it exists.
6059// It will only return an error if the profile URL needs to be fetched due to
6160// the claim not being present in the ID Token.
62−func (c *claimExtractor) GetClaim(claim string) (interface{}, bool, error) {
61+func (c *claimExtractor) GetClaim(claim string) (any, bool, error) {
6362 if claim == "" {
6463 return nil, false, nil
6564 }
@@ -124,7 +123,7 @@ func (c *claimExtractor) loadProfileClaims() (*simplejson.Json, error) {
124123// GetClaimInto loads a claim and places it into the destination interface.
125124// This will attempt to coerce the claim into the specified type.
126125// If it cannot be coerced, an error may be returned.
127−func (c *claimExtractor) GetClaimInto(claim string, dst interface{}) (bool, error) {
126+func (c *claimExtractor) GetClaimInto(claim string, dst any) (bool, error) {
128127 value, exists, err := c.GetClaim(claim)
129128 if err != nil {
130129 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
132131 if !exists {
133132 return false, nil
134133 }
135− if err := coerceClaim(value, dst); err != nil {
136− return false, fmt.Errorf("could no coerce claim: %v", err)
134+ if err := util.CoerceClaim(value, dst); err != nil {
135+ return false, fmt.Errorf("could not coerce claim: %v", err)
137136 }
138137
139138 return true, nil
@@ -156,73 +155,10 @@ func parseJWT(p string) ([]byte, error) {
156155// getClaimFrom gets a claim from a Json object.
157156// It can accept either a single claim name or a json path. The claim is always evaluated first as a single claim name.
158157// Paths with indexes are not supported.
159−func getClaimFrom(claim string, src *simplejson.Json) interface{} {
158+func getClaimFrom(claim string, src *simplejson.Json) any {
160159 if value, ok := src.CheckGet(claim); ok {
161160 return value.Interface()
162161 }
163162 claimParts := strings.Split(claim, ".")
164163 return src.GetPath(claimParts...).Interface()
165164}
166−
167−// coerceClaim tries to convert the value into the destination interface type.
168−// If it can convert the value, it will then store the value in the destination
169−// interface.
170−func coerceClaim(value, dst interface{}) error {
171− switch d := dst.(type) {
172− case *string:
173− str, err := toString(value)
174− if err != nil {
175− return fmt.Errorf("could not convert value to string: %v", err)
176− }
177− *d = str
178− case *[]string:
179− strSlice, err := toStringSlice(value)
180− if err != nil {
181− return fmt.Errorf("could not convert value to string slice: %v", err)
182− }
183− *d = strSlice
184− case *bool:
185− *d = cast.ToBool(value)
186− default:
187− return fmt.Errorf("unknown type for destination: %T", dst)
188− }
189− return nil
190−}
191−
192−// toStringSlice converts an interface (either a slice or single value) into
193−// a slice of strings.
194−func toStringSlice(value interface{}) ([]string, error) {
195− var sliceValues []interface{}
196− switch v := value.(type) {
197− case []interface{}:
198− sliceValues = v
199− case interface{}:
200− sliceValues = []interface{}{v}
201− default:
202− sliceValues = cast.ToSlice(value)
203− }
204−
205− out := []string{}
206− for _, v := range sliceValues {
207− str, err := toString(v)
208− if err != nil {
209− return nil, fmt.Errorf("could not convert slice entry to string %v: %v", v, err)
210− }
211− out = append(out, str)
212− }
213− return out, nil
214−}
215−
216−// toString coerces a value into a string.
217−// If it is non-string, marshal it into JSON.
218−func toString(value interface{}) (string, error) {
219− if str, err := cast.ToStringE(value); err == nil {
220− return str, nil
221− }
222−
223− jsonStr, err := json.Marshal(value)
224− if err != nil {
225− return "", err
226− }
227− return string(jsonStr), nil
228−}
pkg/providers/util/claim_extractor_test.go+2−53
@@ -76,7 +76,7 @@ var _ = Describe("Claim Extractor Suite", func() {
7676 func(in newClaimExtractorTableInput) {
7777 _, err := NewClaimExtractor(context.Background(), in.idToken, nil, nil)
7878 if in.expectedError != nil {
79− Expect(err).To(MatchError(in.expectedError))
79+ Expect(err).To(MatchError(in.expectedError.Error()))
8080 } else {
8181 Expect(err).ToNot(HaveOccurred())
8282 }
@@ -405,7 +405,7 @@ var _ = Describe("Claim Extractor Suite", func() {
405405 into: "",
406406 expectExists: false,
407407 expectedValue: "",
408− expectedError: errors.New("could no coerce claim: unknown type for destination: string"),
408+ expectedError: errors.New("could not coerce claim: unknown type for destination: string"),
409409 }),
410410 Entry("flattens a complex claim value into a JSON string", getClaimIntoTableInput{
411411 testClaimExtractorOpts: testClaimExtractorOpts{
@@ -451,53 +451,6 @@ var _ = Describe("Claim Extractor Suite", func() {
451451 }),
452452 )
453453
454− type coerceClaimTableInput struct {
455− value interface{}
456− dst interface{}
457− expectedDst interface{}
458− expectedError error
459− }
460−
461− DescribeTable("coerceClaim",
462− func(in coerceClaimTableInput) {
463− err := coerceClaim(in.value, in.dst)
464− if in.expectedError != nil {
465− Expect(err).To(MatchError(in.expectedError))
466− return
467− }
468−
469− Expect(err).ToNot(HaveOccurred())
470− Expect(in.dst).To(Equal(in.expectedDst))
471− },
472− Entry("coerces a string to a string", coerceClaimTableInput{
473− value: "some_string",
474− dst: stringPointer(""),
475− expectedDst: stringPointer("some_string"),
476− }),
477− Entry("coerces a slice to a string slice", coerceClaimTableInput{
478− value: []interface{}{"a", "b"},
479− dst: stringSlicePointer([]string{}),
480− expectedDst: stringSlicePointer([]string{"a", "b"}),
481− }),
482− Entry("coerces a bool to a bool", coerceClaimTableInput{
483− value: true,
484− dst: boolPointer(false),
485− expectedDst: boolPointer(true),
486− }),
487− Entry("coerces a string to a bool", coerceClaimTableInput{
488− value: "true",
489− dst: boolPointer(false),
490− expectedDst: boolPointer(true),
491− }),
492− Entry("coerces a map to a string", coerceClaimTableInput{
493− value: map[string]interface{}{
494− "foo": []interface{}{"bar", "baz"},
495− },
496− dst: stringPointer(""),
497− expectedDst: stringPointer("{\"foo\":[\"bar\",\"baz\"]}"),
498− }),
499− )
500−
501454 It("should extract claims from a JWT response", func() {
502455 jwtResponsePayload := `{
503456 "user": "jwtUser",
@@ -605,10 +558,6 @@ func stringSlicePointer(in []string) *[]string {
605558 return &in
606559}
607560
608−func boolPointer(in bool) *bool {
609− return &in
610−}
611−
612561// ******************************
613562// Different profile URL handlers
614563// ******************************
pkg/proxyhttp/server.go+50−2
@@ -8,6 +8,7 @@ import (
88 "net"
99 "net/http"
1010 "os"
11+ "strconv"
1112 "strings"
1213 "time"
1314
@@ -95,15 +96,62 @@ func (s *server) setupListener(opts Opts) error {
9596 networkType := getNetworkScheme(opts.BindAddress)
9697 listenAddr := getListenAddress(opts.BindAddress)
9798
98− listener, err := net.Listen(networkType, listenAddr)
99+ listener, err := func() (net.Listener, error) {
100+ if networkType == "unix" {
101+ return setupUnixSocketListener(networkType, listenAddr)
102+ }
103+ return net.Listen(networkType, listenAddr)
104+ }()
105+
99106 if err != nil {
100107 return fmt.Errorf("listen (%s, %s) failed: %w", networkType, listenAddr, err)
101108 }
102− s.listener = listener
103109
110+ s.listener = listener
104111 return nil
105112}
106113
114+func setupUnixSocketListener(networkType string, address string) (net.Listener, error) {
115+ socketOpts := strings.Split(address, ",")
116+ if len(socketOpts) < 2 {
117+ return net.Listen(networkType, address)
118+ }
119+
120+ socketPath := socketOpts[0]
121+ var socketMode os.FileMode
122+ hasSocketMode := false
123+
124+ for _, socketOpt := range socketOpts[1:] {
125+ socketOpt := strings.SplitN(socketOpt, "=", 2)
126+ if len(socketOpt) != 2 {
127+ return nil, fmt.Errorf("unix socket option %s expects a value", socketOpt[0])
128+ }
129+
130+ if socketOpt[0] == "mode" {
131+ mode, err := strconv.ParseUint(socketOpt[1], 8, 32)
132+ if err != nil {
133+ return nil, fmt.Errorf("unix socket file mode has invalid value %s", socketOpt[1])
134+ }
135+ socketMode = os.FileMode(mode)
136+ hasSocketMode = true
137+ }
138+ }
139+
140+ listener, err := net.Listen(networkType, socketPath)
141+ if err != nil {
142+ return nil, err
143+ }
144+
145+ if hasSocketMode {
146+ err = os.Chmod(socketPath, socketMode)
147+ if err != nil {
148+ return nil, fmt.Errorf("cannot set unix socket file mode on %s: %v", socketPath, err)
149+ }
150+ }
151+
152+ return listener, nil
153+}
154+
107155func parseCipherSuites(names []string) ([]uint16, error) {
108156 cipherNameMap := make(map[string]uint16)
109157
pkg/proxyhttp/server_test.go+50
@@ -28,6 +28,8 @@ var _ = Describe("Server", func() {
2828 expectedErr error
2929 expectHTTPListener bool
3030 expectTLSListener bool
31+ expectedSocketMode os.FileMode
32+ socketPath string
3133 fdAddr string
3234 ipv6 bool
3335 }
@@ -57,6 +59,12 @@ var _ = Describe("Server", func() {
5759 s, ok := srv.(*server)
5860 Expect(ok).To(BeTrue())
5961
62+ if in.socketPath != "" {
63+ fileInfo, err := os.Stat(in.socketPath)
64+ Expect(err).ToNot(HaveOccurred())
65+ Expect(fileInfo.Mode().Perm()).To(Equal(in.expectedSocketMode.Perm()))
66+ }
67+
6068 Expect(s.listener != nil).To(Equal(in.expectHTTPListener))
6169 if in.expectHTTPListener {
6270 Expect(s.listener.Close()).To(Succeed())
@@ -648,6 +656,48 @@ var _ = Describe("Server", func() {
648656 expectTLSListener: true,
649657 ipv6: true,
650658 }),
659+ Entry("with a valid unix socket path", &newServerTableInput{
660+ opts: Opts{
661+ Handler: handler,
662+ BindAddress: "unix:///tmp/oauth2-proxy.sock",
663+ },
664+ expectedErr: nil,
665+ expectHTTPListener: true,
666+ expectTLSListener: false,
667+ ipv6: false,
668+ }),
669+ Entry("with a valid unix socket path and a valid socket file mode", &newServerTableInput{
670+ opts: Opts{
671+ Handler: handler,
672+ BindAddress: "unix:///tmp/oauth2-proxy.sock,mode=0777",
673+ },
674+ expectedErr: nil,
675+ expectHTTPListener: true,
676+ expectTLSListener: false,
677+ expectedSocketMode: 0o777,
678+ socketPath: "/tmp/oauth2-proxy.sock",
679+ ipv6: false,
680+ }),
681+ Entry("with a valid unix socket path and a value-less socket file mode argument", &newServerTableInput{
682+ opts: Opts{
683+ Handler: handler,
684+ BindAddress: "unix:///tmp/oauth2-proxy.sock,mode",
685+ },
686+ expectedErr: errors.New("error setting up listener: listen (unix, /tmp/oauth2-proxy.sock,mode) failed: unix socket option mode expects a value"),
687+ expectHTTPListener: false,
688+ expectTLSListener: false,
689+ ipv6: false,
690+ }),
691+ Entry("with a valid unix socket path and an invalid socket file mode value", &newServerTableInput{
692+ opts: Opts{
693+ Handler: handler,
694+ BindAddress: "unix:///tmp/oauth2-proxy.sock,mode=-1",
695+ },
696+ expectedErr: errors.New("error setting up listener: listen (unix, /tmp/oauth2-proxy.sock,mode=-1) failed: unix socket file mode has invalid value -1"),
697+ expectHTTPListener: false,
698+ expectTLSListener: false,
699+ ipv6: false,
700+ }),
651701 )
652702 })
653703
pkg/requests/builder_test.go+15−15
@@ -31,7 +31,7 @@ var _ = Describe("Builder suite", func() {
3131
3232 Context("with a basic request", func() {
3333 assertSuccessfulRequest(getBuilder, testHTTPRequest{
34− Method: "GET",
34+ Method: http.MethodGet,
3535 Header: baseHeaders,
3636 Body: []byte{},
3737 RequestURI: "/json/path",
@@ -52,7 +52,7 @@ var _ = Describe("Builder suite", func() {
5252 })
5353
5454 assertSuccessfulRequest(getBuilder, testHTTPRequest{
55− Method: "GET",
55+ Method: http.MethodGet,
5656 Header: baseHeaders,
5757 Body: []byte{},
5858 RequestURI: "/json/path",
@@ -78,7 +78,7 @@ var _ = Describe("Builder suite", func() {
7878 })
7979
8080 assertSuccessfulRequest(getBuilder, testHTTPRequest{
81− Method: "GET",
81+ Method: http.MethodGet,
8282 Header: header,
8383 Body: []byte(body),
8484 RequestURI: "/json/path",
@@ -93,11 +93,11 @@ var _ = Describe("Builder suite", func() {
9393
9494 BeforeEach(func() {
9595 buf := bytes.NewBuffer([]byte(body))
96− b = b.WithMethod("POST").WithBody(buf)
96+ b = b.WithMethod(http.MethodPost).WithBody(buf)
9797 })
9898
9999 assertSuccessfulRequest(getBuilder, testHTTPRequest{
100− Method: "POST",
100+ Method: http.MethodPost,
101101 Header: header,
102102 Body: []byte(body),
103103 RequestURI: "/json/path",
@@ -109,11 +109,11 @@ var _ = Describe("Builder suite", func() {
109109 header.Set("Content-Length", "0")
110110
111111 BeforeEach(func() {
112− b = b.WithMethod("POST")
112+ b = b.WithMethod(http.MethodPost)
113113 })
114114
115115 assertSuccessfulRequest(getBuilder, testHTTPRequest{
116− Method: "POST",
116+ Method: http.MethodPost,
117117 Header: header,
118118 Body: []byte{},
119119 RequestURI: "/json/path",
@@ -122,11 +122,11 @@ var _ = Describe("Builder suite", func() {
122122
123123 Context("OPTIONS", func() {
124124 BeforeEach(func() {
125− b = b.WithMethod("OPTIONS")
125+ b = b.WithMethod(http.MethodOptions)
126126 })
127127
128128 assertSuccessfulRequest(getBuilder, testHTTPRequest{
129− Method: "OPTIONS",
129+ Method: http.MethodOptions,
130130 Header: baseHeaders,
131131 Body: []byte{},
132132 RequestURI: "/json/path",
@@ -152,7 +152,7 @@ var _ = Describe("Builder suite", func() {
152152 })
153153
154154 assertSuccessfulRequest(getBuilder, testHTTPRequest{
155− Method: "GET",
155+ Method: http.MethodGet,
156156 Header: header,
157157 Body: []byte{},
158158 RequestURI: "/json/path",
@@ -170,7 +170,7 @@ var _ = Describe("Builder suite", func() {
170170 })
171171
172172 assertSuccessfulRequest(getBuilder, testHTTPRequest{
173− Method: "GET",
173+ Method: http.MethodGet,
174174 Header: replacementHeaders,
175175 Body: []byte{},
176176 RequestURI: "/json/path",
@@ -190,7 +190,7 @@ var _ = Describe("Builder suite", func() {
190190 })
191191
192192 assertSuccessfulRequest(getBuilder, testHTTPRequest{
193− Method: "GET",
193+ Method: http.MethodGet,
194194 Header: replacementHeaders,
195195 Body: []byte{},
196196 RequestURI: "/json/path",
@@ -205,7 +205,7 @@ var _ = Describe("Builder suite", func() {
205205 })
206206
207207 assertSuccessfulRequest(getBuilder, testHTTPRequest{
208− Method: "GET",
208+ Method: http.MethodGet,
209209 Header: header,
210210 Body: []byte{},
211211 RequestURI: "/json/path",
@@ -219,12 +219,12 @@ var _ = Describe("Builder suite", func() {
219219 result := b.Do()
220220 Expect(result.Error()).ToNot(HaveOccurred())
221221
222− b.WithMethod("POST")
222+ b.WithMethod(http.MethodPost)
223223 })
224224
225225 Context("should not redo the request", func() {
226226 assertSuccessfulRequest(getBuilder, testHTTPRequest{
227− Method: "GET",
227+ Method: http.MethodGet,
228228 Header: baseHeaders,
229229 Body: []byte{},
230230 RequestURI: "/json/path",
pkg/requests/util/util.go+28−15
@@ -15,30 +15,30 @@ const (
1515)
1616
1717// GetRequestProto returns the request scheme or X-Forwarded-Proto if present
18−// and the request is proxied.
18+// and the request came from a trusted reverse proxy.
1919func GetRequestProto(req *http.Request) string {
2020 proto := req.Header.Get(XForwardedProto)
21− if !IsProxied(req) || proto == "" {
21+ if !CanTrustForwardedHeaders(req) || proto == "" {
2222 proto = req.URL.Scheme
2323 }
2424 return proto
2525}
2626
2727// GetRequestHost returns the request host header or X-Forwarded-Host if
28−// present and the request is proxied.
28+// present and the request came from a trusted reverse proxy.
2929func GetRequestHost(req *http.Request) string {
3030 host := req.Header.Get(XForwardedHost)
31− if !IsProxied(req) || host == "" {
31+ if !CanTrustForwardedHeaders(req) || host == "" {
3232 host = req.Host
3333 }
3434 return host
3535}
3636
3737// GetRequestURI return the request URI or X-Forwarded-Uri if present and the
38−// request is proxied.
38+// request came from a trusted reverse proxy.
3939func GetRequestURI(req *http.Request) string {
4040 uri := req.Header.Get(XForwardedURI)
41− if !IsProxied(req) || uri == "" {
41+ if !CanTrustForwardedHeaders(req) || uri == "" {
4242 // Use RequestURI to preserve ?query
4343 uri = req.URL.RequestURI()
4444 }
@@ -46,17 +46,29 @@ func GetRequestURI(req *http.Request) string {
4646}
4747
4848// GetRequestPath returns the request URI or X-Forwarded-Uri if present and the
49−// request is proxied but always strips the query parameters and only returns
50−// the pure path
49+// request came from a trusted reverse proxy but always strips the query
50+// parameters and fragment suffixes and only returns the pure path.
5151func GetRequestPath(req *http.Request) string {
52− uri := GetRequestURI(req)
52+ uri := stripRequestFragment(GetRequestURI(req))
5353
5454 // Parse URI and return only the path component
5555 if parsedURL, err := url.Parse(uri); err == nil {
56− return parsedURL.Path
56+ return stripRequestFragment(parsedURL.Path)
5757 }
5858
5959 // Fallback: strip query parameters manually
60+ return stripRequestQuery(uri)
61+}
62+
63+func stripRequestFragment(uri string) string {
64+ if idx := strings.Index(uri, "#"); idx != -1 {
65+ return uri[:idx]
66+ }
67+
68+ return uri
69+}
70+
71+func stripRequestQuery(uri string) string {
6072 if idx := strings.Index(uri, "?"); idx != -1 {
6173 return uri[:idx]
6274 }
@@ -64,17 +76,18 @@ func GetRequestPath(req *http.Request) string {
6476 return uri
6577}
6678
67−// IsProxied determines if a request was from a proxy based on the RequestScope
68−// ReverseProxy tracker.
69−func IsProxied(req *http.Request) bool {
79+// CanTrustForwardedHeaders determines if forwarded headers should be processed
80+// based on the RequestScope and the direct caller's address.
81+func CanTrustForwardedHeaders(req *http.Request) bool {
7082 scope := middlewareapi.GetRequestScope(req)
7183 if scope == nil {
7284 return false
7385 }
74− return scope.ReverseProxy
86+
87+ return scope.CanTrustForwardedHeaders(req)
7588}
7689
7790func IsForwardedRequest(req *http.Request) bool {
78− return IsProxied(req) &&
91+ return CanTrustForwardedHeaders(req) &&
7992 req.Host != GetRequestHost(req)
8093}
pkg/requests/util/util_test.go+74−12
@@ -6,6 +6,7 @@ import (
66 "net/http/httptest"
77
88 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
9+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
910 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests/util"
1011 . "github.com/onsi/ginkgo/v2"
1112 . "github.com/onsi/gomega"
@@ -19,8 +20,13 @@ var _ = Describe("Util Suite", func() {
1920 uriNoQueryParams = "/test/endpoint"
2021 )
2122 var req *http.Request
23+ var trustedProxies *ip.NetSet
2224
2325 BeforeEach(func() {
26+ var err error
27+ trustedProxies, err = ip.ParseNetSet([]string{"127.0.0.1"})
28+ Expect(err).ToNot(HaveOccurred())
29+
2430 req = httptest.NewRequest(
2531 http.MethodGet,
2632 fmt.Sprintf("%s://%s%s", proto, host, uriWithQueryParams),
@@ -29,7 +35,7 @@ var _ = Describe("Util Suite", func() {
2935 })
3036
3137 Context("GetRequestHost", func() {
32− Context("IsProxied is false", func() {
38+ Context("trusted forwarded headers are disabled", func() {
3339 BeforeEach(func() {
3440 req = middleware.AddRequestScope(req, &middleware.RequestScope{})
3541 })
@@ -44,10 +50,12 @@ var _ = Describe("Util Suite", func() {
4450 })
4551 })
4652
47− Context("IsProxied is true", func() {
53+ Context("trusted forwarded headers are enabled", func() {
4854 BeforeEach(func() {
55+ req.RemoteAddr = "127.0.0.1:4180"
4956 req = middleware.AddRequestScope(req, &middleware.RequestScope{
50− ReverseProxy: true,
57+ ReverseProxy: true,
58+ TrustedProxies: trustedProxies,
5159 })
5260 })
5361
@@ -63,7 +71,7 @@ var _ = Describe("Util Suite", func() {
6371 })
6472
6573 Context("GetRequestProto", func() {
66− Context("IsProxied is false", func() {
74+ Context("trusted forwarded headers are disabled", func() {
6775 BeforeEach(func() {
6876 req = middleware.AddRequestScope(req, &middleware.RequestScope{})
6977 })
@@ -78,10 +86,12 @@ var _ = Describe("Util Suite", func() {
7886 })
7987 })
8088
81− Context("IsProxied is true", func() {
89+ Context("trusted forwarded headers are enabled", func() {
8290 BeforeEach(func() {
91+ req.RemoteAddr = "127.0.0.1:4180"
8392 req = middleware.AddRequestScope(req, &middleware.RequestScope{
84− ReverseProxy: true,
93+ ReverseProxy: true,
94+ TrustedProxies: trustedProxies,
8595 })
8696 })
8797
@@ -97,7 +107,7 @@ var _ = Describe("Util Suite", func() {
97107 })
98108
99109 Context("GetRequestURI", func() {
100− Context("IsProxied is false", func() {
110+ Context("trusted forwarded headers are disabled", func() {
101111 BeforeEach(func() {
102112 req = middleware.AddRequestScope(req, &middleware.RequestScope{})
103113 })
@@ -112,10 +122,12 @@ var _ = Describe("Util Suite", func() {
112122 })
113123 })
114124
115− Context("IsProxied is true", func() {
125+ Context("trusted forwarded headers are enabled", func() {
116126 BeforeEach(func() {
127+ req.RemoteAddr = "127.0.0.1:4180"
117128 req = middleware.AddRequestScope(req, &middleware.RequestScope{
118− ReverseProxy: true,
129+ ReverseProxy: true,
130+ TrustedProxies: trustedProxies,
119131 })
120132 })
121133
@@ -131,7 +143,7 @@ var _ = Describe("Util Suite", func() {
131143 })
132144
133145 Context("GetRequestPath", func() {
134− Context("IsProxied is false", func() {
146+ Context("trusted forwarded headers are disabled", func() {
135147 BeforeEach(func() {
136148 req = middleware.AddRequestScope(req, &middleware.RequestScope{})
137149 })
@@ -140,16 +152,35 @@ var _ = Describe("Util Suite", func() {
140152 Expect(util.GetRequestPath(req)).To(Equal(uriNoQueryParams))
141153 })
142154
155+ It("drops fragment content from a parsed request path", func() {
156+ // Simulate net/http ParseRequestURI preserving '#' in URL.Path.
157+ req.URL.Path = "/foo/secret#/bar"
158+ req.URL.RawPath = "/foo/secret%23/bar"
159+ Expect(util.GetRequestPath(req)).To(Equal("/foo/secret"))
160+ })
161+
162+ It("drops fragment-like suffixes from encoded number signs", func() {
163+ req = httptest.NewRequest(
164+ http.MethodGet,
165+ fmt.Sprintf("%s://%s/foo/secret%%23/bar?query=param", proto, host),
166+ nil,
167+ )
168+ req = middleware.AddRequestScope(req, &middleware.RequestScope{})
169+ Expect(util.GetRequestPath(req)).To(Equal("/foo/secret"))
170+ })
171+
143172 It("ignores X-Forwarded-Uri and returns the URI (without query params)", func() {
144173 req.Header.Add("X-Forwarded-Uri", "/some/other/path?query=param")
145174 Expect(util.GetRequestPath(req)).To(Equal(uriNoQueryParams))
146175 })
147176 })
148177
149− Context("IsProxied is true", func() {
178+ Context("trusted forwarded headers are enabled", func() {
150179 BeforeEach(func() {
180+ req.RemoteAddr = "127.0.0.1:4180"
151181 req = middleware.AddRequestScope(req, &middleware.RequestScope{
152− ReverseProxy: true,
182+ ReverseProxy: true,
183+ TrustedProxies: trustedProxies,
153184 })
154185 })
155186
@@ -161,6 +192,37 @@ var _ = Describe("Util Suite", func() {
161192 req.Header.Add("X-Forwarded-Uri", "/some/other/path?query=param")
162193 Expect(util.GetRequestPath(req)).To(Equal("/some/other/path"))
163194 })
195+
196+ It("drops fragment-like suffixes from the X-Forwarded-Uri", func() {
197+ req.Header.Add("X-Forwarded-Uri", "/foo/secret%23/bar?query=param")
198+ Expect(util.GetRequestPath(req)).To(Equal("/foo/secret"))
199+ })
200+ })
201+ })
202+
203+ Context("CanTrustForwardedHeaders", func() {
204+ It("returns false when no scope is present", func() {
205+ Expect(util.CanTrustForwardedHeaders(req)).To(BeFalse())
206+ })
207+
208+ It("returns true when the remote address is trusted", func() {
209+ req.RemoteAddr = "127.0.0.1:4180"
210+ req = middleware.AddRequestScope(req, &middleware.RequestScope{
211+ ReverseProxy: true,
212+ TrustedProxies: trustedProxies,
213+ })
214+
215+ Expect(util.CanTrustForwardedHeaders(req)).To(BeTrue())
216+ })
217+
218+ It("returns false when the remote address is untrusted", func() {
219+ req.RemoteAddr = "192.0.2.10:4180"
220+ req = middleware.AddRequestScope(req, &middleware.RequestScope{
221+ ReverseProxy: true,
222+ TrustedProxies: trustedProxies,
223+ })
224+
225+ Expect(util.CanTrustForwardedHeaders(req)).To(BeFalse())
164226 })
165227 })
166228})
pkg/sessions/cookie/session_store.go+23−13
@@ -76,7 +76,17 @@ func (s *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) error {
7676
7777 for _, c := range req.Cookies() {
7878 if cookieNameRegex.MatchString(c.Name) {
79− clearCookie := s.makeCookie(req, c.Name, "", time.Hour*-1)
79+ sessionCookieOptions := &pkgcookies.CookieOptions{
80+ Name: c.Name,
81+ Value: "",
82+ Domains: s.Cookie.Domains,
83+ Expiration: time.Hour * -1,
84+ SameSite: s.Cookie.SameSite,
85+ Path: s.Cookie.Path,
86+ HTTPOnly: s.Cookie.HTTPOnly,
87+ Secure: s.Cookie.Secure,
88+ }
89+ clearCookie := pkgcookies.MakeCookieFromOptions(req, sessionCookieOptions)
8090
8191 http.SetCookie(rw, clearCookie)
8292 }
@@ -117,7 +127,7 @@ func (s *SessionStore) setSessionCookie(rw http.ResponseWriter, req *http.Reques
117127 return nil
118128}
119129
120−// makeSessionCookie creates an http.Cookie containing the authenticated user's
130+// makeSessionCookie creates a http.Cookie containing the authenticated user's
121131// authentication details
122132func (s *SessionStore) makeSessionCookie(req *http.Request, value []byte, now time.Time) ([]*http.Cookie, error) {
123133 strValue := string(value)
@@ -132,23 +142,23 @@ func (s *SessionStore) makeSessionCookie(req *http.Request, value []byte, now ti
132142 return nil, err
133143 }
134144 }
135− c := s.makeCookie(req, s.Cookie.Name, strValue, s.Cookie.Expire)
145+ sessionCookieOptions := &pkgcookies.CookieOptions{
146+ Name: s.Cookie.Name,
147+ Value: strValue,
148+ Domains: s.Cookie.Domains,
149+ Expiration: s.Cookie.Expire,
150+ SameSite: s.Cookie.SameSite,
151+ Path: s.Cookie.Path,
152+ HTTPOnly: s.Cookie.HTTPOnly,
153+ Secure: s.Cookie.Secure,
154+ }
155+ c := pkgcookies.MakeCookieFromOptions(req, sessionCookieOptions)
136156 if len(c.String()) > maxCookieLength {
137157 return splitCookie(c), nil
138158 }
139159 return []*http.Cookie{c}, nil
140160}
141161
142−func (s *SessionStore) makeCookie(req *http.Request, name string, value string, expiration time.Duration) *http.Cookie {
143− return pkgcookies.MakeCookieFromOptions(
144− req,
145− name,
146− value,
147− s.Cookie,
148− expiration,
149− )
150−}
151−
152162// NewCookieSessionStore initialises a new instance of the SessionStore from
153163// the configuration given
154164func NewCookieSessionStore(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessions.SessionStore, error) {
pkg/sessions/persistence/ticket.go+23−14
@@ -221,13 +221,17 @@ func (t *ticket) setCookie(rw http.ResponseWriter, req *http.Request, s *session
221221// clearCookie removes any cookies that would be where this ticket
222222// would set them
223223func (t *ticket) clearCookie(rw http.ResponseWriter, req *http.Request) {
224− http.SetCookie(rw, cookies.MakeCookieFromOptions(
225− req,
226− t.options.Name,
227− "",
228− t.options,
229− time.Hour*-1,
230− ))
224+ cookieOptions := &cookies.CookieOptions{
225+ Name: t.options.Name,
226+ Value: "",
227+ Domains: t.options.Domains,
228+ Expiration: time.Hour * -1,
229+ SameSite: t.options.SameSite,
230+ Path: t.options.Path,
231+ HTTPOnly: t.options.HTTPOnly,
232+ Secure: t.options.Secure,
233+ }
234+ http.SetCookie(rw, cookies.MakeCookieFromOptions(req, cookieOptions))
231235}
232236
233237// 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
244248 }
245249 }
246250
247− return cookies.MakeCookieFromOptions(
248− req,
249− t.options.Name,
250− value,
251− t.options,
252− expires,
253− ), nil
251+ cookieOptions := &cookies.CookieOptions{
252+ Name: t.options.Name,
253+ Value: value,
254+ Domains: t.options.Domains,
255+ Expiration: expires,
256+ SameSite: t.options.SameSite,
257+ Path: t.options.Path,
258+ HTTPOnly: t.options.HTTPOnly,
259+ Secure: t.options.Secure,
260+ }
261+
262+ return cookies.MakeCookieFromOptions(req, cookieOptions), nil
254263}
255264
256265// makeCipher makes a AES-GCM cipher out of the ticket's secret
pkg/sessions/redis/redis_store.go+15−8
@@ -109,6 +109,9 @@ func buildSentinelClient(opts options.RedisStoreOptions) (Client, error) {
109109 if opts.Username != "" {
110110 opt.Username = opts.Username
111111 }
112+ if opts.IdleTimeout > 0 {
113+ opt.ConnMaxIdleTime = time.Duration(opts.IdleTimeout) * time.Second
114+ }
112115
113116 if err := setupTLSConfig(opts, opt); err != nil {
114117 return nil, err
@@ -118,10 +121,10 @@ func buildSentinelClient(opts options.RedisStoreOptions) (Client, error) {
118121 MasterName: opts.SentinelMasterName,
119122 SentinelAddrs: addrs,
120123 SentinelPassword: opts.SentinelPassword,
121− Username: opts.Username,
122− Password: opts.Password,
124+ Username: opt.Username,
125+ Password: opt.Password,
123126 TLSConfig: opt.TLSConfig,
124− ConnMaxIdleTime: time.Duration(opts.IdleTimeout) * time.Second,
127+ ConnMaxIdleTime: opt.ConnMaxIdleTime,
125128 })
126129 return newClient(client), nil
127130}
@@ -139,6 +142,9 @@ func buildClusterClient(opts options.RedisStoreOptions) (Client, error) {
139142 if opts.Username != "" {
140143 opt.Username = opts.Username
141144 }
145+ if opts.IdleTimeout > 0 {
146+ opt.ConnMaxIdleTime = time.Duration(opts.IdleTimeout) * time.Second
147+ }
142148
143149 if err := setupTLSConfig(opts, opt); err != nil {
144150 return nil, err
@@ -146,10 +152,10 @@ func buildClusterClient(opts options.RedisStoreOptions) (Client, error) {
146152
147153 client := redis.NewClusterClient(&redis.ClusterOptions{
148154 Addrs: addrs,
149− Username: opts.Username,
150− Password: opts.Password,
155+ Username: opt.Username,
156+ Password: opt.Password,
151157 TLSConfig: opt.TLSConfig,
152− ConnMaxIdleTime: time.Duration(opts.IdleTimeout) * time.Second,
158+ ConnMaxIdleTime: opt.ConnMaxIdleTime,
153159 })
154160 return newClusterClient(client), nil
155161}
@@ -168,13 +174,14 @@ func buildStandaloneClient(opts options.RedisStoreOptions) (Client, error) {
168174 if opts.Username != "" {
169175 opt.Username = opts.Username
170176 }
177+ if opts.IdleTimeout > 0 {
178+ opt.ConnMaxIdleTime = time.Duration(opts.IdleTimeout) * time.Second
179+ }
171180
172181 if err := setupTLSConfig(opts, opt); err != nil {
173182 return nil, err
174183 }
175184
176− opt.ConnMaxIdleTime = time.Duration(opts.IdleTimeout) * time.Second
177−
178185 client := redis.NewClient(opt)
179186 return newClient(client), nil
180187}
pkg/sessions/redis/redis_store_test.go+50
@@ -1,6 +1,7 @@
11package redis
22
33import (
4+ "fmt"
45 "time"
56
67 "github.com/Bose/minisentinel"
@@ -246,6 +247,55 @@ var _ = Describe("Redis SessionStore Tests", func() {
246247 })
247248
248249 Describe("Redis URL Parsing", func() {
250+ It("should prefer configured username password and timeout over URL parameters", func() {
251+ configuredUsername := "configured-user"
252+ configuredPassword := "configured-password"
253+ configuredIdleTimeout := 90
254+
255+ urlUsername := "url-user"
256+ urlPassword := "url-password"
257+ urlIdleTimeout := 30
258+
259+ redisClient, err := buildStandaloneClient(options.RedisStoreOptions{
260+ ConnectionURL: fmt.Sprintf("redis://%s:%s@localhost:6379?conn_max_idle_time=%d", urlUsername, urlPassword, urlIdleTimeout),
261+ Username: configuredUsername,
262+ Password: configuredPassword,
263+ IdleTimeout: configuredIdleTimeout,
264+ })
265+ Expect(err).ToNot(HaveOccurred())
266+
267+ rc, ok := redisClient.(*client)
268+ Expect(ok).To(BeTrue())
269+ Expect(rc.Close()).To(Succeed())
270+
271+ redisOptions := rc.Options()
272+ Expect(redisOptions.Username).To(Equal(configuredUsername))
273+ Expect(redisOptions.Password).To(Equal(configuredPassword))
274+ Expect(redisOptions.ConnMaxIdleTime).To(Equal(time.Duration(configuredIdleTimeout) * time.Second))
275+ })
276+ It("should prefer URL username password and timeout when configured values are empty", func() {
277+ urlUsername := "url-user"
278+ urlPassword := "url-password"
279+ urlIdleTimeout := 30
280+
281+ redisClient, err := buildStandaloneClient(options.RedisStoreOptions{
282+ ConnectionURL: fmt.Sprintf("redis://%s:%s@localhost:6379?conn_max_idle_time=%d", urlUsername, urlPassword, urlIdleTimeout),
283+ Username: "",
284+ Password: "",
285+ IdleTimeout: 0,
286+ })
287+ Expect(err).ToNot(HaveOccurred())
288+
289+ rc, ok := redisClient.(*client)
290+ Expect(ok).To(BeTrue())
291+ Expect(rc.Close()).To(Succeed())
292+
293+ redisOptions := rc.Options()
294+ Expect(redisOptions.Username).To(Equal(urlUsername))
295+ Expect(redisOptions.Password).To(Equal(urlPassword))
296+ Expect(redisOptions.ConnMaxIdleTime).To(Equal(time.Duration(urlIdleTimeout) * time.Second))
297+ })
298+
249299 It("should parse valid redis URL", func() {
250300 addrs, opts, err := parseRedisURLs([]string{"redis://localhost:6379"})
251301 Expect(err).ToNot(HaveOccurred())
pkg/sessions/tests/session_store_tests.go+11−1
@@ -422,7 +422,17 @@ func SessionStoreInterfaceTests(in *testInput) {
422422 broken := "BrokenSessionFromADifferentSessionImplementation"
423423 value, err := encryption.SignedValue(in.cookieOpts.Secret, in.cookieOpts.Name, []byte(broken), time.Now())
424424 Expect(err).ToNot(HaveOccurred())
425− cookie := cookiesapi.MakeCookieFromOptions(in.request, in.cookieOpts.Name, value, in.cookieOpts, in.cookieOpts.Expire)
425+ cookieOptions := &cookiesapi.CookieOptions{
426+ Name: in.cookieOpts.Name,
427+ Value: value,
428+ Domains: in.cookieOpts.Domains,
429+ Expiration: in.cookieOpts.Expire,
430+ SameSite: in.cookieOpts.SameSite,
431+ Path: in.cookieOpts.Path,
432+ HTTPOnly: in.cookieOpts.HTTPOnly,
433+ Secure: in.cookieOpts.Secure,
434+ }
435+ cookie := cookiesapi.MakeCookieFromOptions(in.request, cookieOptions)
426436 in.request.AddCookie(cookie)
427437
428438 err = in.ss().Save(in.response, in.request, in.session)
pkg/upstream/http.go+55−16
@@ -123,7 +123,7 @@ func (t *unixRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)
123123// The proxy should render an error page if there are failures connecting to the
124124// upstream server.
125125func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler ProxyErrorHandler) http.Handler {
126− proxy := httputil.NewSingleHostReverseProxy(target)
126+ proxy := newSingleHostReverseProxy(target)
127127
128128 // Inherit default transport options from Go's stdlib
129129 transport := http.DefaultTransport.(*http.Transport).Clone()
@@ -155,7 +155,7 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr
155155 }
156156
157157 // Ensure we always pass the original request path
158− setProxyDirector(proxy)
158+ setProxyRewrite(proxy)
159159
160160 // TODO (@tuunit) - this should be inverted or get a better name in the future to set the upstream host header
161161 // 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
179179 return proxy
180180}
181181
182−// setProxyUpstreamHostHeader sets the proxy.Director so that upstream requests
182+func newSingleHostReverseProxy(target *url.URL) *httputil.ReverseProxy {
183+ return &httputil.ReverseProxy{
184+ Rewrite: func(proxyReq *httputil.ProxyRequest) {
185+ proxyReq.SetURL(target)
186+ proxyReq.Out.Host = proxyReq.In.Host
187+ setProxyForwardingHeaders(proxyReq)
188+ },
189+ }
190+}
191+
192+// setProxyUpstreamHostHeader sets the proxy.Rewrite so that upstream requests
183193// receive a host header matching the target URL.
184194func setProxyUpstreamHostHeader(proxy *httputil.ReverseProxy, target *url.URL) {
185− director := proxy.Director
186− proxy.Director = func(req *http.Request) {
187− director(req)
188− req.Host = target.Host
195+ rewrite := proxy.Rewrite
196+ proxy.Rewrite = func(proxyReq *httputil.ProxyRequest) {
197+ rewrite(proxyReq)
198+ proxyReq.Out.Host = target.Host
189199 }
190200}
191201
192−// setProxyDirector sets the proxy.Director so that request URIs are escaped
202+// setProxyRewrite sets the proxy.Rewrite so that request URIs are escaped
193203// when proxying to usptream servers.
194−func setProxyDirector(proxy *httputil.ReverseProxy) {
195− director := proxy.Director
196− proxy.Director = func(req *http.Request) {
197− director(req)
204+func setProxyRewrite(proxy *httputil.ReverseProxy) {
205+ rewrite := proxy.Rewrite
206+ proxy.Rewrite = func(proxyReq *httputil.ProxyRequest) {
207+ rewrite(proxyReq)
198208 // use RequestURI so that we aren't unescaping encoded slashes in the request path
199− req.URL.Opaque = req.RequestURI
200− req.URL.RawQuery = ""
201− req.URL.ForceQuery = false
209+ proxyReq.Out.URL.Opaque = proxyReq.In.RequestURI
210+ proxyReq.Out.URL.RawQuery = ""
211+ proxyReq.Out.URL.ForceQuery = false
212+ }
213+}
214+
215+func setProxyForwardingHeaders(proxyReq *httputil.ProxyRequest) {
216+ // TODO (@tuunit): Preserve the legacy Director-based forwarding header behavior
217+ // for backwards compatibility. Harden this with saner defaults and/or
218+ // explicit flags in the future.
219+ for _, header := range []string{"Forwarded", "X-Forwarded-Host", "X-Forwarded-Proto"} {
220+ if values, ok := proxyReq.In.Header[header]; ok {
221+ proxyReq.Out.Header[header] = append([]string(nil), values...)
222+ }
223+ }
224+
225+ prior, ok := proxyReq.In.Header["X-Forwarded-For"]
226+ if ok {
227+ proxyReq.Out.Header["X-Forwarded-For"] = append([]string(nil), prior...)
228+ }
229+
230+ clientIP, _, err := net.SplitHostPort(proxyReq.In.RemoteAddr)
231+ if err != nil {
232+ return
233+ }
234+
235+ omit := ok && prior == nil
236+ if len(prior) > 0 {
237+ clientIP = strings.Join(prior, ", ") + ", " + clientIP
238+ }
239+ if !omit {
240+ proxyReq.Out.Header.Set("X-Forwarded-For", clientIP)
202241 }
203242}
204243
205244// newWebSocketReverseProxy creates a new reverse proxy for proxying websocket connections.
206245func newWebSocketReverseProxy(u *url.URL, skipTLSVerify *bool, passHostHeader *bool) http.Handler {
207− wsProxy := httputil.NewSingleHostReverseProxy(u)
246+ wsProxy := newSingleHostReverseProxy(u)
208247
209248 // Inherit default transport options from Go's stdlib
210249 transport := http.DefaultTransport.(*http.Transport).Clone()
pkg/upstream/http_test.go+57−3
@@ -361,7 +361,12 @@ var _ = Describe("HTTP Upstream Suite", func() {
361361 return http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
362362 proxy, ok := h.(*httputil.ReverseProxy)
363363 Expect(ok).To(BeTrue())
364− proxy.Director(req)
364+ outReq := req.Clone(req.Context())
365+ proxy.Rewrite(&httputil.ProxyRequest{
366+ In: req,
367+ Out: outReq,
368+ })
369+ req.Host = outReq.Host
365370 })
366371 }
367372 httpUpstream.handler = requestInterceptor(httpUpstream.handler)
@@ -370,6 +375,54 @@ var _ = Describe("HTTP Upstream Suite", func() {
370375 Expect(req.Host).To(Equal(strings.TrimPrefix(serverAddr, "http://")))
371376 })
372377
378+ It("ServeHTTP preserves forwarding headers when using Rewrite", func() {
379+ req := httptest.NewRequest("", "http://example.localhost/foo", nil)
380+ req.RemoteAddr = "192.0.2.10:1234"
381+ req.Header.Set("Forwarded", "for=192.0.2.1;proto=https;host=example.localhost")
382+ req.Header.Set("X-Forwarded-Host", "forwarded.example.localhost")
383+ req.Header.Set("X-Forwarded-Proto", "https")
384+ req.Header.Set("X-Forwarded-For", "192.0.2.1")
385+ req = middlewareapi.AddRequestScope(req, &middlewareapi.RequestScope{})
386+ rw := httptest.NewRecorder()
387+
388+ upstream := options.Upstream{
389+ ID: "preserveForwardedHeaders",
390+ PassHostHeader: ptr.To(true),
391+ ProxyWebSockets: ptr.To(false),
392+ InsecureSkipTLSVerify: ptr.To(false),
393+ FlushInterval: &defaultFlushInterval,
394+ Timeout: &defaultTimeout,
395+ }
396+
397+ u, err := url.Parse(serverAddr)
398+ Expect(err).ToNot(HaveOccurred())
399+
400+ handler := newHTTPUpstreamProxy(upstream, u, nil, nil)
401+ httpUpstream, ok := handler.(*httpUpstreamProxy)
402+ Expect(ok).To(BeTrue())
403+
404+ requestInterceptor := func(h http.Handler) http.Handler {
405+ return http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
406+ proxy, ok := h.(*httputil.ReverseProxy)
407+ Expect(ok).To(BeTrue())
408+
409+ outReq := req.Clone(req.Context())
410+ proxy.Rewrite(&httputil.ProxyRequest{
411+ In: req,
412+ Out: outReq,
413+ })
414+
415+ Expect(outReq.Header.Values("Forwarded")).To(Equal([]string{"for=192.0.2.1;proto=https;host=example.localhost"}))
416+ Expect(outReq.Header.Values("X-Forwarded-Host")).To(Equal([]string{"forwarded.example.localhost"}))
417+ Expect(outReq.Header.Values("X-Forwarded-Proto")).To(Equal([]string{"https"}))
418+ Expect(outReq.Header.Values("X-Forwarded-For")).To(Equal([]string{"192.0.2.1, 192.0.2.10"}))
419+ })
420+ }
421+ httpUpstream.handler = requestInterceptor(httpUpstream.handler)
422+
423+ httpUpstream.ServeHTTP(rw, req)
424+ })
425+
373426 type newUpstreamTableInput struct {
374427 proxyWebSockets bool
375428 flushInterval time.Duration
@@ -405,6 +458,7 @@ var _ = Describe("HTTP Upstream Suite", func() {
405458
406459 proxy, ok := upstreamProxy.handler.(*httputil.ReverseProxy)
407460 Expect(ok).To(BeTrue())
461+ Expect(proxy.Rewrite).ToNot(BeNil())
408462 Expect(proxy.FlushInterval).To(Equal(in.flushInterval))
409463 transport, ok := proxy.Transport.(*http.Transport)
410464 Expect(ok).To(BeTrue())
@@ -498,7 +552,7 @@ var _ = Describe("HTTP Upstream Suite", func() {
498552
499553 handler := newHTTPUpstreamProxy(upstream, u, nil, nil)
500554
501− proxyServer = httptest.NewServer(middleware.NewScope(false, "X-Request-Id")(handler))
555+ proxyServer = httptest.NewServer(middleware.NewScope(false, "X-Request-Id", nil)(handler))
502556 })
503557
504558 AfterEach(func() {
@@ -549,7 +603,7 @@ var _ = Describe("HTTP Upstream Suite", func() {
549603 Expect(err).ToNot(HaveOccurred())
550604
551605 handler := newHTTPUpstreamProxy(upstream, u, nil, nil)
552− noPassHostServer := httptest.NewServer(middleware.NewScope(false, "X-Request-Id")(handler))
606+ noPassHostServer := httptest.NewServer(middleware.NewScope(false, "X-Request-Id", nil)(handler))
553607 defer noPassHostServer.Close()
554608
555609 origin := "http://example.localhost"
pkg/upstream/proxy.go+14−14
@@ -58,7 +58,9 @@ func NewProxy(upstreams options.UpstreamConfig, sigData *options.SignatureData,
5858 }
5959 }
6060
61− registerTrailingSlashHandler(m.serveMux)
61+ if err := registerTrailingSlashHandler(m.serveMux); err != nil {
62+ return nil, fmt.Errorf("could not register trailing slash handler: %w", err)
63+ }
6264 return m, nil
6365}
6466
@@ -94,8 +96,7 @@ func (m *multiUpstreamProxy) registerHTTPUpstreamProxy(upstream options.Upstream
9496// registerHandler ensures the given handler is regiestered with the serveMux.
9597func (m *multiUpstreamProxy) registerHandler(upstream options.Upstream, handler http.Handler, writer pagewriter.Writer) error {
9698 if upstream.RewriteTarget == "" {
97− m.registerSimpleHandler(upstream.Path, handler)
98− return nil
99+ return m.registerSimpleHandler(upstream.Path, handler)
99100 }
100101
101102 return m.registerRewriteHandler(upstream, handler, writer)
@@ -103,12 +104,12 @@ func (m *multiUpstreamProxy) registerHandler(upstream options.Upstream, handler
103104
104105// registerSimpleHandler maintains the behaviour of the go standard serveMux
105106// by ensuring any path with a trailing `/` matches all paths under that prefix.
106−func (m *multiUpstreamProxy) registerSimpleHandler(path string, handler http.Handler) {
107+func (m *multiUpstreamProxy) registerSimpleHandler(path string, handler http.Handler) error {
107108 if strings.HasSuffix(path, "/") {
108− m.serveMux.PathPrefix(path).Handler(handler)
109− } else {
110− m.serveMux.Path(path).Handler(handler)
109+ return m.serveMux.PathPrefix(path).Handler(handler).GetError()
111110 }
111+
112+ return m.serveMux.Path(path).Handler(handler).GetError()
112113}
113114
114115// registerRewriteHandler ensures the handler is registered for all paths
@@ -123,19 +124,18 @@ func (m *multiUpstreamProxy) registerRewriteHandler(upstream options.Upstream, h
123124
124125 rewrite := newRewritePath(rewriteRegExp, upstream.RewriteTarget, writer)
125126 h := alice.New(rewrite).Then(handler)
126− m.serveMux.MatcherFunc(func(req *http.Request, _ *mux.RouteMatch) bool {
127− return rewriteRegExp.MatchString(req.URL.Path)
128− }).Handler(h)
129127
130− return nil
128+ return m.serveMux.MatcherFunc(func(req *http.Request, _ *mux.RouteMatch) bool {
129+ return rewriteRegExp.MatchString(req.URL.Path)
130+ }).Handler(h).GetError()
131131}
132132
133133// registerTrailingSlashHandler creates a new matcher that will check if the
134134// requested path would match if it had a trailing slash appended.
135135// If the path matches with a trailing slash, we send back a redirect.
136136// This allows us to be consistent with the built in go servemux implementation.
137−func registerTrailingSlashHandler(serveMux *mux.Router) {
138− serveMux.MatcherFunc(func(req *http.Request, _ *mux.RouteMatch) bool {
137+func registerTrailingSlashHandler(serveMux *mux.Router) error {
138+ return serveMux.MatcherFunc(func(req *http.Request, _ *mux.RouteMatch) bool {
139139 if strings.HasSuffix(req.URL.Path, "/") {
140140 return false
141141 }
@@ -149,7 +149,7 @@ func registerTrailingSlashHandler(serveMux *mux.Router) {
149149 return serveMux.Match(slashReq, m)
150150 }).Handler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
151151 http.Redirect(rw, req, req.URL.String()+"/", http.StatusMovedPermanently)
152− }))
152+ })).GetError()
153153}
154154
155155// sortByPathLongest ensures that the upstreams are sorted by longest path.
pkg/upstream/proxy_test.go+33−1
@@ -79,7 +79,7 @@ var _ = Describe("Proxy Suite", func() {
7979 {
8080 ID: "bad-http-backend",
8181 Path: "/bad-http/",
82− URI: "http://::1",
82+ URI: invalidServer,
8383 },
8484 {
8585 ID: "single-path-backend",
@@ -383,6 +383,38 @@ var _ = Describe("Proxy Suite", func() {
383383 )
384384 })
385385
386+ Context("multiUpstreamProxy errors", func() {
387+ type proxyErrorTableInput struct {
388+ upstreams options.UpstreamConfig
389+ expectedError string
390+ }
391+
392+ DescribeTable("NewProxy", func(in *proxyErrorTableInput) {
393+ sigData := &options.SignatureData{Hash: crypto.SHA256, Key: "secret"}
394+
395+ writer := &pagewriter.WriterFuncs{
396+ ProxyErrorFunc: func(rw http.ResponseWriter, _ *http.Request, _ error) {
397+ rw.WriteHeader(502)
398+ rw.Write([]byte("Proxy Error"))
399+ },
400+ }
401+
402+ _, err := NewProxy(in.upstreams, sigData, writer)
403+ Expect(err).To(MatchError(in.expectedError))
404+ },
405+ Entry("regex matcher without rewrite target", &proxyErrorTableInput{
406+ upstreams: options.UpstreamConfig{
407+ Upstreams: []options.Upstream{{
408+ ID: "api",
409+ Path: "^/api/$",
410+ URI: "http://example.com",
411+ }},
412+ },
413+ expectedError: `could not register http upstream "api": mux: path must start with a slash, got "^/api/$"`,
414+ }),
415+ )
416+ })
417+
386418 Context("sortByPathLongest", func() {
387419 type sortByPathLongestTableInput struct {
388420 input []options.Upstream
pkg/upstream/upstream_suite_test.go+1−1
@@ -24,7 +24,7 @@ var (
2424 serverAddr string
2525 unixServer *httptest.Server
2626 unixServerAddr string
27− invalidServer = "http://::1"
27+ invalidServer = "http://127.0.0.1:1"
2828)
2929
3030func TestUpstreamSuite(t *testing.T) {
pkg/util/util.go+64
@@ -5,6 +5,7 @@ import (
55 "crypto/rsa"
66 "crypto/x509"
77 "crypto/x509/pkix"
8+ "encoding/json"
89 "fmt"
910 "math/big"
1011 "net"
@@ -12,6 +13,8 @@ import (
1213 "os"
1314 "strings"
1415 "time"
16+
17+ "github.com/spf13/cast"
1518)
1619
1720func GetCertPool(paths []string, useSystemPool bool) (*x509.CertPool, error) {
@@ -191,3 +194,64 @@ func RemoveDuplicateStr(strSlice []string) []string {
191194 }
192195 return list
193196}
197+
198+// CoerceClaim tries to convert the value into the destination interface type.
199+// If it can convert the value, it will then store the value in the destination
200+// interface.
201+func CoerceClaim(value, dst any) error {
202+ switch d := dst.(type) {
203+ case *string:
204+ str, err := toString(value)
205+ if err != nil {
206+ return fmt.Errorf("could not convert value to string: %v", err)
207+ }
208+ *d = str
209+ case *[]string:
210+ strSlice, err := toStringSlice(value)
211+ if err != nil {
212+ return fmt.Errorf("could not convert value to string slice: %v", err)
213+ }
214+ *d = strSlice
215+ case *bool:
216+ *d = cast.ToBool(value)
217+ default:
218+ return fmt.Errorf("unknown type for destination: %T", dst)
219+ }
220+ return nil
221+}
222+
223+// toStringSlice converts an interface (either a slice or single value) into
224+// a slice of strings.
225+func toStringSlice(value any) ([]string, error) {
226+ var sliceValues []any
227+ switch v := value.(type) {
228+ case []any:
229+ sliceValues = v
230+ default:
231+ sliceValues = []any{v}
232+ }
233+
234+ out := []string{}
235+ for _, v := range sliceValues {
236+ str, err := toString(v)
237+ if err != nil {
238+ return nil, fmt.Errorf("could not convert slice entry to string %v: %v", v, err)
239+ }
240+ out = append(out, str)
241+ }
242+ return out, nil
243+}
244+
245+// toString coerces a value into a string.
246+// If it is non-string, marshal it into JSON.
247+func toString(value any) (string, error) {
248+ if str, err := cast.ToStringE(value); err == nil {
249+ return str, nil
250+ }
251+
252+ jsonStr, err := json.Marshal(value)
253+ if err != nil {
254+ return "", err
255+ }
256+ return string(jsonStr), nil
257+}
pkg/util/util_test.go+70
@@ -2,10 +2,13 @@ package util
22
33import (
44 "crypto/x509"
5+ "encoding/json"
56 "encoding/pem"
67 "os"
8+ "reflect"
79 "testing"
810
11+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
912 "github.com/stretchr/testify/assert"
1013)
1114
@@ -253,3 +256,70 @@ func TestGetCertPool(t *testing.T) {
253256 assert.Error(t, err3)
254257 }
255258}
259+
260+type coerceClaimTableInput struct {
261+ name string
262+ value any
263+ dst any
264+ expectedDst any
265+ expectedError error
266+}
267+
268+func TestCoerceClaim(t *testing.T) {
269+ tests := []coerceClaimTableInput{
270+ {
271+ name: "coerces a string to a string",
272+ value: "some_string",
273+ dst: ptr.To(""),
274+ expectedDst: ptr.To("some_string"),
275+ },
276+ {
277+ name: "coerces a slice to a string slice",
278+ value: []any{"a", "b"},
279+ dst: ptr.To([]string{}),
280+ expectedDst: ptr.To([]string{"a", "b"}),
281+ },
282+ {
283+ name: "coerces a bool to a bool",
284+ value: true,
285+ dst: ptr.To(false),
286+ expectedDst: ptr.To(true),
287+ },
288+ {
289+ name: "coerces a string to a bool",
290+ value: "true",
291+ dst: ptr.To(false),
292+ expectedDst: ptr.To(true),
293+ },
294+ {
295+ name: "coerces a map to a string",
296+ value: map[string]any{
297+ "foo": []any{"bar", "baz"},
298+ },
299+ dst: ptr.To(""),
300+ expectedDst: ptr.To("{\"foo\":[\"bar\",\"baz\"]}"),
301+ },
302+ }
303+
304+ for _, tt := range tests {
305+ t.Run(tt.name, func(t *testing.T) {
306+ err := CoerceClaim(tt.value, tt.dst)
307+ if tt.expectedError != nil {
308+ if err == nil || err.Error() != tt.expectedError.Error() {
309+ t.Errorf("expected error %v, got %v", tt.expectedError, err)
310+ }
311+ return
312+ }
313+
314+ if err != nil {
315+ t.Fatalf("unexpected error: %v", err)
316+ }
317+
318+ if !reflect.DeepEqual(tt.dst, tt.expectedDst) {
319+ gotJSON, _ := json.Marshal(tt.dst)
320+ wantJSON, _ := json.Marshal(tt.expectedDst)
321+ t.Errorf("expected dst to be %+v, got %+v", string(wantJSON), string(gotJSON))
322+ }
323+ })
324+ }
325+}
pkg/validation/allowlist.go+13
@@ -11,10 +11,12 @@ import (
1111)
1212
1313func validateAllowlists(o *options.Options) []string {
14+ //nolint:prealloc
1415 msgs := []string{}
1516
1617 msgs = append(msgs, validateAuthRoutes(o)...)
1718 msgs = append(msgs, validateAuthRegexes(o)...)
19+ msgs = append(msgs, validateTrustedProxyIPs(o)...)
1820 msgs = append(msgs, validateTrustedIPs(o)...)
1921
2022 if len(o.TrustedIPs) > 0 && o.ReverseProxy {
@@ -27,6 +29,17 @@ func validateAllowlists(o *options.Options) []string {
2729 return msgs
2830}
2931
32+// validateTrustedProxyIPs validates IP/CIDRs for trusted reverse proxies.
33+func validateTrustedProxyIPs(o *options.Options) []string {
34+ msgs := []string{}
35+ for i, ipStr := range o.TrustedProxyIPs {
36+ if ip.ParseIPNet(ipStr) == nil {
37+ msgs = append(msgs, fmt.Sprintf("trusted_proxy_ips[%d] (%s) could not be recognized", i, ipStr))
38+ }
39+ }
40+ return msgs
41+}
42+
3043// validateAuthRoutes validates method=path routes passed with options.SkipAuthRoutes
3144func validateAuthRoutes(o *options.Options) []string {
3245 msgs := []string{}
pkg/validation/allowlist_test.go+30
@@ -23,6 +23,11 @@ var _ = Describe("Allowlist", func() {
2323 errStrings []string
2424 }
2525
26+ type validateTrustedProxyIPsTableInput struct {
27+ trustedProxyIPs []string
28+ errStrings []string
29+ }
30+
2631 DescribeTable("validateRoutes",
2732 func(r *validateRoutesTableInput) {
2833 opts := &options.Options{
@@ -121,4 +126,29 @@ var _ = Describe("Allowlist", func() {
121126 },
122127 }),
123128 )
129+
130+ DescribeTable("validateTrustedProxyIPs",
131+ func(t *validateTrustedProxyIPsTableInput) {
132+ opts := &options.Options{
133+ TrustedProxyIPs: t.trustedProxyIPs,
134+ }
135+ Expect(validateTrustedProxyIPs(opts)).To(ConsistOf(t.errStrings))
136+ },
137+ Entry("Valid trusted proxy IPs", &validateTrustedProxyIPsTableInput{
138+ trustedProxyIPs: []string{
139+ "127.0.0.1",
140+ "10.32.0.1/32",
141+ "::1",
142+ "2a12:105:ee7:9234:0:0:0:0/64",
143+ },
144+ errStrings: []string{},
145+ }),
146+ Entry("Invalid trusted proxy IPs", &validateTrustedProxyIPsTableInput{
147+ trustedProxyIPs: []string{"[::1]", "alkwlkbn/32"},
148+ errStrings: []string{
149+ "trusted_proxy_ips[0] ([::1]) could not be recognized",
150+ "trusted_proxy_ips[1] (alkwlkbn/32) could not be recognized",
151+ },
152+ }),
153+ )
124154})
pkg/validation/header.go+1
@@ -7,6 +7,7 @@ import (
77)
88
99func validateHeaders(headers []options.Header) []string {
10+ //nolint:prealloc
1011 msgs := []string{}
1112 names := make(map[string]struct{})
1213
pkg/validation/providers.go+35−1
@@ -4,10 +4,27 @@ import (
44 "fmt"
55 "os"
66
7+ jose "github.com/go-jose/go-jose/v4"
78 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
89 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
910)
1011
12+var supportedOIDCSigningAlgorithms = map[jose.SignatureAlgorithm]struct{}{
13+ jose.EdDSA: {},
14+ jose.HS256: {},
15+ jose.HS384: {},
16+ jose.HS512: {},
17+ jose.RS256: {},
18+ jose.RS384: {},
19+ jose.RS512: {},
20+ jose.ES256: {},
21+ jose.ES384: {},
22+ jose.ES512: {},
23+ jose.PS256: {},
24+ jose.PS384: {},
25+ jose.PS512: {},
26+}
27+
1128// validateProviders is the initial validation migration for multiple providrers
1229// It currently includes only logic that can verify the providers one by one and does not break the valdation pipe
1330func validateProviders(o *options.Options) []string {
@@ -59,6 +76,22 @@ func validateProvider(provider options.Provider, providerIDs map[string]struct{}
5976 msgs = append(msgs, validateEntraConfig(provider)...)
6077 }
6178
79+ msgs = append(msgs, validateOIDCSigningAlgorithms(provider)...)
80+
81+ return msgs
82+}
83+
84+func validateOIDCSigningAlgorithms(provider options.Provider) []string {
85+ msgs := []string{}
86+
87+ for _, algorithm := range provider.OIDCConfig.EnabledSigningAlgs {
88+ if _, ok := supportedOIDCSigningAlgorithms[jose.SignatureAlgorithm(algorithm)]; ok {
89+ continue
90+ }
91+
92+ msgs = append(msgs, fmt.Sprintf("provider %s has invalid EnabledSigningAlgs entry %q", provider.ID, algorithm))
93+ }
94+
6295 return msgs
6396}
6497
@@ -132,7 +165,8 @@ func validateEntraConfig(provider options.Provider) []string {
132165 return msgs
133166 }
134167
135− _, err := os.ReadFile(federatedTokenPath)
168+ // #nosec G703 -- AZURE_FEDERATED_TOKEN_FILE is set by the operator, not user input
169+ _, err := os.Stat(federatedTokenPath)
136170 if err != nil {
137171 msgs = append(msgs, "could not read entra federated token file")
138172 }
pkg/validation/providers_test.go+53
@@ -18,6 +18,33 @@ var _ = Describe("Providers", func() {
1818 ClientSecret: "ClientSecret",
1919 }
2020
21+ validOIDCSigningAlgorithmsProvider := options.Provider{
22+ ID: "ProviderIDOIDCSigningAlgorithms",
23+ ClientID: "ClientID",
24+ ClientSecret: "ClientSecret",
25+ OIDCConfig: options.OIDCOptions{
26+ EnabledSigningAlgs: []string{"RS256", "EdDSA"},
27+ },
28+ }
29+
30+ invalidOIDCSigningAlgorithmsProvider := options.Provider{
31+ ID: "ProviderIDInvalidOIDCSigningAlgorithms",
32+ ClientID: "ClientID",
33+ ClientSecret: "ClientSecret",
34+ OIDCConfig: options.OIDCOptions{
35+ EnabledSigningAlgs: []string{"RS256", "invalid"},
36+ },
37+ }
38+
39+ invalidOIDCSigningAlgorithmCaseProvider := options.Provider{
40+ ID: "ProviderIDInvalidOIDCSigningAlgorithmCase",
41+ ClientID: "ClientID",
42+ ClientSecret: "ClientSecret",
43+ OIDCConfig: options.OIDCOptions{
44+ EnabledSigningAlgs: []string{"rs256"},
45+ },
46+ }
47+
2148 validLoginGovProvider := options.Provider{
2249 Type: "login.gov",
2350 ID: "ProviderIDLoginGov",
@@ -34,6 +61,8 @@ var _ = Describe("Providers", func() {
3461 emptyIDMsg := "provider has empty id: ids are required for all providers"
3562 duplicateProviderIDMsg := "multiple providers found with id ProviderID: provider ids must be unique"
3663 skipButtonAndMultipleProvidersMsg := "SkipProviderButton and multiple providers are mutually exclusive"
64+ invalidOIDCSigningAlgorithmMsg := "provider ProviderIDInvalidOIDCSigningAlgorithms has invalid EnabledSigningAlgs entry \"invalid\""
65+ invalidOIDCSigningAlgorithmCaseMsg := "provider ProviderIDInvalidOIDCSigningAlgorithmCase has invalid EnabledSigningAlgs entry \"rs256\""
3766
3867 DescribeTable("validateProviders",
3968 func(o *validateProvidersTableInput) {
@@ -79,5 +108,29 @@ var _ = Describe("Providers", func() {
79108 },
80109 errStrings: []string{skipButtonAndMultipleProvidersMsg},
81110 }),
111+ Entry("with valid OIDC signing algorithms", &validateProvidersTableInput{
112+ options: &options.Options{
113+ Providers: options.Providers{
114+ validOIDCSigningAlgorithmsProvider,
115+ },
116+ },
117+ errStrings: []string{},
118+ }),
119+ Entry("with an invalid OIDC signing algorithm", &validateProvidersTableInput{
120+ options: &options.Options{
121+ Providers: options.Providers{
122+ invalidOIDCSigningAlgorithmsProvider,
123+ },
124+ },
125+ errStrings: []string{invalidOIDCSigningAlgorithmMsg},
126+ }),
127+ Entry("with an OIDC signing algorithm using invalid casing", &validateProvidersTableInput{
128+ options: &options.Options{
129+ Providers: options.Providers{
130+ invalidOIDCSigningAlgorithmCaseProvider,
131+ },
132+ },
133+ errStrings: []string{invalidOIDCSigningAlgorithmCaseMsg},
134+ }),
82135 )
83136})
pkg/validation/sessions_test.go+2−2
@@ -193,8 +193,8 @@ var _ = Describe("Sessions", func() {
193193 unreachableRedisDelMsg = "unable to delete the redis initialization key: dial tcp 127.0.0.1:65535: connect: connection refused"
194194 unreachableSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: redis: nil"
195195 unrechableSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable: redis: nil"
196− refusedSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: context deadline exceeded"
197− refusedSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable: context deadline exceeded"
196+ 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"
197+ 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"
198198 )
199199
200200 type redisStoreTableInput struct {
pkg/validation/upstreams.go+4−3
@@ -9,6 +9,7 @@ import (
99)
1010
1111func validateUpstreams(upstreams options.UpstreamConfig) []string {
12+ //nolint:prealloc
1213 msgs := []string{}
1314 ids := make(map[string]struct{})
1415 paths := make(map[string]struct{})
@@ -70,13 +71,13 @@ func validateStaticUpstream(upstream options.Upstream) []string {
7071 if ptr.Deref(upstream.InsecureSkipTLSVerify, options.DefaultUpsteamInsecureSkipTLSVerify) {
7172 msgs = append(msgs, fmt.Sprintf("upstream %q has insecureSkipTLSVerify, but is a static upstream, this will have no effect.", upstream.ID))
7273 }
73− if upstream.FlushInterval != nil && *upstream.FlushInterval != options.DefaultUpstreamFlushInterval {
74+ if ptr.Deref(upstream.FlushInterval, options.DefaultUpstreamFlushInterval) != options.DefaultUpstreamFlushInterval {
7475 msgs = append(msgs, fmt.Sprintf("upstream %q has flushInterval, but is a static upstream, this will have no effect.", upstream.ID))
7576 }
76− if upstream.PassHostHeader != nil {
77+ if ptr.Deref(upstream.PassHostHeader, options.DefaultStaticPassHostHeader) != options.DefaultStaticPassHostHeader {
7778 msgs = append(msgs, fmt.Sprintf("upstream %q has passHostHeader, but is a static upstream, this will have no effect.", upstream.ID))
7879 }
79− if upstream.ProxyWebSockets != nil {
80+ if ptr.Deref(upstream.ProxyWebSockets, options.DefaultStaticProxyWebSockets) != options.DefaultStaticProxyWebSockets {
8081 msgs = append(msgs, fmt.Sprintf("upstream %q has proxyWebSockets, but is a static upstream, this will have no effect.", upstream.ID))
8182 }
8283
pkg/validation/upstreams_test.go+19−1
@@ -138,7 +138,7 @@ var _ = Describe("Upstreams", func() {
138138 },
139139 errStrings: []string{invalidURISchemeMsg},
140140 }),
141− Entry("with a static upstream and invalid optons", &validateUpstreamTableInput{
141+ Entry("with a static upstream and invalid options", &validateUpstreamTableInput{
142142 upstreams: options.UpstreamConfig{
143143 Upstreams: []options.Upstream{
144144 {
@@ -161,6 +161,24 @@ var _ = Describe("Upstreams", func() {
161161 staticWithProxyWebSocketsMsg,
162162 },
163163 }),
164+ Entry("with a static upstream and sane default options", &validateUpstreamTableInput{
165+ upstreams: options.UpstreamConfig{
166+ Upstreams: []options.Upstream{
167+ {
168+ ID: "foo",
169+ Path: "/foo",
170+ URI: "ftp://foo",
171+ Static: ptr.To(true),
172+ PassHostHeader: ptr.To(false),
173+ ProxyWebSockets: ptr.To(false),
174+ InsecureSkipTLSVerify: ptr.To(false),
175+ },
176+ },
177+ },
178+ errStrings: []string{
179+ staticWithURIMsg,
180+ },
181+ }),
164182 Entry("with duplicate IDs", &validateUpstreamTableInput{
165183 upstreams: options.UpstreamConfig{
166184 Upstreams: []options.Upstream{
providers/atlassian-cloud.gonew file+99
@@ -0,0 +1,99 @@
1+package providers
2+
3+import (
4+ "context"
5+ "errors"
6+ "net/url"
7+
8+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
9+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests"
10+)
11+
12+// AtlassianProvider represents an Atlassian Cloud based Identity Provider
13+type AtlassianProvider struct {
14+ *ProviderData
15+}
16+
17+var _ Provider = (*AtlassianProvider)(nil)
18+
19+const (
20+ atlassianProviderName = "Atlassian"
21+ atlassianDefaultScope = "read:me"
22+ atlassianPrompt = "consent"
23+ atlassianAudience = "api.atlassian.com"
24+)
25+
26+var (
27+ atlassianDefaultLoginURL = &url.URL{
28+ Scheme: "https",
29+ Host: "auth.atlassian.com",
30+ Path: "/authorize",
31+ }
32+
33+ atlassianDefaultRedeemURL = &url.URL{
34+ Scheme: "https",
35+ Host: "auth.atlassian.com",
36+ Path: "/oauth/token",
37+ }
38+
39+ // atlassianDefaultProfileURL returns the signed-in user's profile.
40+ atlassianDefaultProfileURL = &url.URL{
41+ Scheme: "https",
42+ Host: "api.atlassian.com",
43+ Path: "/me",
44+ }
45+)
46+
47+// NewAtlassianProvider initiates a new AtlassianProvider
48+func NewAtlassianProvider(p *ProviderData) *AtlassianProvider {
49+ p.setProviderDefaults(providerDefaults{
50+ name: atlassianProviderName,
51+ loginURL: atlassianDefaultLoginURL,
52+ redeemURL: atlassianDefaultRedeemURL,
53+ profileURL: atlassianDefaultProfileURL,
54+ validateURL: atlassianDefaultProfileURL,
55+ scope: atlassianDefaultScope,
56+ })
57+ return &AtlassianProvider{ProviderData: p}
58+}
59+
60+// GetLoginURL adds the audience and prompt parameters Atlassian requires.
61+func (p *AtlassianProvider) GetLoginURL(redirectURI, state, _ string, extraParams url.Values) string {
62+ params := url.Values{}
63+ for k, v := range extraParams {
64+ params[k] = v
65+ }
66+ params.Del("approval_prompt")
67+ if params.Get("prompt") == "" {
68+ params.Set("prompt", atlassianPrompt)
69+ }
70+ params.Set("audience", atlassianAudience)
71+
72+ loginURL := makeLoginURL(p.ProviderData, redirectURI, state, params)
73+ return loginURL.String()
74+}
75+
76+// EnrichSession sets the session's email from the Atlassian profile.
77+func (p *AtlassianProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error {
78+ var profile struct {
79+ Email string `json:"email"`
80+ }
81+ err := requests.New(p.ProfileURL.String()).
82+ WithContext(ctx).
83+ WithHeaders(makeOIDCHeader(s.AccessToken)).
84+ Do().
85+ UnmarshalInto(&profile)
86+ if err != nil {
87+ return err
88+ }
89+ if profile.Email == "" {
90+ return errors.New("no email in Atlassian profile")
91+ }
92+ s.Email = profile.Email
93+ return nil
94+}
95+
96+// ValidateSession validates the AccessToken
97+func (p *AtlassianProvider) ValidateSession(ctx context.Context, s *sessions.SessionState) bool {
98+ return validateToken(ctx, p, s.AccessToken, makeOIDCHeader(s.AccessToken))
99+}
providers/atlassian-cloud_test.gonew file+93
@@ -0,0 +1,93 @@
1+package providers
2+
3+import (
4+ "context"
5+ "net/http"
6+ "net/http/httptest"
7+ "net/url"
8+ "testing"
9+
10+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
11+ . "github.com/onsi/gomega"
12+)
13+
14+func testAtlassianBackend(status int, body string) *httptest.Server {
15+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
16+ if r.URL.Path != "/me" || r.Header.Get("Authorization") != "Bearer imaginary_access_token" {
17+ w.WriteHeader(http.StatusUnauthorized)
18+ return
19+ }
20+ w.WriteHeader(status)
21+ _, _ = w.Write([]byte(body))
22+ }))
23+}
24+
25+func testAtlassianProvider(backend *httptest.Server) *AtlassianProvider {
26+ p := NewAtlassianProvider(&ProviderData{})
27+ u, _ := url.Parse(backend.URL)
28+ updateURL(p.ProfileURL, u.Host)
29+ updateURL(p.ValidateURL, u.Host)
30+ return p
31+}
32+
33+func TestNewAtlassianProvider(t *testing.T) {
34+ g := NewWithT(t)
35+
36+ providerData := NewAtlassianProvider(&ProviderData{}).Data()
37+ g.Expect(providerData.ProviderName).To(Equal("Atlassian"))
38+ g.Expect(providerData.LoginURL.String()).To(Equal("https://auth.atlassian.com/authorize"))
39+ g.Expect(providerData.RedeemURL.String()).To(Equal("https://auth.atlassian.com/oauth/token"))
40+ g.Expect(providerData.ProfileURL.String()).To(Equal("https://api.atlassian.com/me"))
41+ g.Expect(providerData.ValidateURL.String()).To(Equal("https://api.atlassian.com/me"))
42+ g.Expect(providerData.Scope).To(Equal("read:me"))
43+}
44+
45+func TestAtlassianProviderGetLoginURL(t *testing.T) {
46+ g := NewWithT(t)
47+ p := NewAtlassianProvider(&ProviderData{ClientID: "client"})
48+
49+ loginURL, err := url.Parse(p.GetLoginURL("https://proxy/oauth2/callback", "state", "",
50+ url.Values{"approval_prompt": {"force"}}))
51+ g.Expect(err).ToNot(HaveOccurred())
52+
53+ q := loginURL.Query()
54+ g.Expect(q.Get("audience")).To(Equal("api.atlassian.com"))
55+ g.Expect(q.Get("prompt")).To(Equal("consent"))
56+ g.Expect(q.Has("approval_prompt")).To(BeFalse())
57+ g.Expect(q.Get("scope")).To(Equal("read:me"))
58+
59+ loginURL, err = url.Parse(p.GetLoginURL("https://proxy/oauth2/callback", "state", "",
60+ url.Values{"prompt": {"login"}}))
61+ g.Expect(err).ToNot(HaveOccurred())
62+ g.Expect(loginURL.Query().Get("prompt")).To(Equal("login"))
63+}
64+
65+func TestAtlassianProviderEnrichSession(t *testing.T) {
66+ g := NewWithT(t)
67+ b := testAtlassianBackend(http.StatusOK, `{"account_id":"abc","email":"user@example.com"}`)
68+ defer b.Close()
69+ p := testAtlassianProvider(b)
70+
71+ session := CreateAuthorizedSession()
72+ g.Expect(p.EnrichSession(context.Background(), session)).To(Succeed())
73+ g.Expect(session.Email).To(Equal("user@example.com"))
74+}
75+
76+func TestAtlassianProviderEnrichSessionWithoutEmail(t *testing.T) {
77+ g := NewWithT(t)
78+ b := testAtlassianBackend(http.StatusOK, `{"account_id":"abc"}`)
79+ defer b.Close()
80+ p := testAtlassianProvider(b)
81+
82+ g.Expect(p.EnrichSession(context.Background(), CreateAuthorizedSession())).ToNot(Succeed())
83+}
84+
85+func TestAtlassianProviderValidateSession(t *testing.T) {
86+ g := NewWithT(t)
87+ b := testAtlassianBackend(http.StatusOK, `{"email":"user@example.com"}`)
88+ defer b.Close()
89+ p := testAtlassianProvider(b)
90+
91+ g.Expect(p.ValidateSession(context.Background(), CreateAuthorizedSession())).To(BeTrue())
92+ g.Expect(p.ValidateSession(context.Background(), &sessions.SessionState{AccessToken: "wrong"})).To(BeFalse())
93+}
providers/azure.go+3−2
@@ -166,7 +166,7 @@ func (p *AzureProvider) Redeem(ctx context.Context, redirectURL, code, codeVerif
166166
167167 err = requests.New(p.RedeemURL.String()).
168168 WithContext(ctx).
169− WithMethod("POST").
169+ WithMethod(http.MethodPost).
170170 WithBody(bytes.NewBufferString(params.Encode())).
171171 SetHeader("Content-Type", "application/x-www-form-urlencoded").
172172 Do().
@@ -334,7 +334,7 @@ func (p *AzureProvider) redeemRefreshToken(ctx context.Context, s *sessions.Sess
334334
335335 err = requests.New(p.RedeemURL.String()).
336336 WithContext(ctx).
337− WithMethod("POST").
337+ WithMethod(http.MethodPost).
338338 WithBody(bytes.NewBufferString(params.Encode())).
339339 SetHeader("Content-Type", "application/x-www-form-urlencoded").
340340 Do().
@@ -399,6 +399,7 @@ func (p *AzureProvider) getGroupsFromProfileAPI(ctx context.Context, s *sessions
399399}
400400
401401func getGroupsFromJSON(json *simplejson.Json, graphGroupField string) []string {
402+ //nolint:prealloc
402403 groups := []string{}
403404
404405 for i := range json.Get("value").MustArray() {
providers/dtt_sso.gonew file+202
@@ -0,0 +1,202 @@
1+package providers
2+
3+import (
4+ "bytes"
5+ "context"
6+ "encoding/base64"
7+ "errors"
8+ "fmt"
9+ "net/http"
10+ "net/url"
11+ "time"
12+
13+ "github.com/golang-jwt/jwt/v5"
14+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
15+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests"
16+)
17+
18+// DTTSSOProvider signs users in with the DTT SSO (auth-server).
19+type DTTSSOProvider struct {
20+ *ProviderData
21+}
22+
23+var _ Provider = (*DTTSSOProvider)(nil)
24+
25+const (
26+ dttSSOProviderName = "DTT SSO"
27+ dttSSODefaultScope = "openid"
28+)
29+
30+var (
31+ dttSSODefaultLoginURL = &url.URL{
32+ Scheme: "https",
33+ Host: "auth.thebestagent.pro",
34+ Path: "/oauth/authorize",
35+ }
36+
37+ dttSSODefaultRedeemURL = &url.URL{
38+ Scheme: "https",
39+ Host: "auth.thebestagent.pro",
40+ Path: "/oauth/token",
41+ }
42+
43+ dttSSODefaultValidateURL = &url.URL{
44+ Scheme: "https",
45+ Host: "auth.thebestagent.pro",
46+ Path: "/oauth/check_token",
47+ }
48+)
49+
50+// NewDTTSSOProvider initiates a new DTTSSOProvider
51+func NewDTTSSOProvider(p *ProviderData) *DTTSSOProvider {
52+ p.setProviderDefaults(providerDefaults{
53+ name: dttSSOProviderName,
54+ loginURL: dttSSODefaultLoginURL,
55+ redeemURL: dttSSODefaultRedeemURL,
56+ profileURL: nil,
57+ validateURL: dttSSODefaultValidateURL,
58+ scope: dttSSODefaultScope,
59+ })
60+ return &DTTSSOProvider{ProviderData: p}
61+}
62+
63+// dttSSOTokenResponse is the SSO's /oauth/token response.
64+type dttSSOTokenResponse struct {
65+ AccessToken string `json:"access_token"`
66+ RefreshToken string `json:"refresh_token"`
67+ ExpiresIn int64 `json:"expires_in"`
68+ IDToken string `json:"id_token"`
69+}
70+
71+// dttSSOClaims holds the id_token claims the provider uses.
72+type dttSSOClaims struct {
73+ jwt.RegisteredClaims
74+ Email string `json:"email"`
75+ Role string `json:"role"`
76+ UserID string `json:"user_id"`
77+}
78+
79+// Redeem exchanges the authorization code for a session.
80+func (p *DTTSSOProvider) Redeem(ctx context.Context, redirectURL, code, _ string) (*sessions.SessionState, error) {
81+ if code == "" {
82+ return nil, ErrMissingCode
83+ }
84+ return p.requestTokens(ctx, url.Values{
85+ "grant_type": {"authorization_code"},
86+ "code": {code},
87+ "redirect_uri": {redirectURL},
88+ })
89+}
90+
91+// RefreshSession renews the tokens and re-reads the email and role.
92+func (p *DTTSSOProvider) RefreshSession(ctx context.Context, s *sessions.SessionState) (bool, error) {
93+ if s == nil || s.RefreshToken == "" {
94+ return false, nil
95+ }
96+ refreshed, err := p.requestTokens(ctx, url.Values{
97+ "grant_type": {"refresh_token"},
98+ "refresh_token": {s.RefreshToken},
99+ })
100+ if err != nil {
101+ return false, fmt.Errorf("unable to redeem refresh token: %v", err)
102+ }
103+ s.AccessToken = refreshed.AccessToken
104+ s.RefreshToken = refreshed.RefreshToken
105+ s.IDToken = refreshed.IDToken
106+ s.Email = refreshed.Email
107+ s.User = refreshed.User
108+ s.Groups = refreshed.Groups
109+ s.CreatedAt = refreshed.CreatedAt
110+ s.ExpiresOn = refreshed.ExpiresOn
111+ return true, nil
112+}
113+
114+// ValidateSession checks the access token with the SSO's check_token endpoint.
115+func (p *DTTSSOProvider) ValidateSession(ctx context.Context, s *sessions.SessionState) bool {
116+ return validateToken(ctx, p, s.AccessToken, makeOIDCHeader(s.AccessToken))
117+}
118+
119+// requestTokens calls the token endpoint and builds a session from the verified id_token.
120+//
121+// The SSO compares the Basic credentials byte for byte, so they are sent unescaped
122+// rather than through golang.org/x/oauth2, which URL-escapes them.
123+func (p *DTTSSOProvider) requestTokens(ctx context.Context, params url.Values) (*sessions.SessionState, error) {
124+ clientSecret, err := p.GetClientSecret()
125+ if err != nil {
126+ return nil, err
127+ }
128+ credentials := base64.StdEncoding.EncodeToString([]byte(p.ClientID + ":" + clientSecret))
129+
130+ result := requests.New(p.RedeemURL.String()).
131+ WithContext(ctx).
132+ WithMethod(http.MethodPost).
133+ WithBody(bytes.NewBufferString(params.Encode())).
134+ SetHeader("Content-Type", "application/x-www-form-urlencoded").
135+ SetHeader("Authorization", "Basic "+credentials).
136+ Do()
137+ if result.Error() != nil {
138+ return nil, result.Error()
139+ }
140+ if result.StatusCode() != http.StatusOK {
141+ return nil, fmt.Errorf("token request failed: status %d - %s", result.StatusCode(), result.Body())
142+ }
143+
144+ var token dttSSOTokenResponse
145+ if err := result.UnmarshalInto(&token); err != nil {
146+ return nil, err
147+ }
148+ if token.AccessToken == "" {
149+ return nil, errors.New("token response carried no access_token")
150+ }
151+ claims, err := p.verifyIDToken(token.IDToken, clientSecret)
152+ if err != nil {
153+ return nil, err
154+ }
155+
156+ s := &sessions.SessionState{
157+ AccessToken: token.AccessToken,
158+ RefreshToken: token.RefreshToken,
159+ IDToken: token.IDToken,
160+ Email: claims.Email,
161+ User: claims.UserID,
162+ }
163+ if claims.Role != "" {
164+ s.Groups = []string{claims.Role}
165+ }
166+ s.CreatedAtNow()
167+ if token.ExpiresIn > 0 {
168+ s.ExpiresIn(time.Duration(token.ExpiresIn) * time.Second)
169+ }
170+ return s, nil
171+}
172+
173+// verifyIDToken checks the id_token's HS256 signature (keyed on the client secret),
174+// issuer, audience and expiry.
175+//
176+// go-jose is not used: it rejects HMAC keys under 32 bytes, and SSO client secrets
177+// can be shorter.
178+func (p *DTTSSOProvider) verifyIDToken(raw, clientSecret string) (*dttSSOClaims, error) {
179+ if raw == "" {
180+ return nil, errors.New("token response carried no id_token; the scope must be exactly \"openid\"")
181+ }
182+ var claims dttSSOClaims
183+ _, err := jwt.ParseWithClaims(raw, &claims,
184+ func(*jwt.Token) (any, error) { return []byte(clientSecret), nil },
185+ jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}),
186+ jwt.WithIssuer(p.issuer()),
187+ jwt.WithAudience(p.ClientID),
188+ jwt.WithExpirationRequired(),
189+ )
190+ if err != nil {
191+ return nil, fmt.Errorf("verifying id_token: %v", err)
192+ }
193+ if claims.Email == "" {
194+ return nil, errors.New("id_token carries no email")
195+ }
196+ return &claims, nil
197+}
198+
199+// issuer is the SSO's site host, the origin of the login URL.
200+func (p *DTTSSOProvider) issuer() string {
201+ return p.LoginURL.Scheme + "://" + p.LoginURL.Host
202+}
providers/dtt_sso_test.gonew file+237
@@ -0,0 +1,237 @@
1+package providers
2+
3+import (
4+ "context"
5+ "encoding/base64"
6+ "encoding/json"
7+ "net/http"
8+ "net/http/httptest"
9+ "net/url"
10+ "testing"
11+ "time"
12+
13+ "github.com/golang-jwt/jwt/v5"
14+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
15+ . "github.com/onsi/gomega"
16+)
17+
18+const (
19+ dttSSOTestClientID = "redash-gate"
20+ // Shorter than 32 bytes, and contains characters golang.org/x/oauth2 would
21+ // URL-escape in Basic auth.
22+ dttSSOTestSecret = "s3cr+t/abc=="
23+)
24+
25+// dttSSOTestServer mimics the SSO's token and check_token endpoints.
26+type dttSSOTestServer struct {
27+ *httptest.Server
28+ claims map[string]interface{}
29+ signingKey []byte
30+ lastForm url.Values
31+ validTokens map[string]bool
32+ tokenCounter int
33+}
34+
35+func newDTTSSOTestServer() *dttSSOTestServer {
36+ s := &dttSSOTestServer{
37+ signingKey: []byte(dttSSOTestSecret),
38+ validTokens: map[string]bool{},
39+ }
40+ s.Server = httptest.NewServer(http.HandlerFunc(s.handle))
41+ u, _ := url.Parse(s.URL)
42+ s.claims = map[string]interface{}{
43+ "iss": "http://" + u.Host,
44+ "aud": dttSSOTestClientID,
45+ "sub": "0b5c1e1a-1111-2222-3333-444455556666",
46+ "user_id": "0b5c1e1a-1111-2222-3333-444455556666",
47+ "email": "admin@example.com",
48+ "role": "dtt_admin",
49+ "exp": time.Now().Add(time.Hour).Unix(),
50+ }
51+ return s
52+}
53+
54+func (s *dttSSOTestServer) handle(w http.ResponseWriter, r *http.Request) {
55+ switch r.URL.Path {
56+ case "/oauth/token":
57+ want := "Basic " + base64.StdEncoding.EncodeToString([]byte(dttSSOTestClientID+":"+dttSSOTestSecret))
58+ if r.Header.Get("Authorization") != want {
59+ w.WriteHeader(http.StatusUnauthorized)
60+ return
61+ }
62+ _ = r.ParseForm()
63+ s.lastForm = r.PostForm
64+ if r.PostForm.Get("grant_type") == "refresh_token" && !s.validTokens["refresh-"+r.PostForm.Get("refresh_token")] {
65+ w.WriteHeader(http.StatusBadRequest)
66+ _, _ = w.Write([]byte(`{"error":"invalid_grant","error_description":"Invalid refresh token"}`))
67+ return
68+ }
69+ s.tokenCounter++
70+ access := "access-" + string(rune('0'+s.tokenCounter))
71+ refresh := "refresh-" + string(rune('0'+s.tokenCounter))
72+ s.validTokens[access] = true
73+ s.validTokens["refresh-"+refresh] = true
74+ w.Header().Set("Content-Type", "application/json")
75+ _ = json.NewEncoder(w).Encode(map[string]interface{}{
76+ "access_token": access,
77+ "token_type": "bearer",
78+ "expires_in": 3600,
79+ "refresh_token": refresh,
80+ "id_token": s.idToken(),
81+ "scope": "openid",
82+ })
83+ case "/oauth/check_token":
84+ token := r.Header.Get("Authorization")
85+ if len(token) > len("Bearer ") && s.validTokens[token[len("Bearer "):]] {
86+ _, _ = w.Write([]byte(`{"user_id":"0b5c1e1a-1111-2222-3333-444455556666","real_user_id":null,"issued_by":"redash-gate"}`))
87+ return
88+ }
89+ w.WriteHeader(http.StatusUnauthorized)
90+ _, _ = w.Write([]byte("Invalid access token"))
91+ default:
92+ w.WriteHeader(http.StatusNotFound)
93+ }
94+}
95+
96+func (s *dttSSOTestServer) idToken() string {
97+ if s.claims == nil {
98+ return ""
99+ }
100+ raw, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(s.claims)).SignedString(s.signingKey)
101+ if err != nil {
102+ panic(err)
103+ }
104+ return raw
105+}
106+
107+func testDTTSSOProvider(server *dttSSOTestServer) *DTTSSOProvider {
108+ p := NewDTTSSOProvider(&ProviderData{ClientID: dttSSOTestClientID, ClientSecret: dttSSOTestSecret})
109+ u, _ := url.Parse(server.URL)
110+ updateURL(p.LoginURL, u.Host)
111+ updateURL(p.RedeemURL, u.Host)
112+ updateURL(p.ValidateURL, u.Host)
113+ return p
114+}
115+
116+func TestNewDTTSSOProvider(t *testing.T) {
117+ g := NewWithT(t)
118+
119+ providerData := NewDTTSSOProvider(&ProviderData{}).Data()
120+ g.Expect(providerData.ProviderName).To(Equal("DTT SSO"))
121+ g.Expect(providerData.LoginURL.String()).To(Equal("https://auth.thebestagent.pro/oauth/authorize"))
122+ g.Expect(providerData.RedeemURL.String()).To(Equal("https://auth.thebestagent.pro/oauth/token"))
123+ g.Expect(providerData.ValidateURL.String()).To(Equal("https://auth.thebestagent.pro/oauth/check_token"))
124+ g.Expect(providerData.Scope).To(Equal("openid"))
125+}
126+
127+func TestDTTSSOProviderRedeem(t *testing.T) {
128+ g := NewWithT(t)
129+ server := newDTTSSOTestServer()
130+ defer server.Close()
131+ p := testDTTSSOProvider(server)
132+
133+ s, err := p.Redeem(context.Background(), "https://redash.example.com/oauth2/callback", "the-code", "")
134+ g.Expect(err).ToNot(HaveOccurred())
135+ g.Expect(s.Email).To(Equal("admin@example.com"))
136+ g.Expect(s.User).To(Equal("0b5c1e1a-1111-2222-3333-444455556666"))
137+ g.Expect(s.Groups).To(Equal([]string{"dtt_admin"}))
138+ g.Expect(s.AccessToken).To(Equal("access-1"))
139+ g.Expect(s.RefreshToken).To(Equal("refresh-1"))
140+ g.Expect(s.IDToken).ToNot(BeEmpty())
141+ g.Expect(s.ExpiresOn).ToNot(BeNil())
142+ g.Expect(*s.ExpiresOn).To(BeTemporally("~", time.Now().Add(time.Hour), time.Minute))
143+
144+ g.Expect(server.lastForm.Get("grant_type")).To(Equal("authorization_code"))
145+ g.Expect(server.lastForm.Get("code")).To(Equal("the-code"))
146+ g.Expect(server.lastForm.Get("redirect_uri")).To(Equal("https://redash.example.com/oauth2/callback"))
147+}
148+
149+func TestDTTSSOProviderRedeemRejectsBadIDTokens(t *testing.T) {
150+ testCases := map[string]func(s *dttSSOTestServer){
151+ "signed with another secret": func(s *dttSSOTestServer) { s.signingKey = []byte("some-other-client-secret") },
152+ "other audience": func(s *dttSSOTestServer) { s.claims["aud"] = "frappe-gate" },
153+ "other issuer": func(s *dttSSOTestServer) { s.claims["iss"] = "https://evil.example.com" },
154+ "expired": func(s *dttSSOTestServer) { s.claims["exp"] = time.Now().Add(-time.Minute).Unix() },
155+ "no email": func(s *dttSSOTestServer) { delete(s.claims, "email") },
156+ "no id_token": func(s *dttSSOTestServer) { s.claims = nil },
157+ }
158+ for name, tamper := range testCases {
159+ t.Run(name, func(t *testing.T) {
160+ g := NewWithT(t)
161+ server := newDTTSSOTestServer()
162+ defer server.Close()
163+ tamper(server)
164+
165+ _, err := testDTTSSOProvider(server).Redeem(context.Background(), "https://redash.example.com/oauth2/callback", "the-code", "")
166+ g.Expect(err).To(HaveOccurred())
167+ })
168+ }
169+}
170+
171+func TestDTTSSOProviderRedeemRejectsUnsignedIDToken(t *testing.T) {
172+ g := NewWithT(t)
173+ server := newDTTSSOTestServer()
174+ defer server.Close()
175+ p := testDTTSSOProvider(server)
176+
177+ header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none"}`))
178+ payload, _ := json.Marshal(server.claims)
179+ unsigned := header + "." + base64.RawURLEncoding.EncodeToString(payload) + "."
180+
181+ _, err := p.verifyIDToken(unsigned, dttSSOTestSecret)
182+ g.Expect(err).To(HaveOccurred())
183+}
184+
185+func TestDTTSSOProviderRefreshSession(t *testing.T) {
186+ g := NewWithT(t)
187+ server := newDTTSSOTestServer()
188+ defer server.Close()
189+ p := testDTTSSOProvider(server)
190+
191+ s, err := p.Redeem(context.Background(), "https://redash.example.com/oauth2/callback", "the-code", "")
192+ g.Expect(err).ToNot(HaveOccurred())
193+ nonce := []byte("keep-me")
194+ s.Nonce = nonce
195+
196+ server.claims["role"] = "agent"
197+ server.claims["email"] = "renamed@example.com"
198+ refreshed, err := p.RefreshSession(context.Background(), s)
199+ g.Expect(err).ToNot(HaveOccurred())
200+ g.Expect(refreshed).To(BeTrue())
201+ g.Expect(s.AccessToken).To(Equal("access-2"))
202+ g.Expect(s.RefreshToken).To(Equal("refresh-2"))
203+ g.Expect(s.Groups).To(Equal([]string{"agent"}))
204+ g.Expect(s.Email).To(Equal("renamed@example.com"))
205+ g.Expect(s.Nonce).To(Equal(nonce))
206+ g.Expect(server.lastForm.Get("grant_type")).To(Equal("refresh_token"))
207+ g.Expect(server.lastForm.Get("refresh_token")).To(Equal("refresh-1"))
208+}
209+
210+func TestDTTSSOProviderRefreshSessionFailures(t *testing.T) {
211+ g := NewWithT(t)
212+ server := newDTTSSOTestServer()
213+ defer server.Close()
214+ p := testDTTSSOProvider(server)
215+
216+ refreshed, err := p.RefreshSession(context.Background(), &sessions.SessionState{})
217+ g.Expect(err).ToNot(HaveOccurred())
218+ g.Expect(refreshed).To(BeFalse())
219+
220+ refreshed, err = p.RefreshSession(context.Background(), &sessions.SessionState{RefreshToken: "revoked"})
221+ g.Expect(err).To(HaveOccurred())
222+ g.Expect(refreshed).To(BeFalse())
223+}
224+
225+func TestDTTSSOProviderValidateSession(t *testing.T) {
226+ g := NewWithT(t)
227+ server := newDTTSSOTestServer()
228+ defer server.Close()
229+ p := testDTTSSOProvider(server)
230+
231+ s, err := p.Redeem(context.Background(), "https://redash.example.com/oauth2/callback", "the-code", "")
232+ g.Expect(err).ToNot(HaveOccurred())
233+ g.Expect(p.ValidateSession(context.Background(), s)).To(BeTrue())
234+
235+ delete(server.validTokens, s.AccessToken)
236+ g.Expect(p.ValidateSession(context.Background(), s)).To(BeFalse())
237+}
providers/google.go+2−2
@@ -219,7 +219,7 @@ func (p *GoogleProvider) Redeem(ctx context.Context, redirectURL, code, codeVeri
219219
220220 err = requests.New(p.RedeemURL.String()).
221221 WithContext(ctx).
222− WithMethod("POST").
222+ WithMethod(http.MethodPost).
223223 WithBody(bytes.NewBufferString(params.Encode())).
224224 SetHeader("Content-Type", "application/x-www-form-urlencoded").
225225 Do().
@@ -543,7 +543,7 @@ func (p *GoogleProvider) redeemRefreshToken(ctx context.Context, s *sessions.Ses
543543
544544 err = requests.New(p.RedeemURL.String()).
545545 WithContext(ctx).
546− WithMethod("POST").
546+ WithMethod(http.MethodPost).
547547 WithBody(bytes.NewBufferString(params.Encode())).
548548 SetHeader("Content-Type", "application/x-www-form-urlencoded").
549549 Do().
providers/keycloak_oidc.go+1
@@ -89,6 +89,7 @@ func (p *KeycloakOIDCProvider) extractRoles(s *sessions.SessionState) error {
8989 return err
9090 }
9191
92+ //nolint:prealloc
9293 var roles []string
9394 roles = append(roles, claims.RealmAccess.Roles...)
9495 roles = append(roles, getClientRoles(claims)...)
providers/logingov.go+2−1
@@ -8,6 +8,7 @@ import (
88 "errors"
99 "fmt"
1010 "math/big"
11+ "net/http"
1112 "net/url"
1213 "os"
1314 "time"
@@ -237,7 +238,7 @@ func (p *LoginGovProvider) Redeem(ctx context.Context, _, code, codeVerifier str
237238 }
238239 err = requests.New(p.RedeemURL.String()).
239240 WithContext(ctx).
240− WithMethod("POST").
241+ WithMethod(http.MethodPost).
241242 WithBody(bytes.NewBufferString(params.Encode())).
242243 SetHeader("Content-Type", "application/x-www-form-urlencoded").
243244 Do().
providers/ms_entra_id.go+4−1
@@ -5,6 +5,7 @@ import (
55 "context"
66 "encoding/json"
77 "fmt"
8+ "net/http"
89 "net/url"
910 "os"
1011 "regexp"
@@ -110,6 +111,7 @@ func (p *MicrosoftEntraIDProvider) Redeem(ctx context.Context, redirectURL, code
110111// redeemWithFederatedToken performs custom token exchange with federated token instead of client secret
111112func (p *MicrosoftEntraIDProvider) redeemWithFederatedToken(ctx context.Context, redirectURL, code, codeVerifier string) (*sessions.SessionState, error) {
112113 federatedTokenPath := os.Getenv("AZURE_FEDERATED_TOKEN_FILE")
114+ // #nosec G703 -- AZURE_FEDERATED_TOKEN_FILE is set by the operator, not user input
113115 federatedToken, err := os.ReadFile(federatedTokenPath)
114116 if err != nil {
115117 return nil, fmt.Errorf("error reading federated token file %s: %s", federatedTokenPath, err)
@@ -162,6 +164,7 @@ func (p *MicrosoftEntraIDProvider) RefreshSession(ctx context.Context, s *sessio
162164// Refresh Token, Access Token and ID Token
163165func (p *MicrosoftEntraIDProvider) redeemRefreshTokenWithFederatedToken(ctx context.Context, s *sessions.SessionState) error {
164166 federatedTokenPath := os.Getenv("AZURE_FEDERATED_TOKEN_FILE")
167+ // #nosec G703 -- AZURE_FEDERATED_TOKEN_FILE is set by the operator, not user input
165168 federatedToken, err := os.ReadFile(federatedTokenPath)
166169 if err != nil {
167170 return fmt.Errorf("error reading federated token file %s: %s", federatedTokenPath, err)
@@ -302,7 +305,7 @@ func (p *MicrosoftEntraIDProvider) checkTenantMatchesTenantList(tenant string, a
302305func (p *MicrosoftEntraIDProvider) fetchToken(ctx context.Context, params url.Values) (*oauth2.Token, error) {
303306 resp := requests.New(p.RedeemURL.String()).
304307 WithContext(ctx).
305− WithMethod("POST").
308+ WithMethod(http.MethodPost).
306309 WithBody(bytes.NewBufferString(params.Encode())).
307310 SetHeader("Content-Type", "application/x-www-form-urlencoded").
308311 Do()
providers/provider_data.go+44−5
@@ -45,11 +45,26 @@ type ProviderData struct {
4545 SupportedCodeChallengeMethods []string `json:"code_challenge_methods_supported,omitempty"`
4646
4747 // Common OIDC options for any OIDC-based providers to consume
48− AllowUnverifiedEmail bool
49− UserClaim string
50− EmailClaim string
51− GroupsClaim string
52− Verifier internaloidc.IDTokenVerifier
48+ AllowUnverifiedEmail bool
49+
50+ // UserClaim is the claim to use for populating the SessionState.User field. Defaults to "sub" if not set.
51+ UserClaim string
52+
53+ // EmailClaim is the claim to use for populating the SessionState.Email field.
54+ EmailClaim string
55+
56+ // GroupsClaim is the claim to use for populating the SessionState.Groups field.
57+ // If not set, groups will not be extracted from the ID Token or userinfo response.
58+ GroupsClaim string
59+
60+ // Verifier is the OIDC ID Token Verifier to be used by any OIDC-based providers to verify ID Tokens returned by the provider.
61+ // It must be set up by the provider implementation and is not expected to be configured directly by users.
62+ Verifier internaloidc.IDTokenVerifier
63+
64+ // Additional claims to be obtained from the upstream IDP, either from the id_token or from the userinfo endpoint if configured.
65+ AdditionalClaims []string `json:"additionalClaims,omitempty"`
66+
67+ // SkipClaimsFromProfileURL indicates that claims should not be fetched from the ProfileURL, even if it is set.
5368 SkipClaimsFromProfileURL bool
5469
5570 // Universal Group authorization data structure
@@ -179,6 +194,10 @@ func regexpForRule(rule options.URLParameterRule) string {
179194func (p *ProviderData) setAllowedGroups(groups []string) {
180195 p.AllowedGroups = make(map[string]struct{}, len(groups))
181196 for _, group := range groups {
197+ if len(group) == 0 {
198+ continue
199+ }
200+
182201 p.AllowedGroups[group] = struct{}{}
183202 }
184203}
@@ -268,6 +287,10 @@ func (p *ProviderData) buildSessionFromClaims(rawIDToken, accessToken string) (*
268287 }
269288 }
270289
290+ if p.AdditionalClaims != nil {
291+ p.extractAdditionalClaims(extractor, ss)
292+ }
293+
271294 // `email_verified` must be present and explicitly set to `false` to be
272295 // considered unverified.
273296 verifyEmail := (p.EmailClaim == options.OIDCEmailClaim) && !p.AllowUnverifiedEmail
@@ -301,6 +324,22 @@ func (p *ProviderData) getClaimExtractor(rawIDToken, accessToken string) (util.C
301324 return extractor, nil
302325}
303326
327+func (p *ProviderData) extractAdditionalClaims(extractor util.ClaimExtractor, ss *sessions.SessionState) {
328+ if ss.AdditionalClaims == nil {
329+ ss.AdditionalClaims = make(map[string]any)
330+ }
331+ for _, claim := range p.AdditionalClaims {
332+ value, exists, err := extractor.GetClaim(claim)
333+ if err != nil {
334+ logger.Printf("error extracting additional claim %q: %v", claim, err)
335+ continue
336+ }
337+ if exists {
338+ ss.AdditionalClaims[claim] = value
339+ }
340+ }
341+}
342+
304343// checkNonce compares the session's nonce with the IDToken's nonce claim
305344func (p *ProviderData) checkNonce(s *sessions.SessionState) error {
306345 extractor, err := p.getClaimExtractor(s.IDToken, "")
providers/provider_data_test.go+23
@@ -237,6 +237,7 @@ func TestProviderData_buildSessionFromClaims(t *testing.T) {
237237 ExpectedError error
238238 ExpectedSession *sessions.SessionState
239239 ExpectProfileURLCalled bool
240+ AdditionalClaims []string
240241 }{
241242 "Standard": {
242243 IDToken: defaultIDToken,
@@ -417,6 +418,27 @@ func TestProviderData_buildSessionFromClaims(t *testing.T) {
417418 SkipClaimsFromProfileURL: true,
418419 ExpectedSession: &sessions.SessionState{},
419420 },
421+ "Additional claims": {
422+ IDToken: defaultIDToken,
423+ AdditionalClaims: []string{"phone_number", "picture"},
424+ ExpectedSession: &sessions.SessionState{
425+ PreferredUsername: "Jane Dobbs",
426+ AdditionalClaims: map[string]interface{}{
427+ "phone_number": "+4798765432",
428+ "picture": "http://mugbook.com/janed/me.jpg",
429+ },
430+ },
431+ },
432+ "Additional claims with missing claim": {
433+ IDToken: defaultIDToken,
434+ AdditionalClaims: []string{"phone_number", "picture1"},
435+ ExpectedSession: &sessions.SessionState{
436+ PreferredUsername: "Jane Dobbs",
437+ AdditionalClaims: map[string]interface{}{
438+ "phone_number": "+4798765432",
439+ },
440+ },
441+ },
420442 }
421443 for testName, tc := range testCases {
422444 t.Run(testName, func(t *testing.T) {
@@ -453,6 +475,7 @@ func TestProviderData_buildSessionFromClaims(t *testing.T) {
453475 provider.EmailClaim = tc.EmailClaim
454476 provider.GroupsClaim = tc.GroupsClaim
455477 provider.SkipClaimsFromProfileURL = tc.SkipClaimsFromProfileURL
478+ provider.AdditionalClaims = tc.AdditionalClaims
456479
457480 rawIDToken, err := newSignedTestIDToken(tc.IDToken)
458481 g.Expect(err).ToNot(HaveOccurred())
providers/provider_default.go+2−1
@@ -5,6 +5,7 @@ import (
55 "context"
66 "errors"
77 "fmt"
8+ "net/http"
89 "net/url"
910
1011 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
@@ -71,7 +72,7 @@ func (p *ProviderData) Redeem(ctx context.Context, redirectURL, code, codeVerifi
7172
7273 result := requests.New(p.RedeemURL.String()).
7374 WithContext(ctx).
74− WithMethod("POST").
75+ WithMethod(http.MethodPost).
7576 WithBody(bytes.NewBufferString(params.Encode())).
7677 SetHeader("Content-Type", "application/x-www-form-urlencoded").
7778 Do()
providers/provider_default_test.go+12
@@ -102,6 +102,18 @@ func TestProviderDataAuthorize(t *testing.T) {
102102 groups: []string{"baz", "foo"},
103103 expectedAuthZ: false,
104104 },
105+ {
106+ name: "AllowedGroupsWithEmptyString",
107+ allowedGroups: []string{"group2", ""},
108+ groups: []string{"group1", "group2"},
109+ expectedAuthZ: true,
110+ },
111+ {
112+ name: "AllowedGroupsOnlyEmptyString",
113+ allowedGroups: []string{""},
114+ groups: []string{"group1", "group2"},
115+ expectedAuthZ: true,
116+ },
105117 }
106118
107119 for _, tc := range testCases {
providers/providers.go+9−3
@@ -40,6 +40,8 @@ func NewProvider(providerConfig options.Provider) (Provider, error) {
4040 switch providerConfig.Type {
4141 case options.ADFSProvider:
4242 return NewADFSProvider(providerData, providerConfig), nil
43+ case options.AtlassianProvider:
44+ return NewAtlassianProvider(providerData), nil
4345 case options.AzureProvider:
4446 return NewAzureProvider(providerData, providerConfig.AzureConfig), nil
4547 case options.MicrosoftEntraIDProvider:
@@ -50,6 +52,8 @@ func NewProvider(providerConfig options.Provider) (Provider, error) {
5052 return NewCIDAASProvider(providerData, providerConfig), nil
5153 case options.DigitalOceanProvider:
5254 return NewDigitalOceanProvider(providerData), nil
55+ case options.DTTSSOProvider:
56+ return NewDTTSSOProvider(providerData), nil
5357 case options.FacebookProvider:
5458 return NewFacebookProvider(providerData), nil
5559 case options.GitHubProvider:
@@ -84,6 +88,7 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData,
8488 ClientSecret: providerConfig.ClientSecret,
8589 ClientSecretFile: providerConfig.ClientSecretFile,
8690 AuthRequestResponseMode: providerConfig.AuthRequestResponseMode,
91+ AdditionalClaims: providerConfig.AdditionalClaims,
8792 }
8893
8994 needsVerifier, err := providerRequiresOIDCProviderVerifier(providerConfig.Type)
@@ -99,6 +104,7 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData,
99104 IssuerURL: providerConfig.OIDCConfig.IssuerURL,
100105 JWKsURL: providerConfig.OIDCConfig.JwksURL,
101106 PublicKeyFiles: providerConfig.OIDCConfig.PublicKeyFiles,
107+ SupportedSigningAlgs: providerConfig.OIDCConfig.EnabledSigningAlgs,
102108 SkipDiscovery: ptr.Deref(providerConfig.OIDCConfig.SkipDiscovery, options.DefaultSkipDiscovery),
103109 SkipIssuerVerification: ptr.Deref(providerConfig.OIDCConfig.InsecureSkipIssuerVerification, options.DefaultInsecureSkipIssuerVerification),
104110 })
@@ -187,9 +193,9 @@ func parseCodeChallengeMethod(providerConfig options.Provider) string {
187193
188194func providerRequiresOIDCProviderVerifier(providerType options.ProviderType) (bool, error) {
189195 switch providerType {
190− case options.BitbucketProvider, options.DigitalOceanProvider, options.FacebookProvider, options.GitHubProvider,
191− options.GoogleProvider, options.KeycloakProvider, options.LinkedInProvider, options.LoginGovProvider,
192− options.NextCloudProvider, options.SourceHutProvider:
196+ case options.AtlassianProvider, options.BitbucketProvider, options.DigitalOceanProvider, options.DTTSSOProvider,
197+ options.FacebookProvider, options.GitHubProvider, options.GoogleProvider, options.KeycloakProvider,
198+ options.LinkedInProvider, options.LoginGovProvider, options.NextCloudProvider, options.SourceHutProvider:
193199 return false, nil
194200 case options.OIDCProvider, options.ADFSProvider, options.AzureProvider, options.CidaasProvider,
195201 options.GitLabProvider, options.KeycloakOIDCProvider, options.MicrosoftEntraIDProvider:
providers/providers_test.go+90
@@ -1,9 +1,14 @@
11package providers
22
33import (
4+ "context"
5+ "net"
46 "os"
57 "testing"
8+ "time"
69
10+ "github.com/golang-jwt/jwt/v5"
11+ "github.com/oauth2-proxy/mockoidc"
712 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
813 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
914 . "github.com/onsi/gomega"
@@ -121,6 +126,91 @@ func TestURLsCorrectlyParsed(t *testing.T) {
121126 g.Expect(pd.RedeemURL.String()).To(Equal(msTokenURL))
122127}
123128
129+func TestEnabledSigningAlgsAreAppliedToProviderVerifier(t *testing.T) {
130+ g := NewWithT(t)
131+
132+ m, err := mockoidc.NewServer(nil)
133+ g.Expect(err).ToNot(HaveOccurred())
134+ m.AddMiddleware(newSigningAlgsIssuerMiddleware(m, []string{"RS256", "HS256"}))
135+
136+ listener, err := net.Listen("tcp", "127.0.0.1:0")
137+ g.Expect(err).ToNot(HaveOccurred())
138+ g.Expect(m.Start(listener, nil)).To(Succeed())
139+ defer func() {
140+ g.Expect(m.Shutdown()).To(Succeed())
141+ }()
142+
143+ providerConfig := options.Provider{
144+ ID: providerID,
145+ Type: "oidc",
146+ ClientID: m.Config().ClientID,
147+ ClientSecretFile: clientSecret,
148+ OIDCConfig: options.OIDCOptions{
149+ IssuerURL: m.Issuer(),
150+ AudienceClaims: []string{"aud"},
151+ EnabledSigningAlgs: []string{"HS256"},
152+ },
153+ }
154+
155+ pd, err := newProviderDataFromConfig(providerConfig)
156+ g.Expect(err).ToNot(HaveOccurred())
157+
158+ rawIDToken, err := m.Keypair.SignJWT(jwt.RegisteredClaims{
159+ Audience: jwt.ClaimStrings{m.Config().ClientID},
160+ Issuer: m.Issuer(),
161+ ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
162+ IssuedAt: jwt.NewNumericDate(time.Now()),
163+ Subject: "user",
164+ })
165+ g.Expect(err).ToNot(HaveOccurred())
166+
167+ _, err = pd.Verifier.Verify(context.Background(), rawIDToken)
168+ g.Expect(err).To(HaveOccurred())
169+ g.Expect(err.Error()).To(ContainSubstring("unexpected signature algorithm"))
170+}
171+
172+func TestEnabledSigningAlgsRejectUnsupportedTokens(t *testing.T) {
173+ g := NewWithT(t)
174+
175+ m, err := mockoidc.Run()
176+ g.Expect(err).ToNot(HaveOccurred())
177+ defer func() {
178+ g.Expect(m.Shutdown()).To(Succeed())
179+ }()
180+
181+ providerConfig := options.Provider{
182+ ID: providerID,
183+ Type: "oidc",
184+ ClientID: m.Config().ClientID,
185+ ClientSecretFile: clientSecret,
186+ LoginURL: m.AuthorizationEndpoint(),
187+ RedeemURL: m.TokenEndpoint(),
188+ OIDCConfig: options.OIDCOptions{
189+ IssuerURL: m.Issuer(),
190+ SkipDiscovery: ptr.To(true),
191+ JwksURL: m.JWKSEndpoint(),
192+ AudienceClaims: []string{"aud"},
193+ EnabledSigningAlgs: []string{"HS256"},
194+ },
195+ }
196+
197+ pd, err := newProviderDataFromConfig(providerConfig)
198+ g.Expect(err).ToNot(HaveOccurred())
199+
200+ rawIDToken, err := m.Keypair.SignJWT(jwt.RegisteredClaims{
201+ Audience: jwt.ClaimStrings{m.Config().ClientID},
202+ Issuer: m.Issuer(),
203+ ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
204+ IssuedAt: jwt.NewNumericDate(time.Now()),
205+ Subject: "user",
206+ })
207+ g.Expect(err).ToNot(HaveOccurred())
208+
209+ _, err = pd.Verifier.Verify(context.Background(), rawIDToken)
210+ g.Expect(err).To(HaveOccurred())
211+ g.Expect(err.Error()).To(ContainSubstring("unexpected signature algorithm"))
212+}
213+
124214func TestScope(t *testing.T) {
125215 g := NewWithT(t)
126216
providers/srht.go+2−1
@@ -4,6 +4,7 @@ import (
44 "bytes"
55 "context"
66 "fmt"
7+ "net/http"
78 "net/url"
89
910 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
@@ -75,7 +76,7 @@ func NewSourceHutProvider(p *ProviderData) *SourceHutProvider {
7576func (p *SourceHutProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error {
7677 json, err := requests.New(p.ProfileURL.String()).
7778 WithContext(ctx).
78− WithMethod("POST").
79+ WithMethod(http.MethodPost).
7980 SetHeader("Content-Type", "application/json").
8081 SetHeader("Authorization", "Bearer "+s.AccessToken).
8182 WithBody(bytes.NewBufferString(`{"query": "{ me { username, email } }"}`)).
providers/util_test.go+33
@@ -1,9 +1,12 @@
11package providers
22
33import (
4+ "encoding/json"
45 "fmt"
6+ "net/http"
57 "testing"
68
9+ "github.com/oauth2-proxy/mockoidc"
710 . "github.com/onsi/gomega"
811 "golang.org/x/oauth2"
912)
@@ -111,3 +114,33 @@ func Test_formatGroup(t *testing.T) {
111114 })
112115 }
113116}
117+
118+func newSigningAlgsIssuerMiddleware(m *mockoidc.MockOIDC, supportedSigningAlgs []string) func(http.Handler) http.Handler {
119+ return func(next http.Handler) http.Handler {
120+ return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
121+ provider := struct {
122+ Issuer string `json:"issuer"`
123+ AuthURL string `json:"authorization_endpoint"`
124+ TokenURL string `json:"token_endpoint"`
125+ JWKsURL string `json:"jwks_uri"`
126+ UserInfoURL string `json:"userinfo_endpoint"`
127+ SupportedSigningAlgs []string `json:"id_token_signing_alg_values_supported"`
128+ }{
129+ Issuer: m.Issuer(),
130+ AuthURL: m.AuthorizationEndpoint(),
131+ TokenURL: m.TokenEndpoint(),
132+ JWKsURL: m.JWKSEndpoint(),
133+ UserInfoURL: m.UserinfoEndpoint(),
134+ SupportedSigningAlgs: supportedSigningAlgs,
135+ }
136+
137+ data, err := json.Marshal(provider)
138+ if err != nil {
139+ rw.WriteHeader(http.StatusInternalServerError)
140+ return
141+ }
142+
143+ _, _ = rw.Write(data)
144+ })
145+ }
146+}
validator.go+4−1
@@ -110,6 +110,10 @@ func NewValidator(domains []string, usersFile string) func(string) bool {
110110
111111// isEmailValidWithDomains checks if the authenticated email is validated against the provided domain
112112func isEmailValidWithDomains(email string, allowedDomains []string) bool {
113+ if strings.Count(email, "@") != 1 {
114+ return false
115+ }
116+
113117 for _, domain := range allowedDomains {
114118 // allow if the domain is perfect suffix match with the email
115119 if strings.HasSuffix(email, "@"+domain) {
@@ -119,7 +123,6 @@ func isEmailValidWithDomains(email string, allowedDomains []string) bool {
119123 // allow if the domain is prefixed with . or *. and
120124 // the last element (split on @) has the suffix as the domain
121125 atoms := strings.Split(email, "@")
122−
123126 if (strings.HasPrefix(domain, ".") && strings.HasSuffix(atoms[len(atoms)-1], domain)) ||
124127 (strings.HasPrefix(domain, "*.") && strings.HasSuffix(atoms[len(atoms)-1], domain[1:])) {
125128 return true
validator_test.go+21
@@ -404,6 +404,27 @@ func TestValidatorCases(t *testing.T) {
404404 allowedDomains: []string{"*.company.com"},
405405 expectedAuthZ: false,
406406 },
407+ {
408+ name: "CheckThatTwoAtSignsIsInvalid",
409+ email: "attacker@evil.com@company.com",
410+ allowedEmails: []string(nil),
411+ allowedDomains: []string{"company.com"},
412+ expectedAuthZ: false,
413+ },
414+ {
415+ name: "CheckThatTwoAtSignsIsInvalidEvenWithDotPrefix",
416+ email: "attacker@evil.com@company.com",
417+ allowedEmails: []string(nil),
418+ allowedDomains: []string{".company.com"},
419+ expectedAuthZ: false,
420+ },
421+ {
422+ name: "CheckThatTwoAtSignsIsInvalidEvenWithWildcardPrefix",
423+ email: "attacker@evil.com@foo.company.com",
424+ allowedEmails: []string(nil),
425+ allowedDomains: []string{"*.company.com"},
426+ expectedAuthZ: false,
427+ },
407428 }
408429
409430 for _, tc := range testCases {