git.iko.soy/typeable/oauth2-proxy
on master help sign in
.devcontainer/Dockerfile+1−1
since splitsnapshots
unifiedsplit
@@ -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
2
2
3SHELL ["/bin/bash", "-o", "pipefail", "-c"]
3SHELL ["/bin/bash", "-o", "pipefail", "-c"]
4
4
.github/ISSUE_TEMPLATE/config.yml+2−2
@@ -1,6 +1,6 @@
1blank_issues_enabled: false
1blank_issues_enabled: false
2contact_links:
2contact_links:
3− - name: OAuth2-Proxy Slack
3+ - name: OAuth2 Proxy Slack
4− url: https://gophers.slack.com/messages/CM2RSS25N
4+ url: https://cloud-native.slack.com/archives/C098Y5URZ2N
5 about: Feel free to ask any questions here.
5 about: Feel free to ask any questions here.
6
6
.github/PULL_REQUEST_TEMPLATE.md+3−2
@@ -20,7 +20,8 @@
20<!--- Go over all the following points, and put an `x` in all the boxes that apply. -->
20<!--- Go over all the following points, and put an `x` in all the boxes that apply. -->
21<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
21<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
22
22
23−- [ ] My change requires a change to the documentation or CHANGELOG.
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 updated the documentation/CHANGELOG accordingly.
24+- [ ] I have [signed off](https://github.com/apps/dco) all my commits.
25- [ ] I have created a feature (non-master) branch for my PR.
25- [ ] 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.
26- [ ] I have written tests for my code changes.
27- [ ] I have written tests for my code changes.
.github/renovate.json5+9
@@ -46,6 +46,15 @@
46 depNameTemplate: "alpine",
46 depNameTemplate: "alpine",
47 datasourceTemplate: "docker",
47 datasourceTemplate: "docker",
48 },
48 },
49+ {
50+ customType: "regex",
51+ fileMatch: [
52+ "^Makefile",
53+ ],
54+ matchStrings: [
55+ "# renovate: datasource=(?<datasource>.*?) depName=(?<depName>.*?)\\s+?GOLANGCILINT_VERSION \\?= (?<currentValue>.*)\\s",
56+ ],
57+ },
49 {
58 {
50 customType: "regex",
59 customType: "regex",
51 fileMatch: ["(^|/)\\.github/workflows/[^/]+\\.ya?ml$"],
60 fileMatch: ["(^|/)\\.github/workflows/[^/]+\\.ya?ml$"],
.github/workflows/ci.yml+57−20
@@ -7,29 +7,33 @@ on:
7 pull_request:
7 pull_request:
8 branches:
8 branches:
9 - '**'
9 - '**'
10+ workflow_dispatch:
11+
12+permissions:
13+ contents: read
14+ id-token: write
15+ security-events: write
16+
10jobs:
17jobs:
11 build:
18 build:
12 runs-on: ubuntu-latest
19 runs-on: ubuntu-latest
13− env:
14− COVER: true
15 steps:
20 steps:
16 - name: Check out code
21 - name: Check out code
17− uses: actions/checkout@v6
22+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
18−
19− - name: Set up Go
20− uses: actions/setup-go@v6
21 with:
23 with:
22− go-version-file: go.mod
24+ fetch-depth: 0
23− id: go
24
25
25− - name: Get dependencies
26+ - name: Get Go version
26− env:
27− # renovate: datasource=github-tags depName=golangci/golangci-lint
28− GOLANGCI_LINT_VERSION: v2.7.2
29 run: |
27 run: |
30− curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION}
28+ version=$(grep "^go " go.mod | cut -d' ' -f2 | cut -d. -f1,2)
31− curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
29+ echo "version=${version}" >> "$GITHUB_OUTPUT"
32− chmod +x ./cc-test-reporter
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
33
37
34 - name: Verify Code Generation
38 - name: Verify Code Generation
35 run: |
39 run: |
@@ -52,22 +56,55 @@ jobs:
52
56
53 - name: Test
57 - name: Test
54 env:
58 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'
56 run: |
65 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'
58
93
59 docker:
94 docker:
60 runs-on: ubuntu-latest
95 runs-on: ubuntu-latest
61 steps:
96 steps:
62 - name: Check out code
97 - name: Check out code
63− uses: actions/checkout@v6
98+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
99+ with:
100+ fetch-depth: 0
64
101
65 - name: Set up QEMU
102 - name: Set up QEMU
66− uses: docker/setup-qemu-action@v3
103+ uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4.2.0
67
104
68 - name: Set up Docker Buildx
105 - name: Set up Docker Buildx
69 id: buildx
106 id: buildx
70− uses: docker/setup-buildx-action@v3
107+ uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
71
108
72 - name: Docker Build
109 - name: Docker Build
73 if: (!startsWith(github.head_ref, 'release'))
110 if: (!startsWith(github.head_ref, 'release'))
.github/workflows/codeql.yml+4−4
@@ -32,18 +32,18 @@ jobs:
32
32
33 steps:
33 steps:
34 - name: Checkout repository
34 - name: Checkout repository
35− uses: actions/checkout@v6
35+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
36
36
37 # Initializes the CodeQL tools for scanning.
37 # Initializes the CodeQL tools for scanning.
38 - name: Initialize CodeQL
38 - name: Initialize CodeQL
39− uses: github/codeql-action/init@v3
39+ uses: github/codeql-action/init@ff2f1c621b7f889edc0d3c761ac2e6a3f8cdb0dd # v4.37.7
40 with:
40 with:
41 languages: go
41 languages: go
42
42
43 # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
43 # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
44 # If this step fails, then you should remove it and run the build manually (see below)
44 # If this step fails, then you should remove it and run the build manually (see below)
45 - name: Autobuild
45 - name: Autobuild
46− uses: github/codeql-action/autobuild@v3
46+ uses: github/codeql-action/autobuild@ff2f1c621b7f889edc0d3c761ac2e6a3f8cdb0dd # v4.37.7
47
47
48 # ℹ️ Command-line programs to run using the OS shell.
48 # ℹ️ Command-line programs to run using the OS shell.
49 # 📚 https://git.io/JvXDl
49 # 📚 https://git.io/JvXDl
@@ -57,4 +57,4 @@ jobs:
57 # make release
57 # make release
58
58
59 - name: Perform CodeQL Analysis
59 - 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:
17 runs-on: ubuntu-latest
17 runs-on: ubuntu-latest
18 steps:
18 steps:
19 - name: Check out code
19 - name: Check out code
20− uses: actions/checkout@v6
20+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
21 with:
21 with:
22 ref: master
22 ref: master
23 fetch-depth: 0
23 fetch-depth: 0
@@ -54,7 +54,7 @@ jobs:
54 git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
54 git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
55
55
56 - name: Setup node
56 - name: Setup node
57− uses: actions/setup-node@v6
57+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
58 with:
58 with:
59 node-version-file: docs/package.json
59 node-version-file: docs/package.json
60
60
.github/workflows/docs.yml+7−7
@@ -14,13 +14,13 @@ jobs:
14 if: github.event_name == 'pull_request'
14 if: github.event_name == 'pull_request'
15 runs-on: ubuntu-latest
15 runs-on: ubuntu-latest
16 steps:
16 steps:
17− - uses: actions/checkout@v6
17+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
18
18
19 - name: Setup Pages
19 - name: Setup Pages
20 id: pages
20 id: pages
21− uses: actions/configure-pages@v5
21+ uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0
22
22
23− - uses: actions/setup-node@v6
23+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
24 with:
24 with:
25 # renovate: datasource=node-version depName=node
25 # renovate: datasource=node-version depName=node
26 node-version: 24
26 node-version: 24
@@ -35,9 +35,9 @@ jobs:
35 if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
35 if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
36 runs-on: ubuntu-latest
36 runs-on: ubuntu-latest
37 steps:
37 steps:
38− - uses: actions/checkout@v6
38+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
39
39
40− - uses: actions/setup-node@v6
40+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
41 with:
41 with:
42 # renovate: datasource=node-version depName=node
42 # renovate: datasource=node-version depName=node
43 node-version: 24
43 node-version: 24
@@ -49,7 +49,7 @@ jobs:
49 npm run build
49 npm run build
50
50
51 - name: Upload artifact
51 - name: Upload artifact
52− uses: actions/upload-pages-artifact@v3
52+ uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0
53 with:
53 with:
54 path: ./docs/build
54 path: ./docs/build
55
55
@@ -65,4 +65,4 @@ jobs:
65 steps:
65 steps:
66 - name: Deploy to GitHub Pages
66 - name: Deploy to GitHub Pages
67 id: deployment
67 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:
9 pull-requests: write
9 pull-requests: write
10 runs-on: ubuntu-latest
10 runs-on: ubuntu-latest
11 steps:
11 steps:
12− - uses: actions/labeler@v6
12+ - uses: actions/labeler@bf12e9b00b37c5c0ca2b87b79b2daf7891dbda13 # v7.0.0
13 with:
13 with:
14 sync-labels: true
14 sync-labels: true
15 dot: true
15 dot: true
.github/workflows/nightly.yml+4−4
@@ -12,21 +12,21 @@ jobs:
12 if: github.repository == 'oauth2-proxy/oauth2-proxy'
12 if: github.repository == 'oauth2-proxy/oauth2-proxy'
13 steps:
13 steps:
14 - name: Check out code
14 - name: Check out code
15− uses: actions/checkout@v6
15+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
16 with:
16 with:
17 ref: master
17 ref: master
18 fetch-depth: 0
18 fetch-depth: 0
19 fetch-tags: true
19 fetch-tags: true
20
20
21 - name: Set up QEMU
21 - name: Set up QEMU
22− uses: docker/setup-qemu-action@v3
22+ uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4.2.0
23
23
24 - name: Set up Docker Buildx
24 - name: Set up Docker Buildx
25 id: buildx
25 id: buildx
26− uses: docker/setup-buildx-action@v3
26+ uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
27
27
28 - name: Login to quay.io
28 - name: Login to quay.io
29− uses: docker/login-action@v3
29+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
30 with:
30 with:
31 registry: quay.io/oauth2-proxy
31 registry: quay.io/oauth2-proxy
32 username: ${{ secrets.REGISTRY_USERNAME_NIGHTLY }}
32 username: ${{ secrets.REGISTRY_USERNAME_NIGHTLY }}
.github/workflows/publish-release.yml+22−22
@@ -14,49 +14,49 @@ permissions:
14
14
15jobs:
15jobs:
16 publish:
16 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
18 runs-on: ubuntu-latest
18 runs-on: ubuntu-latest
19 outputs:
19 outputs:
20 tag: ${{ steps.tag.outputs.version }}
20 tag: ${{ steps.tag.outputs.version }}
21 steps:
21 steps:
22 - name: Check out code
22 - name: Check out code
23− uses: actions/checkout@v6
23+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
24 with:
24 with:
25 ref: ${{ github.event.pull_request.merge_commit_sha }}
25 ref: ${{ github.event.pull_request.merge_commit_sha }}
26 fetch-depth: 0
26 fetch-depth: 0
27 fetch-tags: true
27 fetch-tags: true
28
28
29 - name: Tag release
29 - name: Tag release
30+ env:
31+ BRANCH: ${{ github.event.pull_request.head.ref }}
30 run: |
32 run: |
31 # Set up github-actions[bot] user
33 # Set up github-actions[bot] user
32 git config --local user.name "github-actions[bot]"
34 git config --local user.name "github-actions[bot]"
33 git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
35 git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
34
36
35 # Get the version from the branch name
37 # Get the version from the branch name
36− branch="${{ github.event.pull_request.head.ref }}"
37− version="${branch#release/}"
38+ version="${BRANCH#release/}"
38 echo ${version}
39 echo ${version}
39
40
40 # Tag and create release
41 # Tag and create release
41 git tag -a "${version}" -m "Release ${version}"
42 git tag -a "${version}" -m "Release ${version}"
42 echo "version=${version}" >> $GITHUB_OUTPUT
43 echo "version=${version}" >> $GITHUB_OUTPUT
43 id: tag
44 id: tag
44−
45− - name: Set up go
46− uses: actions/setup-go@v6
47− with:
48− go-version-file: go.mod
49
45
50− - name: Get dependencies
46+ - name: Get Go version
51− env:
52− # renovate: datasource=github-tags depName=golangci/golangci-lint
53− GOLANGCI_LINT_VERSION: v2.7.2
54 run: |
47 run: |
55− curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION}
48+ version=$(grep "^go " go.mod | cut -d' ' -f2 | cut -d. -f1,2)
56− curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
49+ echo "version=${version}" >> "$GITHUB_OUTPUT"
57− chmod +x ./cc-test-reporter
50+ id: go-version
58
51
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+
59− # Install go dependencies
58+ - name: Get go dependencies
59+ run: |
60 go mod download
60 go mod download
61
61
62 - name: Build Artifacts
62 - name: Build Artifacts
@@ -64,7 +64,7 @@ jobs:
64
64
65 # Upload artifacts in case of workflow failure
65 # Upload artifacts in case of workflow failure
66 - name: Upload Artifacts
66 - name: Upload Artifacts
67− uses: actions/upload-artifact@v5
67+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
68 with:
68 with:
69 name: oauth2-proxy-artifacts
69 name: oauth2-proxy-artifacts
70 path: |
70 path: |
@@ -100,21 +100,21 @@ jobs:
100 runs-on: ubuntu-latest
100 runs-on: ubuntu-latest
101 steps:
101 steps:
102 - name: Check out code
102 - name: Check out code
103− uses: actions/checkout@v6
103+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
104 with:
104 with:
105 ref: ${{ needs.publish.outputs.tag }}
105 ref: ${{ needs.publish.outputs.tag }}
106 fetch-depth: 0
106 fetch-depth: 0
107 fetch-tags: true
107 fetch-tags: true
108
108
109 - name: Set up QEMU
109 - name: Set up QEMU
110− uses: docker/setup-qemu-action@v3
110+ uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4.2.0
111
111
112 - name: Set up Docker Buildx
112 - name: Set up Docker Buildx
113 id: buildx
113 id: buildx
114− uses: docker/setup-buildx-action@v3
114+ uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
115
115
116 - name: Login to quay.io
116 - name: Login to quay.io
117− uses: docker/login-action@v3
117+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
118 with:
118 with:
119 registry: quay.io/oauth2-proxy
119 registry: quay.io/oauth2-proxy
120 username: ${{ secrets.REGISTRY_USERNAME }}
120 username: ${{ secrets.REGISTRY_USERNAME }}
.github/workflows/stale.yml+1−1
@@ -10,7 +10,7 @@ jobs:
10 runs-on: ubuntu-latest
10 runs-on: ubuntu-latest
11
11
12 steps:
12 steps:
13− - uses: actions/stale@v10
13+ - uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0
14 with:
14 with:
15 repo-token: ${{ secrets.GITHUB_TOKEN }}
15 repo-token: ${{ secrets.GITHUB_TOKEN }}
16 days-before-stale: 180
16 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:
53 - revive
53 - revive
54 path: util/.*\.go$
54 path: util/.*\.go$
55 text: "var-naming: avoid meaningless package names"
55 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
56 paths:
64 paths:
57 - third_party$
65 - third_party$
58 - builtin$
66 - builtin$
CHANGELOG.md+213
@@ -6,9 +6,222 @@
6
6
7## Breaking Changes
7## Breaking Changes
8
8
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+
9## Changes since v7.14.0
220## Changes since v7.14.0
10
221
11- [#3309](https://github.com/oauth2-proxy/oauth2-proxy/pull/3309) fix: Return 302 redirect from AuthOnly endpoint when skip-provider-button is true (@StefanMarkmann)
222- [#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)
12
225
13# V7.14.0
226# V7.14.0
14
227
MAINTAINERS.md+1−1
@@ -6,7 +6,7 @@ by our [project governance](GOVERNANCE.md).
6| Name | GitHub Handle | Domains of reponsibility | Email Alias | Affiliation |
6| Name | GitHub Handle | Domains of reponsibility | Email Alias | Affiliation |
7| ---------------- | ------------------------------------------------------ | ------------------------ | -------------------------- | ----------- |
7| ---------------- | ------------------------------------------------------ | ------------------------ | -------------------------- | ----------- |
8| Joel Speed | [@JoelSpeed](https://github.com/joelspeed) | Governance, Core | joel@oauth2-proxy.dev | Red Hat |
8| 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 |
10| JJ Łakis | [@jjlakis](https://github.com/jjlakis) | Provider | jj@oauth2-proxy.dev | - |
10| JJ Łakis | [@jjlakis](https://github.com/jjlakis) | Provider | jj@oauth2-proxy.dev | - |
11| Koen van Zuijlen | [@kvanzuijlen](https://github.com/kvanzuijlen) | CI | koen@oauth2-proxy.dev | - |
11| Koen van Zuijlen | [@kvanzuijlen](https://github.com/kvanzuijlen) | CI | koen@oauth2-proxy.dev | - |
12| Pierluigi Lenoci | [@pierluigilenoci](https://github.com/pierluigilenoci) | Helm | pierluigi@oauth2-proxy.dev | SAP |
12| Pierluigi Lenoci | [@pierluigilenoci](https://github.com/pierluigilenoci) | Helm | pierluigi@oauth2-proxy.dev | SAP |
Makefile+10−5
@@ -25,7 +25,8 @@ help: ## Display this help
25
25
26
26
27GO ?= go
27GO ?= go
28−GOLANGCILINT ?= golangci-lint
28+# renovate: datasource=github-tags depName=golangci/golangci-lint
29+GOLANGCILINT_VERSION ?= v2.11.4
29
30
30BINARY := oauth2-proxy
31BINARY := oauth2-proxy
31VERSION ?= $(shell git describe --always --dirty --tags 2>/dev/null || echo "undefined")
32VERSION ?= $(shell git describe --always --dirty --tags 2>/dev/null || echo "undefined")
@@ -66,7 +67,7 @@ DOCKER_BUILDX_PUSH := $(DOCKER_BUILDX) --push
66DOCKER_BUILDX_PUSH_X_PLATFORM := $(DOCKER_BUILDX_PUSH) --platform ${DOCKER_BUILD_PLATFORM}
67DOCKER_BUILDX_PUSH_X_PLATFORM := $(DOCKER_BUILDX_PUSH) --platform ${DOCKER_BUILD_PLATFORM}
67
68
68DOCKER_BUILD_PLATFORM_ALPINE ?= linux/amd64,linux/arm64,linux/ppc64le,linux/arm/v6,linux/arm/v7,linux/s390x
69DOCKER_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
70DOCKER_BUILDX_ARGS_ALPINE ?= --build-arg RUNTIME_IMAGE=${DOCKER_BUILD_RUNTIME_IMAGE_ALPINE} ${DOCKER_BUILDX_COMMON_ARGS}
71DOCKER_BUILDX_ARGS_ALPINE ?= --build-arg RUNTIME_IMAGE=${DOCKER_BUILD_RUNTIME_IMAGE_ALPINE} ${DOCKER_BUILDX_COMMON_ARGS}
71DOCKER_BUILDX_X_PLATFORM_ALPINE := docker buildx build ${DOCKER_BUILDX_ARGS_ALPINE} --platform ${DOCKER_BUILD_PLATFORM_ALPINE}
72DOCKER_BUILDX_X_PLATFORM_ALPINE := docker buildx build ${DOCKER_BUILDX_ARGS_ALPINE} --platform ${DOCKER_BUILD_PLATFORM_ALPINE}
72DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE := $(DOCKER_BUILDX_X_PLATFORM_ALPINE) --push
73DOCKER_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
143##@ Miscellaneous
144##@ Miscellaneous
144
145
145.PHONY: test
146.PHONY: test
146−test: lint ## Run all Go tests
147+test: ## Run all Go tests
147 GO111MODULE=on $(GO) test $(TESTCOVER) -v -race ./...
148 GO111MODULE=on $(GO) test $(TESTCOVER) -v -race ./...
148
149
149.PHONY: release
150.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)
151 BINARY=${BINARY} VERSION=${VERSION} ./dist.sh
152 BINARY=${BINARY} VERSION=${VERSION} ./dist.sh
152
153
153.PHONY: clean
154.PHONY: clean
@@ -157,7 +158,11 @@ clean: ## Cleanup release and build files
157
158
158.PHONY: lint
159.PHONY: lint
159lint: validate-go-version ## Lint all files using golangci-lint
160lint: 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
161
166
162.PHONY: validate-go-version
167.PHONY: validate-go-version
163validate-go-version: ## Validate Go environment requirements
168validate-go-version: ## Validate Go environment requirements
README.md+4−4
@@ -12,7 +12,7 @@
12
12
13OAuth2 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.
13OAuth2 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.
14
14
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.
16
16
17![Simplified Architecture](docs/static/img/simplified-architecture.svg)
17![Simplified Architecture](docs/static/img/simplified-architecture.svg)
18
18
@@ -23,7 +23,7 @@ OAuth2 Proxy's [Installation Docs](https://oauth2-proxy.github.io/oauth2-proxy/i
23## Releases
23## Releases
24
24
25### Binaries
25### 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`.
27
27
28Check out the [latest release](https://github.com/oauth2-proxy/oauth2-proxy/releases/latest).
28Check out the [latest release](https://github.com/oauth2-proxy/oauth2-proxy/releases/latest).
29
29
@@ -49,9 +49,9 @@ SAP Open Source Program
49Microsoft Azure credits for open source projects
49Microsoft Azure credits for open source projects
50
50
51## Getting Involved
51## 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)
53
53
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.
55
55
56OAuth2 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.
56OAuth2 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.
57
57
contrib/local-environment/Makefile+2−2
@@ -49,8 +49,8 @@ kubernetes-down:
49
49
50.PHONY: traefik-up
50.PHONY: traefik-up
51traefik-up:
51traefik-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
53
53
54.PHONY: traefik-%
54.PHONY: traefik-%
55traefik-%:
55traefik-%:
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 @@
3# This should configure Dex to run on port 5556 and provides a static login
3# This should configure Dex to run on port 5556 and provides a static login
4issuer: http://dex.localtest.me:5556/dex
4issuer: http://dex.localtest.me:5556/dex
5storage:
5storage:
6− type: etcd
6+ type: memory
7− config:
8− endpoints:
9− - http://etcd:2379
10− namespace: dex/
11web:
7web:
12 http: 0.0.0.0:5556
8 http: 0.0.0.0:5556
13oauth2:
9oauth2:
@@ -16,17 +12,17 @@ expiry:
16 signingKeys: "4h"
12 signingKeys: "4h"
17 idTokens: "1h"
13 idTokens: "1h"
18staticClients:
14staticClients:
19−- id: oauth2-proxy
15+ - id: oauth2-proxy
20− redirectURIs:
16+ redirectURIs:
21− # These redirect URIs point to the `--redirect-url` for OAuth2 proxy.
17+ # These redirect URIs point to the `--redirect-url` for OAuth2 proxy.
22− - 'http://oauth2-proxy.localtest.me:4180/oauth2/callback' # For basic proxy example.
18+ - "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.
19+ - "http://oauth2-proxy.localtest.me:8080/oauth2/callback" # For nginx example.
24− name: 'OAuth2 Proxy'
20+ name: "OAuth2 Proxy"
25− secret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK
21+ secret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK
26enablePasswordDB: true
22enablePasswordDB: true
27staticPasswords:
23staticPasswords:
28−- email: "admin@example.com"
24+ - email: "admin@example.com"
29− # bcrypt hash of the string "password"
25+ # bcrypt hash of the string "password"
30− hash: "$2a$10$2b2cU8CPhOTaGrs1HRQuAueS7JTT5ZHsHSzYiFPm1leZck7Mc8T4W"
26+ hash: "$2a$10$2b2cU8CPhOTaGrs1HRQuAueS7JTT5ZHsHSzYiFPm1leZck7Mc8T4W"
31− username: "admin"
27+ username: "admin"
32− userID: "08a8684b-db88-4b73-90a9-3cd1661f5466"
28+ userID: "08a8684b-db88-4b73-90a9-3cd1661f5466"
contrib/local-environment/docker-compose-alpha-config.yaml+3−16
@@ -1,7 +1,7 @@
1# This docker-compose file can be used to bring up an example instance of oauth2-proxy
1# This docker-compose file can be used to bring up an example instance of oauth2-proxy
2# for manual testing and exploration of features.
2# for manual testing and exploration of features.
3# Alongside OAuth2-Proxy, this file also starts Dex to act as the identity provider,
3# 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.
5# This file also uses alpha configuration when configuring OAuth2 Proxy.
5# This file also uses alpha configuration when configuring OAuth2 Proxy.
6#
6#
7# This file is an extension of the main compose file and must be used with it
7# This file is an extension of the main compose file and must be used with it
@@ -14,7 +14,7 @@ version: "3.0"
14services:
14services:
15 oauth2-proxy:
15 oauth2-proxy:
16 container_name: oauth2-proxy
16 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
18 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml
18 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml
19 hostname: oauth2-proxy
19 hostname: oauth2-proxy
20 volumes:
20 volumes:
@@ -31,7 +31,7 @@ services:
31 - httpbin
31 - httpbin
32 dex:
32 dex:
33 container_name: dex
33 container_name: dex
34− image: ghcr.io/dexidp/dex:v2.44.0
34+ image: ghcr.io/dexidp/dex:v2.45.1
35 command: dex serve /dex.yaml
35 command: dex serve /dex.yaml
36 hostname: dex
36 hostname: dex
37 volumes:
37 volumes:
@@ -43,25 +43,12 @@ services:
43 dex:
43 dex:
44 aliases:
44 aliases:
45 - dex.localtest.me
45 - dex.localtest.me
46− etcd: {}
47− depends_on:
48− - etcd
49 httpbin:
46 httpbin:
50 container_name: httpbin
47 container_name: httpbin
51 image: kennethreitz/httpbin
48 image: kennethreitz/httpbin
52 ports: []
49 ports: []
53 networks:
50 networks:
54 httpbin: {}
51 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: {}
64networks:
52networks:
65 dex: {}
53 dex: {}
66− etcd: {}
67 httpbin: {}
54 httpbin: {}
contrib/local-environment/docker-compose-gitea.yaml+2−2
@@ -14,7 +14,7 @@ version: '3.0'
14services:
14services:
15 oauth2-proxy:
15 oauth2-proxy:
16 container_name: oauth2-proxy
16 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
18 command: --config /oauth2-proxy.cfg
18 command: --config /oauth2-proxy.cfg
19 hostname: oauth2-proxy
19 hostname: oauth2-proxy
20 volumes:
20 volumes:
@@ -39,7 +39,7 @@ services:
39 httpbin: {}
39 httpbin: {}
40
40
41 gitea:
41 gitea:
42− image: gitea/gitea:1.25.3
42+ image: gitea/gitea:1.27.2
43 container_name: gitea
43 container_name: gitea
44 environment:
44 environment:
45 - USER_UID=1000
45 - USER_UID=1000
contrib/local-environment/docker-compose-keycloak.yaml+6−6
@@ -10,11 +10,11 @@
10#
10#
11# Access http://oauth2-proxy.localtest.me:4180 to initiate a login cycle using user=admin@example.com, password=password
11# Access http://oauth2-proxy.localtest.me:4180 to initiate a login cycle using user=admin@example.com, password=password
12# Access http://keycloak.localtest.me:9080 with the same credentials to check out the settings
12# Access http://keycloak.localtest.me:9080 with the same credentials to check out the settings
13−version: '3.0'
13+version: "3.0"
14services:
14services:
15 oauth2-proxy:
15 oauth2-proxy:
16 container_name: oauth2-proxy
16 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
18 command: --config /oauth2-proxy.cfg
18 command: --config /oauth2-proxy.cfg
19 hostname: oauth2-proxy
19 hostname: oauth2-proxy
20 volumes:
20 volumes:
@@ -40,12 +40,12 @@ services:
40
40
41 keycloak:
41 keycloak:
42 container_name: keycloak
42 container_name: keycloak
43− image: keycloak/keycloak:25.0
43+ image: keycloak/keycloak:26.7
44 hostname: keycloak
44 hostname: keycloak
45 command:
45 command:
46− - 'start-dev'
46+ - "start-dev"
47− - '--http-port=9080'
47+ - "--http-port=9080"
48− - '--import-realm'
48+ - "--import-realm"
49 volumes:
49 volumes:
50 - ./keycloak:/opt/keycloak/data/import
50 - ./keycloak:/opt/keycloak/data/import
51 environment:
51 environment:
contrib/local-environment/docker-compose-nginx.yaml+9−33
@@ -1,38 +1,28 @@
1# This docker-compose file can be used to bring up an example instance of oauth2-proxy
1# This docker-compose file can be used to bring up an example instance of oauth2-proxy
2# for manual testing and exploration of features.
2# for manual testing and exploration of features.
3# Alongside OAuth2-Proxy, this file also starts Dex to act as the identity provider,
3# 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.
5#
5#
6# This file is an extension of the main compose file and must be used with it
6# This file is an extension of the main compose file and must be used with it
7# docker-compose -f docker-compose.yaml -f docker-compose-nginx.yaml <command>
7# docker-compose -f docker-compose.yaml -f docker-compose-nginx.yaml <command>
8# Alternatively:
8# Alternatively:
9# make nginx-<command> (eg make nginx-up, make nginx-down)
9# make nginx-<command> (eg make nginx-up, make nginx-down)
10#
10#
11−# Access one of the following URLs to initiate a login flow:
11+# Access http://oauth2-proxy.localtest.me:8080 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'
12+version: "3.0"
23services:
13services:
24 oauth2-proxy:
14 oauth2-proxy:
25− image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0
15+ image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.4
26 ports: []
16 ports: []
27 hostname: oauth2-proxy
17 hostname: oauth2-proxy
28 container_name: oauth2-proxy
18 container_name: oauth2-proxy
29 command: --config /oauth2-proxy.cfg
19 command: --config /oauth2-proxy.cfg
20+ restart: unless-stopped
30 volumes:
21 volumes:
31 - "./oauth2-proxy-nginx.cfg:/oauth2-proxy.cfg"
22 - "./oauth2-proxy-nginx.cfg:/oauth2-proxy.cfg"
32 networks:
23 networks:
33 oauth2-proxy: {}
24 oauth2-proxy: {}
34 dex: {}
25 dex: {}
35− etcd: {}
36 httpbin: {}
26 httpbin: {}
37 depends_on:
27 depends_on:
38 - dex
28 - dex
@@ -41,52 +31,38 @@ services:
41 depends_on:
31 depends_on:
42 - oauth2-proxy
32 - oauth2-proxy
43 container_name: nginx
33 container_name: nginx
44− image: nginx:1.29
34+ image: nginx:1.31
45 restart: unless-stopped
35 restart: unless-stopped
46 ports:
36 ports:
47− - 80:80/tcp
37+ - 8080:8080/tcp
48 hostname: nginx
38 hostname: nginx
49 volumes:
39 volumes:
50 - "./nginx.conf:/etc/nginx/conf.d/default.conf"
40 - "./nginx.conf:/etc/nginx/conf.d/default.conf"
51 networks:
41 networks:
52 oauth2-proxy: {}
42 oauth2-proxy: {}
53 dex: {}
43 dex: {}
54− etcd: {}
55 httpbin: {}
44 httpbin: {}
56 dex:
45 dex:
57 container_name: dex
46 container_name: dex
58− image: ghcr.io/dexidp/dex:v2.44.0
47+ image: ghcr.io/dexidp/dex:v2.45.1
59 command: dex serve /dex.yaml
48 command: dex serve /dex.yaml
60 hostname: dex
49 hostname: dex
61 volumes:
50 volumes:
62 - "./dex.yaml:/dex.yaml"
51 - "./dex.yaml:/dex.yaml"
63 restart: unless-stopped
52 restart: unless-stopped
64 ports:
53 ports:
65− - 5556:4181/tcp
54+ - 5556:5556/tcp
66 networks:
55 networks:
67 dex:
56 dex:
68 aliases:
57 aliases:
69 - dex.localtest.me
58 - dex.localtest.me
70− etcd: {}
71− depends_on:
72− - etcd
73 httpbin:
59 httpbin:
74 container_name: httpbin
60 container_name: httpbin
75 image: kennethreitz/httpbin
61 image: kennethreitz/httpbin
76 ports: []
62 ports: []
77 networks:
63 networks:
78 httpbin: {}
64 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: {}
88networks:
65networks:
89 dex: {}
66 dex: {}
90− etcd: {}
91 httpbin: {}
67 httpbin: {}
92 oauth2-proxy: {}
68 oauth2-proxy: {}
contrib/local-environment/docker-compose-traefik.yaml+42−18
@@ -1,7 +1,7 @@
1# This docker-compose file can be used to bring up an example instance of oauth2-proxy
1# This docker-compose file can be used to bring up an example instance of oauth2-proxy
2# for manual testing and exploration of features.
2# for manual testing and exploration of features.
3−# Alongside OAuth2-Proxy, this file also starts Dex to act as the identity provider,
3+# Alongside OAuth2-Proxy, this file also starts Dex to act as the identity provider
4−# HTTPBin as an example upstream.
4+# and HTTPBin as an example upstream.
5#
5#
6# This can either be created using docker-compose
6# This can either be created using docker-compose
7# docker-compose -f docker-compose-traefik.yaml <command>
7# docker-compose -f docker-compose-traefik.yaml <command>
@@ -9,32 +9,51 @@
9# make traefik-<command> (eg. make traefik-up, make traefik-down)
9# make traefik-<command> (eg. make traefik-up, make traefik-down)
10#
10#
11# Access one of the following URLs to initiate a login flow:
11# Access one of the following URLs to initiate a login flow:
12−# - http://oauth2-proxy.localhost
12+# - http://oauth2-proxy.localtest.me
13−# - http://httpbin.oauth2-proxy.localhost
13+# - http://httpbin.localtest.me
14+# - http://dex.localtest.me/dex
14#
15#
15−# The OAuth2 Proxy itself is hosted at http://oauth2-proxy.oauth2-proxy.localhost
16+# The OAuth2 Proxy itself is hosted at http://oauth2-proxy.localtest.me
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'
23services:
17services:
24
18
25 oauth2-proxy:
19 oauth2-proxy:
20+ container_name: oauth2-proxy
26− image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0
21+ image: quay.io/oauth2-proxy/oauth2-proxy:v7.15.4
22+ command: --config /oauth2-proxy.cfg
27 ports: []
23 ports: []
28 hostname: oauth2-proxy
24 hostname: oauth2-proxy
29 volumes:
25 volumes:
30 - "./oauth2-proxy-traefik.cfg:/oauth2-proxy.cfg"
26 - "./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
31 networks:
43 networks:
32− oauth2-proxy:
44+ dex: {}
45+
46+ httpbin:
47+ container_name: httpbin
48+ image: kennethreitz/httpbin
49+ ports: []
50+ networks:
51+ httpbin: {}
33
52
34 # Reverse proxy
53 # Reverse proxy
35 gateway:
54 gateway:
36 container_name: traefik
55 container_name: traefik
37− image: traefik:v2.11.35
56+ image: traefik:v3.7.10
38 volumes:
57 volumes:
39 - "./traefik:/etc/traefik"
58 - "./traefik:/etc/traefik"
40 ports:
59 ports:
@@ -43,8 +62,13 @@ services:
43 depends_on:
62 depends_on:
44 - oauth2-proxy
63 - oauth2-proxy
45 networks:
64 networks:
46− oauth2-proxy:
65+ oauth2-proxy: {}
47− httpbin:
66+ httpbin: {}
67+ dex:
68+ aliases:
69+ - dex.localtest.me
48
70
49networks:
71networks:
72+ dex: {}
73+ httpbin: {}
50− oauth2-proxy:
74+ oauth2-proxy: {}
contrib/local-environment/docker-compose.yaml+3−16
@@ -1,7 +1,7 @@
1# This docker-compose file can be used to bring up an example instance of oauth2-proxy
1# This docker-compose file can be used to bring up an example instance of oauth2-proxy
2# for manual testing and exploration of features.
2# for manual testing and exploration of features.
3# Alongside OAuth2-Proxy, this file also starts Dex to act as the identity provider,
3# 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.
5#
5#
6# This can either be created using docker-compose
6# This can either be created using docker-compose
7# docker-compose -f docker-compose.yaml <command>
7# docker-compose -f docker-compose.yaml <command>
@@ -13,7 +13,7 @@ version: "3.0"
13services:
13services:
14 oauth2-proxy:
14 oauth2-proxy:
15 container_name: oauth2-proxy
15 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
17 command: --config /oauth2-proxy.cfg
17 command: --config /oauth2-proxy.cfg
18 hostname: oauth2-proxy
18 hostname: oauth2-proxy
19 volumes:
19 volumes:
@@ -29,7 +29,7 @@ services:
29 - httpbin
29 - httpbin
30 dex:
30 dex:
31 container_name: dex
31 container_name: dex
32− image: ghcr.io/dexidp/dex:v2.44.0
32+ image: ghcr.io/dexidp/dex:v2.45.1
33 command: dex serve /dex.yaml
33 command: dex serve /dex.yaml
34 hostname: dex
34 hostname: dex
35 volumes:
35 volumes:
@@ -41,25 +41,12 @@ services:
41 dex:
41 dex:
42 aliases:
42 aliases:
43 - dex.localtest.me
43 - dex.localtest.me
44− etcd: {}
45− depends_on:
46− - etcd
47 httpbin:
44 httpbin:
48 container_name: httpbin
45 container_name: httpbin
49 image: kennethreitz/httpbin
46 image: kennethreitz/httpbin
50 ports: []
47 ports: []
51 networks:
48 networks:
52 httpbin: {}
49 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: {}
62networks:
50networks:
63 dex: {}
51 dex: {}
64− etcd: {}
65 httpbin: {}
52 httpbin: {}
contrib/local-environment/kubernetes/Chart.lock+3−3
@@ -1,7 +1,7 @@
1dependencies:
1dependencies:
2- name: dex
2- name: dex
3 repository: https://charts.dexidp.io
3 repository: https://charts.dexidp.io
4− version: 0.24.0
4+ version: 0.24.1
5- name: oauth2-proxy
5- name: oauth2-proxy
6 repository: https://oauth2-proxy.github.io/manifests
6 repository: https://oauth2-proxy.github.io/manifests
7 version: 7.18.0
7 version: 7.18.0
@@ -11,5 +11,5 @@ dependencies:
11- name: hello-world
11- name: hello-world
12 repository: https://conservis.github.io/helm-charts
12 repository: https://conservis.github.io/helm-charts
13 version: 1.1.0
13 version: 1.1.0
14−digest: sha256:fee913531bfb67e5555e995d8fb040c330e6eb4b5a8c777ceb9841135ea9bb84
14+digest: sha256:3fff8bf99cebcd20a73c984423d5f1c2dfa1e5a394f82a5dc60d9aaffe5361b7
15−generated: "2025-10-28T06:46:35.38300324Z"
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
3name: kubernetes
3name: kubernetes
4dependencies:
4dependencies:
5 - name: dex
5 - name: dex
6− version: 0.24.0
6+ version: 0.24.1
7 repository: https://charts.dexidp.io
7 repository: https://charts.dexidp.io
8 - name: oauth2-proxy
8 - name: oauth2-proxy
9 version: &chartVersion 7.18.0
9 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−
14# Reverse proxy to httpbin
1# Reverse proxy to httpbin
15server {
2server {
16− listen 80;
3+ listen 8080;
17− server_name httpbin.oauth2-proxy.localhost;
4+ server_name oauth2-proxy.localtest.me;
18−
5+
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 / {
6+ location /oauth2/ {
29− proxy_pass http://httpbin/;
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;
30 }
12 }
31
13
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/ {
14+ location = /oauth2/auth {
36− internal; # Ensure external users can't access this path
15+ proxy_pass http://oauth2-proxy:4180;
37−
38− # Make sure the OAuth2 Proxy knows where the original request came from.
39− proxy_set_header Host $host;
16+ proxy_set_header Host $host;
40− proxy_set_header X-Real-IP $remote_addr;
17+ proxy_set_header X-Real-IP $remote_addr;
41− proxy_set_header X-Forwarded-Uri $request_uri;
18+ proxy_set_header X-Forwarded-Uri $request_uri;
42−
19+ # nginx auth_request includes headers but not body
43− proxy_pass http://oauth2-proxy:4180/;
20+ proxy_set_header Content-Length "";
21+ proxy_pass_request_body off;
44 }
22 }
45−}
46−
47−# Statically serve the nginx welcome
48−server {
49− listen 80;
50− server_name oauth2-proxy.localhost;
51
23
52 location / {
24 location / {
53− auth_request /internal-auth/oauth2/auth;
25+ auth_request /oauth2/auth;
54−
26+ error_page 401 = @oauth2_signin;
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;
58
27
59− # Alternatively send the request to `start` to skip the provider button
28+ # pass information via X-User and X-Email headers to backend,
60− # error_page 401 = http://oauth2-proxy.oauth2-proxy.localhost/oauth2/start?rd=$scheme://$host$request_uri;
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;
61
34
62−
35+ proxy_pass http://httpbin/;
63− root /usr/share/nginx/html;
36+ # or "root /path/to/site;" or "fastcgi_pass ..." etc
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;
71 }
37 }
72
38
73− # auth_request must be a URI so this allows an internal path to then proxy to
39+ # Named location for handling OAuth2 sign-in redirects
74− # the real auth_request path.
40+ # This ensures the browser receives a proper 302 redirect that it will follow
75− # The trailing /'s are required so that nginx strips the prefix before proxying.
41+ location @oauth2_signin {
76− location /internal-auth/ {
42+ return 302 /oauth2/sign_in?rd=$scheme://$http_host$request_uri;
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/;
85 }
43 }
86}
44}
contrib/local-environment/oauth2-proxy-nginx.cfg+11−6
@@ -1,14 +1,19 @@
1http_address="0.0.0.0:4180"
1http_address="0.0.0.0:4180"
2cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w="
2cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w="
3−provider="oidc"
4email_domains="example.com"
3email_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
6client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK"
10client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK"
7client_id="oauth2-proxy"
11client_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"
9
17
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.
13# Enables the use of `X-Forwarded-*` headers to determine request correctly
18# Enables the use of `X-Forwarded-*` headers to determine request correctly
14reverse_proxy="true"
19reverse_proxy="true"
contrib/local-environment/oauth2-proxy-traefik.cfg+4−4
@@ -2,14 +2,14 @@ http_address="0.0.0.0:4180"
2cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w="
2cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w="
3provider="oidc"
3provider="oidc"
4email_domains=["example.com"]
4email_domains=["example.com"]
5−oidc_issuer_url="http://dex.localhost:5556/dex"
5+oidc_issuer_url="http://dex.localtest.me/dex"
6client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK"
6client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK"
7client_id="oauth2-proxy"
7client_id="oauth2-proxy"
8cookie_secure="false"
8cookie_secure="false"
9
9
10−redirect_url="http://oauth2-proxy.oauth2-proxy.localhost/oauth2/callback"
10+redirect_url="http://oauth2-proxy.localtest.me/oauth2/callback"
11−cookie_domains=".oauth2-proxy.localhost" # Required so cookie can be read on all subdomains.
11+cookie_domains=".localtest.me" # Required so cookie can be read on all subdomains.
12−whitelist_domains=".oauth2-proxy.localhost" # Required to allow redirection back to original requested target.
12+whitelist_domains=".localtest.me" # Required to allow redirection back to original requested target.
13
13
14# Mandatory option when using oauth2-proxy with traefik
14# Mandatory option when using oauth2-proxy with traefik
15reverse_proxy="true"
15reverse_proxy="true"
contrib/local-environment/traefik/dynamic.yaml+11−4
@@ -1,22 +1,25 @@
1http:
1http:
2 routers:
2 routers:
3 oauth2-proxy-route:
3 oauth2-proxy-route:
4− rule: "Host(`oauth2-proxy.oauth2-proxy.localhost`)"
4+ rule: "Host(`oauth2-proxy.localtest.me`)"
5 middlewares:
5 middlewares:
6 - auth-headers
6 - auth-headers
7 service: oauth-backend
7 service: oauth-backend
8+ dex-route:
9+ rule: "Host(`dex.localtest.me`)"
10+ service: dex-service
8 httpbin-route:
11 httpbin-route:
9− rule: "Host(`httpbin.oauth2-proxy.localhost`)"
12+ rule: "Host(`httpbin.localtest.me`)"
10 service: httpbin-service
13 service: httpbin-service
11 middlewares:
14 middlewares:
12 - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin
15 - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin
13 httpbin-route-2:
16 httpbin-route-2:
14− rule: "Host(`httpbin.oauth2-proxy.localhost`) && PathPrefix(`/no-auto-redirect`)"
17+ rule: "Host(`httpbin.localtest.me`) && PathPrefix(`/no-auto-redirect`)"
15 service: httpbin-service
18 service: httpbin-service
16 middlewares:
19 middlewares:
17 - oauth-auth-wo-redirect # unauthenticated session will return a 401
20 - oauth-auth-wo-redirect # unauthenticated session will return a 401
18 services-oauth2-route:
21 services-oauth2-route:
19− rule: "Host(`httpbin.oauth2-proxy.localhost`) && PathPrefix(`/oauth2/`)"
22+ rule: "Host(`httpbin.localtest.me`) && PathPrefix(`/oauth2/`)"
20 middlewares:
23 middlewares:
21 - auth-headers
24 - auth-headers
22 service: oauth-backend
25 service: oauth-backend
@@ -30,6 +33,10 @@ http:
30 loadBalancer:
33 loadBalancer:
31 servers:
34 servers:
32 - url: http://oauth2-proxy:4180
35 - url: http://oauth2-proxy:4180
36+ dex-service:
37+ loadBalancer:
38+ servers:
39+ - url: http://dex:5556
33
40
34 middlewares:
41 middlewares:
35 auth-headers:
42 auth-headers:
contrib/local-environment/traefik/traefik.yaml+2
@@ -5,3 +5,5 @@ log:
5providers:
5providers:
6 file:
6 file:
7 filename: /etc/traefik/dynamic.yaml
7 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
30 GO_OS=$(echo $ARCH | awk -F- '{print $1}')
30 GO_OS=$(echo $ARCH | awk -F- '{print $1}')
31 GO_ARCH=$(echo $ARCH | awk -F- '{print $2}')
31 GO_ARCH=$(echo $ARCH | awk -F- '{print $2}')
32
32
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+
33 # Create architecture specific binaries
40 # Create architecture specific binaries
34 if [[ ${GO_ARCH} == armv* ]]; then
41 if [[ ${GO_ARCH} == armv* ]]; then
35 GO_ARM=$(echo $GO_ARCH | awk -Fv '{print $2}')
42 GO_ARM=$(echo $GO_ARCH | awk -Fv '{print $2}')
36 GO111MODULE=on GOOS=${GO_OS} GOARCH=arm GOARM=${GO_ARM} CGO_ENABLED=0 go build \
43 GO111MODULE=on GOOS=${GO_OS} GOARCH=arm GOARM=${GO_ARM} CGO_ENABLED=0 go build \
37 -ldflags="-X github.com/oauth2-proxy/oauth2-proxy/v7/pkg/version.VERSION=${VERSION}" \
44 -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} .
39 else
46 else
40 GO111MODULE=on GOOS=${GO_OS} GOARCH=${GO_ARCH} CGO_ENABLED=0 go build \
47 GO111MODULE=on GOOS=${GO_OS} GOARCH=${GO_ARCH} CGO_ENABLED=0 go build \
41 -ldflags="-X github.com/oauth2-proxy/oauth2-proxy/v7/pkg/version.VERSION=${VERSION}" \
48 -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} .
43 fi
50 fi
44
51
45 cd release
52 cd release
@@ -51,7 +58,7 @@ for ARCH in "${ARCHS[@]}"; do
51 sha256sum ${BINARY}-${VERSION}.${ARCH}.tar.gz > ${BINARY}-${VERSION}.${ARCH}.tar.gz-sha256sum.txt
58 sha256sum ${BINARY}-${VERSION}.${ARCH}.tar.gz > ${BINARY}-${VERSION}.${ARCH}.tar.gz-sha256sum.txt
52
59
53 # Create sha256sum for architecture specific binary
60 # 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
55
62
56 cd ..
63 cd ..
57done
64done
docs/docs/configuration/alpha_config.md+79−3
@@ -106,6 +106,17 @@ the new config.
106oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg
106oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg
107```
107```
108
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+
109### How to use environment variables
120### How to use environment variables
110
121
111The 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.
122The 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:
156* `claimSource` - `claim` (session claims either from id token or from profile URL)
167* `claimSource` - `claim` (session claims either from id token or from profile URL)
157* `secretSource` - `value` (base64), `fromFile` (file path)
168* `secretSource` - `value` (base64), `fromFile` (file path)
158
169
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+
159**Request option:** `preserveRequestValue: true` retains existing header values
181**Request option:** `preserveRequestValue: true` retains existing header values
160
182
161**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest`
183**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest`
162
184
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+
163## Removed options
237## Removed options
164
238
165The following flags/options and their respective environment variables are no
239The following flags/options and their respective environment variables are no
@@ -488,6 +562,7 @@ character.
488| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID<br/>default set to 'email' |
562| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID<br/>default set to 'email' |
489| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id<br/>By default `aud` claim is used for verification. |
563| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id<br/>By default `aud` claim is used for verification. |
490| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed<br/>to pass verification in addition to the client id. |
564| `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. |
491
566
492### Provider
567### Provider
493
568
@@ -526,6 +601,7 @@ Provider holds all configuration for a single provider
526| `scope` | _string_ | Scope is the OAuth scope specification |
601| `scope` | _string_ | Scope is the OAuth scope specification |
527| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group |
602| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group |
528| `code_challenge_method` | _string_ | The code challenge method |
603| `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. |
529| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session |
605| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session |
530
606
531### ProviderType
607### ProviderType
@@ -571,8 +647,8 @@ Server represents the configuration for an HTTP(S) server
571
647
572| Field | Type | Description |
648| Field | Type | Description |
573| ----- | ---- | ----------- |
649| ----- | ---- | ----------- |
574−| `bindAddress` | _string_ | BindAddress is the address on which to serve 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. |
575−| `secureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.<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. |
576| `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. |
652| `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. |
577
653
578### TLS
654### TLS
@@ -613,7 +689,7 @@ Requests will be proxied to this upstream if the path matches the request path.
613| Field | Type | Description |
689| Field | Type | Description |
614| ----- | ---- | ----------- |
690| ----- | ---- | ----------- |
615| `id` | _string_ | ID should be a unique identifier for the upstream.<br/>This value is required for all upstreams. |
691| `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. |
617| `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`. |
693| `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`. |
618| `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". |
694| `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". |
619| `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. |
695| `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.
106oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg
106oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg
107```
107```
108
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+
109### How to use environment variables
120### How to use environment variables
110
121
111The 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.
122The 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:
156* `claimSource` - `claim` (session claims either from id token or from profile URL)
167* `claimSource` - `claim` (session claims either from id token or from profile URL)
157* `secretSource` - `value` (base64), `fromFile` (file path)
168* `secretSource` - `value` (base64), `fromFile` (file path)
158
169
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+
159**Request option:** `preserveRequestValue: true` retains existing header values
181**Request option:** `preserveRequestValue: true` retains existing header values
160
182
161**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest`
183**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest`
162
184
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+
163## Removed options
237## Removed options
164
238
165The following flags/options and their respective environment variables are no
239The following flags/options and their respective environment variables are no
docs/docs/configuration/integrations/nginx.md+95−12
@@ -43,7 +43,7 @@ server {
43
43
44 location / {
44 location / {
45 auth_request /oauth2/auth;
45 auth_request /oauth2/auth;
46− error_page 401 =403 /oauth2/sign_in;
46+ error_page 401 = @oauth2_signin;
47
47
48 # pass information via X-User and X-Email headers to backend,
48 # pass information via X-User and X-Email headers to backend,
49 # requires running with --set-xauthrequest flag
49 # requires running with --set-xauthrequest flag
@@ -60,31 +60,116 @@ server {
60 auth_request_set $auth_cookie $upstream_http_set_cookie;
60 auth_request_set $auth_cookie $upstream_http_set_cookie;
61 add_header Set-Cookie $auth_cookie;
61 add_header Set-Cookie $auth_cookie;
62
62
63− # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb
63+ # Large OIDC tokens can make the session cookie exceed the 4KB limit,
64− # limit and so the OAuth2 Proxy splits these into multiple parts.
64+ # causing OAuth2 Proxy to split the cookie into multiple parts.
65 # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response,
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.
66+ # so extract the second part when using the default cookie name, `_oauth2_proxy`.
67− auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1;
67+ auth_request_set $auth_cookie_upstream_1 $upstream_cookie__oauth2_proxy_1;
68
68
69 # Extract the Cookie attributes from the first Set-Cookie header and append them
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)
70 # to the second part ($upstream_cookie_* variables only contain the raw cookie content)
71 if ($auth_cookie ~* "(; .*)") {
71 if ($auth_cookie ~* "(; .*)") {
72− set $auth_cookie_name_0 $auth_cookie;
72+ set $auth_cookie_0 $auth_cookie;
73− set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1";
73+ set $auth_cookie_1 "_oauth2_proxy_1=$auth_cookie_upstream_1$1";
74 }
74 }
75
75
76 # Send both Set-Cookie headers now if there was a second part
76 # Send both Set-Cookie headers now if there was a second part
77− if ($auth_cookie_name_upstream_1) {
77+ if ($auth_cookie_upstream_1) {
78− add_header Set-Cookie $auth_cookie_name_0;
78+ add_header Set-Cookie $auth_cookie_0;
79− add_header Set-Cookie $auth_cookie_name_1;
79+ add_header Set-Cookie $auth_cookie_1;
80 }
80 }
81
81
82 proxy_pass http://backend/;
82 proxy_pass http://backend/;
83 # or "root /path/to/site;" or "fastcgi_pass ..." etc
83 # or "root /path/to/site;" or "fastcgi_pass ..." etc
84 }
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+### 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/;
85}
165}
86```
166```
87
167
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+
88When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
173When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
89
174
90```yaml
175```yaml
@@ -100,8 +185,6 @@ It is recommended to use `--session-store-type=redis` when expecting large sessi
100For 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.
185For 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.
101:::
186:::
102
187
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−
105:::note
188:::note
106If 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.
189If 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.
107:::
190:::
docs/docs/configuration/integrations/traefik.md+8
@@ -79,8 +79,16 @@ http:
79 - "401-403"
79 - "401-403"
80 service: oauth-backend
80 service: oauth-backend
81 query: "/oauth2/sign_in?rd={url}"
81 query: "/oauth2/sign_in?rd={url}"
82+ statusRewrites:
83+ "401": 302
82```
84```
83
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+
84### ForwardAuth with static upstreams configuration
92### ForwardAuth with static upstreams configuration
85
93
86Redirect 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
94Redirect 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/
66
66
67### Command Line Options
67### Command Line Options
68
68
69−| Flag | Description |
69+| Flag | Description |
70−| ----------- | -------------------- |
70+| ---------------- | ------------------------------------------------------- |
71−| `--config` | path to config file |
71+| `--config` | path to config file |
72+| `--config-test` | test configuration and exit (for CI/CD validation) |
72−| `--version` | print version string |
73+| `--version` | print version string |
73−
74
74
75### General Provider Options
75### General Provider Options
76
76
@@ -83,7 +83,7 @@ Provider specific options can be found on their respective subpages.
83| flag: `--approval-prompt`<br/>toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` |
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 | |
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"` | |
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 | |
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 | |
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) | |
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 |
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 |
@@ -99,10 +99,11 @@ Provider specific options can be found on their respective subpages.
99| flag: `--oidc-groups-claim`<br/>toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` |
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"` | |
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 | |
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 | 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. | |
103| flag: `--profile-url`<br/>toml: `profile_url` | string | Profile access endpoint | |
104| flag: `--profile-url`<br/>toml: `profile_url` | string | Profile access endpoint | |
104| 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: `--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. | |
106| 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) |
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) |
107| flag: `--provider`<br/>toml: `provider` | string | OAuth provider | google |
108| flag: `--provider`<br/>toml: `provider` | string | OAuth provider | google |
108| flag: `--pubjwk-url`<br/>toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | |
109| 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.
120| flag: `--cookie-csrf-expire`<br/>toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m |
121| flag: `--cookie-csrf-expire`<br/>toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m |
121| 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 |
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 |
122| 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" |
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. | `""` |
123| 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). | |
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). | |
124| 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 |
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 |
125| flag: `--cookie-httponly`<br/>toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true |
127| 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.
128| flag: `--cookie-refresh`<br/>toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers&nbsp;[^1] | |
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] | |
129| flag: `--cookie-samesite`<br/>toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` |
131| flag: `--cookie-samesite`<br/>toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` |
130| flag: `--cookie-secret`<br/>toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | |
132| 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 | |
132| flag: `--cookie-secure`<br/>toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true |
134| flag: `--cookie-secure`<br/>toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true |
133
135
134[^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)
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)
@@ -174,7 +176,7 @@ Provider specific options can be found on their respective subpages.
174| Flag / Config Field | Type | Description | Default |
176| Flag / Config Field | Type | Description | Default |
175| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- |
177| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- |
176| flag: `--banner`<br/>toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | |
178| 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. | |
178| flag: `--custom-templates-dir`<br/>toml: `custom_templates_dir` | string | path to custom html templates | |
180| flag: `--custom-templates-dir`<br/>toml: `custom_templates_dir` | string | path to custom html templates | |
179| flag: `--display-htpasswd-form`<br/>toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true |
181| flag: `--display-htpasswd-form`<br/>toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true |
180| flag: `--footer`<br/>toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | |
182| 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.
191
193
192### Proxy Options
194### Proxy Options
193
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+
194| Flag / Config Field | Type | Description | Default |
200| Flag / Config Field | Type | Description | Default |
195| ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
201| ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
196| 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` |
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` |
@@ -209,12 +215,13 @@ Provider specific options can be found on their respective subpages.
209| flag: `--redirect-url`<br/>toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | |
215| flag: `--redirect-url`<br/>toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | |
210| flag: `--relative-redirect-url`<br/>toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false |
216| flag: `--relative-redirect-url`<br/>toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false |
211| 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 |
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"` |
212| flag: `--signature-key`<br/>toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | |
219| flag: `--signature-key`<br/>toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | |
213| flag: `--skip-auth-preflight`<br/>toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false |
220| 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) | |
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. | |
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 | |
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. | |
216| 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 |
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 |
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 |
218| flag: `--ssl-insecure-skip-verify`<br/>toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false |
225| flag: `--ssl-insecure-skip-verify`<br/>toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false |
219| 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. | |
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. | |
220| 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] | |
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] | |
@@ -225,7 +232,7 @@ Provider specific options can be found on their respective subpages.
225
232
226| Flag / Config Field | Type | Description | Default |
233| Flag / Config Field | Type | Description | Default |
227| ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
234| ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
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"` |
229| 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"` |
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"` |
230| flag: `--metrics-address`<br/>toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` |
237| flag: `--metrics-address`<br/>toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` |
231| flag: `--metrics-secure-address`<br/>toml: `metrics_secure_address` | string | the address prometheus metrics will be scraped from if using HTTPS | `""` |
238| 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.
244| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
251| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
245| 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` | |
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` | |
246| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
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. | |
247| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
255| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
248| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
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` | |
249| 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` | |
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` | |
@@ -265,6 +273,43 @@ Provider specific options can be found on their respective subpages.
265| flag: `--upstream-timeout`<br/>toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s |
273| flag: `--upstream-timeout`<br/>toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s |
266| 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 | |
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 | |
267
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+
268## Upstreams Configuration
313## Upstreams Configuration
269
314
270`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.
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.
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
8| Flag | Toml Field | Type | Description | Default |
8| Flag | Toml Field | Type | Description | Default |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
10| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
10| `--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 | |
12
12
13## Usage
13## Usage
14
14
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.
9Valid providers are :
9Valid providers are :
10
10
11- [ADFS](adfs.md)
11- [ADFS](adfs.md)
12+- [Atlassian Cloud](atlassian.md)
12- [Bitbucket](bitbucket.md)
13- [Bitbucket](bitbucket.md)
13- [Cidaas](cidaas.md)
14- [Cidaas](cidaas.md)
14- [CiscoDuo](cisco_duo.md)
15- [CiscoDuo](cisco_duo.md)
15- [DigitalOcean](digitalocean.md)
16- [DigitalOcean](digitalocean.md)
17+- [DTT SSO](dtt_sso.md)
16- [Facebook](facebook.md)
18- [Facebook](facebook.md)
17- [Gitea](gitea.md)
19- [Gitea](gitea.md)
18- [GitHub](github.md)
20- [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.
40 --client-secret=...
40 --client-secret=...
41```
41```
42
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+
43Currently TLS is not supported (but it's doable).
51Currently 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
38
38
39BEWARE 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").
39BEWARE 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
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+
41### Auth
55### Auth
42
56
43This endpoint returns 202 Accepted response or a 401 Unauthorized response.
57This endpoint returns 202 Accepted response or a 401 Unauthorized response.
docs/docs/installation.md+1−1
@@ -5,7 +5,7 @@ title: Installation
5
5
61. Choose how to deploy:
61. Choose how to deploy:
7
7
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`)
9
9
10 b. Using Go to install the latest release
10 b. Using Go to install the latest release
11 ```bash
11 ```bash
docs/docusaurus.config.js+1−1
@@ -105,7 +105,7 @@ const config = {
105 dropdownActiveClassDisabled: true,
105 dropdownActiveClassDisabled: true,
106 },
106 },
107 {
107 {
108− href: 'https://gophers.slack.com/messages/CM2RSS25N',
108+ href: 'https://cloud-native.slack.com/archives/C098Y5URZ2N',
109 label: 'Slack',
109 label: 'Slack',
110 position: 'right',
110 position: 'right',
111 },
111 },
docs/package.json+4−1
@@ -17,7 +17,7 @@
17 "@docusaurus/core": "^3.3.2",
17 "@docusaurus/core": "^3.3.2",
18 "@docusaurus/preset-classic": "^3.3.2",
18 "@docusaurus/preset-classic": "^3.3.2",
19 "@docusaurus/theme-mermaid": "^3.3.2",
19 "@docusaurus/theme-mermaid": "^3.3.2",
20− "@easyops-cn/docusaurus-search-local": "^0.52.0",
20+ "@easyops-cn/docusaurus-search-local": "^0.55.0",
21 "@mdx-js/react": "^3.0.0",
21 "@mdx-js/react": "^3.0.0",
22 "clsx": "^2.0.0",
22 "clsx": "^2.0.0",
23 "prism-react-renderer": "^2.3.0",
23 "prism-react-renderer": "^2.3.0",
@@ -42,5 +42,8 @@
42 },
42 },
43 "engines": {
43 "engines": {
44 "node": ">=18.0"
44 "node": ">=18.0"
45+ },
46+ "overrides" : {
47+ "webpackbar" : "^7.0.0"
45 }
48 }
46}
49}
docs/sidebars.js+2
@@ -46,11 +46,13 @@ const sidebars = {
46 },
46 },
47 items: [
47 items: [
48 "configuration/providers/adfs",
48 "configuration/providers/adfs",
49+ "configuration/providers/atlassian",
49 "configuration/providers/azure",
50 "configuration/providers/azure",
50 "configuration/providers/bitbucket",
51 "configuration/providers/bitbucket",
51 "configuration/providers/cidaas",
52 "configuration/providers/cidaas",
52 "configuration/providers/cisco_duo",
53 "configuration/providers/cisco_duo",
53 "configuration/providers/digitalocean",
54 "configuration/providers/digitalocean",
55+ "configuration/providers/dtt_sso",
54 "configuration/providers/facebook",
56 "configuration/providers/facebook",
55 "configuration/providers/gitea",
57 "configuration/providers/gitea",
56 "configuration/providers/github",
58 "configuration/providers/github",
docs/versioned_docs/version-7.10.x/configuration/integration.md+77−1
@@ -33,9 +33,15 @@ server {
33 proxy_pass_request_body off;
33 proxy_pass_request_body off;
34 }
34 }
35
35
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+
36 location / {
42 location / {
37 auth_request /oauth2/auth;
43 auth_request /oauth2/auth;
38− error_page 401 =403 /oauth2/sign_in;
44+ error_page 401 = @oauth2_signin;
39
45
40 # pass information via X-User and X-Email headers to backend,
46 # pass information via X-User and X-Email headers to backend,
41 # requires running with --set-xauthrequest flag
47 # requires running with --set-xauthrequest flag
@@ -77,6 +83,68 @@ server {
77}
83}
78```
84```
79
85
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+
80When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
148When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
81
149
82```yaml
150```yaml
@@ -157,8 +225,16 @@ http:
157 - "401-403"
225 - "401-403"
158 service: oauth-backend
226 service: oauth-backend
159 query: "/oauth2/sign_in?rd={url}"
227 query: "/oauth2/sign_in?rd={url}"
228+ statusRewrites:
229+ "401": 302
160```
230```
161
231
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+
162### ForwardAuth with static upstreams configuration
238### ForwardAuth with static upstreams configuration
163
239
164Redirect 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
240Redirect 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.
241| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
241| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
242| 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` | |
242| 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` | |
243| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
243| 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. |
244| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
245| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
245| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
246| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
246| 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` | |
247| 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
8| Flag | Toml Field | Type | Description | Default |
8| Flag | Toml Field | Type | Description | Default |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
10| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
10| `--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 | |
12
12
13## Usage
13## Usage
14
14
docs/versioned_docs/version-7.11.x/configuration/integration.md+77−1
@@ -33,9 +33,15 @@ server {
33 proxy_pass_request_body off;
33 proxy_pass_request_body off;
34 }
34 }
35
35
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+
36 location / {
42 location / {
37 auth_request /oauth2/auth;
43 auth_request /oauth2/auth;
38− error_page 401 =403 /oauth2/sign_in;
44+ error_page 401 = @oauth2_signin;
39
45
40 # pass information via X-User and X-Email headers to backend,
46 # pass information via X-User and X-Email headers to backend,
41 # requires running with --set-xauthrequest flag
47 # requires running with --set-xauthrequest flag
@@ -77,6 +83,68 @@ server {
77}
83}
78```
84```
79
85
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+
80When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
148When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
81
149
82```yaml
150```yaml
@@ -157,8 +225,16 @@ http:
157 - "401-403"
225 - "401-403"
158 service: oauth-backend
226 service: oauth-backend
159 query: "/oauth2/sign_in?rd={url}"
227 query: "/oauth2/sign_in?rd={url}"
228+ statusRewrites:
229+ "401": 302
160```
230```
161
231
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+
162### ForwardAuth with static upstreams configuration
238### ForwardAuth with static upstreams configuration
163
239
164Redirect 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
240Redirect 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.
244| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
244| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
245| 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` | |
245| 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` | |
246| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
246| 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. |
247| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
248| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
248| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
249| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
249| 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` | |
250| 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
8| Flag | Toml Field | Type | Description | Default |
8| Flag | Toml Field | Type | Description | Default |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
10| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
10| `--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 | |
12
12
13## Usage
13## Usage
14
14
docs/versioned_docs/version-7.12.x/configuration/integration.md+77−1
@@ -33,9 +33,15 @@ server {
33 proxy_pass_request_body off;
33 proxy_pass_request_body off;
34 }
34 }
35
35
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+
36 location / {
42 location / {
37 auth_request /oauth2/auth;
43 auth_request /oauth2/auth;
38− error_page 401 =403 /oauth2/sign_in;
44+ error_page 401 = @oauth2_signin;
39
45
40 # pass information via X-User and X-Email headers to backend,
46 # pass information via X-User and X-Email headers to backend,
41 # requires running with --set-xauthrequest flag
47 # requires running with --set-xauthrequest flag
@@ -77,6 +83,68 @@ server {
77}
83}
78```
84```
79
85
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+
80When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
148When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
81
149
82```yaml
150```yaml
@@ -157,8 +225,16 @@ http:
157 - "401-403"
225 - "401-403"
158 service: oauth-backend
226 service: oauth-backend
159 query: "/oauth2/sign_in?rd={url}"
227 query: "/oauth2/sign_in?rd={url}"
228+ statusRewrites:
229+ "401": 302
160```
230```
161
231
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+
162### ForwardAuth with static upstreams configuration
238### ForwardAuth with static upstreams configuration
163
239
164Redirect 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
240Redirect 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.
244| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
244| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
245| 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` | |
245| 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` | |
246| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
246| 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. |
247| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
248| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
248| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
249| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
249| 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` | |
250| 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
8| Flag | Toml Field | Type | Description | Default |
8| Flag | Toml Field | Type | Description | Default |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
10| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
10| `--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 | |
12
12
13## Usage
13## Usage
14
14
docs/versioned_docs/version-7.13.x/configuration/integrations/nginx.md+68−1
@@ -43,7 +43,7 @@ server {
43
43
44 location / {
44 location / {
45 auth_request /oauth2/auth;
45 auth_request /oauth2/auth;
46− error_page 401 =403 /oauth2/sign_in;
46+ error_page 401 = @oauth2_signin;
47
47
48 # pass information via X-User and X-Email headers to backend,
48 # pass information via X-User and X-Email headers to backend,
49 # requires running with --set-xauthrequest flag
49 # requires running with --set-xauthrequest flag
@@ -82,9 +82,76 @@ server {
82 proxy_pass http://backend/;
82 proxy_pass http://backend/;
83 # or "root /path/to/site;" or "fastcgi_pass ..." etc
83 # or "root /path/to/site;" or "fastcgi_pass ..." etc
84 }
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;
85}
107}
86```
108```
87
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+
88When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
155When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
89
156
90```yaml
157```yaml
docs/versioned_docs/version-7.13.x/configuration/integrations/traefik.md+8
@@ -79,8 +79,16 @@ http:
79 - "401-403"
79 - "401-403"
80 service: oauth-backend
80 service: oauth-backend
81 query: "/oauth2/sign_in?rd={url}"
81 query: "/oauth2/sign_in?rd={url}"
82+ statusRewrites:
83+ "401": 302
82```
84```
83
85
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+
84### ForwardAuth with static upstreams configuration
92### ForwardAuth with static upstreams configuration
85
93
86Redirect 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
94Redirect 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.
244| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
244| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
245| 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` | |
245| 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` | |
246| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
246| 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. |
247| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
248| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
248| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
249| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
249| 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` | |
250| 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
8| Flag | Toml Field | Type | Description | Default |
8| Flag | Toml Field | Type | Description | Default |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
10| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
10| `--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 | |
12
12
13## Usage
13## Usage
14
14
docs/versioned_docs/version-7.14.x/configuration/integrations/nginx.md+68−1
@@ -43,7 +43,7 @@ server {
43
43
44 location / {
44 location / {
45 auth_request /oauth2/auth;
45 auth_request /oauth2/auth;
46− error_page 401 =403 /oauth2/sign_in;
46+ error_page 401 = @oauth2_signin;
47
47
48 # pass information via X-User and X-Email headers to backend,
48 # pass information via X-User and X-Email headers to backend,
49 # requires running with --set-xauthrequest flag
49 # requires running with --set-xauthrequest flag
@@ -82,9 +82,76 @@ server {
82 proxy_pass http://backend/;
82 proxy_pass http://backend/;
83 # or "root /path/to/site;" or "fastcgi_pass ..." etc
83 # or "root /path/to/site;" or "fastcgi_pass ..." etc
84 }
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;
85}
107}
86```
108```
87
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+
88When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
155When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource:
89
156
90```yaml
157```yaml
docs/versioned_docs/version-7.14.x/configuration/integrations/traefik.md+8
@@ -79,8 +79,16 @@ http:
79 - "401-403"
79 - "401-403"
80 service: oauth-backend
80 service: oauth-backend
81 query: "/oauth2/sign_in?rd={url}"
81 query: "/oauth2/sign_in?rd={url}"
82+ statusRewrites:
83+ "401": 302
82```
84```
83
85
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+
84### ForwardAuth with static upstreams configuration
92### ForwardAuth with static upstreams configuration
85
93
86Redirect 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
94Redirect 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.
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) | |
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 | |
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 | |
216| 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 |
216| 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 |
218| flag: `--ssl-insecure-skip-verify`<br/>toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false |
218| flag: `--ssl-insecure-skip-verify`<br/>toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false |
219| 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. | |
219| 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. | |
220| 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] | |
220| 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.
244| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
244| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
245| 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` | |
245| 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` | |
246| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
246| 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. |
247| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
248| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
248| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
249| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
249| 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` | |
250| 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
8| Flag | Toml Field | Type | Description | Default |
8| Flag | Toml Field | Type | Description | Default |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
10| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
10| `--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 | |
12
12
13## Usage
13## Usage
14
14
docs/versioned_docs/version-7.14.x/installation.md+1−1
@@ -5,7 +5,7 @@ title: Installation
5
5
61. Choose how to deploy:
61. Choose how to deploy:
7
7
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`)
9
9
10 b. Using Go to install the latest release
10 b. Using Go to install the latest release
11 ```bash
11 ```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.
237| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
237| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
238| 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` | |
238| 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` | |
239| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
239| 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. |
240| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
241| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
241| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
242| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
242| 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` | |
243| 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
8| Flag | Toml Field | Type | Description | Default |
8| Flag | Toml Field | Type | Description | Default |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
10| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
10| `--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 | |
12
12
13## Usage
13## Usage
14
14
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.
237| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
237| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
238| 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` | |
238| 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` | |
239| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
239| 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. |
240| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
241| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
241| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
242| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
242| 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` | |
243| 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
8| Flag | Toml Field | Type | Description | Default |
8| Flag | Toml Field | Type | Description | Default |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
10| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
10| `--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 | |
12
12
13## Usage
13## Usage
14
14
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.
239| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
239| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
240| 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` | |
240| 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` | |
241| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
241| 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. |
242| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
243| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
243| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
244| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
244| 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` | |
245| 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
8| Flag | Toml Field | Type | Description | Default |
8| Flag | Toml Field | Type | Description | Default |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
10| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
10| `--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 | |
12
12
13## Usage
13## Usage
14
14
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.
241| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
241| flag: `--session-store-type`<br/>toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie |
242| 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` | |
242| 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` | |
243| flag: `--redis-connection-url`<br/>toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | |
243| 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. |
244| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
245| flag: `--redis-insecure-skip-tls-verify`<br/>toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false |
245| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
246| flag: `--redis-password`<br/>toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | |
246| 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` | |
247| 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
8| Flag | Toml Field | Type | Description | Default |
8| Flag | Toml Field | Type | Description | Default |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
9| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
10| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | |
10| `--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 | |
12
12
13## Usage
13## Usage
14
14
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 @@
1[
1[
2+ "7.15.x",
2 "7.14.x",
3 "7.14.x",
3 "7.13.x",
4 "7.13.x",
4 "7.12.x",
5 "7.12.x",
go.mod+45−48
@@ -1,86 +1,83 @@
1module github.com/oauth2-proxy/oauth2-proxy/v7
1module github.com/oauth2-proxy/oauth2-proxy/v7
2
2
3−go 1.25.5
3+go 1.26.0
4
4
5require (
5require (
6 cloud.google.com/go/compute/metadata v0.9.0
6 cloud.google.com/go/compute/metadata v0.9.0
7 github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb
7 github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb
8 github.com/a8m/envsubst v1.4.3
8 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
10 github.com/bitly/go-simplejson v0.5.1
10 github.com/bitly/go-simplejson v0.5.1
11− github.com/bsm/redislock v0.9.4
11+ github.com/bsm/redislock v0.10.0
12− github.com/coreos/go-oidc/v3 v3.17.0
12+ github.com/coreos/go-oidc/v3 v3.20.0
13 github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf
13 github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf
14− github.com/fsnotify/fsnotify v1.9.0
14+ github.com/fsnotify/fsnotify v1.10.1
15− github.com/go-jose/go-jose/v3 v3.0.4
15+ github.com/go-jose/go-jose/v3 v3.0.5
16+ github.com/go-jose/go-jose/v4 v4.1.4
16− github.com/go-viper/mapstructure/v2 v2.4.0
17+ github.com/go-viper/mapstructure/v2 v2.5.0
17− github.com/golang-jwt/jwt/v5 v5.3.0
18+ github.com/golang-jwt/jwt/v5 v5.3.1
18 github.com/google/go-cmp v0.7.0
19 github.com/google/go-cmp v0.7.0
19 github.com/google/uuid v1.6.0
20 github.com/google/uuid v1.6.0
20 github.com/gorilla/mux v1.8.1
21 github.com/gorilla/mux v1.8.1
21 github.com/justinas/alice v1.2.0
22 github.com/justinas/alice v1.2.0
22 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25
23 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25
23− github.com/onsi/ginkgo/v2 v2.27.3
24+ github.com/onsi/ginkgo/v2 v2.32.1
24− github.com/onsi/gomega v1.38.3
25+ github.com/onsi/gomega v1.42.1
25− github.com/pierrec/lz4/v4 v4.1.23
26+ github.com/pierrec/lz4/v4 v4.1.28
26− github.com/prometheus/client_golang v1.23.2
27+ github.com/prometheus/client_golang v1.24.1
27− github.com/redis/go-redis/v9 v9.17.2
28+ github.com/redis/go-redis/v9 v9.22.0
28 github.com/spf13/cast v1.10.0
29 github.com/spf13/cast v1.10.0
29 github.com/spf13/pflag v1.0.10
30 github.com/spf13/pflag v1.0.10
30 github.com/spf13/viper v1.21.0
31 github.com/spf13/viper v1.21.0
31− github.com/stretchr/testify v1.11.1
32+ github.com/stretchr/testify v1.12.0
32 github.com/vmihailenco/msgpack/v5 v5.4.1
33 github.com/vmihailenco/msgpack/v5 v5.4.1
33− go.yaml.in/yaml/v3 v3.0.4
34+ go.yaml.in/yaml/v3 v3.0.5
34− golang.org/x/crypto v0.46.0
35+ golang.org/x/crypto v0.55.0
35− golang.org/x/net v0.48.0
36+ golang.org/x/net v0.58.0
36− golang.org/x/oauth2 v0.34.0
37+ golang.org/x/oauth2 v0.36.0
37− golang.org/x/sync v0.19.0
38+ golang.org/x/sync v0.22.0
38− google.golang.org/api v0.258.0
39+ google.golang.org/api v0.293.0
39 gopkg.in/natefinch/lumberjack.v2 v2.2.1
40 gopkg.in/natefinch/lumberjack.v2 v2.2.1
40− k8s.io/apimachinery v0.35.0
41+ k8s.io/apimachinery v0.36.3
41)
42)
42
43
43require (
44require (
44− cloud.google.com/go/auth v0.18.0 // indirect
45+ cloud.google.com/go/auth v0.23.1 // indirect
45 cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
46 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
47 github.com/beorn7/perks v1.0.1 // indirect
48 github.com/beorn7/perks v1.0.1 // indirect
48 github.com/cespare/xxhash/v2 v2.3.0 // indirect
49 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
50+ github.com/felixge/httpsnoop v1.1.0 // indirect
52− github.com/go-jose/go-jose/v4 v4.1.3 // indirect
53− github.com/go-logr/logr v1.4.3 // indirect
51+ github.com/go-logr/logr v1.4.4 // indirect
54 github.com/go-logr/stdr v1.2.2 // indirect
52 github.com/go-logr/stdr v1.2.2 // indirect
55 github.com/go-task/slim-sprig/v3 v3.0.0 // indirect
53 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
57 github.com/google/s2a-go v0.1.9 // indirect
55 github.com/google/s2a-go v0.1.9 // indirect
58− github.com/googleapis/enterprise-certificate-proxy v0.3.7 // indirect
56+ github.com/googleapis/enterprise-certificate-proxy v0.3.21 // indirect
59− github.com/googleapis/gax-go/v2 v2.16.0 // indirect
57+ github.com/googleapis/gax-go/v2 v2.23.0 // indirect
60 github.com/kylelemons/godebug v1.1.0 // indirect
58 github.com/kylelemons/godebug v1.1.0 // indirect
61 github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
59 github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
62− github.com/pelletier/go-toml/v2 v2.2.4 // indirect
60+ github.com/pelletier/go-toml/v2 v2.4.3 // indirect
63− github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
64 github.com/prometheus/client_model v0.6.2 // indirect
61 github.com/prometheus/client_model v0.6.2 // indirect
65− github.com/prometheus/common v0.67.4 // indirect
62+ github.com/prometheus/common v0.70.1 // indirect
66− github.com/prometheus/procfs v0.19.2 // indirect
63+ github.com/prometheus/procfs v0.21.1 // indirect
67 github.com/sagikazarmark/locafero v0.12.0 // indirect
64 github.com/sagikazarmark/locafero v0.12.0 // indirect
68 github.com/spf13/afero v1.15.0 // indirect
65 github.com/spf13/afero v1.15.0 // indirect
69 github.com/subosito/gotenv v1.6.0 // indirect
66 github.com/subosito/gotenv v1.6.0 // indirect
70 github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
67 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
72 go.opentelemetry.io/auto/sdk v1.2.1 // indirect
69 go.opentelemetry.io/auto/sdk v1.2.1 // indirect
73− go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0 // indirect
70+ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 // indirect
74− go.opentelemetry.io/otel v1.39.0 // indirect
71+ go.opentelemetry.io/otel v1.45.0 // indirect
75− go.opentelemetry.io/otel/metric v1.39.0 // indirect
72+ go.opentelemetry.io/otel/metric v1.45.0 // indirect
76− go.opentelemetry.io/otel/trace v1.39.0 // indirect
73+ go.opentelemetry.io/otel/trace v1.45.0 // indirect
77− go.yaml.in/yaml/v2 v2.4.3 // indirect
74+ go.uber.org/atomic v1.11.0 // indirect
78− golang.org/x/mod v0.31.0 // indirect
75+ golang.org/x/mod v0.40.0 // indirect
79− golang.org/x/sys v0.39.0 // indirect
76+ golang.org/x/sys v0.47.0 // indirect
80− golang.org/x/text v0.32.0 // indirect
77+ golang.org/x/text v0.41.0 // indirect
81− golang.org/x/tools v0.40.0 // indirect
78+ golang.org/x/tools v0.49.0 // indirect
82− google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect
79+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260817212433-ac3dfec99bb1 // indirect
83− google.golang.org/grpc v1.78.0 // indirect
80+ google.golang.org/grpc v1.83.0 // indirect
84− google.golang.org/protobuf v1.36.11 // indirect
81+ google.golang.org/protobuf v1.36.12 // indirect
85 gopkg.in/yaml.v3 v3.0.1 // indirect
82 gopkg.in/yaml.v3 v3.0.1 // indirect
86)
83)
go.sum+110−110
@@ -1,5 +1,5 @@
1−cloud.google.com/go/auth v0.18.0 h1:wnqy5hrv7p3k7cShwAU/Br3nzod7fxoqG+k0VZ+/Pk0=
1+cloud.google.com/go/auth v0.23.1 h1:1tPpBPG02lQHmoiAvs9egyCASqXP0xgobptjZzov/Jg=
2−cloud.google.com/go/auth v0.18.0/go.mod h1:wwkPM1AgE1f2u6dG443MiWoD8C3BtOywNsUMcUTVDRo=
2+cloud.google.com/go/auth v0.23.1/go.mod h1:4DhBRcqvtljQN3dJ57qtqbib5ZGCYE5f2crfiiC2EM0=
3cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc=
3cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc=
4cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c=
4cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c=
5cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
5cloud.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
8github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb/go.mod h1:WsAABbY4HQBgd3mGuG4KMNTbHJCPvx9IVBHzysbknss=
8github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb/go.mod h1:WsAABbY4HQBgd3mGuG4KMNTbHJCPvx9IVBHzysbknss=
9github.com/FZambia/sentinel v1.0.0 h1:KJ0ryjKTZk5WMp0dXvSdNqp3lFaW1fNFuEYfrkLOYIc=
9github.com/FZambia/sentinel v1.0.0 h1:KJ0ryjKTZk5WMp0dXvSdNqp3lFaW1fNFuEYfrkLOYIc=
10github.com/FZambia/sentinel v1.0.0/go.mod h1:ytL1Am/RLlAoAXG6Kj5LNuw/TRRQrv2rt2FT26vP5gI=
10github.com/FZambia/sentinel v1.0.0/go.mod h1:ytL1Am/RLlAoAXG6Kj5LNuw/TRRQrv2rt2FT26vP5gI=
11−github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
11+github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE=
12−github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
12+github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
13github.com/a8m/envsubst v1.4.3 h1:kDF7paGK8QACWYaQo6KtyYBozY2jhQrTuNNuUxQkhJY=
13github.com/a8m/envsubst v1.4.3 h1:kDF7paGK8QACWYaQo6KtyYBozY2jhQrTuNNuUxQkhJY=
14github.com/a8m/envsubst v1.4.3/go.mod h1:4jjHWQlZoaXPoLQUb7H2qT4iLkZDdmEQiOUogdUmqVU=
14github.com/a8m/envsubst v1.4.3/go.mod h1:4jjHWQlZoaXPoLQUb7H2qT4iLkZDdmEQiOUogdUmqVU=
15github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
15github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
16github.com/alicebob/miniredis/v2 v2.11.1/go.mod h1:UA48pmi7aSazcGAvcdKcBB49z521IC9VjTTRz2nIaJE=
16github.com/alicebob/miniredis/v2 v2.11.1/go.mod h1:UA48pmi7aSazcGAvcdKcBB49z521IC9VjTTRz2nIaJE=
17−github.com/alicebob/miniredis/v2 v2.35.0 h1:QwLphYqCEAo1eu1TqPRN2jgVMPBweeQcR21jeqDCONI=
17+github.com/alicebob/miniredis/v2 v2.38.0 h1:nZAzCR+Lj+Vxk4ZXzm2NuKq2O33RXj1XxJ2e2uP9jiw=
18−github.com/alicebob/miniredis/v2 v2.35.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM=
18+github.com/alicebob/miniredis/v2 v2.38.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM=
19github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
19github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
20github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
20github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
21github.com/bitly/go-simplejson v0.5.1 h1:xgwPbetQScXt1gh9BmoJ6j9JMr3TElvuIyjR8pgdoow=
21github.com/bitly/go-simplejson v0.5.1 h1:xgwPbetQScXt1gh9BmoJ6j9JMr3TElvuIyjR8pgdoow=
@@ -24,51 +24,47 @@ github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
24github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
24github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
25github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
25github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
26github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
26github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
27−github.com/bsm/redislock v0.9.4 h1:X/Wse1DPpiQgHbVYRE9zv6m070UcKoOGekgvpNhiSvw=
27+github.com/bsm/redislock v0.10.0 h1:NAe1OHDnwPmWEzD+LpWBZXAdZrWld/xj/wmqEcQednQ=
28−github.com/bsm/redislock v0.9.4/go.mod h1:Epf7AJLiSFwLCiZcfi6pWFO/8eAYrYpQXFxEDPoDeAk=
28+github.com/bsm/redislock v0.10.0/go.mod h1:M05WZGjPbX/8ne7LmB7AbOsa2kv7Jzx4fqkLpDFZvJs=
29github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
29github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
30github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
30github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
31github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
31github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
32github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
32github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
33github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
33github.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=
34+github.com/coreos/go-oidc/v3 v3.20.0 h1:EtE0WIBHk03N+DqGkY4+UONzzZHk7amKt6IyNd7OsZE=
35−github.com/coreos/go-oidc/v3 v3.17.0/go.mod h1:wqPbKFrVnE90vty060SB40FCJ8fTHTxSwyXJqZH+sI8=
35+github.com/coreos/go-oidc/v3 v3.20.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
36github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf h1:iW4rZ826su+pqaw19uhpSCzhj44qo35pNgKFGqzDKkU=
36github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf h1:iW4rZ826su+pqaw19uhpSCzhj44qo35pNgKFGqzDKkU=
37github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
37github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
38github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
38github.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=
39+github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
40−github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
40+github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
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=
45github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
41github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
46github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
42github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
47−github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
43+github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
48−github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
44+github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
49github.com/gkampitakis/ciinfo v0.3.2 h1:JcuOPk8ZU7nZQjdUhctuhQofk7BGHuIy0c9Ez8BNhXs=
45github.com/gkampitakis/ciinfo v0.3.2 h1:JcuOPk8ZU7nZQjdUhctuhQofk7BGHuIy0c9Ez8BNhXs=
50github.com/gkampitakis/ciinfo v0.3.2/go.mod h1:1NIwaOcFChN4fa/B0hEBdAb6npDlFL8Bwx4dfRLRqAo=
46github.com/gkampitakis/ciinfo v0.3.2/go.mod h1:1NIwaOcFChN4fa/B0hEBdAb6npDlFL8Bwx4dfRLRqAo=
51github.com/gkampitakis/go-diff v1.3.2 h1:Qyn0J9XJSDTgnsgHRdz9Zp24RaJeKMUHg2+PDZZdC4M=
47github.com/gkampitakis/go-diff v1.3.2 h1:Qyn0J9XJSDTgnsgHRdz9Zp24RaJeKMUHg2+PDZZdC4M=
52github.com/gkampitakis/go-diff v1.3.2/go.mod h1:LLgOrpqleQe26cte8s36HTWcTmMEur6OPYerdAAS9tk=
48github.com/gkampitakis/go-diff v1.3.2/go.mod h1:LLgOrpqleQe26cte8s36HTWcTmMEur6OPYerdAAS9tk=
53github.com/gkampitakis/go-snaps v0.5.15 h1:amyJrvM1D33cPHwVrjo9jQxX8g/7E2wYdZ+01KS3zGE=
49github.com/gkampitakis/go-snaps v0.5.15 h1:amyJrvM1D33cPHwVrjo9jQxX8g/7E2wYdZ+01KS3zGE=
54github.com/gkampitakis/go-snaps v0.5.15/go.mod h1:HNpx/9GoKisdhw9AFOBT1N7DBs9DiHo/hGheFGBZ+mc=
50github.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=
51+github.com/go-jose/go-jose/v3 v3.0.5 h1:BLLJWbC4nMZOfuPVxoZIxeYsn6Nl2r1fITaJ78UQlVQ=
56−github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ=
52+github.com/go-jose/go-jose/v3 v3.0.5/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ=
57−github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs=
53+github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
58−github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
54+github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
59github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
55github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
60−github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
56+github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
61−github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
57+github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
62github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
58github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
63github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
59github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
64github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=
60github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=
65github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=
61github.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=
62+github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
67−github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
63+github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
68github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
64github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
69github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
65github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
70−github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
66+github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
71−github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
67+github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
72github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
68github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
73github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
69github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
74github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3 h1:6amM4HsNPOvMLVc2ZnyqrjeQ92YAVWn7T4WBKK87inY=
70github.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
76github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
72github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
77github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
73github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
78github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
74github.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=
75+github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
80−github.com/google/pprof v0.0.0-20251213031049-b05bdaca462f/go.mod h1:67FPmZWbr+KDT/VlpWtw6sO9XSjpJmLuHpoLmWiTGgY=
76+github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
81github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
77github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
82github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
78github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
83github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
79github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
84github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
80github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
85github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
81github.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=
82+github.com/googleapis/enterprise-certificate-proxy v0.3.21 h1:OFdQ3tnCX/zaQ0Cedur3D3z7kI6HiLX9g3TiAN4/DFU=
87−github.com/googleapis/enterprise-certificate-proxy v0.3.7/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA=
83+github.com/googleapis/enterprise-certificate-proxy v0.3.21/go.mod h1:L3D/IQExI6LqEjBdXcZQ1WluSgigQmSwBboFstVPM4w=
88−github.com/googleapis/gax-go/v2 v2.16.0 h1:iHbQmKLLZrexmb0OSsNGTeSTS0HO4YvFOG8g5E4Zd0Y=
84+github.com/googleapis/gax-go/v2 v2.23.0 h1:Tchl7qkvE7Ip3y+ztvNufYFvkfqTe7NfLTYGIdJRLuE=
89−github.com/googleapis/gax-go/v2 v2.16.0/go.mod h1:o1vfQjjNZn4+dPnRdl/4ZD7S9414Y4xA+a/6Icj6l14=
85+github.com/googleapis/gax-go/v2 v2.23.0/go.mod h1:rBQKOVJCdb8IFEzg+FCwlt1LP/xMDGuqUXhUG+XMXEg=
90github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
86github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
91github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
87github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
92github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE=
88github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE=
93github.com/joshdk/go-junit v1.0.0/go.mod h1:TiiV0PqkaNfFXjEiyjWM3XXrhVyCa1K4Zfga6W52ung=
89github.com/joshdk/go-junit v1.0.0/go.mod h1:TiiV0PqkaNfFXjEiyjWM3XXrhVyCa1K4Zfga6W52ung=
94github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo=
90github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo=
95github.com/justinas/alice v1.2.0/go.mod h1:fN5HRH/reO/zrUflLfTN43t3vXvKzvZIENsNEe7i7qA=
91github.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=
92+github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
97−github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
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=
98github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
96github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
99github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
97github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
100github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
98github.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
111github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
109github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
112github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk=
110github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk=
113github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw=
111github.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=
112+github.com/onsi/ginkgo/v2 v2.32.1 h1:6tlvcDm/3sE8lGJbZ4+d4mO3RLy24/tQWOFzVSQNIfw=
115−github.com/onsi/ginkgo/v2 v2.27.3/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo=
113+github.com/onsi/ginkgo/v2 v2.32.1/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44=
116−github.com/onsi/gomega v1.38.3 h1:eTX+W6dobAYfFeGC2PV6RwXRu/MyT+cQguijutvkpSM=
114+github.com/onsi/gomega v1.42.1 h1:iN1rCUX+44NZ1Dc97MPoeFYbFR0vh8zxoxMFwKdyZ6I=
117−github.com/onsi/gomega v1.38.3/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4=
115+github.com/onsi/gomega v1.42.1/go.mod h1:REff/hsDsodHoKlWsP2mAPhu1+5/6hVYNf9rIEBpeSg=
118−github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
116+github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
119−github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
117+github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
120−github.com/pierrec/lz4/v4 v4.1.23 h1:oJE7T90aYBGtFNrI8+KbETnPymobAhzRrR8Mu8n1yfU=
118+github.com/pierrec/lz4/v4 v4.1.28 h1:pPEPwRJ4kybBTfGt28q7lQsRJQHhC08axprdLD5Ppio=
121−github.com/pierrec/lz4/v4 v4.1.23/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
119+github.com/pierrec/lz4/v4 v4.1.28/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
122github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
120github.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=
121+github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
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=
122+github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
127github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
123github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
128github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
124github.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=
125+github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
130−github.com/prometheus/common v0.67.4/go.mod h1:gP0fq6YjjNCLssJCQp0yk4M8W6ikLURwkdd/YKtTbyI=
126+github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
131−github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws=
127+github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
132−github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw=
128+github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
133−github.com/redis/go-redis/v9 v9.17.2 h1:P2EGsA4qVIM3Pp+aPocCJ7DguDHhqrXNhVcEp4ViluI=
129+github.com/redis/go-redis/v9 v9.22.0 h1:laDvpYXTJtZLloinw1fA5Kqd6HAEH2XKxOkG/PDq2F0=
134−github.com/redis/go-redis/v9 v9.17.2/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
130+github.com/redis/go-redis/v9 v9.22.0/go.mod h1:y2g0Wj8rQvuK0ELM+oxSudcLtC09JScs98I/X9gRWY4=
135github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
131github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
136github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
132github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
137github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4=
133github.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=
146github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
142github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
147github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
143github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
148github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
144github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
149−github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
145+github.com/stretchr/testify v1.12.0 h1:K6Mr6jO9JICuend/5xzTM03ydSV3vdNRYAdPSukj8uI=
150−github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
146+github.com/stretchr/testify v1.12.0/go.mod h1:bOYBZb5qJ00vPzWfIqBUZPaxK8jWiXc6d3ErP4Ca9Gw=
151github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
147github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
152github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
148github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
153github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
149github.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
165github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
161github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
166github.com/yuin/gopher-lua v0.0.0-20190206043414-8bfc7677f583/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ=
162github.com/yuin/gopher-lua v0.0.0-20190206043414-8bfc7677f583/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ=
167github.com/yuin/gopher-lua v0.0.0-20191213034115-f46add6fdb5c/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ=
163github.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=
164+github.com/yuin/gopher-lua v1.1.2 h1:yF/FjE3hD65tBbt0VXLE13HWS9h34fdzJmrWRXwobGA=
169−github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
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=
170go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
168go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
171go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
169go.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=
170+go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04=
173−go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo=
171+go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc=
174−go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0 h1:ssfIgGNANqpVFCndZvcuyKbl0g+UAVcbBcqGkG28H0Y=
172+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 h1:LMuyCAyfalSjDyjdC65nK6N0zoTT63+E/u95X0JovZI=
175−go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0/go.mod h1:GQ/474YrbE4Jx8gZ4q5I4hrhUzM6UPzyrqJYV2AqPoQ=
173+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0/go.mod h1:085m8qbm4hgc8rZWGDEa4vmyyo2c3nPxUslYUKUIU04=
176−go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48=
174+go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU=
177−go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8=
175+go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ=
178−go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0=
176+go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M=
179−go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs=
177+go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s=
180−go.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18=
178+go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw=
181−go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE=
179+go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA=
182−go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8=
180+go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o=
183−go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=
181+go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA=
184−go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI=
182+go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag=
185−go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA=
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=
186go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
186go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
187go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
187go.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=
188+go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
189−go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
189+go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
190−go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
190+go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
191−go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
191+go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
192golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
192golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
193golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
193golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
194golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
194golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
195−golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
195+golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
196−golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
196+golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
197golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
197golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
198golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
198golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
199−golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
199+golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs=
200−golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
200+golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE=
201golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
201golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
202golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
202golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
203golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
203golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
204golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
204golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
205golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
205golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
206−golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
206+golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
207−golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
207+golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
208−golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
208+golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
209−golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
209+golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
210golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
210golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
211golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
211golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
212golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
212golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
213−golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
213+golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
214−golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
214+golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
215golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
215golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
216golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
216golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
217golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
217golang.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
221golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
221golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
222golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
222golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
223golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
223golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
224−golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
224+golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
225−golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
225+golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
226golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
226golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
227golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
227golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
228golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
228golang.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=
234golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
234golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
235golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
235golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
236golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
236golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
237−golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
237+golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
238−golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
238+golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
239−golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
239+golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
240−golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
240+golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
241golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
241golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
242golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
242golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
243golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
243golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
244golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
244golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
245−golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
245+golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
246−golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
246+golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
247golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
247golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
248−gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
248+gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
249−gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
249+gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
250−google.golang.org/api v0.258.0 h1:IKo1j5FBlN74fe5isA2PVozN3Y5pwNKriEgAXPOkDAc=
250+google.golang.org/api v0.293.0 h1:p9XIWOf63U4OgYx120ZwVU8+vl4XTPmWfgVPnmOAS9w=
251−google.golang.org/api v0.258.0/go.mod h1:qhOMTQEZ6lUps63ZNq9jhODswwjkjYYguA7fA3TBFww=
251+google.golang.org/api v0.293.0/go.mod h1:6n5tjEB1gzwniZTepZ0g5u+wM7Bof5GeULCx/zh8ZE0=
252−google.golang.org/genproto v0.0.0-20251202230838-ff82c1b0f217 h1:GvESR9BIyHUahIb0NcTum6itIWtdoglGX+rnGxm2934=
252+google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0=
253−google.golang.org/genproto v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:yJ2HH4EHEDTd3JiLmhds6NkJ17ITVYOdV3m3VKOnws0=
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-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls=
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-20251202230838-ff82c1b0f217/go.mod h1:+rXWjjaukWZun3mLfjmVnQi18E1AsFbDN9QdJ5YXLto=
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-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=
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-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
257+google.golang.org/genproto/googleapis/rpc v0.0.0-20260817212433-ac3dfec99bb1/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
258−google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc=
258+google.golang.org/grpc v1.83.0 h1:JeNZEKJFbQxArAMl+hiytHauacDNqJUllNfmIMmpqnQ=
259−google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U=
259+google.golang.org/grpc v1.83.0/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ=
260−google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
260+google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
261−google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
261+google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
262gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
262gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
263gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
263gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
264gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
264gopkg.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
267gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
267gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
268gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
268gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
269gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
269gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
270−k8s.io/apimachinery v0.35.0 h1:Z2L3IHvPVv/MJ7xRxHEtk6GoJElaAqDCCU0S6ncYok8=
270+k8s.io/apimachinery v0.36.3 h1:PkzMRBRG8joFD8EhCuQAtNPvJlxb82FwplP26HIzvAM=
271−k8s.io/apimachinery v0.35.0/go.mod h1:jQCgFZFR1F4Ik7hvr2g84RTJSZegBc8yHgFWKn//hns=
271+k8s.io/apimachinery v0.36.3/go.mod h1:cTSjBWgPe/6CQyBKzY/hDIRWCQQQeK0mfLbml0UYFHE=
main.go+14
@@ -26,6 +26,7 @@ func main() {
26 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)")
26 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)")
27 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")
27 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")
28 showVersion := configFlagSet.Bool("version", false, "print version string")
28 showVersion := configFlagSet.Bool("version", false, "print version string")
29+ configTest := configFlagSet.Bool("config-test", false, "test the configuration and exit")
29 configFlagSet.Parse(os.Args[1:])
30 configFlagSet.Parse(os.Args[1:])
30
31
31 if *showVersion {
32 if *showVersion {
@@ -37,11 +38,24 @@ func main() {
37 logger.Fatal("cannot use alpha-config and convert-config-to-alpha together")
38 logger.Fatal("cannot use alpha-config and convert-config-to-alpha together")
38 }
39 }
39
40
41+ if *configTest && *convertConfig {
42+ logger.Fatal("cannot use config-test and convert-config-to-alpha together")
43+ }
44+
40 opts, err := loadConfiguration(*config, *alphaConfig, configFlagSet, os.Args[1:])
45 opts, err := loadConfiguration(*config, *alphaConfig, configFlagSet, os.Args[1:])
41 if err != nil {
46 if err != nil {
42 logger.Fatalf("ERROR: %v", err)
47 logger.Fatalf("ERROR: %v", err)
43 }
48 }
44
49
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+
45 if *convertConfig {
59 if *convertConfig {
46 if err := printConvertedConfig(opts); err != nil {
60 if err := printConvertedConfig(opts); err != nil {
47 logger.Fatalf("ERROR: could not convert config: %v", err)
61 logger.Fatalf("ERROR: could not convert config: %v", err)
main_test.go+78−2
@@ -7,6 +7,7 @@ import (
7 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
7 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
8 . "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options/testutil"
8 . "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options/testutil"
9 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
9 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
10+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/validation"
10 . "github.com/onsi/ginkgo/v2"
11 . "github.com/onsi/ginkgo/v2"
11 . "github.com/onsi/gomega"
12 . "github.com/onsi/gomega"
12 "github.com/onsi/gomega/format"
13 "github.com/onsi/gomega/format"
@@ -186,6 +187,7 @@ redirect_url="http://localhost:4180/oauth2/callback"
186 InsecureAllowUnverifiedEmail: ptr.To(false),
187 InsecureAllowUnverifiedEmail: ptr.To(false),
187 InsecureSkipIssuerVerification: ptr.To(false),
188 InsecureSkipIssuerVerification: ptr.To(false),
188 SkipDiscovery: ptr.To(false),
189 SkipDiscovery: ptr.To(false),
190+ EnabledSigningAlgs: []string{},
189 },
191 },
190 MicrosoftEntraIDConfig: options.MicrosoftEntraIDOptions{
192 MicrosoftEntraIDConfig: options.MicrosoftEntraIDOptions{
191 FederatedTokenAuth: ptr.To(false),
193 FederatedTokenAuth: ptr.To(false),
@@ -276,7 +278,7 @@ redirect_url="http://localhost:4180/oauth2/callback"
276 Entry("with bad legacy configuration", loadConfigurationTableInput{
278 Entry("with bad legacy configuration", loadConfigurationTableInput{
277 configContent: testCoreConfig + "unknown_field=\"something\"",
279 configContent: testCoreConfig + "unknown_field=\"something\"",
278 expectedOptions: func() *options.Options { return nil },
280 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"),
280 }),
282 }),
281 Entry("with bad alpha configuration", loadConfigurationTableInput{
283 Entry("with bad alpha configuration", loadConfigurationTableInput{
282 configContent: testCoreConfig,
284 configContent: testCoreConfig,
@@ -288,7 +290,81 @@ redirect_url="http://localhost:4180/oauth2/callback"
288 configContent: testCoreConfig + "unknown_field=\"something\"",
290 configContent: testCoreConfig + "unknown_field=\"something\"",
289 alphaConfigContent: testAlphaConfig,
291 alphaConfigContent: testAlphaConfig,
290 expectedOptions: func() *options.Options { return nil },
292 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"),
292 }),
294 }),
293 )
295 )
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+ })
294})
370})
oauthproxy.go+61−39
@@ -54,9 +54,13 @@ const (
54 authOnlyPath = "/auth"
54 authOnlyPath = "/auth"
55 userInfoPath = "/userinfo"
55 userInfoPath = "/userinfo"
56 staticPathPrefix = "/static/"
56 staticPathPrefix = "/static/"
57+
58+ idTokenPlaceholder = "{id_token}"
57)
59)
58
60
59var (
61var (
62+ defaultTrustedProxyIPs = []string{"0.0.0.0/0", "::/0"}
63+
60 // ErrNeedsLogin means the user should be redirected to the login page
64 // ErrNeedsLogin means the user should be redirected to the login page
61 ErrNeedsLogin = errors.New("redirect to login page")
65 ErrNeedsLogin = errors.New("redirect to login page")
62
66
@@ -181,13 +185,14 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
181
185
182 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)
186 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)
183
187
184− trustedIPs := ip.NewNetSet()
185− for _, ipStr := range opts.TrustedIPs {
188+ trustedIPs, err := ip.ParseNetSet(opts.TrustedIPs)
186− if ipNet := ip.ParseIPNet(ipStr); ipNet != nil {
189+ if err != nil {
187− trustedIPs.AddIPNet(*ipNet)
190+ return nil, err
188− } else {
191+ }
189− return nil, fmt.Errorf("could not parse IP network (%s)", ipStr)
192+
190− }
193+ trustedProxies, err := buildTrustedProxyNetSet(opts)
194+ if err != nil {
195+ return nil, err
191 }
196 }
192
197
193 allowedRoutes, err := buildRoutesAllowlist(opts)
198 allowedRoutes, err := buildRoutesAllowlist(opts)
@@ -200,7 +205,7 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
200 return nil, err
205 return nil, err
201 }
206 }
202
207
203− preAuthChain, err := buildPreAuthChain(opts, sessionStore)
208+ preAuthChain, err := buildPreAuthChain(opts, sessionStore, trustedProxies)
204 if err != nil {
209 if err != nil {
205 return nil, fmt.Errorf("could not build pre-auth chain: %v", err)
210 return nil, fmt.Errorf("could not build pre-auth chain: %v", err)
206 }
211 }
@@ -353,8 +358,8 @@ func (p *OAuthProxy) buildProxySubrouter(s *mux.Router) {
353// buildPreAuthChain constructs a chain that should process every request before
358// buildPreAuthChain constructs a chain that should process every request before
354// the OAuth2 Proxy authentication logic kicks in.
359// the OAuth2 Proxy authentication logic kicks in.
355// For example forcing HTTPS or health checks.
360// For example forcing HTTPS or health checks.
356−func buildPreAuthChain(opts *options.Options, sessionStore sessionsapi.SessionStore) (alice.Chain, error) {
361+func buildPreAuthChain(opts *options.Options, sessionStore sessionsapi.SessionStore, trustedProxies *ip.NetSet) (alice.Chain, error) {
357− chain := alice.New(middleware.NewScope(opts.ReverseProxy, opts.Logging.RequestIDHeader))
362+ chain := alice.New(middleware.NewScope(opts.ReverseProxy, opts.Logging.RequestIDHeader, trustedProxies))
358
363
359 if opts.ForceHTTPS {
364 if opts.ForceHTTPS {
360 _, httpsPort, err := net.SplitHostPort(opts.Server.SecureBindAddress)
365 _, httpsPort, err := net.SplitHostPort(opts.Server.SecureBindAddress)
@@ -393,13 +398,24 @@ func buildPreAuthChain(opts *options.Options, sessionStore sessionsapi.SessionSt
393 return chain, nil
398 return chain, nil
394}
399}
395
400
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+
396func buildSessionChain(opts *options.Options, provider providers.Provider, sessionStore sessionsapi.SessionStore, validator basic.Validator) alice.Chain {
411func buildSessionChain(opts *options.Options, provider providers.Provider, sessionStore sessionsapi.SessionStore, validator basic.Validator) alice.Chain {
397 chain := alice.New()
412 chain := alice.New()
398
413
399 if opts.SkipJwtBearerTokens {
414 if opts.SkipJwtBearerTokens {
415+ verifiers := opts.GetJWTBearerVerifiers()
416+
400− sessionLoaders := []middlewareapi.TokenToSessionFunc{
417+ sessionLoaders := make([]middlewareapi.TokenToSessionFunc, 0, len(verifiers)+1)
401− provider.CreateSessionFromToken,
418+ sessionLoaders = append(sessionLoaders, provider.CreateSessionFromToken)
402− }
403
419
404 for _, verifier := range opts.GetJWTBearerVerifiers() {
420 for _, verifier := range opts.GetJWTBearerVerifiers() {
405 sessionLoaders = append(sessionLoaders,
421 sessionLoaders = append(sessionLoaders,
@@ -571,7 +587,7 @@ func (p *OAuthProxy) ErrorPage(rw http.ResponseWriter, req *http.Request, code i
571
587
572// IsAllowedRequest is used to check if auth should be skipped for this request
588// IsAllowedRequest is used to check if auth should be skipped for this request
573func (p *OAuthProxy) IsAllowedRequest(req *http.Request) bool {
589func (p *OAuthProxy) IsAllowedRequest(req *http.Request) bool {
574− isPreflightRequestAllowed := p.skipAuthPreflight && req.Method == "OPTIONS"
590+ isPreflightRequestAllowed := p.skipAuthPreflight && req.Method == http.MethodOptions
575 return isPreflightRequestAllowed || p.isAllowedRoute(req) || p.isTrustedIP(req)
591 return isPreflightRequestAllowed || p.isAllowedRoute(req) || p.isTrustedIP(req)
576}
592}
577
593
@@ -610,9 +626,7 @@ func (p *OAuthProxy) isAPIPath(req *http.Request) bool {
610
626
611// isTrustedIP is used to check if a request comes from a trusted client IP address.
627// isTrustedIP is used to check if a request comes from a trusted client IP address.
612func (p *OAuthProxy) isTrustedIP(req *http.Request) bool {
628func (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 {
616 return false
630 return false
617 }
631 }
618
632
@@ -633,6 +647,10 @@ func (p *OAuthProxy) isTrustedIP(req *http.Request) bool {
633// SignInPage writes the sign in template to the response
647// SignInPage writes the sign in template to the response
634func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code int) {
648func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code int) {
635 prepareNoCache(rw)
649 prepareNoCache(rw)
650+
651+ if err := p.ClearSessionCookie(rw, req); err != nil {
652+ logger.Printf("Error clearing session cookie: %v", err)
653+ }
636 rw.WriteHeader(code)
654 rw.WriteHeader(code)
637
655
638 redirectURL, err := p.appDirector.GetRedirect(req)
656 redirectURL, err := p.appDirector.GetRedirect(req)
@@ -646,16 +664,12 @@ func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code
646 redirectURL = "/"
664 redirectURL = "/"
647 }
665 }
648
666
649− if err := p.ClearSessionCookie(rw, req); err != nil {
650− logger.Printf("Error clearing session cookie: %v", err)
651− }
652−
653 p.pageWriter.WriteSignInPage(rw, req, redirectURL, code)
667 p.pageWriter.WriteSignInPage(rw, req, redirectURL, code)
654}
668}
655
669
656// ManualSignIn handles basic auth logins to the proxy
670// ManualSignIn handles basic auth logins to the proxy
657func (p *OAuthProxy) ManualSignIn(req *http.Request) (string, bool, int) {
671func (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 {
659 return "", false, http.StatusOK
673 return "", false, http.StatusOK
660 }
674 }
661 user := req.FormValue("username")
675 user := req.FormValue("username")
@@ -720,15 +734,17 @@ func (p *OAuthProxy) UserInfo(rw http.ResponseWriter, req *http.Request) {
720 }
734 }
721
735
722 userInfo := struct {
736 userInfo := struct {
723− User string `json:"user"`
737+ User string `json:"user"`
724− Email string `json:"email"`
738+ Email string `json:"email"`
725− Groups []string `json:"groups,omitempty"`
739+ Groups []string `json:"groups,omitempty"`
726− PreferredUsername string `json:"preferredUsername,omitempty"`
740+ PreferredUsername string `json:"preferredUsername,omitempty"`
741+ AdditionalClaims map[string]interface{} `json:"additionalClaims,omitempty"`
727 }{
742 }{
728 User: session.User,
743 User: session.User,
729 Email: session.Email,
744 Email: session.Email,
730 Groups: session.Groups,
745 Groups: session.Groups,
731 PreferredUsername: session.PreferredUsername,
746 PreferredUsername: session.PreferredUsername,
747+ AdditionalClaims: session.AdditionalClaims,
732 }
748 }
733
749
734 if err := json.NewEncoder(rw).Encode(userInfo); err != nil {
750 if err := json.NewEncoder(rw).Encode(userInfo); err != nil {
@@ -745,6 +761,20 @@ func (p *OAuthProxy) SignOut(rw http.ResponseWriter, req *http.Request) {
745 p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
761 p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error())
746 return
762 return
747 }
763 }
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+
748 err = p.ClearSessionCookie(rw, req)
778 err = p.ClearSessionCookie(rw, req)
749 if err != nil {
779 if err != nil {
750 logger.Errorf("Error clearing session cookie: %v", err)
780 logger.Errorf("Error clearing session cookie: %v", err)
@@ -752,8 +782,6 @@ func (p *OAuthProxy) SignOut(rw http.ResponseWriter, req *http.Request) {
752 return
782 return
753 }
783 }
754
784
755− p.backendLogout(rw, req)
756−
757 http.Redirect(rw, req, redirect, http.StatusFound)
785 http.Redirect(rw, req, redirect, http.StatusFound)
758}
786}
759
787
@@ -773,7 +801,7 @@ func (p *OAuthProxy) backendLogout(rw http.ResponseWriter, req *http.Request) {
773 return
801 return
774 }
802 }
775
803
776− backendLogoutURL := strings.ReplaceAll(providerData.BackendLogoutURL, "{id_token}", session.IDToken)
804+ backendLogoutURL := strings.ReplaceAll(providerData.BackendLogoutURL, idTokenPlaceholder, session.IDToken)
777 // security exception because URL is dynamic ({id_token} replacement) but
805 // security exception because URL is dynamic ({id_token} replacement) but
778 // base is not end-user provided but comes from configuration somewhat secure
806 // base is not end-user provided but comes from configuration somewhat secure
779 resp, err := http.Get(backendLogoutURL) // #nosec G107
807 resp, err := http.Get(backendLogoutURL) // #nosec G107
@@ -783,7 +811,7 @@ func (p *OAuthProxy) backendLogout(rw http.ResponseWriter, req *http.Request) {
783 }
811 }
784
812
785 defer resp.Body.Close()
813 defer resp.Body.Close()
786− if resp.StatusCode != 200 {
814+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
787 logger.Errorf("error while calling backend logout url, returned error code %v", resp.StatusCode)
815 logger.Errorf("error while calling backend logout url, returned error code %v", resp.StatusCode)
788 }
816 }
789}
817}
@@ -858,6 +886,8 @@ func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
858 remoteAddr := ip.GetClientString(p.realClientIPParser, req, true)
886 remoteAddr := ip.GetClientString(p.realClientIPParser, req, true)
859
887
860 // finish the oauth cycle
888 // 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.
861 err := req.ParseForm()
891 err := req.ParseForm()
862 if err != nil {
892 if err != nil {
863 logger.Errorf("Error while parsing OAuth2 callback: %v", err)
893 logger.Errorf("Error while parsing OAuth2 callback: %v", err)
@@ -987,15 +1017,7 @@ func (p *OAuthProxy) enrichSessionState(ctx context.Context, s *sessionsapi.Sess
987// and optional authorization).
1017// and optional authorization).
988func (p *OAuthProxy) AuthOnly(rw http.ResponseWriter, req *http.Request) {
1018func (p *OAuthProxy) AuthOnly(rw http.ResponseWriter, req *http.Request) {
989 session, err := p.getAuthenticatedSession(rw, req)
1019 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 {
999 http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
1021 http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
1000 return
1022 return
1001 }
1023 }
oauthproxy_test.go+342−106
@@ -15,6 +15,7 @@ import (
15 "time"
15 "time"
16
16
17 "github.com/coreos/go-oidc/v3/oidc"
17 "github.com/coreos/go-oidc/v3/oidc"
18+ middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
18 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
19 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
19 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
20 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
20 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/hmacauth"
21 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/hmacauth"
@@ -53,7 +54,7 @@ func TestRobotsTxt(t *testing.T) {
53 t.Fatal(err)
54 t.Fatal(err)
54 }
55 }
55 rw := httptest.NewRecorder()
56 rw := httptest.NewRecorder()
56− req, _ := http.NewRequest("GET", "/robots.txt", nil)
57+ req, _ := http.NewRequest(http.MethodGet, "/robots.txt", nil)
57 proxy.ServeHTTP(rw, req)
58 proxy.ServeHTTP(rw, req)
58 assert.Equal(t, 200, rw.Code)
59 assert.Equal(t, 200, rw.Code)
59 assert.Equal(t, "User-agent: *\nDisallow: /\n", rw.Body.String())
60 assert.Equal(t, "User-agent: *\nDisallow: /\n", rw.Body.String())
@@ -240,7 +241,7 @@ func TestBasicAuthPassword(t *testing.T) {
240
241
241 // Save the required session
242 // Save the required session
242 rw := httptest.NewRecorder()
243 rw := httptest.NewRecorder()
243− req, _ := http.NewRequest("GET", "/", nil)
244+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
244 err = proxy.sessionStore.Save(rw, req, &sessions.SessionState{
245 err = proxy.sessionStore.Save(rw, req, &sessions.SessionState{
245 Email: emailAddress,
246 Email: emailAddress,
246 })
247 })
@@ -249,7 +250,7 @@ func TestBasicAuthPassword(t *testing.T) {
249 // Extract the cookie value to inject into the test request
250 // Extract the cookie value to inject into the test request
250 cookie := rw.Header().Values("Set-Cookie")[0]
251 cookie := rw.Header().Values("Set-Cookie")[0]
251
252
252− req, _ = http.NewRequest("GET", "/", nil)
253+ req, _ = http.NewRequest(http.MethodGet, "/", nil)
253 req.Header.Set("Cookie", cookie)
254 req.Header.Set("Cookie", cookie)
254 rw = httptest.NewRecorder()
255 rw = httptest.NewRecorder()
255 proxy.ServeHTTP(rw, req)
256 proxy.ServeHTTP(rw, req)
@@ -299,14 +300,14 @@ func TestPassGroupsHeadersWithGroups(t *testing.T) {
299
300
300 // Save the required session
301 // Save the required session
301 rw := httptest.NewRecorder()
302 rw := httptest.NewRecorder()
302− req, _ := http.NewRequest("GET", "/", nil)
303+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
303 err = proxy.sessionStore.Save(rw, req, session)
304 err = proxy.sessionStore.Save(rw, req, session)
304 assert.NoError(t, err)
305 assert.NoError(t, err)
305
306
306 // Extract the cookie value to inject into the test request
307 // Extract the cookie value to inject into the test request
307 cookie := rw.Header().Values("Set-Cookie")[0]
308 cookie := rw.Header().Values("Set-Cookie")[0]
308
309
309− req, _ = http.NewRequest("GET", "/", nil)
310+ req, _ = http.NewRequest(http.MethodGet, "/", nil)
310 req.Header.Set("Cookie", cookie)
311 req.Header.Set("Cookie", cookie)
311 rw = httptest.NewRecorder()
312 rw = httptest.NewRecorder()
312 proxy.ServeHTTP(rw, req)
313 proxy.ServeHTTP(rw, req)
@@ -456,7 +457,7 @@ func (patTest *PassAccessTokenTest) getEndpointWithCookie(cookie string, endpoin
456 return 0, ""
457 return 0, ""
457 }
458 }
458
459
459− req, err := http.NewRequest("GET", endpoint, strings.NewReader(""))
460+ req, err := http.NewRequest(http.MethodGet, endpoint, strings.NewReader(""))
460 if err != nil {
461 if err != nil {
461 return 0, ""
462 return 0, ""
462 }
463 }
@@ -607,7 +608,7 @@ func NewSignInPageTest(skipProvider bool) (*SignInPageTest, error) {
607
608
608func (sipTest *SignInPageTest) GetEndpoint(endpoint string) (int, string) {
609func (sipTest *SignInPageTest) GetEndpoint(endpoint string) (int, string) {
609 rw := httptest.NewRecorder()
610 rw := httptest.NewRecorder()
610− req, _ := http.NewRequest("GET", endpoint, strings.NewReader(""))
611+ req, _ := http.NewRequest(http.MethodGet, endpoint, strings.NewReader(""))
611 sipTest.proxy.ServeHTTP(rw, req)
612 sipTest.proxy.ServeHTTP(rw, req)
612 return rw.Code, rw.Body.String()
613 return rw.Code, rw.Body.String()
613}
614}
@@ -712,6 +713,50 @@ func TestManualSignInCorrectCredentials(t *testing.T) {
712 assert.Equal(t, http.StatusFound, statusCode)
713 assert.Equal(t, http.StatusFound, statusCode)
713}
714}
714
715
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+
715func TestSignInPageIncludesTargetRedirect(t *testing.T) {
760func TestSignInPageIncludesTargetRedirect(t *testing.T) {
716 sipTest, err := NewSignInPageTest(false)
761 sipTest, err := NewSignInPageTest(false)
717 if err != nil {
762 if err != nil {
@@ -834,20 +879,8 @@ func NewProcessCookieTest(opts ProcessCookieTestOpts, modifiers ...OptionsModifi
834 return nil, err
879 return nil, err
835 }
880 }
836 testProvider := &TestProvider{
881 testProvider := &TestProvider{
837− ProviderData: &providers.ProviderData{
882+ 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,
883+ ValidToken: opts.providerValidateCookieResponse,
851 }
884 }
852
885
853 groups := pcTest.opts.Providers[0].AllowedGroups
886 groups := pcTest.opts.Providers[0].AllowedGroups
@@ -861,7 +894,7 @@ func NewProcessCookieTest(opts ProcessCookieTestOpts, modifiers ...OptionsModifi
861 // access_token validation.
894 // access_token validation.
862 pcTest.proxy.CookieOptions.Refresh = time.Duration(0)
895 pcTest.proxy.CookieOptions.Refresh = time.Duration(0)
863 pcTest.rw = httptest.NewRecorder()
896 pcTest.rw = httptest.NewRecorder()
864− pcTest.req, _ = http.NewRequest("GET", "/", strings.NewReader(""))
897+ pcTest.req, _ = http.NewRequest(http.MethodGet, "/", strings.NewReader(""))
865 pcTest.validateUser = true
898 pcTest.validateUser = true
866 return &pcTest, nil
899 return &pcTest, nil
867}
900}
@@ -994,7 +1027,7 @@ func NewUserInfoEndpointTest() (*ProcessCookieTest, error) {
994 if err != nil {
1027 if err != nil {
995 return nil, err
1028 return nil, err
996 }
1029 }
997− pcTest.req, _ = http.NewRequest("GET",
1030+ pcTest.req, _ = http.NewRequest(http.MethodGet,
998 pcTest.opts.ProxyPrefix+"/userinfo", nil)
1031 pcTest.opts.ProxyPrefix+"/userinfo", nil)
999 return pcTest, nil
1032 return pcTest, nil
1000}
1033}
@@ -1044,6 +1077,20 @@ func TestUserInfoEndpointAccepted(t *testing.T) {
1044 },
1077 },
1045 expectedResponse: "{\"user\":\"john.doe\",\"email\":\"john.doe@example.com\",\"groups\":[\"example\",\"groups\"],\"preferredUsername\":\"john\"}\n",
1078 expectedResponse: "{\"user\":\"john.doe\",\"email\":\"john.doe@example.com\",\"groups\":[\"example\",\"groups\"],\"preferredUsername\":\"john\"}\n",
1046 },
1079 },
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+ },
1047 }
1094 }
1048
1095
1049 for _, tc := range testCases {
1096 for _, tc := range testCases {
@@ -1088,7 +1135,7 @@ func NewAuthOnlyEndpointTest(querystring string, modifiers ...OptionsModifier) (
1088 return nil, err
1135 return nil, err
1089 }
1136 }
1090 pcTest.req, _ = http.NewRequest(
1137 pcTest.req, _ = http.NewRequest(
1091− "GET",
1138+ http.MethodGet,
1092 fmt.Sprintf("%s/auth%s", pcTest.opts.ProxyPrefix, querystring),
1139 fmt.Sprintf("%s/auth%s", pcTest.opts.ProxyPrefix, querystring),
1093 nil)
1140 nil)
1094 return pcTest, nil
1141 return pcTest, nil
@@ -1124,35 +1171,6 @@ func TestAuthOnlyEndpointUnauthorizedOnNoCookieSetError(t *testing.T) {
1124 assert.Equal(t, "Unauthorized\n", string(bodyBytes))
1171 assert.Equal(t, "Unauthorized\n", string(bodyBytes))
1125}
1172}
1126
1173
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−
1156func TestAuthOnlyEndpointUnauthorizedOnExpiration(t *testing.T) {
1174func TestAuthOnlyEndpointUnauthorizedOnExpiration(t *testing.T) {
1157 test, err := NewAuthOnlyEndpointTest("", func(opts *options.Options) {
1175 test, err := NewAuthOnlyEndpointTest("", func(opts *options.Options) {
1158 opts.Cookie.Expire = time.Duration(24) * time.Hour
1176 opts.Cookie.Expire = time.Duration(24) * time.Hour
@@ -1256,7 +1274,7 @@ func TestAuthOnlyEndpointSetXAuthRequestHeaders(t *testing.T) {
1256 pcTest.validateUser = true
1274 pcTest.validateUser = true
1257
1275
1258 pcTest.rw = httptest.NewRecorder()
1276 pcTest.rw = httptest.NewRecorder()
1259− pcTest.req, _ = http.NewRequest("GET",
1277+ pcTest.req, _ = http.NewRequest(http.MethodGet,
1260 pcTest.opts.ProxyPrefix+authOnlyPath, nil)
1278 pcTest.opts.ProxyPrefix+authOnlyPath, nil)
1261
1279
1262 created := time.Now()
1280 created := time.Now()
@@ -1349,7 +1367,7 @@ func TestAuthOnlyEndpointSetBasicAuthTrueRequestHeaders(t *testing.T) {
1349 pcTest.validateUser = true
1367 pcTest.validateUser = true
1350
1368
1351 pcTest.rw = httptest.NewRecorder()
1369 pcTest.rw = httptest.NewRecorder()
1352− pcTest.req, _ = http.NewRequest("GET",
1370+ pcTest.req, _ = http.NewRequest(http.MethodGet,
1353 pcTest.opts.ProxyPrefix+authOnlyPath, nil)
1371 pcTest.opts.ProxyPrefix+authOnlyPath, nil)
1354
1372
1355 created := time.Now()
1373 created := time.Now()
@@ -1429,7 +1447,7 @@ func TestAuthOnlyEndpointSetBasicAuthFalseRequestHeaders(t *testing.T) {
1429 pcTest.validateUser = true
1447 pcTest.validateUser = true
1430
1448
1431 pcTest.rw = httptest.NewRecorder()
1449 pcTest.rw = httptest.NewRecorder()
1432− pcTest.req, _ = http.NewRequest("GET",
1450+ pcTest.req, _ = http.NewRequest(http.MethodGet,
1433 pcTest.opts.ProxyPrefix+authOnlyPath, nil)
1451 pcTest.opts.ProxyPrefix+authOnlyPath, nil)
1434
1452
1435 created := time.Now()
1453 created := time.Now()
@@ -1477,7 +1495,7 @@ func TestAuthSkippedForPreflightRequests(t *testing.T) {
1477 }
1495 }
1478 proxy.provider = NewTestProvider(upstreamURL, "")
1496 proxy.provider = NewTestProvider(upstreamURL, "")
1479 rw := httptest.NewRecorder()
1497 rw := httptest.NewRecorder()
1480− req, _ := http.NewRequest("OPTIONS", "/preflight-request", nil)
1498+ req, _ := http.NewRequest(http.MethodOptions, "/preflight-request", nil)
1481 proxy.ServeHTTP(rw, req)
1499 proxy.ServeHTTP(rw, req)
1482
1500
1483 assert.Equal(t, 200, rw.Code)
1501 assert.Equal(t, 200, rw.Code)
@@ -1634,19 +1652,19 @@ func TestRequestSignature(t *testing.T) {
1634 resp string
1652 resp string
1635 }{
1653 }{
1636 "No request signature": {
1654 "No request signature": {
1637− method: "GET",
1655+ method: http.MethodGet,
1638 body: "",
1656 body: "",
1639 key: "",
1657 key: "",
1640 resp: "no signature received",
1658 resp: "no signature received",
1641 },
1659 },
1642 "Get request": {
1660 "Get request": {
1643− method: "GET",
1661+ method: http.MethodGet,
1644 body: "",
1662 body: "",
1645 key: "7d9e1aa87a5954e6f9fc59266b3af9d7c35fda2d",
1663 key: "7d9e1aa87a5954e6f9fc59266b3af9d7c35fda2d",
1646 resp: "signatures match",
1664 resp: "signatures match",
1647 },
1665 },
1648 "Post request": {
1666 "Post request": {
1649− method: "POST",
1667+ method: http.MethodPost,
1650 body: `{ "hello": "world!" }`,
1668 body: `{ "hello": "world!" }`,
1651 key: "d90df39e2d19282840252612dd7c81421a372f61",
1669 key: "d90df39e2d19282840252612dd7c81421a372f61",
1652 resp: "signatures match",
1670 resp: "signatures match",
@@ -2069,6 +2087,44 @@ func Test_noCacheHeaders(t *testing.T) {
2069 })
2087 })
2070}
2088}
2071
2089
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+
2072func baseTestOptions() *options.Options {
2128func baseTestOptions() *options.Options {
2073 opts := options.NewOptions()
2129 opts := options.NewOptions()
2074 opts.Cookie.Secret = rawCookieSecret
2130 opts.Cookie.Secret = rawCookieSecret
@@ -2133,7 +2189,33 @@ func TestTrustedIPs(t *testing.T) {
2133 reverseProxy: false,
2189 reverseProxy: false,
2134 realClientIPHeader: "X-Real-IP", // Default value
2190 realClientIPHeader: "X-Real-IP", // Default value
2135 req: func() *http.Request {
2191 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 = "@"
2137 return req
2219 return req
2138 }(),
2220 }(),
2139 expectTrusted: false,
2221 expectTrusted: false,
@@ -2145,7 +2227,7 @@ func TestTrustedIPs(t *testing.T) {
2145 reverseProxy: false,
2227 reverseProxy: false,
2146 realClientIPHeader: "X-Real-IP", // Default value
2228 realClientIPHeader: "X-Real-IP", // Default value
2147 req: func() *http.Request {
2229 req: func() *http.Request {
2148− req, _ := http.NewRequest("GET", "/", nil)
2230+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
2149 req.RemoteAddr = "127.0.0.1:43670"
2231 req.RemoteAddr = "127.0.0.1:43670"
2150 return req
2232 return req
2151 }(),
2233 }(),
@@ -2158,7 +2240,7 @@ func TestTrustedIPs(t *testing.T) {
2158 reverseProxy: true,
2240 reverseProxy: true,
2159 realClientIPHeader: "X-Real-IP", // Default value
2241 realClientIPHeader: "X-Real-IP", // Default value
2160 req: func() *http.Request {
2242 req: func() *http.Request {
2161− req, _ := http.NewRequest("GET", "/", nil)
2243+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
2162 req.RemoteAddr = "127.0.0.1:44324"
2244 req.RemoteAddr = "127.0.0.1:44324"
2163 return req
2245 return req
2164 }(),
2246 }(),
@@ -2171,7 +2253,7 @@ func TestTrustedIPs(t *testing.T) {
2171 reverseProxy: true,
2253 reverseProxy: true,
2172 realClientIPHeader: "X-Forwarded-For",
2254 realClientIPHeader: "X-Forwarded-For",
2173 req: func() *http.Request {
2255 req: func() *http.Request {
2174− req, _ := http.NewRequest("GET", "/", nil)
2256+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
2175 req.Header.Add("X-Forwarded-For", "127.0.0.1")
2257 req.Header.Add("X-Forwarded-For", "127.0.0.1")
2176 return req
2258 return req
2177 }(),
2259 }(),
@@ -2184,7 +2266,7 @@ func TestTrustedIPs(t *testing.T) {
2184 reverseProxy: true,
2266 reverseProxy: true,
2185 realClientIPHeader: "X-Forwarded-For",
2267 realClientIPHeader: "X-Forwarded-For",
2186 req: func() *http.Request {
2268 req: func() *http.Request {
2187− req, _ := http.NewRequest("GET", "/", nil)
2269+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
2188 req.Header.Add("X-Forwarded-For", "::1")
2270 req.Header.Add("X-Forwarded-For", "::1")
2189 return req
2271 return req
2190 }(),
2272 }(),
@@ -2197,7 +2279,7 @@ func TestTrustedIPs(t *testing.T) {
2197 reverseProxy: true,
2279 reverseProxy: true,
2198 realClientIPHeader: "X-Forwarded-For",
2280 realClientIPHeader: "X-Forwarded-For",
2199 req: func() *http.Request {
2281 req: func() *http.Request {
2200− req, _ := http.NewRequest("GET", "/", nil)
2282+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
2201 req.Header.Add("X-Forwarded-For", "12.34.56.78")
2283 req.Header.Add("X-Forwarded-For", "12.34.56.78")
2202 return req
2284 return req
2203 }(),
2285 }(),
@@ -2210,7 +2292,7 @@ func TestTrustedIPs(t *testing.T) {
2210 reverseProxy: true,
2292 reverseProxy: true,
2211 realClientIPHeader: "X-Forwarded-For",
2293 realClientIPHeader: "X-Forwarded-For",
2212 req: func() *http.Request {
2294 req: func() *http.Request {
2213− req, _ := http.NewRequest("GET", "/", nil)
2295+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
2214 req.Header.Add("X-Forwarded-For", "::2")
2296 req.Header.Add("X-Forwarded-For", "::2")
2215 return req
2297 return req
2216 }(),
2298 }(),
@@ -2223,7 +2305,7 @@ func TestTrustedIPs(t *testing.T) {
2223 reverseProxy: true,
2305 reverseProxy: true,
2224 realClientIPHeader: "X-Forwarded-For",
2306 realClientIPHeader: "X-Forwarded-For",
2225 req: func() *http.Request {
2307 req: func() *http.Request {
2226− req, _ := http.NewRequest("GET", "/", nil)
2308+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
2227 req.Header.Add("X-Real-IP", "::1")
2309 req.Header.Add("X-Real-IP", "::1")
2228 return req
2310 return req
2229 }(),
2311 }(),
@@ -2236,7 +2318,7 @@ func TestTrustedIPs(t *testing.T) {
2236 reverseProxy: true,
2318 reverseProxy: true,
2237 realClientIPHeader: "X-Forwarded-For",
2319 realClientIPHeader: "X-Forwarded-For",
2238 req: func() *http.Request {
2320 req: func() *http.Request {
2239− req, _ := http.NewRequest("GET", "/", nil)
2321+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
2240 req.Header.Add("X-Forwarded-For", "adsfljk29242as!!")
2322 req.Header.Add("X-Forwarded-For", "adsfljk29242as!!")
2241 return req
2323 return req
2242 }(),
2324 }(),
@@ -2249,7 +2331,7 @@ func TestTrustedIPs(t *testing.T) {
2249 reverseProxy: false,
2331 reverseProxy: false,
2250 realClientIPHeader: "X-Real-IP",
2332 realClientIPHeader: "X-Real-IP",
2251 req: func() *http.Request {
2333 req: func() *http.Request {
2252− req, _ := http.NewRequest("GET", "/", nil)
2334+ req, _ := http.NewRequest(http.MethodGet, "/", nil)
2253 req.RemoteAddr = "adsfljk29242as!!"
2335 req.RemoteAddr = "adsfljk29242as!!"
2254 return req
2336 return req
2255 }(),
2337 }(),
@@ -2345,12 +2427,12 @@ func Test_buildRoutesAllowlist(t *testing.T) {
2345 },
2427 },
2346 expectedRoutes: []expectedAllowedRoute{
2428 expectedRoutes: []expectedAllowedRoute{
2347 {
2429 {
2348− method: "GET",
2430+ method: http.MethodGet,
2349 negate: false,
2431 negate: false,
2350 regexString: "^/foo/bar",
2432 regexString: "^/foo/bar",
2351 },
2433 },
2352 {
2434 {
2353− method: "POST",
2435+ method: http.MethodPost,
2354 negate: false,
2436 negate: false,
2355 regexString: "^/baz/[0-9]+/thing",
2437 regexString: "^/baz/[0-9]+/thing",
2356 },
2438 },
@@ -2403,11 +2485,11 @@ func Test_buildRoutesAllowlist(t *testing.T) {
2403 regexString: "^/baz/[0-9]+/thing/regex",
2485 regexString: "^/baz/[0-9]+/thing/regex",
2404 },
2486 },
2405 {
2487 {
2406− method: "GET",
2488+ method: http.MethodGet,
2407 regexString: "^/foo/bar",
2489 regexString: "^/foo/bar",
2408 },
2490 },
2409 {
2491 {
2410− method: "POST",
2492+ method: http.MethodPost,
2411 regexString: "^/baz/[0-9]+/thing",
2493 regexString: "^/baz/[0-9]+/thing",
2412 },
2494 },
2413 {
2495 {
@@ -2559,7 +2641,7 @@ func TestApiRoutes(t *testing.T) {
2559
2641
2560 for _, tc := range testCases {
2642 for _, tc := range testCases {
2561 t.Run(tc.name, func(t *testing.T) {
2643 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)
2563 req.Header.Set("Accept", tc.contentType)
2645 req.Header.Set("Accept", tc.contentType)
2564 assert.NoError(t, err)
2646 assert.NoError(t, err)
2565
2647
@@ -2597,9 +2679,11 @@ func TestAllowedRequest(t *testing.T) {
2597 }
2679 }
2598 opts.SkipAuthRegex = []string{
2680 opts.SkipAuthRegex = []string{
2599 "^/skip/auth/regex$",
2681 "^/skip/auth/regex$",
2682+ "^/public/.*/endpoint$",
2600 }
2683 }
2601 opts.SkipAuthRoutes = []string{
2684 opts.SkipAuthRoutes = []string{
2602 "GET=^/skip/auth/routes/get",
2685 "GET=^/skip/auth/routes/get",
2686+ "^/foo/.*/bar$",
2603 }
2687 }
2604 err := validation.Validate(opts)
2688 err := validation.Validate(opts)
2605 assert.NoError(t, err)
2689 assert.NoError(t, err)
@@ -2616,25 +2700,37 @@ func TestAllowedRequest(t *testing.T) {
2616 }{
2700 }{
2617 {
2701 {
2618 name: "Regex GET allowed",
2702 name: "Regex GET allowed",
2619− method: "GET",
2703+ method: http.MethodGet,
2620 url: "/skip/auth/regex",
2704 url: "/skip/auth/regex",
2621 allowed: true,
2705 allowed: true,
2622 },
2706 },
2623 {
2707 {
2624 name: "Regex POST allowed ",
2708 name: "Regex POST allowed ",
2625− method: "POST",
2709+ method: http.MethodPost,
2626 url: "/skip/auth/regex",
2710 url: "/skip/auth/regex",
2627 allowed: true,
2711 allowed: true,
2628 },
2712 },
2629 {
2713 {
2630 name: "Regex denied",
2714 name: "Regex denied",
2631− method: "GET",
2715+ method: http.MethodGet,
2632 url: "/wrong/denied",
2716 url: "/wrong/denied",
2633 allowed: false,
2717 allowed: false,
2634 },
2718 },
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+ },
2635 {
2731 {
2636 name: "Route allowed",
2732 name: "Route allowed",
2637− method: "GET",
2733+ method: http.MethodGet,
2638 url: "/skip/auth/routes/get",
2734 url: "/skip/auth/routes/get",
2639 allowed: true,
2735 allowed: true,
2640 },
2736 },
@@ -2646,16 +2742,28 @@ func TestAllowedRequest(t *testing.T) {
2646 },
2742 },
2647 {
2743 {
2648 name: "Route denied with wrong path",
2744 name: "Route denied with wrong path",
2649− method: "GET",
2745+ method: http.MethodGet,
2650 url: "/skip/auth/routes/wrong/path",
2746 url: "/skip/auth/routes/wrong/path",
2651 allowed: false,
2747 allowed: false,
2652 },
2748 },
2653 {
2749 {
2654 name: "Route denied with wrong path and method",
2750 name: "Route denied with wrong path and method",
2655− method: "POST",
2751+ method: http.MethodPost,
2656 url: "/skip/auth/routes/wrong/path",
2752 url: "/skip/auth/routes/wrong/path",
2657 allowed: false,
2753 allowed: false,
2658 },
2754 },
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+ },
2659 }
2767 }
2660
2768
2661 for _, tc := range testCases {
2769 for _, tc := range testCases {
@@ -2696,9 +2804,11 @@ func TestAllowedRequestWithForwardedUriHeader(t *testing.T) {
2696 }
2804 }
2697 opts.SkipAuthRegex = []string{
2805 opts.SkipAuthRegex = []string{
2698 "^/skip/auth/regex$",
2806 "^/skip/auth/regex$",
2807+ "^/public/.*/endpoint$",
2699 }
2808 }
2700 opts.SkipAuthRoutes = []string{
2809 opts.SkipAuthRoutes = []string{
2701 "GET=^/skip/auth/routes/get",
2810 "GET=^/skip/auth/routes/get",
2811+ "^/foo/.*/bar$",
2702 }
2812 }
2703 err := validation.Validate(opts)
2813 err := validation.Validate(opts)
2704 assert.NoError(t, err)
2814 assert.NoError(t, err)
@@ -2715,25 +2825,37 @@ func TestAllowedRequestWithForwardedUriHeader(t *testing.T) {
2715 }{
2825 }{
2716 {
2826 {
2717 name: "Regex GET allowed",
2827 name: "Regex GET allowed",
2718− method: "GET",
2828+ method: http.MethodGet,
2719 url: "/skip/auth/regex",
2829 url: "/skip/auth/regex",
2720 allowed: true,
2830 allowed: true,
2721 },
2831 },
2722 {
2832 {
2723 name: "Regex POST allowed ",
2833 name: "Regex POST allowed ",
2724− method: "POST",
2834+ method: http.MethodPost,
2725 url: "/skip/auth/regex",
2835 url: "/skip/auth/regex",
2726 allowed: true,
2836 allowed: true,
2727 },
2837 },
2728 {
2838 {
2729 name: "Regex denied",
2839 name: "Regex denied",
2730− method: "GET",
2840+ method: http.MethodGet,
2731 url: "/wrong/denied",
2841 url: "/wrong/denied",
2732 allowed: false,
2842 allowed: false,
2733 },
2843 },
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+ },
2734 {
2856 {
2735 name: "Route allowed",
2857 name: "Route allowed",
2736− method: "GET",
2858+ method: http.MethodGet,
2737 url: "/skip/auth/routes/get",
2859 url: "/skip/auth/routes/get",
2738 allowed: true,
2860 allowed: true,
2739 },
2861 },
@@ -2745,22 +2867,35 @@ func TestAllowedRequestWithForwardedUriHeader(t *testing.T) {
2745 },
2867 },
2746 {
2868 {
2747 name: "Route denied with wrong path",
2869 name: "Route denied with wrong path",
2748− method: "GET",
2870+ method: http.MethodGet,
2749 url: "/skip/auth/routes/wrong/path",
2871 url: "/skip/auth/routes/wrong/path",
2750 allowed: false,
2872 allowed: false,
2751 },
2873 },
2752 {
2874 {
2753 name: "Route denied with wrong path and method",
2875 name: "Route denied with wrong path and method",
2754− method: "POST",
2876+ method: http.MethodPost,
2755 url: "/skip/auth/routes/wrong/path",
2877 url: "/skip/auth/routes/wrong/path",
2756 allowed: false,
2878 allowed: false,
2757 },
2879 },
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+ },
2758 }
2892 }
2759
2893
2760 for _, tc := range testCases {
2894 for _, tc := range testCases {
2761 t.Run(tc.name, func(t *testing.T) {
2895 t.Run(tc.name, func(t *testing.T) {
2762 req, err := http.NewRequest(tc.method, opts.ProxyPrefix+authOnlyPath, nil)
2896 req, err := http.NewRequest(tc.method, opts.ProxyPrefix+authOnlyPath, nil)
2763 req.Header.Set("X-Forwarded-Uri", tc.url)
2897 req.Header.Set("X-Forwarded-Uri", tc.url)
2898+ req.RemoteAddr = "127.0.0.1:4180"
2764 assert.NoError(t, err)
2899 assert.NoError(t, err)
2765
2900
2766 rw := httptest.NewRecorder()
2901 rw := httptest.NewRecorder()
@@ -2775,6 +2910,43 @@ func TestAllowedRequestWithForwardedUriHeader(t *testing.T) {
2775 }
2910 }
2776}
2911}
2777
2912
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+
2778func TestAllowedRequestNegateWithoutMethod(t *testing.T) {
2950func TestAllowedRequestNegateWithoutMethod(t *testing.T) {
2779 upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2951 upstreamServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2780 w.WriteHeader(200)
2952 w.WriteHeader(200)
@@ -2814,37 +2986,37 @@ func TestAllowedRequestNegateWithoutMethod(t *testing.T) {
2814 }{
2986 }{
2815 {
2987 {
2816 name: "Some static file allowed",
2988 name: "Some static file allowed",
2817− method: "GET",
2989+ method: http.MethodGet,
2818 url: "/static/file.txt",
2990 url: "/static/file.txt",
2819 allowed: true,
2991 allowed: true,
2820 },
2992 },
2821 {
2993 {
2822 name: "POST to contact form allowed",
2994 name: "POST to contact form allowed",
2823− method: "POST",
2995+ method: http.MethodPost,
2824 url: "/contact",
2996 url: "/contact",
2825 allowed: true,
2997 allowed: true,
2826 },
2998 },
2827 {
2999 {
2828 name: "Regex POST allowed",
3000 name: "Regex POST allowed",
2829− method: "POST",
3001+ method: http.MethodPost,
2830 url: "/api/public-entity",
3002 url: "/api/public-entity",
2831 allowed: true,
3003 allowed: true,
2832 },
3004 },
2833 {
3005 {
2834 name: "Regex POST with trailing slash allowed",
3006 name: "Regex POST with trailing slash allowed",
2835− method: "POST",
3007+ method: http.MethodPost,
2836 url: "/api/public-entity/",
3008 url: "/api/public-entity/",
2837 allowed: true,
3009 allowed: true,
2838 },
3010 },
2839 {
3011 {
2840 name: "Regex GET api route denied",
3012 name: "Regex GET api route denied",
2841− method: "GET",
3013+ method: http.MethodGet,
2842 url: "/api/users",
3014 url: "/api/users",
2843 allowed: false,
3015 allowed: false,
2844 },
3016 },
2845 {
3017 {
2846 name: "Regex POST api route denied",
3018 name: "Regex POST api route denied",
2847− method: "POST",
3019+ method: http.MethodPost,
2848 url: "/api/users",
3020 url: "/api/users",
2849 allowed: false,
3021 allowed: false,
2850 },
3022 },
@@ -2914,37 +3086,37 @@ func TestAllowedRequestNegateWithMethod(t *testing.T) {
2914 }{
3086 }{
2915 {
3087 {
2916 name: "Some static file allowed",
3088 name: "Some static file allowed",
2917− method: "GET",
3089+ method: http.MethodGet,
2918 url: "/static/file.txt",
3090 url: "/static/file.txt",
2919 allowed: true,
3091 allowed: true,
2920 },
3092 },
2921 {
3093 {
2922 name: "POST to contact form not allowed",
3094 name: "POST to contact form not allowed",
2923− method: "POST",
3095+ method: http.MethodPost,
2924 url: "/contact",
3096 url: "/contact",
2925 allowed: false,
3097 allowed: false,
2926 },
3098 },
2927 {
3099 {
2928 name: "Regex POST allowed",
3100 name: "Regex POST allowed",
2929− method: "POST",
3101+ method: http.MethodPost,
2930 url: "/api/public-entity",
3102 url: "/api/public-entity",
2931 allowed: true,
3103 allowed: true,
2932 },
3104 },
2933 {
3105 {
2934 name: "Regex POST with trailing slash allowed",
3106 name: "Regex POST with trailing slash allowed",
2935− method: "POST",
3107+ method: http.MethodPost,
2936 url: "/api/public-entity/",
3108 url: "/api/public-entity/",
2937 allowed: true,
3109 allowed: true,
2938 },
3110 },
2939 {
3111 {
2940 name: "Regex GET api route denied",
3112 name: "Regex GET api route denied",
2941− method: "GET",
3113+ method: http.MethodGet,
2942 url: "/api/users",
3114 url: "/api/users",
2943 allowed: false,
3115 allowed: false,
2944 },
3116 },
2945 {
3117 {
2946 name: "Regex POST api route denied",
3118 name: "Regex POST api route denied",
2947− method: "POST",
3119+ method: http.MethodPost,
2948 url: "/api/users",
3120 url: "/api/users",
2949 allowed: false,
3121 allowed: false,
2950 },
3122 },
@@ -3084,7 +3256,7 @@ func TestProxyAllowedGroups(t *testing.T) {
3084 t.Fatal(err)
3256 t.Fatal(err)
3085 }
3257 }
3086
3258
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)
3088
3260
3089 test.req.Header.Add("accept", applicationJSON)
3261 test.req.Header.Add("accept", applicationJSON)
3090 err = test.SaveSession(session)
3262 err = test.SaveSession(session)
@@ -3228,7 +3400,7 @@ func TestAuthOnlyAllowedGroupsWithSkipMethods(t *testing.T) {
3228 {
3400 {
3229 name: "UserWithGroupSkipAuthPreflight",
3401 name: "UserWithGroupSkipAuthPreflight",
3230 groups: []string{"a", "c"},
3402 groups: []string{"a", "c"},
3231− method: "OPTIONS",
3403+ method: http.MethodOptions,
3232 ip: "1.2.3.5:43670",
3404 ip: "1.2.3.5:43670",
3233 withSession: true,
3405 withSession: true,
3234 expectedStatusCode: http.StatusAccepted,
3406 expectedStatusCode: http.StatusAccepted,
@@ -3236,7 +3408,7 @@ func TestAuthOnlyAllowedGroupsWithSkipMethods(t *testing.T) {
3236 {
3408 {
3237 name: "UserWithGroupTrustedIp",
3409 name: "UserWithGroupTrustedIp",
3238 groups: []string{"a", "c"},
3410 groups: []string{"a", "c"},
3239− method: "GET",
3411+ method: http.MethodGet,
3240 ip: "1.2.3.4:43670",
3412 ip: "1.2.3.4:43670",
3241 withSession: true,
3413 withSession: true,
3242 expectedStatusCode: http.StatusAccepted,
3414 expectedStatusCode: http.StatusAccepted,
@@ -3244,7 +3416,7 @@ func TestAuthOnlyAllowedGroupsWithSkipMethods(t *testing.T) {
3244 {
3416 {
3245 name: "UserWithoutGroupSkipAuthPreflight",
3417 name: "UserWithoutGroupSkipAuthPreflight",
3246 groups: []string{"c"},
3418 groups: []string{"c"},
3247− method: "OPTIONS",
3419+ method: http.MethodOptions,
3248 ip: "1.2.3.5:43670",
3420 ip: "1.2.3.5:43670",
3249 withSession: true,
3421 withSession: true,
3250 expectedStatusCode: http.StatusForbidden,
3422 expectedStatusCode: http.StatusForbidden,
@@ -3252,21 +3424,21 @@ func TestAuthOnlyAllowedGroupsWithSkipMethods(t *testing.T) {
3252 {
3424 {
3253 name: "UserWithoutGroupTrustedIp",
3425 name: "UserWithoutGroupTrustedIp",
3254 groups: []string{"c"},
3426 groups: []string{"c"},
3255− method: "GET",
3427+ method: http.MethodGet,
3256 ip: "1.2.3.4:43670",
3428 ip: "1.2.3.4:43670",
3257 withSession: true,
3429 withSession: true,
3258 expectedStatusCode: http.StatusForbidden,
3430 expectedStatusCode: http.StatusForbidden,
3259 },
3431 },
3260 {
3432 {
3261 name: "UserWithoutSessionSkipAuthPreflight",
3433 name: "UserWithoutSessionSkipAuthPreflight",
3262− method: "OPTIONS",
3434+ method: http.MethodOptions,
3263 ip: "1.2.3.5:43670",
3435 ip: "1.2.3.5:43670",
3264 withSession: false,
3436 withSession: false,
3265 expectedStatusCode: http.StatusAccepted,
3437 expectedStatusCode: http.StatusAccepted,
3266 },
3438 },
3267 {
3439 {
3268 name: "UserWithoutSessionTrustedIp",
3440 name: "UserWithoutSessionTrustedIp",
3269− method: "GET",
3441+ method: http.MethodGet,
3270 ip: "1.2.3.4:43670",
3442 ip: "1.2.3.4:43670",
3271 withSession: false,
3443 withSession: false,
3272 expectedStatusCode: http.StatusAccepted,
3444 expectedStatusCode: http.StatusAccepted,
@@ -3366,6 +3538,24 @@ func TestAuthOnlyAllowedEmailDomains(t *testing.T) {
3366 querystring: "?allowed_email_domains=a.b.c.example.com,*.c.example.com",
3538 querystring: "?allowed_email_domains=a.b.c.example.com,*.c.example.com",
3367 expectedStatusCode: http.StatusAccepted,
3539 expectedStatusCode: http.StatusAccepted,
3368 },
3540 },
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+ },
3369 }
3559 }
3370
3560
3371 for _, tc := range testCases {
3561 for _, tc := range testCases {
@@ -3572,3 +3762,49 @@ func TestGetOAuthRedirectURI(t *testing.T) {
3572 })
3762 })
3573 }
3763 }
3574}
3764}
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
2
2
3import (
3import (
4 "context"
4 "context"
5+ "net"
5 "net/http"
6 "net/http"
7+ "strings"
6
8
7 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
9 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
10+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
8)
11)
9
12
10type scopeKey string
13type scopeKey string
@@ -18,9 +21,13 @@ const RequestScopeKey scopeKey = "request-scope"
18// within the chain.
21// within the chain.
19type RequestScope struct {
22type RequestScope struct {
20 // ReverseProxy tracks whether OAuth2-Proxy is operating in reverse proxy
23 // 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
22 ReverseProxy bool
25 ReverseProxy bool
23
26
27+ // TrustedProxies tracks which direct callers are allowed to supply
28+ // forwarded headers when ReverseProxy mode is enabled.
29+ TrustedProxies *ip.NetSet
30+
24 // RequestID is set to the request's `X-Request-Id` header if set.
31 // RequestID is set to the request's `X-Request-Id` header if set.
25 // Otherwise a random UUID is set.
32 // Otherwise a random UUID is set.
26 RequestID string
33 RequestID string
@@ -58,3 +65,43 @@ func AddRequestScope(req *http.Request, scope *RequestScope) *http.Request {
58 ctx := context.WithValue(req.Context(), RequestScopeKey, scope)
65 ctx := context.WithValue(req.Context(), RequestScopeKey, scope)
59 return req.WithContext(ctx)
66 return req.WithContext(ctx)
60}
67}
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 (
4 "net/http"
4 "net/http"
5
5
6 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
6 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
7+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
7 . "github.com/onsi/ginkgo/v2"
8 . "github.com/onsi/ginkgo/v2"
8 . "github.com/onsi/gomega"
9 . "github.com/onsi/gomega"
9)
10)
@@ -53,4 +54,37 @@ var _ = Describe("Scope Suite", func() {
53 })
54 })
54 })
55 })
55 })
56 })
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+ })
56})
90})
pkg/apis/options/cookie.go+3
@@ -24,6 +24,7 @@ type Cookie struct {
24 CSRFPerRequest bool `flag:"cookie-csrf-per-request" cfg:"cookie_csrf_per_request"`
24 CSRFPerRequest bool `flag:"cookie-csrf-per-request" cfg:"cookie_csrf_per_request"`
25 CSRFPerRequestLimit int `flag:"cookie-csrf-per-request-limit" cfg:"cookie_csrf_per_request_limit"`
25 CSRFPerRequestLimit int `flag:"cookie-csrf-per-request-limit" cfg:"cookie_csrf_per_request_limit"`
26 CSRFExpire time.Duration `flag:"cookie-csrf-expire" cfg:"cookie_csrf_expire"`
26 CSRFExpire time.Duration `flag:"cookie-csrf-expire" cfg:"cookie_csrf_expire"`
27+ CSRFSameSite string `flag:"cookie-csrf-samesite" cfg:"cookie_csrf_samesite"`
27}
28}
28
29
29func cookieFlagSet() *pflag.FlagSet {
30func cookieFlagSet() *pflag.FlagSet {
@@ -42,6 +43,7 @@ func cookieFlagSet() *pflag.FlagSet {
42 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.")
43 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.")
43 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.")
44 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.")
44 flagSet.Duration("cookie-csrf-expire", time.Duration(15)*time.Minute, "expire timeframe for CSRF cookie")
45 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.")
45 return flagSet
47 return flagSet
46}
48}
47
49
@@ -61,6 +63,7 @@ func cookieDefaults() Cookie {
61 CSRFPerRequest: false,
63 CSRFPerRequest: false,
62 CSRFPerRequestLimit: 0,
64 CSRFPerRequestLimit: 0,
63 CSRFExpire: time.Duration(15) * time.Minute,
65 CSRFExpire: time.Duration(15) * time.Minute,
66+ CSRFSameSite: "",
64 }
67 }
65}
68}
66
69
pkg/apis/options/legacy_options.go+18−14
@@ -51,15 +51,16 @@ func NewLegacyOptions() *LegacyOptions {
51 },
51 },
52
52
53 LegacyProvider: LegacyProvider{
53 LegacyProvider: LegacyProvider{
54− ProviderType: "google",
54+ ProviderType: "google",
55− AzureTenant: "common",
55+ AzureTenant: "common",
56− ApprovalPrompt: "force",
56+ ApprovalPrompt: "force",
57− UserIDClaim: "email",
57+ UserIDClaim: "email",
58− OIDCEmailClaim: "email",
58+ OIDCEmailClaim: "email",
59− OIDCGroupsClaim: "groups",
59+ OIDCGroupsClaim: "groups",
60− OIDCAudienceClaims: []string{"aud"},
60+ OIDCAudienceClaims: []string{"aud"},
61− OIDCExtraAudiences: []string{},
61+ OIDCExtraAudiences: []string{},
62+ OIDCEnabledSigningAlgs: []string{},
62− InsecureOIDCSkipNonce: true,
63+ InsecureOIDCSkipNonce: true,
63 },
64 },
64
65
65 Options: *NewOptions(),
66 Options: *NewOptions(),
@@ -179,10 +180,10 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) {
179 upstream.URI = ""
180 upstream.URI = ""
180 upstream.InsecureSkipTLSVerify = ptr.To(false)
181 upstream.InsecureSkipTLSVerify = ptr.To(false)
181 upstream.DisableKeepAlives = ptr.To(false)
182 upstream.DisableKeepAlives = ptr.To(false)
182− upstream.PassHostHeader = nil
183+ upstream.PassHostHeader = ptr.To(false)
183− upstream.ProxyWebSockets = nil
184+ upstream.ProxyWebSockets = ptr.To(false)
184− upstream.FlushInterval = nil
185+ upstream.FlushInterval = ptr.To(DefaultUpstreamFlushInterval)
185− upstream.Timeout = nil
186+ upstream.Timeout = ptr.To(DefaultUpstreamTimeout)
186 case "unix":
187 case "unix":
187 upstream.Path = "/"
188 upstream.Path = "/"
188 }
189 }
@@ -545,6 +546,7 @@ type LegacyProvider struct {
545 OIDCAudienceClaims []string `flag:"oidc-audience-claim" cfg:"oidc_audience_claims"`
546 OIDCAudienceClaims []string `flag:"oidc-audience-claim" cfg:"oidc_audience_claims"`
546 OIDCExtraAudiences []string `flag:"oidc-extra-audience" cfg:"oidc_extra_audiences"`
547 OIDCExtraAudiences []string `flag:"oidc-extra-audience" cfg:"oidc_extra_audiences"`
547 OIDCPublicKeyFiles []string `flag:"oidc-public-key-file" cfg:"oidc_public_key_files"`
548 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"`
548 LoginURL string `flag:"login-url" cfg:"login_url"`
550 LoginURL string `flag:"login-url" cfg:"login_url"`
549 AuthRequestResponseMode string `flag:"auth-request-response-mode" cfg:"auth_request_response_mode"`
551 AuthRequestResponseMode string `flag:"auth-request-response-mode" cfg:"auth_request_response_mode"`
550 RedeemURL string `flag:"redeem-url" cfg:"redeem_url"`
552 RedeemURL string `flag:"redeem-url" cfg:"redeem_url"`
@@ -606,6 +608,7 @@ func legacyProviderFlagSet() *pflag.FlagSet {
606 flagSet.StringSlice("oidc-audience-claim", OIDCAudienceClaims, "which OIDC claims are used as audience to verify against client id")
608 flagSet.StringSlice("oidc-audience-claim", OIDCAudienceClaims, "which OIDC claims are used as audience to verify against client id")
607 flagSet.StringSlice("oidc-extra-audience", []string{}, "additional audiences allowed to pass audience verification")
609 flagSet.StringSlice("oidc-extra-audience", []string{}, "additional audiences allowed to pass audience verification")
608 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)")
610 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")
609 flagSet.String("login-url", "", "Authentication endpoint")
612 flagSet.String("login-url", "", "Authentication endpoint")
610 flagSet.String("redeem-url", "", "Token redemption endpoint")
613 flagSet.String("redeem-url", "", "Token redemption endpoint")
611 flagSet.String("profile-url", "", "Profile access endpoint")
614 flagSet.String("profile-url", "", "Profile access endpoint")
@@ -691,7 +694,7 @@ func (l LegacyServer) convert() (Server, Server) {
691}
694}
692
695
693func (l *LegacyProvider) convert() (Providers, error) {
696func (l *LegacyProvider) convert() (Providers, error) {
694− providers := Providers{}
697+ providers := make(Providers, 0, 1)
695
698
696 provider := Provider{
699 provider := Provider{
697 ClientID: l.ClientID,
700 ClientID: l.ClientID,
@@ -727,6 +730,7 @@ func (l *LegacyProvider) convert() (Providers, error) {
727 AudienceClaims: l.OIDCAudienceClaims,
730 AudienceClaims: l.OIDCAudienceClaims,
728 ExtraAudiences: l.OIDCExtraAudiences,
731 ExtraAudiences: l.OIDCExtraAudiences,
729 PublicKeyFiles: l.OIDCPublicKeyFiles,
732 PublicKeyFiles: l.OIDCPublicKeyFiles,
733+ EnabledSigningAlgs: l.OIDCEnabledSigningAlgs,
730 }
734 }
731
735
732 // Support for legacy configuration option
736 // Support for legacy configuration option
pkg/apis/options/legacy_options_test.go+14−12
@@ -27,6 +27,7 @@ var _ = Describe("Legacy Options", func() {
27 legacyOpts.LegacyUpstreams.Upstreams = []string{"http://foo.bar/baz", "file:///var/lib/website#/bar", "static://204"}
27 legacyOpts.LegacyUpstreams.Upstreams = []string{"http://foo.bar/baz", "file:///var/lib/website#/bar", "static://204"}
28 legacyOpts.LegacyProvider.ClientID = "oauth-proxy"
28 legacyOpts.LegacyProvider.ClientID = "oauth-proxy"
29 legacyOpts.LegacyUpstreams.DisableKeepAlives = false
29 legacyOpts.LegacyUpstreams.DisableKeepAlives = false
30+ legacyOpts.LegacyProvider.OIDCEnabledSigningAlgs = []string{"RS256", "EdDSA"}
30
31
31 staticCode := 204
32 staticCode := 204
32 opts.UpstreamServers = UpstreamConfig{
33 opts.UpstreamServers = UpstreamConfig{
@@ -128,6 +129,7 @@ var _ = Describe("Legacy Options", func() {
128 opts.Providers[0].OIDCConfig.ExtraAudiences = []string{}
129 opts.Providers[0].OIDCConfig.ExtraAudiences = []string{}
129 opts.Providers[0].OIDCConfig.InsecureSkipNonce = ptr.To(true)
130 opts.Providers[0].OIDCConfig.InsecureSkipNonce = ptr.To(true)
130 opts.Providers[0].OIDCConfig.InsecureSkipIssuerVerification = ptr.To(false)
131 opts.Providers[0].OIDCConfig.InsecureSkipIssuerVerification = ptr.To(false)
132+ opts.Providers[0].OIDCConfig.EnabledSigningAlgs = []string{"RS256", "EdDSA"}
131 opts.Providers[0].LoginURLParameters = []LoginURLParameter{
133 opts.Providers[0].LoginURLParameters = []LoginURLParameter{
132 {Name: "approval_prompt", Default: []string{"force"}},
134 {Name: "approval_prompt", Default: []string{"force"}},
133 }
135 }
@@ -204,12 +206,12 @@ var _ = Describe("Legacy Options", func() {
204 URI: "",
206 URI: "",
205 Static: ptr.To(true),
207 Static: ptr.To(true),
206 StaticCode: &validStaticCode,
208 StaticCode: &validStaticCode,
207− InsecureSkipTLSVerify: ptr.To(false),
209+ InsecureSkipTLSVerify: ptr.To(DefaultUpsteamInsecureSkipTLSVerify),
208− PassHostHeader: nil,
210+ PassHostHeader: ptr.To(DefaultStaticPassHostHeader),
209− ProxyWebSockets: nil,
211+ ProxyWebSockets: ptr.To(DefaultStaticProxyWebSockets),
210− FlushInterval: nil,
212+ FlushInterval: ptr.To(DefaultUpstreamFlushInterval),
211− Timeout: nil,
213+ Timeout: ptr.To(DefaultUpstreamTimeout),
212− DisableKeepAlives: ptr.To(false),
214+ DisableKeepAlives: ptr.To(DefaultUpstreamDisableKeepAlives),
213 }
215 }
214
216
215 invalidStatic := "static://abc"
217 invalidStatic := "static://abc"
@@ -220,12 +222,12 @@ var _ = Describe("Legacy Options", func() {
220 URI: "",
222 URI: "",
221 Static: ptr.To(true),
223 Static: ptr.To(true),
222 StaticCode: &invalidStaticCode,
224 StaticCode: &invalidStaticCode,
223− InsecureSkipTLSVerify: ptr.To(false),
225+ InsecureSkipTLSVerify: ptr.To(DefaultUpsteamInsecureSkipTLSVerify),
224− PassHostHeader: nil,
226+ PassHostHeader: ptr.To(DefaultStaticPassHostHeader),
225− ProxyWebSockets: nil,
227+ ProxyWebSockets: ptr.To(DefaultStaticProxyWebSockets),
226− FlushInterval: nil,
228+ FlushInterval: ptr.To(DefaultUpstreamFlushInterval),
227− Timeout: nil,
229+ Timeout: ptr.To(DefaultUpstreamTimeout),
228− DisableKeepAlives: ptr.To(false),
230+ DisableKeepAlives: ptr.To(DefaultUpstreamDisableKeepAlives),
229 }
231 }
230
232
231 invalidHTTP := ":foo"
233 invalidHTTP := ":foo"
pkg/apis/options/load.go+1−1
@@ -145,7 +145,7 @@ func loadAndSubstituteEnvs(configFileName string) ([]byte, error) {
145func registerFlags(v *viper.Viper, prefix string, flagSet *pflag.FlagSet, options interface{}) error {
145func registerFlags(v *viper.Viper, prefix string, flagSet *pflag.FlagSet, options interface{}) error {
146 val := reflect.ValueOf(options)
146 val := reflect.ValueOf(options)
147 var typ reflect.Type
147 var typ reflect.Type
148− if val.Kind() == reflect.Ptr {
148+ if val.Kind() == reflect.Pointer {
149 typ = val.Elem().Type()
149 typ = val.Elem().Type()
150 } else {
150 } else {
151 typ = val.Type()
151 typ = val.Type()
pkg/apis/options/load_test.go+2−2
@@ -282,7 +282,7 @@ var _ = Describe("Load", func() {
282 Entry("with an invalid config file", &testOptionsTableInput{
282 Entry("with an invalid config file", &testOptionsTableInput{
283 configFile: []byte(`slice_option = foo`),
283 configFile: []byte(`slice_option = foo`),
284 flagSet: func() *pflag.FlagSet { return testOptionsFlagSet },
284 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\""),
286 expectedOutput: &TestOptions{},
286 expectedOutput: &TestOptions{},
287 }),
287 }),
288 Entry("with an invalid flagset", &testOptionsTableInput{
288 Entry("with an invalid flagset", &testOptionsTableInput{
@@ -329,7 +329,7 @@ var _ = Describe("Load", func() {
329 Entry("with an unknown option in the config file", &testOptionsTableInput{
329 Entry("with an unknown option in the config file", &testOptionsTableInput{
330 configFile: []byte(`unknown_option="foo"`),
330 configFile: []byte(`unknown_option="foo"`),
331 flagSet: func() *pflag.FlagSet { return testOptionsFlagSet },
331 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"),
333 // Viper will unmarshal before returning the error, so this is the default output
333 // Viper will unmarshal before returning the error, so this is the default output
334 expectedOutput: &TestOptions{
334 expectedOutput: &TestOptions{
335 StringOption: "default",
335 StringOption: "default",
pkg/apis/options/options.go+2
@@ -24,6 +24,7 @@ type Options struct {
24 ReadyPath string `flag:"ready-path" cfg:"ready_path"`
24 ReadyPath string `flag:"ready-path" cfg:"ready_path"`
25 ReverseProxy bool `flag:"reverse-proxy" cfg:"reverse_proxy"`
25 ReverseProxy bool `flag:"reverse-proxy" cfg:"reverse_proxy"`
26 RealClientIPHeader string `flag:"real-client-ip-header" cfg:"real_client_ip_header"`
26 RealClientIPHeader string `flag:"real-client-ip-header" cfg:"real_client_ip_header"`
27+ TrustedProxyIPs []string `flag:"trusted-proxy-ip" cfg:"trusted_proxy_ips"`
27 TrustedIPs []string `flag:"trusted-ip" cfg:"trusted_ips"`
28 TrustedIPs []string `flag:"trusted-ip" cfg:"trusted_ips"`
28 ForceHTTPS bool `flag:"force-https" cfg:"force_https"`
29 ForceHTTPS bool `flag:"force-https" cfg:"force_https"`
29 RawRedirectURL string `flag:"redirect-url" cfg:"redirect_url"`
30 RawRedirectURL string `flag:"redirect-url" cfg:"redirect_url"`
@@ -119,6 +120,7 @@ func NewFlagSet() *pflag.FlagSet {
119
120
120 flagSet.Bool("reverse-proxy", false, "are we running behind a reverse proxy, controls whether headers like X-Real-Ip are accepted")
121 flagSet.Bool("reverse-proxy", false, "are we running behind a reverse proxy, controls whether headers like X-Real-Ip are accepted")
121 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)")
122 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.")
122 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.")
124 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.")
123 flagSet.Bool("force-https", false, "force HTTPS redirect for HTTP requests")
125 flagSet.Bool("force-https", false, "force HTTPS redirect for HTTP requests")
124 flagSet.String("redirect-url", "", "the OAuth Redirect URL. ie: \"https://internalapp.yourcompany.com/oauth2/callback\"")
126 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 {
134 // The code challenge method
134 // The code challenge method
135 CodeChallengeMethod string `yaml:"code_challenge_method,omitempty"`
135 CodeChallengeMethod string `yaml:"code_challenge_method,omitempty"`
136
136
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+
137 // URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session
140 // URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session
138 BackendLogoutURL string `yaml:"backendLogoutURL"`
141 BackendLogoutURL string `yaml:"backendLogoutURL"`
139}
142}
@@ -148,6 +151,9 @@ const (
148 // ADFSProvider is the provider type for ADFS
151 // ADFSProvider is the provider type for ADFS
149 ADFSProvider ProviderType = "adfs"
152 ADFSProvider ProviderType = "adfs"
150
153
154+ // AtlassianProvider is the provider type for Atlassian Cloud
155+ AtlassianProvider ProviderType = "atlassian"
156+
151 // AzureProvider is the provider type for Azure
157 // AzureProvider is the provider type for Azure
152 AzureProvider ProviderType = "azure"
158 AzureProvider ProviderType = "azure"
153
159
@@ -163,6 +169,9 @@ const (
163 // DigitalOceanProvider is the provider type for DigitalOcean
169 // DigitalOceanProvider is the provider type for DigitalOcean
164 DigitalOceanProvider ProviderType = "digitalocean"
170 DigitalOceanProvider ProviderType = "digitalocean"
165
171
172+ // DTTSSOProvider is the provider type for the DTT SSO
173+ DTTSSOProvider ProviderType = "dtt-sso"
174+
166 // FacebookProvider is the provider type for Facebook
175 // FacebookProvider is the provider type for Facebook
167 FacebookProvider ProviderType = "facebook"
176 FacebookProvider ProviderType = "facebook"
168
177
@@ -318,6 +327,11 @@ type OIDCOptions struct {
318 // ExtraAudiences is a list of additional audiences that are allowed
327 // ExtraAudiences is a list of additional audiences that are allowed
319 // to pass verification in addition to the client id.
328 // to pass verification in addition to the client id.
320 ExtraAudiences []string `yaml:"extraAudiences,omitempty"`
329 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"`
321}
335}
322
336
323type LoginGovOptions struct {
337type LoginGovOptions struct {
pkg/apis/options/server.go+9
@@ -3,10 +3,19 @@ package options
3// Server represents the configuration for an HTTP(S) server
3// Server represents the configuration for an HTTP(S) server
4type Server struct {
4type Server struct {
5 // BindAddress is the address on which to serve traffic.
5 // 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`
6 // Leave blank or set to "-" to disable.
12 // Leave blank or set to "-" to disable.
7 BindAddress string `yaml:"bindAddress,omitempty"`
13 BindAddress string `yaml:"bindAddress,omitempty"`
8
14
9 // SecureBindAddress is the address on which to serve secure traffic.
15 // 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`
10 // Leave blank or set to "-" to disable.
19 // Leave blank or set to "-" to disable.
11 SecureBindAddress string `yaml:"secureBindAddress,omitempty"`
20 SecureBindAddress string `yaml:"secureBindAddress,omitempty"`
12
21
pkg/apis/options/upstreams.go+28−8
@@ -29,9 +29,15 @@ const (
29 // DefaultUpstreamPassHostHeader determines if upstreams will pass the host header by default.
29 // DefaultUpstreamPassHostHeader determines if upstreams will pass the host header by default.
30 DefaultUpstreamPassHostHeader bool = true
30 DefaultUpstreamPassHostHeader bool = true
31
31
32+ // Static upstreams cannot pass the host header.
33+ DefaultStaticPassHostHeader bool = false
34+
32 // DefaultUpstreamProxyWebSockets determines if upstreams will proxy websockets by default.
35 // DefaultUpstreamProxyWebSockets determines if upstreams will proxy websockets by default.
33 DefaultUpstreamProxyWebSockets bool = true
36 DefaultUpstreamProxyWebSockets bool = true
34
37
38+ // Static upstreams cannot proxy websockets.
39+ DefaultStaticProxyWebSockets bool = false
40+
35 // DefaultUpstreamDisableKeepAlives determines if upstreams will disable keep-alives by default.
41 // DefaultUpstreamDisableKeepAlives determines if upstreams will disable keep-alives by default.
36 DefaultUpstreamDisableKeepAlives bool = false
42 DefaultUpstreamDisableKeepAlives bool = false
37)
43)
@@ -56,12 +62,14 @@ type Upstream struct {
56
62
57 // Path is used to map requests to the upstream server.
63 // Path is used to map requests to the upstream server.
58 // The closest match will take precedence and all Paths must be unique.
64 // The closest match will take precedence and all Paths must be unique.
59− // Path can also take a pattern when used with RewriteTarget.
65+ // Without RewriteTarget, Path follows gorilla/mux route syntax.
60− // Path segments can be captured and matched using regular experessions.
61 // Eg:
66 // Eg:
62− // - `^/foo$`: Match only the explicit path `/foo`
67+ // - `/foo`: Match only the explicit path `/foo`
63− // - `^/bar/$`: Match any path prefixed with `/bar/`
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
64− // - `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget
72+ // remaining path for use with RewriteTarget.
65 Path string `yaml:"path,omitempty"`
73 Path string `yaml:"path,omitempty"`
66
74
67 // RewriteTarget allows users to rewrite the request path before it is sent to
75 // RewriteTarget allows users to rewrite the request path before it is sent to
@@ -143,19 +151,31 @@ func (u *Upstream) EnsureDefaults() {
143 if u.Static == nil {
151 if u.Static == nil {
144 u.Static = ptr.To(DefaultUpstreamStatic)
152 u.Static = ptr.To(DefaultUpstreamStatic)
145 }
153 }
146− if u.FlushInterval == nil {
147− u.FlushInterval = ptr.To(DefaultUpstreamFlushInterval)
148− }
149 if u.PassHostHeader == nil {
154 if u.PassHostHeader == nil {
150 u.PassHostHeader = ptr.To(DefaultUpstreamPassHostHeader)
155 u.PassHostHeader = ptr.To(DefaultUpstreamPassHostHeader)
151 }
156 }
152 if u.ProxyWebSockets == nil {
157 if u.ProxyWebSockets == nil {
153 u.ProxyWebSockets = ptr.To(DefaultUpstreamProxyWebSockets)
158 u.ProxyWebSockets = ptr.To(DefaultUpstreamProxyWebSockets)
154 }
159 }
160+ if u.FlushInterval == nil {
161+ u.FlushInterval = ptr.To(DefaultUpstreamFlushInterval)
162+ }
155 if u.Timeout == nil {
163 if u.Timeout == nil {
156 u.Timeout = ptr.To(DefaultUpstreamTimeout)
164 u.Timeout = ptr.To(DefaultUpstreamTimeout)
157 }
165 }
158 if u.DisableKeepAlives == nil {
166 if u.DisableKeepAlives == nil {
159 u.DisableKeepAlives = ptr.To(DefaultUpstreamDisableKeepAlives)
167 u.DisableKeepAlives = ptr.To(DefaultUpstreamDisableKeepAlives)
160 }
168 }
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+ }
161}
181}
pkg/apis/sessions/session_state.go+17−1
@@ -8,6 +8,7 @@ import (
8 "time"
8 "time"
9
9
10 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption"
10 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption"
11+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util"
11 "github.com/pierrec/lz4/v4"
12 "github.com/pierrec/lz4/v4"
12 "github.com/vmihailenco/msgpack/v5"
13 "github.com/vmihailenco/msgpack/v5"
13)
14)
@@ -28,6 +29,9 @@ type SessionState struct {
28 Groups []string `msgpack:"g,omitempty"`
29 Groups []string `msgpack:"g,omitempty"`
29 PreferredUsername string `msgpack:"pu,omitempty"`
30 PreferredUsername string `msgpack:"pu,omitempty"`
30
31
32+ // Additional claims
33+ AdditionalClaims map[string]interface{} `msgpack:"ac,omitempty"`
34+
31 // Internal helpers, not serialized
35 // Internal helpers, not serialized
32 Clock func() time.Time `msgpack:"-"` // override for time.Now, for testing
36 Clock func() time.Time `msgpack:"-"` // override for time.Now, for testing
33 Lock Lock `msgpack:"-"`
37 Lock Lock `msgpack:"-"`
@@ -123,6 +127,8 @@ func (s *SessionState) String() string {
123 }
127 }
124 if s.RefreshToken != "" {
128 if s.RefreshToken != "" {
125 o += " refresh_token:true"
129 o += " refresh_token:true"
130+ } else {
131+ o += " refresh_token:false"
126 }
132 }
127 if len(s.Groups) > 0 {
133 if len(s.Groups) > 0 {
128 o += fmt.Sprintf(" groups:%v", s.Groups)
134 o += fmt.Sprintf(" groups:%v", s.Groups)
@@ -156,8 +162,18 @@ func (s *SessionState) GetClaim(claim string) []string {
156 case "preferred_username":
162 case "preferred_username":
157 return []string{s.PreferredUsername}
163 return []string{s.PreferredUsername}
158 default:
164 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+ }
160 }
175 }
176+ return []string{}
161}
177}
162
178
163// CheckNonce compares the Nonce against a potential hash of it
179// CheckNonce compares the Nonce against a potential hash of it
pkg/apis/sessions/session_state_test.go+98−5
@@ -4,6 +4,7 @@ import (
4 "crypto/rand"
4 "crypto/rand"
5 "fmt"
5 "fmt"
6 "io"
6 "io"
7+ "strings"
7 "testing"
8 "testing"
8 "time"
9 "time"
9
10
@@ -57,7 +58,7 @@ func TestString(t *testing.T) {
57 User: "some.user",
58 User: "some.user",
58 PreferredUsername: "preferred.user",
59 PreferredUsername: "preferred.user",
59 },
60 },
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}",
61 },
62 },
62 {
63 {
63 name: "Full Session",
64 name: "Full Session",
@@ -81,7 +82,7 @@ func TestString(t *testing.T) {
81 PreferredUsername: "preferred.user",
82 PreferredUsername: "preferred.user",
82 CreatedAt: &created,
83 CreatedAt: &created,
83 },
84 },
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}",
85 },
86 },
86 {
87 {
87 name: "With an ExpiresOn",
88 name: "With an ExpiresOn",
@@ -91,7 +92,7 @@ func TestString(t *testing.T) {
91 PreferredUsername: "preferred.user",
92 PreferredUsername: "preferred.user",
92 ExpiresOn: &expires,
93 ExpiresOn: &expires,
93 },
94 },
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}",
95 },
96 },
96 {
97 {
97 name: "With an AccessToken",
98 name: "With an AccessToken",
@@ -101,7 +102,7 @@ func TestString(t *testing.T) {
101 PreferredUsername: "preferred.user",
102 PreferredUsername: "preferred.user",
102 AccessToken: "access.token",
103 AccessToken: "access.token",
103 },
104 },
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}",
105 },
106 },
106 {
107 {
107 name: "With an IDToken",
108 name: "With an IDToken",
@@ -111,7 +112,7 @@ func TestString(t *testing.T) {
111 PreferredUsername: "preferred.user",
112 PreferredUsername: "preferred.user",
112 IDToken: "id.token",
113 IDToken: "id.token",
113 },
114 },
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}",
115 },
116 },
116 {
117 {
117 name: "With a RefreshToken",
118 name: "With a RefreshToken",
@@ -222,6 +223,23 @@ func TestEncodeAndDecodeSessionState(t *testing.T) {
222 Nonce: []byte("abcdef1234567890abcdef1234567890"),
223 Nonce: []byte("abcdef1234567890abcdef1234567890"),
223 Groups: []string{"group-a", "group-b"},
224 Groups: []string{"group-a", "group-b"},
224 },
225 },
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+ },
225 }
243 }
226
244
227 for _, secretSize := range []int{16, 24, 32} {
245 for _, secretSize := range []int{16, 24, 32} {
@@ -289,3 +307,78 @@ func compareSessionStates(t *testing.T, expected *SessionState, actual *SessionS
289 act.ExpiresOn = nil
307 act.ExpiresOn = nil
290 assert.Equal(t, exp, act)
308 assert.Equal(t, exp, act)
291}
309}
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 (
4 "net/http"
4 "net/http"
5
5
6 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
6 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
7+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
7 . "github.com/onsi/ginkgo/v2"
8 . "github.com/onsi/ginkgo/v2"
8 . "github.com/onsi/gomega"
9 . "github.com/onsi/gomega"
9)
10)
@@ -33,9 +34,16 @@ var _ = Describe("Director Suite", func() {
33 req.Header.Add(header, value)
34 req.Header.Add(header, value)
34 }
35 }
35 }
36 }
36− req = middleware.AddRequestScope(req, &middleware.RequestScope{
37+ scope := &middleware.RequestScope{
37 ReverseProxy: in.reverseProxy,
38 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)
39
47
40 redirect, err := appDirector.GetRedirect(req)
48 redirect, err := appDirector.GetRedirect(req)
41 Expect(err).ToNot(HaveOccurred())
49 Expect(err).ToNot(HaveOccurred())
@@ -174,4 +182,27 @@ var _ = Describe("Director Suite", func() {
174 expectedRedirect: "https://a-service.example.com/foo/bar",
182 expectedRedirect: "https://a-service.example.com/foo/bar",
175 }),
183 }),
176 )
184 )
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+ })
177})
208})
pkg/authentication/hmacauth/hmacauth_test.go+1−1
@@ -286,7 +286,7 @@ func TestSendAuthenticatedPostRequestToServer(t *testing.T) {
286 upstream := httptest.NewServer(
286 upstream := httptest.NewServer(
287 http.HandlerFunc(authenticator.Authenticate))
287 http.HandlerFunc(authenticator.Authenticate))
288
288
289− req, err := http.NewRequest("POST", upstream.URL+"/foo/bar",
289+ req, err := http.NewRequest(http.MethodPost, upstream.URL+"/foo/bar",
290 io.NopCloser(&fakeNetConn{reqBody: payload}))
290 io.NopCloser(&fakeNetConn{reqBody: payload}))
291 if err != nil {
291 if err != nil {
292 panic(err)
292 panic(err)
pkg/cookies/cookies.go+18−8
@@ -7,14 +7,24 @@ import (
7 "strings"
7 "strings"
8 "time"
8 "time"
9
9
10− "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
11 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
10 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
12 requestutil "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests/util"
11 requestutil "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests/util"
13)
12)
14
13
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+
15// MakeCookieFromOptions constructs a cookie based on the given *options.CookieOptions,
25// MakeCookieFromOptions constructs a cookie based on the given *options.CookieOptions,
16// value and creation time
26// 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 {
18 domain := GetCookieDomain(req, opts.Domains)
28 domain := GetCookieDomain(req, opts.Domains)
19 // If nothing matches, create the cookie with the shortest domain
29 // If nothing matches, create the cookie with the shortest domain
20 if domain == "" && len(opts.Domains) > 0 {
30 if domain == "" && len(opts.Domains) > 0 {
@@ -26,8 +36,8 @@ func MakeCookieFromOptions(req *http.Request, name string, value string, opts *o
26 }
36 }
27
37
28 c := &http.Cookie{
38 c := &http.Cookie{
29− Name: name,
39+ Name: opts.Name,
30− Value: value,
40+ Value: opts.Value,
31 Path: opts.Path,
41 Path: opts.Path,
32 Domain: domain,
42 Domain: domain,
33 HttpOnly: opts.HTTPOnly,
43 HttpOnly: opts.HTTPOnly,
@@ -35,9 +45,9 @@ func MakeCookieFromOptions(req *http.Request, name string, value string, opts *o
35 SameSite: ParseSameSite(opts.SameSite),
45 SameSite: ParseSameSite(opts.SameSite),
36 }
46 }
37
47
38− if expiration > time.Duration(0) {
48+ if opts.Expiration > time.Duration(0) {
39− c.MaxAge = int(expiration.Seconds())
49+ c.MaxAge = int(opts.Expiration.Seconds())
40− } else if expiration < time.Duration(0) {
50+ } else if opts.Expiration < time.Duration(0) {
41 c.MaxAge = -1
51 c.MaxAge = -1
42 }
52 }
43
53
@@ -58,7 +68,7 @@ func GetCookieDomain(req *http.Request, cookieDomains []string) string {
58 return ""
68 return ""
59}
69}
60
70
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.
62func ParseSameSite(v string) http.SameSite {
72func ParseSameSite(v string) http.SameSite {
63 switch v {
73 switch v {
64 case "lax":
74 case "lax":
pkg/cookies/cookies_suite_test.go+4
@@ -17,6 +17,10 @@ const (
17 cookieDomain = "o2p.cookies.test"
17 cookieDomain = "o2p.cookies.test"
18 cookiePath = "/cookie-tests"
18 cookiePath = "/cookie-tests"
19
19
20+ sameSiteLax = "lax"
21+ sameSiteStrict = "strict"
22+ sameSiteNone = "none"
23+
20 nowEpoch = 1609366421
24 nowEpoch = 1609366421
21)
25)
22
26
pkg/cookies/cookies_test.go+39−51
@@ -5,9 +5,8 @@ import (
5 "net/http"
5 "net/http"
6 "time"
6 "time"
7
7
8− "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
9−
10 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
8 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
9+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
11 . "github.com/onsi/ginkgo/v2"
10 . "github.com/onsi/ginkgo/v2"
12 . "github.com/onsi/gomega"
11 . "github.com/onsi/gomega"
13)
12)
@@ -32,8 +31,13 @@ var _ = Describe("Cookie Tests", func() {
32
31
33 if in.xForwardedHost != "" {
32 if in.xForwardedHost != "" {
34 req.Header.Add("X-Forwarded-Host", in.xForwardedHost)
33 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+
35 req = middlewareapi.AddRequestScope(req, &middlewareapi.RequestScope{
38 req = middlewareapi.AddRequestScope(req, &middlewareapi.RequestScope{
36− ReverseProxy: true,
39+ ReverseProxy: true,
40+ TrustedProxies: trustedProxies,
37 })
41 })
38 }
42 }
39
43
@@ -82,16 +86,12 @@ var _ = Describe("Cookie Tests", func() {
82 Context("MakeCookieFromOptions", func() {
86 Context("MakeCookieFromOptions", func() {
83 type makeCookieFromOptionsTableInput struct {
87 type makeCookieFromOptionsTableInput struct {
84 host string
88 host string
85− name string
89+ opts CookieOptions
86− value string
87− opts options.Cookie
88− expiration time.Duration
89 now time.Time
90 now time.Time
90 expectedOutput int
91 expectedOutput int
91 }
92 }
92
93
93 validName := "_oauth2_proxy"
94 validName := "_oauth2_proxy"
94− validSecret := "secretthirtytwobytes+abcdefghijk"
95 domains := []string{"www.cookies.test"}
95 domains := []string{"www.cookies.test"}
96
96
97 now := time.Now()
97 now := time.Now()
@@ -106,62 +106,50 @@ var _ = Describe("Cookie Tests", func() {
106 )
106 )
107 Expect(err).ToNot(HaveOccurred())
107 Expect(err).ToNot(HaveOccurred())
108
108
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))
110 },
110 },
111 Entry("persistent cookie", makeCookieFromOptionsTableInput{
111 Entry("persistent cookie", makeCookieFromOptionsTableInput{
112− host: "www.cookies.test",
112+ host: "www.cookies.test",
113− name: validName,
113+ opts: CookieOptions{
114− value: "1",
115− opts: options.Cookie{
116− Name: validName,
114+ Name: validName,
117− Secret: validSecret,
115+ Value: "1",
118− Domains: domains,
116+ Domains: domains,
119− Path: "",
120− Expire: time.Hour,
121− Refresh: 15 * time.Minute,
117+ Expiration: 15 * time.Minute,
122− Secure: true,
118+ SameSite: "",
119+ Path: "",
123− HTTPOnly: false,
120+ HTTPOnly: false,
124− SameSite: "",
121+ Secure: true,
125 },
122 },
126− expiration: 15 * time.Minute,
127 now: now,
123 now: now,
128 expectedOutput: int((15 * time.Minute).Seconds()),
124 expectedOutput: int((15 * time.Minute).Seconds()),
129 }),
125 }),
130 Entry("persistent cookie to be cleared", makeCookieFromOptionsTableInput{
126 Entry("persistent cookie to be cleared", makeCookieFromOptionsTableInput{
131− host: "www.cookies.test",
127+ host: "www.cookies.test",
132− name: validName,
128+ opts: CookieOptions{
133− value: "1",
134− opts: options.Cookie{
135− Name: validName,
129+ Name: validName,
136− Secret: validSecret,
130+ Value: "1",
137− Domains: domains,
131+ Domains: domains,
138− Path: "",
139− Expire: time.Hour * -1,
132+ Expiration: time.Hour * -1,
140− Refresh: 15 * time.Minute,
133+ SameSite: "",
141− Secure: true,
134+ Path: "",
142− HTTPOnly: false,
135+ HTTPOnly: false,
143− SameSite: "",
136+ Secure: true,
144 },
137 },
145− expiration: time.Hour * -1,
146 now: now,
138 now: now,
147 expectedOutput: -1,
139 expectedOutput: -1,
148 }),
140 }),
149 Entry("session cookie", makeCookieFromOptionsTableInput{
141 Entry("session cookie", makeCookieFromOptionsTableInput{
150− host: "www.cookies.test",
142+ host: "www.cookies.test",
151− name: validName,
143+ opts: CookieOptions{
152− value: "1",
153− opts: options.Cookie{
154− Name: validName,
144+ Name: validName,
155− Secret: validSecret,
145+ Value: "1",
156− Domains: domains,
146+ Domains: domains,
157− Path: "",
147+ Expiration: 0,
158− Expire: 0,
148+ SameSite: "",
159− Refresh: 15 * time.Minute,
149+ Path: "",
150+ HTTPOnly: false,
160− Secure: true,
151+ Secure: true,
161− HTTPOnly: false,
162− SameSite: "",
163 },
152 },
164− expiration: 0,
165 now: now,
153 now: now,
166 expectedOutput: expectedMaxAge,
154 expectedOutput: expectedMaxAge,
167 }),
155 }),
pkg/cookies/csrf.go+34−15
@@ -134,6 +134,15 @@ func (c *csrf) SetSessionNonce(s *sessions.SessionState) {
134 s.Nonce = c.OIDCNonce
134 s.Nonce = c.OIDCNonce
135}
135}
136
136
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+
137// SetCookie encodes the CSRF to a signed cookie and sets it on the ResponseWriter
146// SetCookie encodes the CSRF to a signed cookie and sets it on the ResponseWriter
138func (c *csrf) SetCookie(rw http.ResponseWriter, req *http.Request) (*http.Cookie, error) {
147func (c *csrf) SetCookie(rw http.ResponseWriter, req *http.Request) (*http.Cookie, error) {
139 encoded, err := c.encodeCookie()
148 encoded, err := c.encodeCookie()
@@ -141,13 +150,18 @@ func (c *csrf) SetCookie(rw http.ResponseWriter, req *http.Request) (*http.Cooki
141 return nil, err
150 return nil, err
142 }
151 }
143
152
144− cookie := MakeCookieFromOptions(
153+ csrfCookieOptions := &CookieOptions{
145− req,
146− c.cookieName(),
154+ Name: c.cookieName(),
147− encoded,
155+ Value: encoded,
148− c.cookieOpts,
156+ Domains: c.cookieOpts.Domains,
149− c.cookieOpts.CSRFExpire,
157+ Expiration: c.cookieOpts.CSRFExpire,
150− )
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)
151 http.SetCookie(rw, cookie)
165 http.SetCookie(rw, cookie)
152
166
153 return cookie, nil
167 return cookie, nil
@@ -197,13 +211,18 @@ func ClearExtraCsrfCookies(opts *options.Cookie, rw http.ResponseWriter, req *ht
197
211
198// ClearCookie removes the CSRF cookie
212// ClearCookie removes the CSRF cookie
199func (c *csrf) ClearCookie(rw http.ResponseWriter, req *http.Request) {
213func (c *csrf) ClearCookie(rw http.ResponseWriter, req *http.Request) {
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+
200− http.SetCookie(rw, MakeCookieFromOptions(
225+ http.SetCookie(rw, MakeCookieFromOptions(req, csrfCookieOptions))
201− req,
202− c.cookieName(),
203− "",
204− c.cookieOpts,
205− time.Hour*-1,
206− ))
207}
226}
208
227
209// encodeCookie MessagePack encodes and encrypts the CSRF and then creates a
228// 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)
234 return nil, fmt.Errorf("error getting cookie secret: %v", err)
253 return nil, fmt.Errorf("error getting cookie secret: %v", err)
235 }
254 }
236
255
237− val, t, ok := encryption.Validate(cookie, secret, opts.Expire)
256+ val, t, ok := encryption.Validate(cookie, secret, opts.CSRFExpire)
238 if !ok {
257 if !ok {
239 return nil, errors.New("CSRF cookie failed validation")
258 return nil, errors.New("CSRF cookie failed validation")
240 }
259 }
pkg/cookies/csrf_per_request_test.go+12−7
@@ -216,13 +216,18 @@ var _ = Describe("CSRF Cookie with non-fixed name Tests", func() {
216 for _, csrf := range []*csrf{privateCSRF1, privateCSRF2, privateCSRF3} {
216 for _, csrf := range []*csrf{privateCSRF1, privateCSRF2, privateCSRF3} {
217 encoded, err := csrf.encodeCookie()
217 encoded, err := csrf.encodeCookie()
218 Expect(err).ToNot(HaveOccurred())
218 Expect(err).ToNot(HaveOccurred())
219− cookie := MakeCookieFromOptions(
219+ csrfCookieOptions := &CookieOptions{
220− req,
221− csrf.cookieName(),
220+ Name: csrf.cookieName(),
222− encoded,
221+ Value: encoded,
223− csrf.cookieOpts,
222+ Domains: csrf.cookieOpts.Domains,
224− csrf.cookieOpts.CSRFExpire,
223+ Expiration: csrf.cookieOpts.CSRFExpire,
225− )
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)
226 cookies = append(cookies, fmt.Sprintf("%v=%v", cookie.Name, cookie.Value))
231 cookies = append(cookies, fmt.Sprintf("%v=%v", cookie.Name, cookie.Value))
227 }
232 }
228
233
pkg/cookies/csrf_test.go+284−1
@@ -119,9 +119,33 @@ var _ = Describe("CSRF Cookie Tests", func() {
119 Value: encoded,
119 Value: encoded,
120 }
120 }
121
121
122− _, _, valid := encryption.Validate(cookie, cookieOpts.Secret, cookieOpts.Expire)
122+ _, _, valid := encryption.Validate(cookie, cookieOpts.Secret, cookieOpts.CSRFExpire)
123 Expect(valid).To(BeTrue())
123 Expect(valid).To(BeTrue())
124 })
124 })
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+ })
125 })
149 })
126
150
127 Context("Cookie Management", func() {
151 Context("Cookie Management", func() {
@@ -254,4 +278,263 @@ var _ = Describe("CSRF Cookie Tests", func() {
254 })
278 })
255 })
279 })
256 })
280 })
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+ })
257})
540})
pkg/ip/parse_ip_net.go+16
@@ -1,6 +1,7 @@
1package ip
1package ip
2
2
3import (
3import (
4+ "fmt"
4 "net"
5 "net"
5 "strings"
6 "strings"
6)
7)
@@ -37,3 +38,18 @@ func ParseIPNet(s string) *net.IPNet {
37 return ipNet
38 return ipNet
38 }
39 }
39}
40}
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)
73
73
74// getRemoteIP obtains the IP of the low-level connected network host
74// getRemoteIP obtains the IP of the low-level connected network host
75func getRemoteIP(req *http.Request) (net.IP, error) {
75func 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+
76 //revive:disable:indent-error-flow
82 //revive:disable:indent-error-flow
77 if ipStr, _, err := net.SplitHostPort(req.RemoteAddr); err != nil {
83 if ipStr, _, err := net.SplitHostPort(req.RemoteAddr); err != nil {
78 return nil, fmt.Errorf("unable to get ip and port from http.RemoteAddr (%s)", req.RemoteAddr)
84 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) (
94 }
100 }
95
101
96 var remoteIPStr string
102 var remoteIPStr string
97− if remoteIP, err := getRemoteIP(req); err == nil {
103+ if remoteIP, err := getRemoteIP(req); err == nil && remoteIP != nil {
98 remoteIPStr = remoteIP.String()
104 remoteIPStr = remoteIP.String()
99 }
105 }
100
106
pkg/ip/realclientip_test.go+4
@@ -112,6 +112,8 @@ func TestGetRemoteIP(t *testing.T) {
112 errString string
112 errString string
113 expectedIP net.IP
113 expectedIP net.IP
114 }{
114 }{
115+ // Unix domain sockets set RemoteAddr to "@"
116+ {"@", "", nil},
115 {"", "unable to get ip and port from http.RemoteAddr ()", nil},
117 {"", "unable to get ip and port from http.RemoteAddr ()", nil},
116 {"nil", "unable to get ip and port from http.RemoteAddr (nil)", nil},
118 {"nil", "unable to get ip and port from http.RemoteAddr (nil)", nil},
117 {"235.28.129.186", "unable to get ip and port from http.RemoteAddr (235.28.129.186)", nil},
119 {"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) {
155 }{
157 }{
156 // Should fail quietly, only printing warnings to the log
158 // Should fail quietly, only printing warnings to the log
157 {nil, "", "", "", ""},
159 {nil, "", "", "", ""},
160+ // Unix domain socket — no IP available
161+ {nil, "@", "", "", ""},
158 {p, "127.0.0.1:11950", "", "127.0.0.1", "127.0.0.1"},
162 {p, "127.0.0.1:11950", "", "127.0.0.1", "127.0.0.1"},
159 {p, "[::1]:28660", "99.103.56.12", "99.103.56.12", "::1 (99.103.56.12)"},
163 {p, "[::1]:28660", "99.103.56.12", "99.103.56.12", "::1 (99.103.56.12)"},
160 {nil, "10.254.244.165:62750", "", "10.254.244.165", "10.254.244.165"},
164 {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 {
43
43
44func isHealthCheckRequest(paths, userAgents map[string]struct{}, req *http.Request) bool {
44func isHealthCheckRequest(paths, userAgents map[string]struct{}, req *http.Request) bool {
45 if _, ok := paths[req.URL.EscapedPath()]; ok {
45 if _, ok := paths[req.URL.EscapedPath()]; ok {
46+ if len(userAgents) == 0 {
46− return true
47+ return true
47− }
48+ }
49+
48− if _, ok := userAgents[req.Header.Get("User-Agent")]; ok {
50+ if _, ok := userAgents[req.Header.Get("User-Agent")]; ok {
49− return true
51+ return true
52+ }
50 }
53 }
51 return false
54 return false
52}
55}
pkg/middleware/healthcheck_test.go+31−9
@@ -45,6 +45,16 @@ var _ = Describe("HealthCheck suite", func() {
45 healthCheckPaths: []string{"/ping"},
45 healthCheckPaths: []string{"/ping"},
46 healthCheckUserAgents: []string{"hc/1.0"},
46 healthCheckUserAgents: []string{"hc/1.0"},
47 requestString: "http://example.com/ping",
47 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",
48 headers: map[string]string{},
58 headers: map[string]string{},
49 expectedStatus: 200,
59 expectedStatus: 200,
50 expectedBody: "OK",
60 expectedBody: "OK",
@@ -85,15 +95,25 @@ var _ = Describe("HealthCheck suite", func() {
85 expectedStatus: 404,
95 expectedStatus: 404,
86 expectedBody: "404 page not found\n",
96 expectedBody: "404 page not found\n",
87 }),
97 }),
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{
89 healthCheckPaths: []string{"/ping"},
99 healthCheckPaths: []string{"/ping"},
90 healthCheckUserAgents: []string{"hc/1.0"},
100 healthCheckUserAgents: []string{"hc/1.0"},
91 requestString: "http://example.com/abc",
101 requestString: "http://example.com/abc",
92 headers: map[string]string{
102 headers: map[string]string{
93 "User-Agent": "hc/1.0",
103 "User-Agent": "hc/1.0",
94 },
104 },
95− expectedStatus: 200,
105+ expectedStatus: 404,
96− expectedBody: "OK",
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",
97 }),
117 }),
98 Entry("when a blank string is configured as a health check agent and a request has no user agent", &requestTableInput{
118 Entry("when a blank string is configured as a health check agent and a request has no user agent", &requestTableInput{
99 healthCheckPaths: []string{"/ping"},
119 healthCheckPaths: []string{"/ping"},
@@ -107,9 +127,11 @@ var _ = Describe("HealthCheck suite", func() {
107 healthCheckPaths: []string{"/ping", "/liveness_check", "/readiness_check"},
127 healthCheckPaths: []string{"/ping", "/liveness_check", "/readiness_check"},
108 healthCheckUserAgents: []string{"hc/1.0"},
128 healthCheckUserAgents: []string{"hc/1.0"},
109 requestString: "http://example.com/readiness_check",
129 requestString: "http://example.com/readiness_check",
110− headers: map[string]string{},
130+ headers: map[string]string{
131+ "User-Agent": "hc/1.0",
132+ },
111− expectedStatus: 200,
133+ expectedStatus: 200,
112− expectedBody: "OK",
134+ expectedBody: "OK",
113 }),
135 }),
114 Entry("with multiple paths, request none of the healthcheck paths", &requestTableInput{
136 Entry("with multiple paths, request none of the healthcheck paths", &requestTableInput{
115 healthCheckPaths: []string{"/ping", "/liveness_check", "/readiness_check"},
137 healthCheckPaths: []string{"/ping", "/liveness_check", "/readiness_check"},
@@ -121,15 +143,15 @@ var _ = Describe("HealthCheck suite", func() {
121 expectedStatus: 404,
143 expectedStatus: 404,
122 expectedBody: "404 page not found\n",
144 expectedBody: "404 page not found\n",
123 }),
145 }),
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{
125 healthCheckPaths: []string{"/ping"},
147 healthCheckPaths: []string{"/ping"},
126 healthCheckUserAgents: []string{"hc/1.0", "GoogleHC/1.0"},
148 healthCheckUserAgents: []string{"hc/1.0", "GoogleHC/1.0"},
127 requestString: "http://example.com/abc",
149 requestString: "http://example.com/abc",
128 headers: map[string]string{
150 headers: map[string]string{
129 "User-Agent": "GoogleHC/1.0",
151 "User-Agent": "GoogleHC/1.0",
130 },
152 },
131− expectedStatus: 200,
153+ expectedStatus: 404,
132− expectedBody: "OK",
154+ expectedBody: "404 page not found\n",
133 }),
155 }),
134 Entry("with multiple user agents, request from none of the health check user agents", &requestTableInput{
156 Entry("with multiple user agents, request from none of the health check user agents", &requestTableInput{
135 healthCheckPaths: []string{"/ping"},
157 healthCheckPaths: []string{"/ping"},
pkg/middleware/redirect_to_https_test.go+15
@@ -6,6 +6,7 @@ import (
6 "net/http/httptest"
6 "net/http/httptest"
7
7
8 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
8 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
9+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
9 . "github.com/onsi/ginkgo/v2"
10 . "github.com/onsi/ginkgo/v2"
10 . "github.com/onsi/gomega"
11 . "github.com/onsi/gomega"
11)
12)
@@ -39,6 +40,10 @@ var _ = Describe("RedirectToHTTPS suite", func() {
39 scope := &middlewareapi.RequestScope{
40 scope := &middlewareapi.RequestScope{
40 ReverseProxy: in.reverseProxy,
41 ReverseProxy: in.reverseProxy,
41 }
42 }
43+ if in.reverseProxy {
44+ req.RemoteAddr = "127.0.0.1:4180"
45+ scope.TrustedProxies = newRedirectTrustedProxySet("127.0.0.1")
46+ }
42 req = middlewareapi.AddRequestScope(req, scope)
47 req = middlewareapi.AddRequestScope(req, scope)
43
48
44 rw := httptest.NewRecorder()
49 rw := httptest.NewRecorder()
@@ -207,3 +212,13 @@ var _ = Describe("RedirectToHTTPS suite", func() {
207 }),
212 }),
208 )
213 )
209})
214})
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 (
6 "github.com/google/uuid"
6 "github.com/google/uuid"
7 "github.com/justinas/alice"
7 "github.com/justinas/alice"
8 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
8 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
9+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
9)
10)
10
11
11−func NewScope(reverseProxy bool, idHeader string) alice.Constructor {
12+func NewScope(reverseProxy bool, idHeader string, trustedProxies *ip.NetSet) alice.Constructor {
12 return func(next http.Handler) http.Handler {
13 return func(next http.Handler) http.Handler {
13 return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
14 return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
14 scope := &middlewareapi.RequestScope{
15 scope := &middlewareapi.RequestScope{
15− ReverseProxy: reverseProxy,
16+ ReverseProxy: reverseProxy,
17+ TrustedProxies: trustedProxies,
16− RequestID: genRequestID(req, idHeader),
18+ RequestID: genRequestID(req, idHeader),
17 }
19 }
18 req = middlewareapi.AddRequestScope(req, scope)
20 req = middlewareapi.AddRequestScope(req, scope)
19 next.ServeHTTP(rw, req)
21 next.ServeHTTP(rw, req)
pkg/middleware/scope_test.go+18−4
@@ -6,6 +6,7 @@ import (
6
6
7 "github.com/google/uuid"
7 "github.com/google/uuid"
8 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
8 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
9+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
9 . "github.com/onsi/ginkgo/v2"
10 . "github.com/onsi/ginkgo/v2"
10 . "github.com/onsi/gomega"
11 . "github.com/onsi/gomega"
11)
12)
@@ -32,7 +33,7 @@ var _ = Describe("Scope Suite", func() {
32
33
33 Context("ReverseProxy is false", func() {
34 Context("ReverseProxy is false", func() {
34 BeforeEach(func() {
35 BeforeEach(func() {
35− handler := NewScope(false, testRequestHeader)(
36+ handler := NewScope(false, testRequestHeader, nil)(
36 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
37 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
37 nextRequest = r
38 nextRequest = r
38 w.WriteHeader(200)
39 w.WriteHeader(200)
@@ -60,8 +61,15 @@ var _ = Describe("Scope Suite", func() {
60 })
61 })
61
62
62 Context("ReverseProxy is true", func() {
63 Context("ReverseProxy is true", func() {
64+ var trustedProxies *ip.NetSet
65+
63 BeforeEach(func() {
66 BeforeEach(func() {
67+ var err error
68+
69+ trustedProxies, err = ip.ParseNetSet([]string{"127.0.0.1"})
70+ Expect(err).ToNot(HaveOccurred())
71+
64− handler := NewScope(true, testRequestHeader)(
72+ handler := NewScope(true, testRequestHeader, trustedProxies)(
65 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
73 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
66 nextRequest = r
74 nextRequest = r
67 w.WriteHeader(200)
75 w.WriteHeader(200)
@@ -74,12 +82,18 @@ var _ = Describe("Scope Suite", func() {
74 Expect(scope).ToNot(BeNil())
82 Expect(scope).ToNot(BeNil())
75 Expect(scope.ReverseProxy).To(BeTrue())
83 Expect(scope.ReverseProxy).To(BeTrue())
76 })
84 })
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+ })
77 })
91 })
78
92
79 Context("Request ID header is present", func() {
93 Context("Request ID header is present", func() {
80 BeforeEach(func() {
94 BeforeEach(func() {
81 request.Header.Add(testRequestHeader, testRequestID)
95 request.Header.Add(testRequestHeader, testRequestID)
82− handler := NewScope(false, testRequestHeader)(
96+ handler := NewScope(false, testRequestHeader, nil)(
83 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
97 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
84 nextRequest = r
98 nextRequest = r
85 w.WriteHeader(200)
99 w.WriteHeader(200)
@@ -97,7 +111,7 @@ var _ = Describe("Scope Suite", func() {
97 BeforeEach(func() {
111 BeforeEach(func() {
98 uuid.SetRand(mockRand{})
112 uuid.SetRand(mockRand{})
99
113
100− handler := NewScope(true, testRequestHeader)(
114+ handler := NewScope(true, testRequestHeader, nil)(
101 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
115 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
102 nextRequest = r
116 nextRequest = r
103 w.WriteHeader(200)
117 w.WriteHeader(200)
pkg/middleware/stored_session.go+46−2
@@ -5,6 +5,7 @@ import (
5 "errors"
5 "errors"
6 "fmt"
6 "fmt"
7 "net/http"
7 "net/http"
8+ "strings"
8 "time"
9 "time"
9
10
10 "github.com/justinas/alice"
11 "github.com/justinas/alice"
@@ -31,6 +32,33 @@ const (
31 sessionRefreshRetryPeriod = 10 * time.Millisecond
32 sessionRefreshRetryPeriod = 10 * time.Millisecond
32)
33)
33
34
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+
34// StoredSessionLoaderOptions contains all of the requirements to construct
62// StoredSessionLoaderOptions contains all of the requirements to construct
35// a stored session loader.
63// a stored session loader.
36// All options must be provided.
64// All options must be provided.
@@ -188,9 +216,24 @@ func (s *storedSessionLoader) refreshSessionIfNeeded(rw http.ResponseWriter, req
188 // We are holding the lock and the session needs a refresh
216 // We are holding the lock and the session needs a refresh
189 logger.Printf("Refreshing session - User: %s; SessionAge: %s", session.User, session.Age())
217 logger.Printf("Refreshing session - User: %s; SessionAge: %s", session.User, session.Age())
190 if err := s.refreshSession(rw, req, session); err != nil {
218 if err := s.refreshSession(rw, req, session); err != nil {
191− // If a preemptive refresh fails, we still keep the session
192− // if validateSession succeeds.
193 logger.Errorf("Unable to refresh session: %v", err)
219 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
194 }
237 }
195
238
196 // Validate all sessions after any Redeem/Refresh operation (fail or success)
239 // 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
222
265
223 // Session not refreshed, nothing to persist.
266 // Session not refreshed, nothing to persist.
224 if !refreshed {
267 if !refreshed {
268+ logger.Printf("Session not refreshed - User: %s; no refresh token available or provider returned false", session.User)
225 return nil
269 return nil
226 }
270 }
227
271
pkg/middleware/stored_session_test.go+51
@@ -7,6 +7,7 @@ import (
7 "net/http"
7 "net/http"
8 "net/http/httptest"
8 "net/http/httptest"
9 "sync"
9 "sync"
10+ "testing"
10 "time"
11 "time"
11
12
12 middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
13 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
801func (f *fakeSessionStore) VerifyConnection(_ context.Context) error {
802func (f *fakeSessionStore) VerifyConnection(_ context.Context) error {
802 return nil
803 return nil
803}
804}
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
155 return nil, nil, fmt.Errorf("error while discovery OIDC configuration: %w", err)
155 return nil, nil, fmt.Errorf("error while discovery OIDC configuration: %w", err)
156 }
156 }
157
157
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+
158 return newVerifierBuilder(
163 return newVerifierBuilder(
159 opts.IssuerURL,
164 opts.IssuerURL,
160 oidc.NewRemoteKeySet(ctx, provider.Endpoints().JWKsURL),
165 oidc.NewRemoteKeySet(ctx, provider.Endpoints().JWKsURL),
161− provider.SupportedSigningAlgs(),
166+ supportedSigningAlgs,
162 ), provider, nil
167 ), provider, nil
163}
168}
164
169
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+
165// GetPublicKeyFromBytes parses a PEM-encoded public key from a byte array
200// GetPublicKeyFromBytes parses a PEM-encoded public key from a byte array
166// and returns a crypto.PublicKey object.
201// and returns a crypto.PublicKey object.
167func getPublicKeyFromBytes(bytes []byte) (crypto.PublicKey, error) {
202func getPublicKeyFromBytes(bytes []byte) (crypto.PublicKey, error) {
pkg/providers/oidc/provider_verifier_test.go+92
@@ -2,6 +2,9 @@ package oidc
2
2
3import (
3import (
4 "context"
4 "context"
5+ "encoding/json"
6+ "net"
7+ "net/http"
5 "os"
8 "os"
6 "path/filepath"
9 "path/filepath"
7 "time"
10 "time"
@@ -195,6 +198,21 @@ var _ = Describe("ProviderVerifier", func() {
195 Expect(idToken.Subject).To(Equal(claims.Subject))
198 Expect(idToken.Subject).To(Equal(claims.Subject))
196 },
199 },
197 Entry("with the default opts and claims", &verifierTableInput{}),
200 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+ }),
198 Entry("when the audience is mismatched", &verifierTableInput{
216 Entry("when the audience is mismatched", &verifierTableInput{
199 modifyClaims: func(j *jwt.RegisteredClaims) {
217 modifyClaims: func(j *jwt.RegisteredClaims) {
200 j.Audience = jwt.ClaimStrings{"OtherClient"}
218 j.Audience = jwt.ClaimStrings{"OtherClient"}
@@ -230,4 +248,78 @@ var _ = Describe("ProviderVerifier", func() {
230 expectedError: "failed to verify token: oidc: token is expired",
248 expectedError: "failed to verify token: oidc: token is expired",
231 }),
249 }),
232 )
250 )
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+ })
233})
302})
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
3import (
3import (
4 "context"
4 "context"
5 "encoding/base64"
5 "encoding/base64"
6− "encoding/json"
7 "fmt"
6 "fmt"
8 "mime"
7 "mime"
9 "net/http"
8 "net/http"
@@ -12,17 +11,17 @@ import (
12
11
13 "github.com/bitly/go-simplejson"
12 "github.com/bitly/go-simplejson"
14 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests"
13 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests"
15− "github.com/spf13/cast"
14+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util"
16)
15)
17
16
18// ClaimExtractor is used to extract claim values from an ID Token, or, if not
17// ClaimExtractor is used to extract claim values from an ID Token, or, if not
19// present, from the profile URL.
18// present, from the profile URL.
20type ClaimExtractor interface {
19type ClaimExtractor interface {
21 // GetClaim fetches a named claim and returns the value.
20 // GetClaim fetches a named claim and returns the value.
22− GetClaim(claim string) (interface{}, bool, error)
21+ GetClaim(claim string) (any, bool, error)
23
22
24 // GetClaimInto fetches a named claim and puts the value into the destination.
23 // 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)
26}
25}
27
26
28// NewClaimExtractor constructs a new ClaimExtractor from the raw ID Token.
27// NewClaimExtractor constructs a new ClaimExtractor from the raw ID Token.
@@ -31,12 +30,12 @@ type ClaimExtractor interface {
31func NewClaimExtractor(ctx context.Context, idToken string, profileURL *url.URL, profileRequestHeaders http.Header) (ClaimExtractor, error) {
30func NewClaimExtractor(ctx context.Context, idToken string, profileURL *url.URL, profileRequestHeaders http.Header) (ClaimExtractor, error) {
32 payload, err := parseJWT(idToken)
31 payload, err := parseJWT(idToken)
33 if err != nil {
32 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)
35 }
34 }
36
35
37 tokenClaims, err := simplejson.NewJson(payload)
36 tokenClaims, err := simplejson.NewJson(payload)
38 if err != nil {
37 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)
40 }
39 }
41
40
42 return &claimExtractor{
41 return &claimExtractor{
@@ -59,7 +58,7 @@ type claimExtractor struct {
59// GetClaim will return the value claim if it exists.
58// GetClaim will return the value claim if it exists.
60// It will only return an error if the profile URL needs to be fetched due to
59// It will only return an error if the profile URL needs to be fetched due to
61// the claim not being present in the ID Token.
60// 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) {
63 if claim == "" {
62 if claim == "" {
64 return nil, false, nil
63 return nil, false, nil
65 }
64 }
@@ -124,7 +123,7 @@ func (c *claimExtractor) loadProfileClaims() (*simplejson.Json, error) {
124// GetClaimInto loads a claim and places it into the destination interface.
123// GetClaimInto loads a claim and places it into the destination interface.
125// This will attempt to coerce the claim into the specified type.
124// This will attempt to coerce the claim into the specified type.
126// If it cannot be coerced, an error may be returned.
125// 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) {
128 value, exists, err := c.GetClaim(claim)
127 value, exists, err := c.GetClaim(claim)
129 if err != nil {
128 if err != nil {
130 return false, fmt.Errorf("could not get claim %q: %v", claim, err)
129 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
132 if !exists {
131 if !exists {
133 return false, nil
132 return false, nil
134 }
133 }
135− if err := coerceClaim(value, dst); err != nil {
134+ if err := util.CoerceClaim(value, dst); err != nil {
136− return false, fmt.Errorf("could no coerce claim: %v", err)
135+ return false, fmt.Errorf("could not coerce claim: %v", err)
137 }
136 }
138
137
139 return true, nil
138 return true, nil
@@ -156,73 +155,10 @@ func parseJWT(p string) ([]byte, error) {
156// getClaimFrom gets a claim from a Json object.
155// getClaimFrom gets a claim from a Json object.
157// It can accept either a single claim name or a json path. The claim is always evaluated first as a single claim name.
156// It can accept either a single claim name or a json path. The claim is always evaluated first as a single claim name.
158// Paths with indexes are not supported.
157// Paths with indexes are not supported.
159−func getClaimFrom(claim string, src *simplejson.Json) interface{} {
158+func getClaimFrom(claim string, src *simplejson.Json) any {
160 if value, ok := src.CheckGet(claim); ok {
159 if value, ok := src.CheckGet(claim); ok {
161 return value.Interface()
160 return value.Interface()
162 }
161 }
163 claimParts := strings.Split(claim, ".")
162 claimParts := strings.Split(claim, ".")
164 return src.GetPath(claimParts...).Interface()
163 return src.GetPath(claimParts...).Interface()
165}
164}
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() {
76 func(in newClaimExtractorTableInput) {
76 func(in newClaimExtractorTableInput) {
77 _, err := NewClaimExtractor(context.Background(), in.idToken, nil, nil)
77 _, err := NewClaimExtractor(context.Background(), in.idToken, nil, nil)
78 if in.expectedError != nil {
78 if in.expectedError != nil {
79− Expect(err).To(MatchError(in.expectedError))
79+ Expect(err).To(MatchError(in.expectedError.Error()))
80 } else {
80 } else {
81 Expect(err).ToNot(HaveOccurred())
81 Expect(err).ToNot(HaveOccurred())
82 }
82 }
@@ -405,7 +405,7 @@ var _ = Describe("Claim Extractor Suite", func() {
405 into: "",
405 into: "",
406 expectExists: false,
406 expectExists: false,
407 expectedValue: "",
407 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"),
409 }),
409 }),
410 Entry("flattens a complex claim value into a JSON string", getClaimIntoTableInput{
410 Entry("flattens a complex claim value into a JSON string", getClaimIntoTableInput{
411 testClaimExtractorOpts: testClaimExtractorOpts{
411 testClaimExtractorOpts: testClaimExtractorOpts{
@@ -451,53 +451,6 @@ var _ = Describe("Claim Extractor Suite", func() {
451 }),
451 }),
452 )
452 )
453
453
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−
501 It("should extract claims from a JWT response", func() {
454 It("should extract claims from a JWT response", func() {
502 jwtResponsePayload := `{
455 jwtResponsePayload := `{
503 "user": "jwtUser",
456 "user": "jwtUser",
@@ -605,10 +558,6 @@ func stringSlicePointer(in []string) *[]string {
605 return &in
558 return &in
606}
559}
607
560
608−func boolPointer(in bool) *bool {
609− return &in
610−}
611−
612// ******************************
561// ******************************
613// Different profile URL handlers
562// Different profile URL handlers
614// ******************************
563// ******************************
pkg/proxyhttp/server.go+50−2
@@ -8,6 +8,7 @@ import (
8 "net"
8 "net"
9 "net/http"
9 "net/http"
10 "os"
10 "os"
11+ "strconv"
11 "strings"
12 "strings"
12 "time"
13 "time"
13
14
@@ -95,15 +96,62 @@ func (s *server) setupListener(opts Opts) error {
95 networkType := getNetworkScheme(opts.BindAddress)
96 networkType := getNetworkScheme(opts.BindAddress)
96 listenAddr := getListenAddress(opts.BindAddress)
97 listenAddr := getListenAddress(opts.BindAddress)
97
98
99+ listener, err := func() (net.Listener, error) {
100+ if networkType == "unix" {
101+ return setupUnixSocketListener(networkType, listenAddr)
102+ }
98− listener, err := net.Listen(networkType, listenAddr)
103+ return net.Listen(networkType, listenAddr)
104+ }()
105+
99 if err != nil {
106 if err != nil {
100 return fmt.Errorf("listen (%s, %s) failed: %w", networkType, listenAddr, err)
107 return fmt.Errorf("listen (%s, %s) failed: %w", networkType, listenAddr, err)
101 }
108 }
102− s.listener = listener
103
109
110+ s.listener = listener
104 return nil
111 return nil
105}
112}
106
113
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+
107func parseCipherSuites(names []string) ([]uint16, error) {
155func parseCipherSuites(names []string) ([]uint16, error) {
108 cipherNameMap := make(map[string]uint16)
156 cipherNameMap := make(map[string]uint16)
109
157
pkg/proxyhttp/server_test.go+50
@@ -28,6 +28,8 @@ var _ = Describe("Server", func() {
28 expectedErr error
28 expectedErr error
29 expectHTTPListener bool
29 expectHTTPListener bool
30 expectTLSListener bool
30 expectTLSListener bool
31+ expectedSocketMode os.FileMode
32+ socketPath string
31 fdAddr string
33 fdAddr string
32 ipv6 bool
34 ipv6 bool
33 }
35 }
@@ -57,6 +59,12 @@ var _ = Describe("Server", func() {
57 s, ok := srv.(*server)
59 s, ok := srv.(*server)
58 Expect(ok).To(BeTrue())
60 Expect(ok).To(BeTrue())
59
61
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+
60 Expect(s.listener != nil).To(Equal(in.expectHTTPListener))
68 Expect(s.listener != nil).To(Equal(in.expectHTTPListener))
61 if in.expectHTTPListener {
69 if in.expectHTTPListener {
62 Expect(s.listener.Close()).To(Succeed())
70 Expect(s.listener.Close()).To(Succeed())
@@ -648,6 +656,48 @@ var _ = Describe("Server", func() {
648 expectTLSListener: true,
656 expectTLSListener: true,
649 ipv6: true,
657 ipv6: true,
650 }),
658 }),
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+ }),
651 )
701 )
652 })
702 })
653
703
pkg/requests/builder_test.go+15−15
@@ -31,7 +31,7 @@ var _ = Describe("Builder suite", func() {
31
31
32 Context("with a basic request", func() {
32 Context("with a basic request", func() {
33 assertSuccessfulRequest(getBuilder, testHTTPRequest{
33 assertSuccessfulRequest(getBuilder, testHTTPRequest{
34− Method: "GET",
34+ Method: http.MethodGet,
35 Header: baseHeaders,
35 Header: baseHeaders,
36 Body: []byte{},
36 Body: []byte{},
37 RequestURI: "/json/path",
37 RequestURI: "/json/path",
@@ -52,7 +52,7 @@ var _ = Describe("Builder suite", func() {
52 })
52 })
53
53
54 assertSuccessfulRequest(getBuilder, testHTTPRequest{
54 assertSuccessfulRequest(getBuilder, testHTTPRequest{
55− Method: "GET",
55+ Method: http.MethodGet,
56 Header: baseHeaders,
56 Header: baseHeaders,
57 Body: []byte{},
57 Body: []byte{},
58 RequestURI: "/json/path",
58 RequestURI: "/json/path",
@@ -78,7 +78,7 @@ var _ = Describe("Builder suite", func() {
78 })
78 })
79
79
80 assertSuccessfulRequest(getBuilder, testHTTPRequest{
80 assertSuccessfulRequest(getBuilder, testHTTPRequest{
81− Method: "GET",
81+ Method: http.MethodGet,
82 Header: header,
82 Header: header,
83 Body: []byte(body),
83 Body: []byte(body),
84 RequestURI: "/json/path",
84 RequestURI: "/json/path",
@@ -93,11 +93,11 @@ var _ = Describe("Builder suite", func() {
93
93
94 BeforeEach(func() {
94 BeforeEach(func() {
95 buf := bytes.NewBuffer([]byte(body))
95 buf := bytes.NewBuffer([]byte(body))
96− b = b.WithMethod("POST").WithBody(buf)
96+ b = b.WithMethod(http.MethodPost).WithBody(buf)
97 })
97 })
98
98
99 assertSuccessfulRequest(getBuilder, testHTTPRequest{
99 assertSuccessfulRequest(getBuilder, testHTTPRequest{
100− Method: "POST",
100+ Method: http.MethodPost,
101 Header: header,
101 Header: header,
102 Body: []byte(body),
102 Body: []byte(body),
103 RequestURI: "/json/path",
103 RequestURI: "/json/path",
@@ -109,11 +109,11 @@ var _ = Describe("Builder suite", func() {
109 header.Set("Content-Length", "0")
109 header.Set("Content-Length", "0")
110
110
111 BeforeEach(func() {
111 BeforeEach(func() {
112− b = b.WithMethod("POST")
112+ b = b.WithMethod(http.MethodPost)
113 })
113 })
114
114
115 assertSuccessfulRequest(getBuilder, testHTTPRequest{
115 assertSuccessfulRequest(getBuilder, testHTTPRequest{
116− Method: "POST",
116+ Method: http.MethodPost,
117 Header: header,
117 Header: header,
118 Body: []byte{},
118 Body: []byte{},
119 RequestURI: "/json/path",
119 RequestURI: "/json/path",
@@ -122,11 +122,11 @@ var _ = Describe("Builder suite", func() {
122
122
123 Context("OPTIONS", func() {
123 Context("OPTIONS", func() {
124 BeforeEach(func() {
124 BeforeEach(func() {
125− b = b.WithMethod("OPTIONS")
125+ b = b.WithMethod(http.MethodOptions)
126 })
126 })
127
127
128 assertSuccessfulRequest(getBuilder, testHTTPRequest{
128 assertSuccessfulRequest(getBuilder, testHTTPRequest{
129− Method: "OPTIONS",
129+ Method: http.MethodOptions,
130 Header: baseHeaders,
130 Header: baseHeaders,
131 Body: []byte{},
131 Body: []byte{},
132 RequestURI: "/json/path",
132 RequestURI: "/json/path",
@@ -152,7 +152,7 @@ var _ = Describe("Builder suite", func() {
152 })
152 })
153
153
154 assertSuccessfulRequest(getBuilder, testHTTPRequest{
154 assertSuccessfulRequest(getBuilder, testHTTPRequest{
155− Method: "GET",
155+ Method: http.MethodGet,
156 Header: header,
156 Header: header,
157 Body: []byte{},
157 Body: []byte{},
158 RequestURI: "/json/path",
158 RequestURI: "/json/path",
@@ -170,7 +170,7 @@ var _ = Describe("Builder suite", func() {
170 })
170 })
171
171
172 assertSuccessfulRequest(getBuilder, testHTTPRequest{
172 assertSuccessfulRequest(getBuilder, testHTTPRequest{
173− Method: "GET",
173+ Method: http.MethodGet,
174 Header: replacementHeaders,
174 Header: replacementHeaders,
175 Body: []byte{},
175 Body: []byte{},
176 RequestURI: "/json/path",
176 RequestURI: "/json/path",
@@ -190,7 +190,7 @@ var _ = Describe("Builder suite", func() {
190 })
190 })
191
191
192 assertSuccessfulRequest(getBuilder, testHTTPRequest{
192 assertSuccessfulRequest(getBuilder, testHTTPRequest{
193− Method: "GET",
193+ Method: http.MethodGet,
194 Header: replacementHeaders,
194 Header: replacementHeaders,
195 Body: []byte{},
195 Body: []byte{},
196 RequestURI: "/json/path",
196 RequestURI: "/json/path",
@@ -205,7 +205,7 @@ var _ = Describe("Builder suite", func() {
205 })
205 })
206
206
207 assertSuccessfulRequest(getBuilder, testHTTPRequest{
207 assertSuccessfulRequest(getBuilder, testHTTPRequest{
208− Method: "GET",
208+ Method: http.MethodGet,
209 Header: header,
209 Header: header,
210 Body: []byte{},
210 Body: []byte{},
211 RequestURI: "/json/path",
211 RequestURI: "/json/path",
@@ -219,12 +219,12 @@ var _ = Describe("Builder suite", func() {
219 result := b.Do()
219 result := b.Do()
220 Expect(result.Error()).ToNot(HaveOccurred())
220 Expect(result.Error()).ToNot(HaveOccurred())
221
221
222− b.WithMethod("POST")
222+ b.WithMethod(http.MethodPost)
223 })
223 })
224
224
225 Context("should not redo the request", func() {
225 Context("should not redo the request", func() {
226 assertSuccessfulRequest(getBuilder, testHTTPRequest{
226 assertSuccessfulRequest(getBuilder, testHTTPRequest{
227− Method: "GET",
227+ Method: http.MethodGet,
228 Header: baseHeaders,
228 Header: baseHeaders,
229 Body: []byte{},
229 Body: []byte{},
230 RequestURI: "/json/path",
230 RequestURI: "/json/path",
pkg/requests/util/util.go+28−15
@@ -15,30 +15,30 @@ const (
15)
15)
16
16
17// GetRequestProto returns the request scheme or X-Forwarded-Proto if present
17// 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.
19func GetRequestProto(req *http.Request) string {
19func GetRequestProto(req *http.Request) string {
20 proto := req.Header.Get(XForwardedProto)
20 proto := req.Header.Get(XForwardedProto)
21− if !IsProxied(req) || proto == "" {
21+ if !CanTrustForwardedHeaders(req) || proto == "" {
22 proto = req.URL.Scheme
22 proto = req.URL.Scheme
23 }
23 }
24 return proto
24 return proto
25}
25}
26
26
27// GetRequestHost returns the request host header or X-Forwarded-Host if
27// 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.
29func GetRequestHost(req *http.Request) string {
29func GetRequestHost(req *http.Request) string {
30 host := req.Header.Get(XForwardedHost)
30 host := req.Header.Get(XForwardedHost)
31− if !IsProxied(req) || host == "" {
31+ if !CanTrustForwardedHeaders(req) || host == "" {
32 host = req.Host
32 host = req.Host
33 }
33 }
34 return host
34 return host
35}
35}
36
36
37// GetRequestURI return the request URI or X-Forwarded-Uri if present and the
37// 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.
39func GetRequestURI(req *http.Request) string {
39func GetRequestURI(req *http.Request) string {
40 uri := req.Header.Get(XForwardedURI)
40 uri := req.Header.Get(XForwardedURI)
41− if !IsProxied(req) || uri == "" {
41+ if !CanTrustForwardedHeaders(req) || uri == "" {
42 // Use RequestURI to preserve ?query
42 // Use RequestURI to preserve ?query
43 uri = req.URL.RequestURI()
43 uri = req.URL.RequestURI()
44 }
44 }
@@ -46,17 +46,29 @@ func GetRequestURI(req *http.Request) string {
46}
46}
47
47
48// GetRequestPath returns the request URI or X-Forwarded-Uri if present and the
48// 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
49+// request came from a trusted reverse proxy but always strips the query
50−// the pure path
50+// parameters and fragment suffixes and only returns the pure path.
51func GetRequestPath(req *http.Request) string {
51func GetRequestPath(req *http.Request) string {
52− uri := GetRequestURI(req)
52+ uri := stripRequestFragment(GetRequestURI(req))
53
53
54 // Parse URI and return only the path component
54 // Parse URI and return only the path component
55 if parsedURL, err := url.Parse(uri); err == nil {
55 if parsedURL, err := url.Parse(uri); err == nil {
56− return parsedURL.Path
56+ return stripRequestFragment(parsedURL.Path)
57 }
57 }
58
58
59 // Fallback: strip query parameters manually
59 // 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 {
60 if idx := strings.Index(uri, "?"); idx != -1 {
72 if idx := strings.Index(uri, "?"); idx != -1 {
61 return uri[:idx]
73 return uri[:idx]
62 }
74 }
@@ -64,17 +76,18 @@ func GetRequestPath(req *http.Request) string {
64 return uri
76 return uri
65}
77}
66
78
67−// IsProxied determines if a request was from a proxy based on the RequestScope
79+// CanTrustForwardedHeaders determines if forwarded headers should be processed
68−// ReverseProxy tracker.
80+// based on the RequestScope and the direct caller's address.
69−func IsProxied(req *http.Request) bool {
81+func CanTrustForwardedHeaders(req *http.Request) bool {
70 scope := middlewareapi.GetRequestScope(req)
82 scope := middlewareapi.GetRequestScope(req)
71 if scope == nil {
83 if scope == nil {
72 return false
84 return false
73 }
85 }
74− return scope.ReverseProxy
86+
87+ return scope.CanTrustForwardedHeaders(req)
75}
88}
76
89
77func IsForwardedRequest(req *http.Request) bool {
90func IsForwardedRequest(req *http.Request) bool {
78− return IsProxied(req) &&
91+ return CanTrustForwardedHeaders(req) &&
79 req.Host != GetRequestHost(req)
92 req.Host != GetRequestHost(req)
80}
93}
pkg/requests/util/util_test.go+74−12
@@ -6,6 +6,7 @@ import (
6 "net/http/httptest"
6 "net/http/httptest"
7
7
8 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
8 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
9+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
9 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests/util"
10 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests/util"
10 . "github.com/onsi/ginkgo/v2"
11 . "github.com/onsi/ginkgo/v2"
11 . "github.com/onsi/gomega"
12 . "github.com/onsi/gomega"
@@ -19,8 +20,13 @@ var _ = Describe("Util Suite", func() {
19 uriNoQueryParams = "/test/endpoint"
20 uriNoQueryParams = "/test/endpoint"
20 )
21 )
21 var req *http.Request
22 var req *http.Request
23+ var trustedProxies *ip.NetSet
22
24
23 BeforeEach(func() {
25 BeforeEach(func() {
26+ var err error
27+ trustedProxies, err = ip.ParseNetSet([]string{"127.0.0.1"})
28+ Expect(err).ToNot(HaveOccurred())
29+
24 req = httptest.NewRequest(
30 req = httptest.NewRequest(
25 http.MethodGet,
31 http.MethodGet,
26 fmt.Sprintf("%s://%s%s", proto, host, uriWithQueryParams),
32 fmt.Sprintf("%s://%s%s", proto, host, uriWithQueryParams),
@@ -29,7 +35,7 @@ var _ = Describe("Util Suite", func() {
29 })
35 })
30
36
31 Context("GetRequestHost", func() {
37 Context("GetRequestHost", func() {
32− Context("IsProxied is false", func() {
38+ Context("trusted forwarded headers are disabled", func() {
33 BeforeEach(func() {
39 BeforeEach(func() {
34 req = middleware.AddRequestScope(req, &middleware.RequestScope{})
40 req = middleware.AddRequestScope(req, &middleware.RequestScope{})
35 })
41 })
@@ -44,10 +50,12 @@ var _ = Describe("Util Suite", func() {
44 })
50 })
45 })
51 })
46
52
47− Context("IsProxied is true", func() {
53+ Context("trusted forwarded headers are enabled", func() {
48 BeforeEach(func() {
54 BeforeEach(func() {
55+ req.RemoteAddr = "127.0.0.1:4180"
49 req = middleware.AddRequestScope(req, &middleware.RequestScope{
56 req = middleware.AddRequestScope(req, &middleware.RequestScope{
50− ReverseProxy: true,
57+ ReverseProxy: true,
58+ TrustedProxies: trustedProxies,
51 })
59 })
52 })
60 })
53
61
@@ -63,7 +71,7 @@ var _ = Describe("Util Suite", func() {
63 })
71 })
64
72
65 Context("GetRequestProto", func() {
73 Context("GetRequestProto", func() {
66− Context("IsProxied is false", func() {
74+ Context("trusted forwarded headers are disabled", func() {
67 BeforeEach(func() {
75 BeforeEach(func() {
68 req = middleware.AddRequestScope(req, &middleware.RequestScope{})
76 req = middleware.AddRequestScope(req, &middleware.RequestScope{})
69 })
77 })
@@ -78,10 +86,12 @@ var _ = Describe("Util Suite", func() {
78 })
86 })
79 })
87 })
80
88
81− Context("IsProxied is true", func() {
89+ Context("trusted forwarded headers are enabled", func() {
82 BeforeEach(func() {
90 BeforeEach(func() {
91+ req.RemoteAddr = "127.0.0.1:4180"
83 req = middleware.AddRequestScope(req, &middleware.RequestScope{
92 req = middleware.AddRequestScope(req, &middleware.RequestScope{
84− ReverseProxy: true,
93+ ReverseProxy: true,
94+ TrustedProxies: trustedProxies,
85 })
95 })
86 })
96 })
87
97
@@ -97,7 +107,7 @@ var _ = Describe("Util Suite", func() {
97 })
107 })
98
108
99 Context("GetRequestURI", func() {
109 Context("GetRequestURI", func() {
100− Context("IsProxied is false", func() {
110+ Context("trusted forwarded headers are disabled", func() {
101 BeforeEach(func() {
111 BeforeEach(func() {
102 req = middleware.AddRequestScope(req, &middleware.RequestScope{})
112 req = middleware.AddRequestScope(req, &middleware.RequestScope{})
103 })
113 })
@@ -112,10 +122,12 @@ var _ = Describe("Util Suite", func() {
112 })
122 })
113 })
123 })
114
124
115− Context("IsProxied is true", func() {
125+ Context("trusted forwarded headers are enabled", func() {
116 BeforeEach(func() {
126 BeforeEach(func() {
127+ req.RemoteAddr = "127.0.0.1:4180"
117 req = middleware.AddRequestScope(req, &middleware.RequestScope{
128 req = middleware.AddRequestScope(req, &middleware.RequestScope{
118− ReverseProxy: true,
129+ ReverseProxy: true,
130+ TrustedProxies: trustedProxies,
119 })
131 })
120 })
132 })
121
133
@@ -131,7 +143,7 @@ var _ = Describe("Util Suite", func() {
131 })
143 })
132
144
133 Context("GetRequestPath", func() {
145 Context("GetRequestPath", func() {
134− Context("IsProxied is false", func() {
146+ Context("trusted forwarded headers are disabled", func() {
135 BeforeEach(func() {
147 BeforeEach(func() {
136 req = middleware.AddRequestScope(req, &middleware.RequestScope{})
148 req = middleware.AddRequestScope(req, &middleware.RequestScope{})
137 })
149 })
@@ -140,16 +152,35 @@ var _ = Describe("Util Suite", func() {
140 Expect(util.GetRequestPath(req)).To(Equal(uriNoQueryParams))
152 Expect(util.GetRequestPath(req)).To(Equal(uriNoQueryParams))
141 })
153 })
142
154
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+
143 It("ignores X-Forwarded-Uri and returns the URI (without query params)", func() {
172 It("ignores X-Forwarded-Uri and returns the URI (without query params)", func() {
144 req.Header.Add("X-Forwarded-Uri", "/some/other/path?query=param")
173 req.Header.Add("X-Forwarded-Uri", "/some/other/path?query=param")
145 Expect(util.GetRequestPath(req)).To(Equal(uriNoQueryParams))
174 Expect(util.GetRequestPath(req)).To(Equal(uriNoQueryParams))
146 })
175 })
147 })
176 })
148
177
149− Context("IsProxied is true", func() {
178+ Context("trusted forwarded headers are enabled", func() {
150 BeforeEach(func() {
179 BeforeEach(func() {
180+ req.RemoteAddr = "127.0.0.1:4180"
151 req = middleware.AddRequestScope(req, &middleware.RequestScope{
181 req = middleware.AddRequestScope(req, &middleware.RequestScope{
152− ReverseProxy: true,
182+ ReverseProxy: true,
183+ TrustedProxies: trustedProxies,
153 })
184 })
154 })
185 })
155
186
@@ -161,6 +192,37 @@ var _ = Describe("Util Suite", func() {
161 req.Header.Add("X-Forwarded-Uri", "/some/other/path?query=param")
192 req.Header.Add("X-Forwarded-Uri", "/some/other/path?query=param")
162 Expect(util.GetRequestPath(req)).To(Equal("/some/other/path"))
193 Expect(util.GetRequestPath(req)).To(Equal("/some/other/path"))
163 })
194 })
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())
164 })
226 })
165 })
227 })
166})
228})
pkg/sessions/cookie/session_store.go+23−13
@@ -76,7 +76,17 @@ func (s *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) error {
76
76
77 for _, c := range req.Cookies() {
77 for _, c := range req.Cookies() {
78 if cookieNameRegex.MatchString(c.Name) {
78 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)
80
90
81 http.SetCookie(rw, clearCookie)
91 http.SetCookie(rw, clearCookie)
82 }
92 }
@@ -117,7 +127,7 @@ func (s *SessionStore) setSessionCookie(rw http.ResponseWriter, req *http.Reques
117 return nil
127 return nil
118}
128}
119
129
120−// makeSessionCookie creates an http.Cookie containing the authenticated user's
130+// makeSessionCookie creates a http.Cookie containing the authenticated user's
121// authentication details
131// authentication details
122func (s *SessionStore) makeSessionCookie(req *http.Request, value []byte, now time.Time) ([]*http.Cookie, error) {
132func (s *SessionStore) makeSessionCookie(req *http.Request, value []byte, now time.Time) ([]*http.Cookie, error) {
123 strValue := string(value)
133 strValue := string(value)
@@ -132,23 +142,23 @@ func (s *SessionStore) makeSessionCookie(req *http.Request, value []byte, now ti
132 return nil, err
142 return nil, err
133 }
143 }
134 }
144 }
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)
136 if len(c.String()) > maxCookieLength {
156 if len(c.String()) > maxCookieLength {
137 return splitCookie(c), nil
157 return splitCookie(c), nil
138 }
158 }
139 return []*http.Cookie{c}, nil
159 return []*http.Cookie{c}, nil
140}
160}
141
161
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−
152// NewCookieSessionStore initialises a new instance of the SessionStore from
162// NewCookieSessionStore initialises a new instance of the SessionStore from
153// the configuration given
163// the configuration given
154func NewCookieSessionStore(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessions.SessionStore, error) {
164func 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
221// clearCookie removes any cookies that would be where this ticket
221// clearCookie removes any cookies that would be where this ticket
222// would set them
222// would set them
223func (t *ticket) clearCookie(rw http.ResponseWriter, req *http.Request) {
223func (t *ticket) clearCookie(rw http.ResponseWriter, req *http.Request) {
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+ }
224− http.SetCookie(rw, cookies.MakeCookieFromOptions(
234+ http.SetCookie(rw, cookies.MakeCookieFromOptions(req, cookieOptions))
225− req,
226− t.options.Name,
227− "",
228− t.options,
229− time.Hour*-1,
230− ))
231}
235}
232
236
233// makeCookie makes a cookie, signing the value if present
237// 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
244 }
248 }
245 }
249 }
246
250
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+
247− return cookies.MakeCookieFromOptions(
262+ return cookies.MakeCookieFromOptions(req, cookieOptions), nil
248− req,
249− t.options.Name,
250− value,
251− t.options,
252− expires,
253− ), nil
254}
263}
255
264
256// makeCipher makes a AES-GCM cipher out of the ticket's secret
265// 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) {
109 if opts.Username != "" {
109 if opts.Username != "" {
110 opt.Username = opts.Username
110 opt.Username = opts.Username
111 }
111 }
112+ if opts.IdleTimeout > 0 {
113+ opt.ConnMaxIdleTime = time.Duration(opts.IdleTimeout) * time.Second
114+ }
112
115
113 if err := setupTLSConfig(opts, opt); err != nil {
116 if err := setupTLSConfig(opts, opt); err != nil {
114 return nil, err
117 return nil, err
@@ -118,10 +121,10 @@ func buildSentinelClient(opts options.RedisStoreOptions) (Client, error) {
118 MasterName: opts.SentinelMasterName,
121 MasterName: opts.SentinelMasterName,
119 SentinelAddrs: addrs,
122 SentinelAddrs: addrs,
120 SentinelPassword: opts.SentinelPassword,
123 SentinelPassword: opts.SentinelPassword,
121− Username: opts.Username,
124+ Username: opt.Username,
122− Password: opts.Password,
125+ Password: opt.Password,
123 TLSConfig: opt.TLSConfig,
126 TLSConfig: opt.TLSConfig,
124− ConnMaxIdleTime: time.Duration(opts.IdleTimeout) * time.Second,
127+ ConnMaxIdleTime: opt.ConnMaxIdleTime,
125 })
128 })
126 return newClient(client), nil
129 return newClient(client), nil
127}
130}
@@ -139,6 +142,9 @@ func buildClusterClient(opts options.RedisStoreOptions) (Client, error) {
139 if opts.Username != "" {
142 if opts.Username != "" {
140 opt.Username = opts.Username
143 opt.Username = opts.Username
141 }
144 }
145+ if opts.IdleTimeout > 0 {
146+ opt.ConnMaxIdleTime = time.Duration(opts.IdleTimeout) * time.Second
147+ }
142
148
143 if err := setupTLSConfig(opts, opt); err != nil {
149 if err := setupTLSConfig(opts, opt); err != nil {
144 return nil, err
150 return nil, err
@@ -146,10 +152,10 @@ func buildClusterClient(opts options.RedisStoreOptions) (Client, error) {
146
152
147 client := redis.NewClusterClient(&redis.ClusterOptions{
153 client := redis.NewClusterClient(&redis.ClusterOptions{
148 Addrs: addrs,
154 Addrs: addrs,
149− Username: opts.Username,
155+ Username: opt.Username,
150− Password: opts.Password,
156+ Password: opt.Password,
151 TLSConfig: opt.TLSConfig,
157 TLSConfig: opt.TLSConfig,
152− ConnMaxIdleTime: time.Duration(opts.IdleTimeout) * time.Second,
158+ ConnMaxIdleTime: opt.ConnMaxIdleTime,
153 })
159 })
154 return newClusterClient(client), nil
160 return newClusterClient(client), nil
155}
161}
@@ -168,13 +174,14 @@ func buildStandaloneClient(opts options.RedisStoreOptions) (Client, error) {
168 if opts.Username != "" {
174 if opts.Username != "" {
169 opt.Username = opts.Username
175 opt.Username = opts.Username
170 }
176 }
177+ if opts.IdleTimeout > 0 {
178+ opt.ConnMaxIdleTime = time.Duration(opts.IdleTimeout) * time.Second
179+ }
171
180
172 if err := setupTLSConfig(opts, opt); err != nil {
181 if err := setupTLSConfig(opts, opt); err != nil {
173 return nil, err
182 return nil, err
174 }
183 }
175
184
176− opt.ConnMaxIdleTime = time.Duration(opts.IdleTimeout) * time.Second
177−
178 client := redis.NewClient(opt)
185 client := redis.NewClient(opt)
179 return newClient(client), nil
186 return newClient(client), nil
180}
187}
pkg/sessions/redis/redis_store_test.go+50
@@ -1,6 +1,7 @@
1package redis
1package redis
2
2
3import (
3import (
4+ "fmt"
4 "time"
5 "time"
5
6
6 "github.com/Bose/minisentinel"
7 "github.com/Bose/minisentinel"
@@ -246,6 +247,55 @@ var _ = Describe("Redis SessionStore Tests", func() {
246 })
247 })
247
248
248 Describe("Redis URL Parsing", func() {
249 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+
249 It("should parse valid redis URL", func() {
299 It("should parse valid redis URL", func() {
250 addrs, opts, err := parseRedisURLs([]string{"redis://localhost:6379"})
300 addrs, opts, err := parseRedisURLs([]string{"redis://localhost:6379"})
251 Expect(err).ToNot(HaveOccurred())
301 Expect(err).ToNot(HaveOccurred())
pkg/sessions/tests/session_store_tests.go+11−1
@@ -422,7 +422,17 @@ func SessionStoreInterfaceTests(in *testInput) {
422 broken := "BrokenSessionFromADifferentSessionImplementation"
422 broken := "BrokenSessionFromADifferentSessionImplementation"
423 value, err := encryption.SignedValue(in.cookieOpts.Secret, in.cookieOpts.Name, []byte(broken), time.Now())
423 value, err := encryption.SignedValue(in.cookieOpts.Secret, in.cookieOpts.Name, []byte(broken), time.Now())
424 Expect(err).ToNot(HaveOccurred())
424 Expect(err).ToNot(HaveOccurred())
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+ }
425− cookie := cookiesapi.MakeCookieFromOptions(in.request, in.cookieOpts.Name, value, in.cookieOpts, in.cookieOpts.Expire)
435+ cookie := cookiesapi.MakeCookieFromOptions(in.request, cookieOptions)
426 in.request.AddCookie(cookie)
436 in.request.AddCookie(cookie)
427
437
428 err = in.ss().Save(in.response, in.request, in.session)
438 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)
123// The proxy should render an error page if there are failures connecting to the
123// The proxy should render an error page if there are failures connecting to the
124// upstream server.
124// upstream server.
125func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler ProxyErrorHandler) http.Handler {
125func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler ProxyErrorHandler) http.Handler {
126− proxy := httputil.NewSingleHostReverseProxy(target)
126+ proxy := newSingleHostReverseProxy(target)
127
127
128 // Inherit default transport options from Go's stdlib
128 // Inherit default transport options from Go's stdlib
129 transport := http.DefaultTransport.(*http.Transport).Clone()
129 transport := http.DefaultTransport.(*http.Transport).Clone()
@@ -155,7 +155,7 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr
155 }
155 }
156
156
157 // Ensure we always pass the original request path
157 // Ensure we always pass the original request path
158− setProxyDirector(proxy)
158+ setProxyRewrite(proxy)
159
159
160 // TODO (@tuunit) - this should be inverted or get a better name in the future to set the upstream host header
160 // TODO (@tuunit) - this should be inverted or get a better name in the future to set the upstream host header
161 // only if PassHostHeader is explicitly set to true. Currently this would be a breaking change.
161 // 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
179 return proxy
179 return proxy
180}
180}
181
181
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+
182−// setProxyUpstreamHostHeader sets the proxy.Director so that upstream requests
192+// setProxyUpstreamHostHeader sets the proxy.Rewrite so that upstream requests
183// receive a host header matching the target URL.
193// receive a host header matching the target URL.
184func setProxyUpstreamHostHeader(proxy *httputil.ReverseProxy, target *url.URL) {
194func setProxyUpstreamHostHeader(proxy *httputil.ReverseProxy, target *url.URL) {
185− director := proxy.Director
195+ rewrite := proxy.Rewrite
186− proxy.Director = func(req *http.Request) {
196+ proxy.Rewrite = func(proxyReq *httputil.ProxyRequest) {
187− director(req)
197+ rewrite(proxyReq)
188− req.Host = target.Host
198+ proxyReq.Out.Host = target.Host
189 }
199 }
190}
200}
191
201
192−// setProxyDirector sets the proxy.Director so that request URIs are escaped
202+// setProxyRewrite sets the proxy.Rewrite so that request URIs are escaped
193// when proxying to usptream servers.
203// when proxying to usptream servers.
194−func setProxyDirector(proxy *httputil.ReverseProxy) {
204+func setProxyRewrite(proxy *httputil.ReverseProxy) {
195− director := proxy.Director
205+ rewrite := proxy.Rewrite
196− proxy.Director = func(req *http.Request) {
206+ proxy.Rewrite = func(proxyReq *httputil.ProxyRequest) {
197− director(req)
207+ rewrite(proxyReq)
198 // use RequestURI so that we aren't unescaping encoded slashes in the request path
208 // use RequestURI so that we aren't unescaping encoded slashes in the request path
199− req.URL.Opaque = req.RequestURI
209+ proxyReq.Out.URL.Opaque = proxyReq.In.RequestURI
200− req.URL.RawQuery = ""
210+ proxyReq.Out.URL.RawQuery = ""
201− req.URL.ForceQuery = false
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)
202 }
241 }
203}
242}
204
243
205// newWebSocketReverseProxy creates a new reverse proxy for proxying websocket connections.
244// newWebSocketReverseProxy creates a new reverse proxy for proxying websocket connections.
206func newWebSocketReverseProxy(u *url.URL, skipTLSVerify *bool, passHostHeader *bool) http.Handler {
245func newWebSocketReverseProxy(u *url.URL, skipTLSVerify *bool, passHostHeader *bool) http.Handler {
207− wsProxy := httputil.NewSingleHostReverseProxy(u)
246+ wsProxy := newSingleHostReverseProxy(u)
208
247
209 // Inherit default transport options from Go's stdlib
248 // Inherit default transport options from Go's stdlib
210 transport := http.DefaultTransport.(*http.Transport).Clone()
249 transport := http.DefaultTransport.(*http.Transport).Clone()
pkg/upstream/http_test.go+57−3
@@ -361,7 +361,12 @@ var _ = Describe("HTTP Upstream Suite", func() {
361 return http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
361 return http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
362 proxy, ok := h.(*httputil.ReverseProxy)
362 proxy, ok := h.(*httputil.ReverseProxy)
363 Expect(ok).To(BeTrue())
363 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
365 })
370 })
366 }
371 }
367 httpUpstream.handler = requestInterceptor(httpUpstream.handler)
372 httpUpstream.handler = requestInterceptor(httpUpstream.handler)
@@ -370,6 +375,54 @@ var _ = Describe("HTTP Upstream Suite", func() {
370 Expect(req.Host).To(Equal(strings.TrimPrefix(serverAddr, "http://")))
375 Expect(req.Host).To(Equal(strings.TrimPrefix(serverAddr, "http://")))
371 })
376 })
372
377
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+
373 type newUpstreamTableInput struct {
426 type newUpstreamTableInput struct {
374 proxyWebSockets bool
427 proxyWebSockets bool
375 flushInterval time.Duration
428 flushInterval time.Duration
@@ -405,6 +458,7 @@ var _ = Describe("HTTP Upstream Suite", func() {
405
458
406 proxy, ok := upstreamProxy.handler.(*httputil.ReverseProxy)
459 proxy, ok := upstreamProxy.handler.(*httputil.ReverseProxy)
407 Expect(ok).To(BeTrue())
460 Expect(ok).To(BeTrue())
461+ Expect(proxy.Rewrite).ToNot(BeNil())
408 Expect(proxy.FlushInterval).To(Equal(in.flushInterval))
462 Expect(proxy.FlushInterval).To(Equal(in.flushInterval))
409 transport, ok := proxy.Transport.(*http.Transport)
463 transport, ok := proxy.Transport.(*http.Transport)
410 Expect(ok).To(BeTrue())
464 Expect(ok).To(BeTrue())
@@ -498,7 +552,7 @@ var _ = Describe("HTTP Upstream Suite", func() {
498
552
499 handler := newHTTPUpstreamProxy(upstream, u, nil, nil)
553 handler := newHTTPUpstreamProxy(upstream, u, nil, nil)
500
554
501− proxyServer = httptest.NewServer(middleware.NewScope(false, "X-Request-Id")(handler))
555+ proxyServer = httptest.NewServer(middleware.NewScope(false, "X-Request-Id", nil)(handler))
502 })
556 })
503
557
504 AfterEach(func() {
558 AfterEach(func() {
@@ -549,7 +603,7 @@ var _ = Describe("HTTP Upstream Suite", func() {
549 Expect(err).ToNot(HaveOccurred())
603 Expect(err).ToNot(HaveOccurred())
550
604
551 handler := newHTTPUpstreamProxy(upstream, u, nil, nil)
605 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))
553 defer noPassHostServer.Close()
607 defer noPassHostServer.Close()
554
608
555 origin := "http://example.localhost"
609 origin := "http://example.localhost"
pkg/upstream/proxy.go+14−14
@@ -58,7 +58,9 @@ func NewProxy(upstreams options.UpstreamConfig, sigData *options.SignatureData,
58 }
58 }
59 }
59 }
60
60
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+ }
62 return m, nil
64 return m, nil
63}
65}
64
66
@@ -94,8 +96,7 @@ func (m *multiUpstreamProxy) registerHTTPUpstreamProxy(upstream options.Upstream
94// registerHandler ensures the given handler is regiestered with the serveMux.
96// registerHandler ensures the given handler is regiestered with the serveMux.
95func (m *multiUpstreamProxy) registerHandler(upstream options.Upstream, handler http.Handler, writer pagewriter.Writer) error {
97func (m *multiUpstreamProxy) registerHandler(upstream options.Upstream, handler http.Handler, writer pagewriter.Writer) error {
96 if upstream.RewriteTarget == "" {
98 if upstream.RewriteTarget == "" {
97− m.registerSimpleHandler(upstream.Path, handler)
99+ return m.registerSimpleHandler(upstream.Path, handler)
98− return nil
99 }
100 }
100
101
101 return m.registerRewriteHandler(upstream, handler, writer)
102 return m.registerRewriteHandler(upstream, handler, writer)
@@ -103,12 +104,12 @@ func (m *multiUpstreamProxy) registerHandler(upstream options.Upstream, handler
103
104
104// registerSimpleHandler maintains the behaviour of the go standard serveMux
105// registerSimpleHandler maintains the behaviour of the go standard serveMux
105// by ensuring any path with a trailing `/` matches all paths under that prefix.
106// 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 {
107 if strings.HasSuffix(path, "/") {
108 if strings.HasSuffix(path, "/") {
108− m.serveMux.PathPrefix(path).Handler(handler)
109+ return m.serveMux.PathPrefix(path).Handler(handler).GetError()
109− } else {
110− m.serveMux.Path(path).Handler(handler)
111 }
110 }
111+
112+ return m.serveMux.Path(path).Handler(handler).GetError()
112}
113}
113
114
114// registerRewriteHandler ensures the handler is registered for all paths
115// registerRewriteHandler ensures the handler is registered for all paths
@@ -123,19 +124,18 @@ func (m *multiUpstreamProxy) registerRewriteHandler(upstream options.Upstream, h
123
124
124 rewrite := newRewritePath(rewriteRegExp, upstream.RewriteTarget, writer)
125 rewrite := newRewritePath(rewriteRegExp, upstream.RewriteTarget, writer)
125 h := alice.New(rewrite).Then(handler)
126 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)
129
127
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()
131}
131}
132
132
133// registerTrailingSlashHandler creates a new matcher that will check if the
133// registerTrailingSlashHandler creates a new matcher that will check if the
134// requested path would match if it had a trailing slash appended.
134// requested path would match if it had a trailing slash appended.
135// If the path matches with a trailing slash, we send back a redirect.
135// If the path matches with a trailing slash, we send back a redirect.
136// This allows us to be consistent with the built in go servemux implementation.
136// This allows us to be consistent with the built in go servemux implementation.
137−func registerTrailingSlashHandler(serveMux *mux.Router) {
137+func registerTrailingSlashHandler(serveMux *mux.Router) error {
138− serveMux.MatcherFunc(func(req *http.Request, _ *mux.RouteMatch) bool {
138+ return serveMux.MatcherFunc(func(req *http.Request, _ *mux.RouteMatch) bool {
139 if strings.HasSuffix(req.URL.Path, "/") {
139 if strings.HasSuffix(req.URL.Path, "/") {
140 return false
140 return false
141 }
141 }
@@ -149,7 +149,7 @@ func registerTrailingSlashHandler(serveMux *mux.Router) {
149 return serveMux.Match(slashReq, m)
149 return serveMux.Match(slashReq, m)
150 }).Handler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
150 }).Handler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
151 http.Redirect(rw, req, req.URL.String()+"/", http.StatusMovedPermanently)
151 http.Redirect(rw, req, req.URL.String()+"/", http.StatusMovedPermanently)
152− }))
152+ })).GetError()
153}
153}
154
154
155// sortByPathLongest ensures that the upstreams are sorted by longest path.
155// 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() {
79 {
79 {
80 ID: "bad-http-backend",
80 ID: "bad-http-backend",
81 Path: "/bad-http/",
81 Path: "/bad-http/",
82− URI: "http://::1",
82+ URI: invalidServer,
83 },
83 },
84 {
84 {
85 ID: "single-path-backend",
85 ID: "single-path-backend",
@@ -383,6 +383,38 @@ var _ = Describe("Proxy Suite", func() {
383 )
383 )
384 })
384 })
385
385
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+
386 Context("sortByPathLongest", func() {
418 Context("sortByPathLongest", func() {
387 type sortByPathLongestTableInput struct {
419 type sortByPathLongestTableInput struct {
388 input []options.Upstream
420 input []options.Upstream
pkg/upstream/upstream_suite_test.go+1−1
@@ -24,7 +24,7 @@ var (
24 serverAddr string
24 serverAddr string
25 unixServer *httptest.Server
25 unixServer *httptest.Server
26 unixServerAddr string
26 unixServerAddr string
27− invalidServer = "http://::1"
27+ invalidServer = "http://127.0.0.1:1"
28)
28)
29
29
30func TestUpstreamSuite(t *testing.T) {
30func TestUpstreamSuite(t *testing.T) {
pkg/util/util.go+64
@@ -5,6 +5,7 @@ import (
5 "crypto/rsa"
5 "crypto/rsa"
6 "crypto/x509"
6 "crypto/x509"
7 "crypto/x509/pkix"
7 "crypto/x509/pkix"
8+ "encoding/json"
8 "fmt"
9 "fmt"
9 "math/big"
10 "math/big"
10 "net"
11 "net"
@@ -12,6 +13,8 @@ import (
12 "os"
13 "os"
13 "strings"
14 "strings"
14 "time"
15 "time"
16+
17+ "github.com/spf13/cast"
15)
18)
16
19
17func GetCertPool(paths []string, useSystemPool bool) (*x509.CertPool, error) {
20func GetCertPool(paths []string, useSystemPool bool) (*x509.CertPool, error) {
@@ -191,3 +194,64 @@ func RemoveDuplicateStr(strSlice []string) []string {
191 }
194 }
192 return list
195 return list
193}
196}
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
2
2
3import (
3import (
4 "crypto/x509"
4 "crypto/x509"
5+ "encoding/json"
5 "encoding/pem"
6 "encoding/pem"
6 "os"
7 "os"
8+ "reflect"
7 "testing"
9 "testing"
8
10
11+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
9 "github.com/stretchr/testify/assert"
12 "github.com/stretchr/testify/assert"
10)
13)
11
14
@@ -253,3 +256,70 @@ func TestGetCertPool(t *testing.T) {
253 assert.Error(t, err3)
256 assert.Error(t, err3)
254 }
257 }
255}
258}
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 (
11)
11)
12
12
13func validateAllowlists(o *options.Options) []string {
13func validateAllowlists(o *options.Options) []string {
14+ //nolint:prealloc
14 msgs := []string{}
15 msgs := []string{}
15
16
16 msgs = append(msgs, validateAuthRoutes(o)...)
17 msgs = append(msgs, validateAuthRoutes(o)...)
17 msgs = append(msgs, validateAuthRegexes(o)...)
18 msgs = append(msgs, validateAuthRegexes(o)...)
19+ msgs = append(msgs, validateTrustedProxyIPs(o)...)
18 msgs = append(msgs, validateTrustedIPs(o)...)
20 msgs = append(msgs, validateTrustedIPs(o)...)
19
21
20 if len(o.TrustedIPs) > 0 && o.ReverseProxy {
22 if len(o.TrustedIPs) > 0 && o.ReverseProxy {
@@ -27,6 +29,17 @@ func validateAllowlists(o *options.Options) []string {
27 return msgs
29 return msgs
28}
30}
29
31
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+
30// validateAuthRoutes validates method=path routes passed with options.SkipAuthRoutes
43// validateAuthRoutes validates method=path routes passed with options.SkipAuthRoutes
31func validateAuthRoutes(o *options.Options) []string {
44func validateAuthRoutes(o *options.Options) []string {
32 msgs := []string{}
45 msgs := []string{}
pkg/validation/allowlist_test.go+30
@@ -23,6 +23,11 @@ var _ = Describe("Allowlist", func() {
23 errStrings []string
23 errStrings []string
24 }
24 }
25
25
26+ type validateTrustedProxyIPsTableInput struct {
27+ trustedProxyIPs []string
28+ errStrings []string
29+ }
30+
26 DescribeTable("validateRoutes",
31 DescribeTable("validateRoutes",
27 func(r *validateRoutesTableInput) {
32 func(r *validateRoutesTableInput) {
28 opts := &options.Options{
33 opts := &options.Options{
@@ -121,4 +126,29 @@ var _ = Describe("Allowlist", func() {
121 },
126 },
122 }),
127 }),
123 )
128 )
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+ )
124})
154})
pkg/validation/header.go+1
@@ -7,6 +7,7 @@ import (
7)
7)
8
8
9func validateHeaders(headers []options.Header) []string {
9func validateHeaders(headers []options.Header) []string {
10+ //nolint:prealloc
10 msgs := []string{}
11 msgs := []string{}
11 names := make(map[string]struct{})
12 names := make(map[string]struct{})
12
13
pkg/validation/providers.go+35−1
@@ -4,10 +4,27 @@ import (
4 "fmt"
4 "fmt"
5 "os"
5 "os"
6
6
7+ jose "github.com/go-jose/go-jose/v4"
7 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
8 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
8 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
9 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
9)
10)
10
11
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+
11// validateProviders is the initial validation migration for multiple providrers
28// validateProviders is the initial validation migration for multiple providrers
12// It currently includes only logic that can verify the providers one by one and does not break the valdation pipe
29// It currently includes only logic that can verify the providers one by one and does not break the valdation pipe
13func validateProviders(o *options.Options) []string {
30func validateProviders(o *options.Options) []string {
@@ -59,6 +76,22 @@ func validateProvider(provider options.Provider, providerIDs map[string]struct{}
59 msgs = append(msgs, validateEntraConfig(provider)...)
76 msgs = append(msgs, validateEntraConfig(provider)...)
60 }
77 }
61
78
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+
62 return msgs
95 return msgs
63}
96}
64
97
@@ -132,7 +165,8 @@ func validateEntraConfig(provider options.Provider) []string {
132 return msgs
165 return msgs
133 }
166 }
134
167
168+ // #nosec G703 -- AZURE_FEDERATED_TOKEN_FILE is set by the operator, not user input
135− _, err := os.ReadFile(federatedTokenPath)
169+ _, err := os.Stat(federatedTokenPath)
136 if err != nil {
170 if err != nil {
137 msgs = append(msgs, "could not read entra federated token file")
171 msgs = append(msgs, "could not read entra federated token file")
138 }
172 }
pkg/validation/providers_test.go+53
@@ -18,6 +18,33 @@ var _ = Describe("Providers", func() {
18 ClientSecret: "ClientSecret",
18 ClientSecret: "ClientSecret",
19 }
19 }
20
20
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+
21 validLoginGovProvider := options.Provider{
48 validLoginGovProvider := options.Provider{
22 Type: "login.gov",
49 Type: "login.gov",
23 ID: "ProviderIDLoginGov",
50 ID: "ProviderIDLoginGov",
@@ -34,6 +61,8 @@ var _ = Describe("Providers", func() {
34 emptyIDMsg := "provider has empty id: ids are required for all providers"
61 emptyIDMsg := "provider has empty id: ids are required for all providers"
35 duplicateProviderIDMsg := "multiple providers found with id ProviderID: provider ids must be unique"
62 duplicateProviderIDMsg := "multiple providers found with id ProviderID: provider ids must be unique"
36 skipButtonAndMultipleProvidersMsg := "SkipProviderButton and multiple providers are mutually exclusive"
63 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\""
37
66
38 DescribeTable("validateProviders",
67 DescribeTable("validateProviders",
39 func(o *validateProvidersTableInput) {
68 func(o *validateProvidersTableInput) {
@@ -79,5 +108,29 @@ var _ = Describe("Providers", func() {
79 },
108 },
80 errStrings: []string{skipButtonAndMultipleProvidersMsg},
109 errStrings: []string{skipButtonAndMultipleProvidersMsg},
81 }),
110 }),
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+ }),
82 )
135 )
83})
136})
pkg/validation/sessions_test.go+2−2
@@ -193,8 +193,8 @@ var _ = Describe("Sessions", func() {
193 unreachableRedisDelMsg = "unable to delete the redis initialization key: dial tcp 127.0.0.1:65535: connect: connection refused"
193 unreachableRedisDelMsg = "unable to delete the redis initialization key: dial tcp 127.0.0.1:65535: connect: connection refused"
194 unreachableSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: redis: nil"
194 unreachableSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: redis: nil"
195 unrechableSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable: redis: nil"
195 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"
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: context deadline exceeded"
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"
198 )
198 )
199
199
200 type redisStoreTableInput struct {
200 type redisStoreTableInput struct {
pkg/validation/upstreams.go+4−3
@@ -9,6 +9,7 @@ import (
9)
9)
10
10
11func validateUpstreams(upstreams options.UpstreamConfig) []string {
11func validateUpstreams(upstreams options.UpstreamConfig) []string {
12+ //nolint:prealloc
12 msgs := []string{}
13 msgs := []string{}
13 ids := make(map[string]struct{})
14 ids := make(map[string]struct{})
14 paths := make(map[string]struct{})
15 paths := make(map[string]struct{})
@@ -70,13 +71,13 @@ func validateStaticUpstream(upstream options.Upstream) []string {
70 if ptr.Deref(upstream.InsecureSkipTLSVerify, options.DefaultUpsteamInsecureSkipTLSVerify) {
71 if ptr.Deref(upstream.InsecureSkipTLSVerify, options.DefaultUpsteamInsecureSkipTLSVerify) {
71 msgs = append(msgs, fmt.Sprintf("upstream %q has insecureSkipTLSVerify, but is a static upstream, this will have no effect.", upstream.ID))
72 msgs = append(msgs, fmt.Sprintf("upstream %q has insecureSkipTLSVerify, but is a static upstream, this will have no effect.", upstream.ID))
72 }
73 }
73− if upstream.FlushInterval != nil && *upstream.FlushInterval != options.DefaultUpstreamFlushInterval {
74+ if ptr.Deref(upstream.FlushInterval, options.DefaultUpstreamFlushInterval) != options.DefaultUpstreamFlushInterval {
74 msgs = append(msgs, fmt.Sprintf("upstream %q has flushInterval, but is a static upstream, this will have no effect.", upstream.ID))
75 msgs = append(msgs, fmt.Sprintf("upstream %q has flushInterval, but is a static upstream, this will have no effect.", upstream.ID))
75 }
76 }
76− if upstream.PassHostHeader != nil {
77+ if ptr.Deref(upstream.PassHostHeader, options.DefaultStaticPassHostHeader) != options.DefaultStaticPassHostHeader {
77 msgs = append(msgs, fmt.Sprintf("upstream %q has passHostHeader, but is a static upstream, this will have no effect.", upstream.ID))
78 msgs = append(msgs, fmt.Sprintf("upstream %q has passHostHeader, but is a static upstream, this will have no effect.", upstream.ID))
78 }
79 }
79− if upstream.ProxyWebSockets != nil {
80+ if ptr.Deref(upstream.ProxyWebSockets, options.DefaultStaticProxyWebSockets) != options.DefaultStaticProxyWebSockets {
80 msgs = append(msgs, fmt.Sprintf("upstream %q has proxyWebSockets, but is a static upstream, this will have no effect.", upstream.ID))
81 msgs = append(msgs, fmt.Sprintf("upstream %q has proxyWebSockets, but is a static upstream, this will have no effect.", upstream.ID))
81 }
82 }
82
83
pkg/validation/upstreams_test.go+19−1
@@ -138,7 +138,7 @@ var _ = Describe("Upstreams", func() {
138 },
138 },
139 errStrings: []string{invalidURISchemeMsg},
139 errStrings: []string{invalidURISchemeMsg},
140 }),
140 }),
141− Entry("with a static upstream and invalid optons", &validateUpstreamTableInput{
141+ Entry("with a static upstream and invalid options", &validateUpstreamTableInput{
142 upstreams: options.UpstreamConfig{
142 upstreams: options.UpstreamConfig{
143 Upstreams: []options.Upstream{
143 Upstreams: []options.Upstream{
144 {
144 {
@@ -161,6 +161,24 @@ var _ = Describe("Upstreams", func() {
161 staticWithProxyWebSocketsMsg,
161 staticWithProxyWebSocketsMsg,
162 },
162 },
163 }),
163 }),
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+ }),
164 Entry("with duplicate IDs", &validateUpstreamTableInput{
182 Entry("with duplicate IDs", &validateUpstreamTableInput{
165 upstreams: options.UpstreamConfig{
183 upstreams: options.UpstreamConfig{
166 Upstreams: []options.Upstream{
184 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
166
166
167 err = requests.New(p.RedeemURL.String()).
167 err = requests.New(p.RedeemURL.String()).
168 WithContext(ctx).
168 WithContext(ctx).
169− WithMethod("POST").
169+ WithMethod(http.MethodPost).
170 WithBody(bytes.NewBufferString(params.Encode())).
170 WithBody(bytes.NewBufferString(params.Encode())).
171 SetHeader("Content-Type", "application/x-www-form-urlencoded").
171 SetHeader("Content-Type", "application/x-www-form-urlencoded").
172 Do().
172 Do().
@@ -334,7 +334,7 @@ func (p *AzureProvider) redeemRefreshToken(ctx context.Context, s *sessions.Sess
334
334
335 err = requests.New(p.RedeemURL.String()).
335 err = requests.New(p.RedeemURL.String()).
336 WithContext(ctx).
336 WithContext(ctx).
337− WithMethod("POST").
337+ WithMethod(http.MethodPost).
338 WithBody(bytes.NewBufferString(params.Encode())).
338 WithBody(bytes.NewBufferString(params.Encode())).
339 SetHeader("Content-Type", "application/x-www-form-urlencoded").
339 SetHeader("Content-Type", "application/x-www-form-urlencoded").
340 Do().
340 Do().
@@ -399,6 +399,7 @@ func (p *AzureProvider) getGroupsFromProfileAPI(ctx context.Context, s *sessions
399}
399}
400
400
401func getGroupsFromJSON(json *simplejson.Json, graphGroupField string) []string {
401func getGroupsFromJSON(json *simplejson.Json, graphGroupField string) []string {
402+ //nolint:prealloc
402 groups := []string{}
403 groups := []string{}
403
404
404 for i := range json.Get("value").MustArray() {
405 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
219
219
220 err = requests.New(p.RedeemURL.String()).
220 err = requests.New(p.RedeemURL.String()).
221 WithContext(ctx).
221 WithContext(ctx).
222− WithMethod("POST").
222+ WithMethod(http.MethodPost).
223 WithBody(bytes.NewBufferString(params.Encode())).
223 WithBody(bytes.NewBufferString(params.Encode())).
224 SetHeader("Content-Type", "application/x-www-form-urlencoded").
224 SetHeader("Content-Type", "application/x-www-form-urlencoded").
225 Do().
225 Do().
@@ -543,7 +543,7 @@ func (p *GoogleProvider) redeemRefreshToken(ctx context.Context, s *sessions.Ses
543
543
544 err = requests.New(p.RedeemURL.String()).
544 err = requests.New(p.RedeemURL.String()).
545 WithContext(ctx).
545 WithContext(ctx).
546− WithMethod("POST").
546+ WithMethod(http.MethodPost).
547 WithBody(bytes.NewBufferString(params.Encode())).
547 WithBody(bytes.NewBufferString(params.Encode())).
548 SetHeader("Content-Type", "application/x-www-form-urlencoded").
548 SetHeader("Content-Type", "application/x-www-form-urlencoded").
549 Do().
549 Do().
providers/keycloak_oidc.go+1
@@ -89,6 +89,7 @@ func (p *KeycloakOIDCProvider) extractRoles(s *sessions.SessionState) error {
89 return err
89 return err
90 }
90 }
91
91
92+ //nolint:prealloc
92 var roles []string
93 var roles []string
93 roles = append(roles, claims.RealmAccess.Roles...)
94 roles = append(roles, claims.RealmAccess.Roles...)
94 roles = append(roles, getClientRoles(claims)...)
95 roles = append(roles, getClientRoles(claims)...)
providers/logingov.go+2−1
@@ -8,6 +8,7 @@ import (
8 "errors"
8 "errors"
9 "fmt"
9 "fmt"
10 "math/big"
10 "math/big"
11+ "net/http"
11 "net/url"
12 "net/url"
12 "os"
13 "os"
13 "time"
14 "time"
@@ -237,7 +238,7 @@ func (p *LoginGovProvider) Redeem(ctx context.Context, _, code, codeVerifier str
237 }
238 }
238 err = requests.New(p.RedeemURL.String()).
239 err = requests.New(p.RedeemURL.String()).
239 WithContext(ctx).
240 WithContext(ctx).
240− WithMethod("POST").
241+ WithMethod(http.MethodPost).
241 WithBody(bytes.NewBufferString(params.Encode())).
242 WithBody(bytes.NewBufferString(params.Encode())).
242 SetHeader("Content-Type", "application/x-www-form-urlencoded").
243 SetHeader("Content-Type", "application/x-www-form-urlencoded").
243 Do().
244 Do().
providers/ms_entra_id.go+4−1
@@ -5,6 +5,7 @@ import (
5 "context"
5 "context"
6 "encoding/json"
6 "encoding/json"
7 "fmt"
7 "fmt"
8+ "net/http"
8 "net/url"
9 "net/url"
9 "os"
10 "os"
10 "regexp"
11 "regexp"
@@ -110,6 +111,7 @@ func (p *MicrosoftEntraIDProvider) Redeem(ctx context.Context, redirectURL, code
110// redeemWithFederatedToken performs custom token exchange with federated token instead of client secret
111// redeemWithFederatedToken performs custom token exchange with federated token instead of client secret
111func (p *MicrosoftEntraIDProvider) redeemWithFederatedToken(ctx context.Context, redirectURL, code, codeVerifier string) (*sessions.SessionState, error) {
112func (p *MicrosoftEntraIDProvider) redeemWithFederatedToken(ctx context.Context, redirectURL, code, codeVerifier string) (*sessions.SessionState, error) {
112 federatedTokenPath := os.Getenv("AZURE_FEDERATED_TOKEN_FILE")
113 federatedTokenPath := os.Getenv("AZURE_FEDERATED_TOKEN_FILE")
114+ // #nosec G703 -- AZURE_FEDERATED_TOKEN_FILE is set by the operator, not user input
113 federatedToken, err := os.ReadFile(federatedTokenPath)
115 federatedToken, err := os.ReadFile(federatedTokenPath)
114 if err != nil {
116 if err != nil {
115 return nil, fmt.Errorf("error reading federated token file %s: %s", federatedTokenPath, err)
117 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
162// Refresh Token, Access Token and ID Token
164// Refresh Token, Access Token and ID Token
163func (p *MicrosoftEntraIDProvider) redeemRefreshTokenWithFederatedToken(ctx context.Context, s *sessions.SessionState) error {
165func (p *MicrosoftEntraIDProvider) redeemRefreshTokenWithFederatedToken(ctx context.Context, s *sessions.SessionState) error {
164 federatedTokenPath := os.Getenv("AZURE_FEDERATED_TOKEN_FILE")
166 federatedTokenPath := os.Getenv("AZURE_FEDERATED_TOKEN_FILE")
167+ // #nosec G703 -- AZURE_FEDERATED_TOKEN_FILE is set by the operator, not user input
165 federatedToken, err := os.ReadFile(federatedTokenPath)
168 federatedToken, err := os.ReadFile(federatedTokenPath)
166 if err != nil {
169 if err != nil {
167 return fmt.Errorf("error reading federated token file %s: %s", federatedTokenPath, err)
170 return fmt.Errorf("error reading federated token file %s: %s", federatedTokenPath, err)
@@ -302,7 +305,7 @@ func (p *MicrosoftEntraIDProvider) checkTenantMatchesTenantList(tenant string, a
302func (p *MicrosoftEntraIDProvider) fetchToken(ctx context.Context, params url.Values) (*oauth2.Token, error) {
305func (p *MicrosoftEntraIDProvider) fetchToken(ctx context.Context, params url.Values) (*oauth2.Token, error) {
303 resp := requests.New(p.RedeemURL.String()).
306 resp := requests.New(p.RedeemURL.String()).
304 WithContext(ctx).
307 WithContext(ctx).
305− WithMethod("POST").
308+ WithMethod(http.MethodPost).
306 WithBody(bytes.NewBufferString(params.Encode())).
309 WithBody(bytes.NewBufferString(params.Encode())).
307 SetHeader("Content-Type", "application/x-www-form-urlencoded").
310 SetHeader("Content-Type", "application/x-www-form-urlencoded").
308 Do()
311 Do()
providers/provider_data.go+44−5
@@ -45,11 +45,26 @@ type ProviderData struct {
45 SupportedCodeChallengeMethods []string `json:"code_challenge_methods_supported,omitempty"`
45 SupportedCodeChallengeMethods []string `json:"code_challenge_methods_supported,omitempty"`
46
46
47 // Common OIDC options for any OIDC-based providers to consume
47 // Common OIDC options for any OIDC-based providers to consume
48− AllowUnverifiedEmail bool
48+ AllowUnverifiedEmail bool
49+
50+ // UserClaim is the claim to use for populating the SessionState.User field. Defaults to "sub" if not set.
49− UserClaim string
51+ UserClaim string
50− EmailClaim 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.
51− GroupsClaim string
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.
52− Verifier internaloidc.IDTokenVerifier
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.
53 SkipClaimsFromProfileURL bool
68 SkipClaimsFromProfileURL bool
54
69
55 // Universal Group authorization data structure
70 // Universal Group authorization data structure
@@ -179,6 +194,10 @@ func regexpForRule(rule options.URLParameterRule) string {
179func (p *ProviderData) setAllowedGroups(groups []string) {
194func (p *ProviderData) setAllowedGroups(groups []string) {
180 p.AllowedGroups = make(map[string]struct{}, len(groups))
195 p.AllowedGroups = make(map[string]struct{}, len(groups))
181 for _, group := range groups {
196 for _, group := range groups {
197+ if len(group) == 0 {
198+ continue
199+ }
200+
182 p.AllowedGroups[group] = struct{}{}
201 p.AllowedGroups[group] = struct{}{}
183 }
202 }
184}
203}
@@ -268,6 +287,10 @@ func (p *ProviderData) buildSessionFromClaims(rawIDToken, accessToken string) (*
268 }
287 }
269 }
288 }
270
289
290+ if p.AdditionalClaims != nil {
291+ p.extractAdditionalClaims(extractor, ss)
292+ }
293+
271 // `email_verified` must be present and explicitly set to `false` to be
294 // `email_verified` must be present and explicitly set to `false` to be
272 // considered unverified.
295 // considered unverified.
273 verifyEmail := (p.EmailClaim == options.OIDCEmailClaim) && !p.AllowUnverifiedEmail
296 verifyEmail := (p.EmailClaim == options.OIDCEmailClaim) && !p.AllowUnverifiedEmail
@@ -301,6 +324,22 @@ func (p *ProviderData) getClaimExtractor(rawIDToken, accessToken string) (util.C
301 return extractor, nil
324 return extractor, nil
302}
325}
303
326
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+
304// checkNonce compares the session's nonce with the IDToken's nonce claim
343// checkNonce compares the session's nonce with the IDToken's nonce claim
305func (p *ProviderData) checkNonce(s *sessions.SessionState) error {
344func (p *ProviderData) checkNonce(s *sessions.SessionState) error {
306 extractor, err := p.getClaimExtractor(s.IDToken, "")
345 extractor, err := p.getClaimExtractor(s.IDToken, "")
providers/provider_data_test.go+23
@@ -237,6 +237,7 @@ func TestProviderData_buildSessionFromClaims(t *testing.T) {
237 ExpectedError error
237 ExpectedError error
238 ExpectedSession *sessions.SessionState
238 ExpectedSession *sessions.SessionState
239 ExpectProfileURLCalled bool
239 ExpectProfileURLCalled bool
240+ AdditionalClaims []string
240 }{
241 }{
241 "Standard": {
242 "Standard": {
242 IDToken: defaultIDToken,
243 IDToken: defaultIDToken,
@@ -417,6 +418,27 @@ func TestProviderData_buildSessionFromClaims(t *testing.T) {
417 SkipClaimsFromProfileURL: true,
418 SkipClaimsFromProfileURL: true,
418 ExpectedSession: &sessions.SessionState{},
419 ExpectedSession: &sessions.SessionState{},
419 },
420 },
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+ },
420 }
442 }
421 for testName, tc := range testCases {
443 for testName, tc := range testCases {
422 t.Run(testName, func(t *testing.T) {
444 t.Run(testName, func(t *testing.T) {
@@ -453,6 +475,7 @@ func TestProviderData_buildSessionFromClaims(t *testing.T) {
453 provider.EmailClaim = tc.EmailClaim
475 provider.EmailClaim = tc.EmailClaim
454 provider.GroupsClaim = tc.GroupsClaim
476 provider.GroupsClaim = tc.GroupsClaim
455 provider.SkipClaimsFromProfileURL = tc.SkipClaimsFromProfileURL
477 provider.SkipClaimsFromProfileURL = tc.SkipClaimsFromProfileURL
478+ provider.AdditionalClaims = tc.AdditionalClaims
456
479
457 rawIDToken, err := newSignedTestIDToken(tc.IDToken)
480 rawIDToken, err := newSignedTestIDToken(tc.IDToken)
458 g.Expect(err).ToNot(HaveOccurred())
481 g.Expect(err).ToNot(HaveOccurred())
providers/provider_default.go+2−1
@@ -5,6 +5,7 @@ import (
5 "context"
5 "context"
6 "errors"
6 "errors"
7 "fmt"
7 "fmt"
8+ "net/http"
8 "net/url"
9 "net/url"
9
10
10 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
11 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
@@ -71,7 +72,7 @@ func (p *ProviderData) Redeem(ctx context.Context, redirectURL, code, codeVerifi
71
72
72 result := requests.New(p.RedeemURL.String()).
73 result := requests.New(p.RedeemURL.String()).
73 WithContext(ctx).
74 WithContext(ctx).
74− WithMethod("POST").
75+ WithMethod(http.MethodPost).
75 WithBody(bytes.NewBufferString(params.Encode())).
76 WithBody(bytes.NewBufferString(params.Encode())).
76 SetHeader("Content-Type", "application/x-www-form-urlencoded").
77 SetHeader("Content-Type", "application/x-www-form-urlencoded").
77 Do()
78 Do()
providers/provider_default_test.go+12
@@ -102,6 +102,18 @@ func TestProviderDataAuthorize(t *testing.T) {
102 groups: []string{"baz", "foo"},
102 groups: []string{"baz", "foo"},
103 expectedAuthZ: false,
103 expectedAuthZ: false,
104 },
104 },
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+ },
105 }
117 }
106
118
107 for _, tc := range testCases {
119 for _, tc := range testCases {
providers/providers.go+9−3
@@ -40,6 +40,8 @@ func NewProvider(providerConfig options.Provider) (Provider, error) {
40 switch providerConfig.Type {
40 switch providerConfig.Type {
41 case options.ADFSProvider:
41 case options.ADFSProvider:
42 return NewADFSProvider(providerData, providerConfig), nil
42 return NewADFSProvider(providerData, providerConfig), nil
43+ case options.AtlassianProvider:
44+ return NewAtlassianProvider(providerData), nil
43 case options.AzureProvider:
45 case options.AzureProvider:
44 return NewAzureProvider(providerData, providerConfig.AzureConfig), nil
46 return NewAzureProvider(providerData, providerConfig.AzureConfig), nil
45 case options.MicrosoftEntraIDProvider:
47 case options.MicrosoftEntraIDProvider:
@@ -50,6 +52,8 @@ func NewProvider(providerConfig options.Provider) (Provider, error) {
50 return NewCIDAASProvider(providerData, providerConfig), nil
52 return NewCIDAASProvider(providerData, providerConfig), nil
51 case options.DigitalOceanProvider:
53 case options.DigitalOceanProvider:
52 return NewDigitalOceanProvider(providerData), nil
54 return NewDigitalOceanProvider(providerData), nil
55+ case options.DTTSSOProvider:
56+ return NewDTTSSOProvider(providerData), nil
53 case options.FacebookProvider:
57 case options.FacebookProvider:
54 return NewFacebookProvider(providerData), nil
58 return NewFacebookProvider(providerData), nil
55 case options.GitHubProvider:
59 case options.GitHubProvider:
@@ -84,6 +88,7 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData,
84 ClientSecret: providerConfig.ClientSecret,
88 ClientSecret: providerConfig.ClientSecret,
85 ClientSecretFile: providerConfig.ClientSecretFile,
89 ClientSecretFile: providerConfig.ClientSecretFile,
86 AuthRequestResponseMode: providerConfig.AuthRequestResponseMode,
90 AuthRequestResponseMode: providerConfig.AuthRequestResponseMode,
91+ AdditionalClaims: providerConfig.AdditionalClaims,
87 }
92 }
88
93
89 needsVerifier, err := providerRequiresOIDCProviderVerifier(providerConfig.Type)
94 needsVerifier, err := providerRequiresOIDCProviderVerifier(providerConfig.Type)
@@ -99,6 +104,7 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData,
99 IssuerURL: providerConfig.OIDCConfig.IssuerURL,
104 IssuerURL: providerConfig.OIDCConfig.IssuerURL,
100 JWKsURL: providerConfig.OIDCConfig.JwksURL,
105 JWKsURL: providerConfig.OIDCConfig.JwksURL,
101 PublicKeyFiles: providerConfig.OIDCConfig.PublicKeyFiles,
106 PublicKeyFiles: providerConfig.OIDCConfig.PublicKeyFiles,
107+ SupportedSigningAlgs: providerConfig.OIDCConfig.EnabledSigningAlgs,
102 SkipDiscovery: ptr.Deref(providerConfig.OIDCConfig.SkipDiscovery, options.DefaultSkipDiscovery),
108 SkipDiscovery: ptr.Deref(providerConfig.OIDCConfig.SkipDiscovery, options.DefaultSkipDiscovery),
103 SkipIssuerVerification: ptr.Deref(providerConfig.OIDCConfig.InsecureSkipIssuerVerification, options.DefaultInsecureSkipIssuerVerification),
109 SkipIssuerVerification: ptr.Deref(providerConfig.OIDCConfig.InsecureSkipIssuerVerification, options.DefaultInsecureSkipIssuerVerification),
104 })
110 })
@@ -187,9 +193,9 @@ func parseCodeChallengeMethod(providerConfig options.Provider) string {
187
193
188func providerRequiresOIDCProviderVerifier(providerType options.ProviderType) (bool, error) {
194func providerRequiresOIDCProviderVerifier(providerType options.ProviderType) (bool, error) {
189 switch providerType {
195 switch providerType {
190− case options.BitbucketProvider, options.DigitalOceanProvider, options.FacebookProvider, options.GitHubProvider,
196+ case options.AtlassianProvider, options.BitbucketProvider, options.DigitalOceanProvider, options.DTTSSOProvider,
191− options.GoogleProvider, options.KeycloakProvider, options.LinkedInProvider, options.LoginGovProvider,
197+ options.FacebookProvider, options.GitHubProvider, options.GoogleProvider, options.KeycloakProvider,
192− options.NextCloudProvider, options.SourceHutProvider:
198+ options.LinkedInProvider, options.LoginGovProvider, options.NextCloudProvider, options.SourceHutProvider:
193 return false, nil
199 return false, nil
194 case options.OIDCProvider, options.ADFSProvider, options.AzureProvider, options.CidaasProvider,
200 case options.OIDCProvider, options.ADFSProvider, options.AzureProvider, options.CidaasProvider,
195 options.GitLabProvider, options.KeycloakOIDCProvider, options.MicrosoftEntraIDProvider:
201 options.GitLabProvider, options.KeycloakOIDCProvider, options.MicrosoftEntraIDProvider:
providers/providers_test.go+90
@@ -1,9 +1,14 @@
1package providers
1package providers
2
2
3import (
3import (
4+ "context"
5+ "net"
4 "os"
6 "os"
5 "testing"
7 "testing"
8+ "time"
6
9
10+ "github.com/golang-jwt/jwt/v5"
11+ "github.com/oauth2-proxy/mockoidc"
7 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
12 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
8 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
13 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
9 . "github.com/onsi/gomega"
14 . "github.com/onsi/gomega"
@@ -121,6 +126,91 @@ func TestURLsCorrectlyParsed(t *testing.T) {
121 g.Expect(pd.RedeemURL.String()).To(Equal(msTokenURL))
126 g.Expect(pd.RedeemURL.String()).To(Equal(msTokenURL))
122}
127}
123
128
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+
124func TestScope(t *testing.T) {
214func TestScope(t *testing.T) {
125 g := NewWithT(t)
215 g := NewWithT(t)
126
216
providers/srht.go+2−1
@@ -4,6 +4,7 @@ import (
4 "bytes"
4 "bytes"
5 "context"
5 "context"
6 "fmt"
6 "fmt"
7+ "net/http"
7 "net/url"
8 "net/url"
8
9
9 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
10 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
@@ -75,7 +76,7 @@ func NewSourceHutProvider(p *ProviderData) *SourceHutProvider {
75func (p *SourceHutProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error {
76func (p *SourceHutProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error {
76 json, err := requests.New(p.ProfileURL.String()).
77 json, err := requests.New(p.ProfileURL.String()).
77 WithContext(ctx).
78 WithContext(ctx).
78− WithMethod("POST").
79+ WithMethod(http.MethodPost).
79 SetHeader("Content-Type", "application/json").
80 SetHeader("Content-Type", "application/json").
80 SetHeader("Authorization", "Bearer "+s.AccessToken).
81 SetHeader("Authorization", "Bearer "+s.AccessToken).
81 WithBody(bytes.NewBufferString(`{"query": "{ me { username, email } }"}`)).
82 WithBody(bytes.NewBufferString(`{"query": "{ me { username, email } }"}`)).
providers/util_test.go+33
@@ -1,9 +1,12 @@
1package providers
1package providers
2
2
3import (
3import (
4+ "encoding/json"
4 "fmt"
5 "fmt"
6+ "net/http"
5 "testing"
7 "testing"
6
8
9+ "github.com/oauth2-proxy/mockoidc"
7 . "github.com/onsi/gomega"
10 . "github.com/onsi/gomega"
8 "golang.org/x/oauth2"
11 "golang.org/x/oauth2"
9)
12)
@@ -111,3 +114,33 @@ func Test_formatGroup(t *testing.T) {
111 })
114 })
112 }
115 }
113}
116}
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 {
110
110
111// isEmailValidWithDomains checks if the authenticated email is validated against the provided domain
111// isEmailValidWithDomains checks if the authenticated email is validated against the provided domain
112func isEmailValidWithDomains(email string, allowedDomains []string) bool {
112func isEmailValidWithDomains(email string, allowedDomains []string) bool {
113+ if strings.Count(email, "@") != 1 {
114+ return false
115+ }
116+
113 for _, domain := range allowedDomains {
117 for _, domain := range allowedDomains {
114 // allow if the domain is perfect suffix match with the email
118 // allow if the domain is perfect suffix match with the email
115 if strings.HasSuffix(email, "@"+domain) {
119 if strings.HasSuffix(email, "@"+domain) {
@@ -119,7 +123,6 @@ func isEmailValidWithDomains(email string, allowedDomains []string) bool {
119 // allow if the domain is prefixed with . or *. and
123 // allow if the domain is prefixed with . or *. and
120 // the last element (split on @) has the suffix as the domain
124 // the last element (split on @) has the suffix as the domain
121 atoms := strings.Split(email, "@")
125 atoms := strings.Split(email, "@")
122−
123 if (strings.HasPrefix(domain, ".") && strings.HasSuffix(atoms[len(atoms)-1], domain)) ||
126 if (strings.HasPrefix(domain, ".") && strings.HasSuffix(atoms[len(atoms)-1], domain)) ||
124 (strings.HasPrefix(domain, "*.") && strings.HasSuffix(atoms[len(atoms)-1], domain[1:])) {
127 (strings.HasPrefix(domain, "*.") && strings.HasSuffix(atoms[len(atoms)-1], domain[1:])) {
125 return true
128 return true
validator_test.go+21
@@ -404,6 +404,27 @@ func TestValidatorCases(t *testing.T) {
404 allowedDomains: []string{"*.company.com"},
404 allowedDomains: []string{"*.company.com"},
405 expectedAuthZ: false,
405 expectedAuthZ: false,
406 },
406 },
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+ },
407 }
428 }
408
429
409 for _, tc := range testCases {
430 for _, tc := range testCases {