From c8c160da79436068f246fcdc80e3aed73c1c3002 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 11 Jul 2025 09:58:16 +0200 Subject: [PATCH 001/125] Create FUNDING.yml --- .github/FUNDING.yml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .github/FUNDING.yml diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000000..dd45098008 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,15 @@ +# These are supported funding model platforms + +github: tuunit # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: oauth2-proxy # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry +polar: # Replace with a single Polar username +buy_me_a_coffee: # Replace with a single Buy Me a Coffee username +thanks_dev: # Replace with a single thanks.dev username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] From abb0a35bf33fb6c17312a849ef57d113c5c01f60 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Sun, 13 Jul 2025 14:55:57 -0500 Subject: [PATCH 002/125] feat: bump to go1.24.5 and full dependency update (#3116) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * upgrade to go1.24.5 dependency updates lint fixes chore(deps): upgrade github.com/spf13/viper to v1.20.1 Note that this upgrade also implied to upgrade github.com/mitchellh/mapstructure (nowadays unmaintained: https://gist.github.com/mitchellh/90029601268e59a29e64e55bab1c5bdc) to github.com/go-viper/mapstructure/v2. fix: adapt tests to match mapstructure v2 error messages pkg/apis/options/load_test.go: skip tests on Go 1.23 Add a compile guard for Go < 1.24 for the pkg/apis/options/load_test.go because the LoadYAML test depends on error messages produced by encoding/json that changed slightly (names of embedded structs are now reported). As we updated the test for go1.24, the test now fails on 1.23, but just for a slight difference, so we disable the test there. fix: adapt tests to match mapstructure v2 error messages remove pre 1.24 disclaimer add changelog entry Signed-off-by: Jan Larwig Co-Authored-By: Olivier Mengué * add exclusion for 'avoid meaningless package names' in .golangci.yml * chore(dep): upgrade all dependencies Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Olivier Mengué Co-authored-by: Jan Larwig --- .golangci.yml | 4 + CHANGELOG.md | 1 + go.mod | 90 ++++++------- go.sum | 227 +++++++++++++++++--------------- main_test.go | 4 +- pkg/apis/options/load.go | 2 +- pkg/apis/options/load_test.go | 4 +- pkg/encryption/cipher.go | 4 +- pkg/validation/sessions_test.go | 8 +- 9 files changed, 177 insertions(+), 167 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 0ebecab619..edab12d06e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -49,6 +49,10 @@ linters: - linters: - staticcheck text: QF1008 + - linters: + - revive + path: util/.*\.go$ + text: "var-naming: avoid meaningless package names" paths: - third_party$ - builtin$ diff --git a/CHANGELOG.md b/CHANGELOG.md index eb7b3e2bb5..013f32b550 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ## Changes since v7.9.0 - [#3072](https://github.com/oauth2-proxy/oauth2-proxy/pull/3072) feat: support for multiple github orgs #3072 (@daniel-mersch) +- [#3116](https://github.com/oauth2-proxy/oauth2-proxy/pull/3116) feat: bump to go1.24.5 and full dependency update (@wardviaene / @dolmen) # V7.9.0 diff --git a/go.mod b/go.mod index 9d7079c17e..087dad8afa 100644 --- a/go.mod +++ b/go.mod @@ -1,97 +1,91 @@ module github.com/oauth2-proxy/oauth2-proxy/v7 -go 1.23.8 +go 1.24.5 require ( - cloud.google.com/go/compute/metadata v0.6.0 + cloud.google.com/go/compute/metadata v0.7.0 github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb - github.com/a8m/envsubst v1.4.2 - github.com/alicebob/miniredis/v2 v2.34.0 + github.com/a8m/envsubst v1.4.3 + github.com/alicebob/miniredis/v2 v2.35.0 github.com/benbjohnson/clock v1.3.5 github.com/bitly/go-simplejson v0.5.1 github.com/bsm/redislock v0.9.4 - github.com/coreos/go-oidc/v3 v3.13.0 + github.com/coreos/go-oidc/v3 v3.14.1 github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf - github.com/fsnotify/fsnotify v1.8.0 + github.com/fsnotify/fsnotify v1.9.0 github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 github.com/go-jose/go-jose/v3 v3.0.4 + github.com/go-viper/mapstructure/v2 v2.3.0 github.com/golang-jwt/jwt/v5 v5.2.2 github.com/google/go-cmp v0.7.0 github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 github.com/justinas/alice v1.2.0 github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa - github.com/mitchellh/mapstructure v1.5.0 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 - github.com/onsi/ginkgo/v2 v2.23.3 - github.com/onsi/gomega v1.36.3 + github.com/onsi/ginkgo/v2 v2.23.4 + github.com/onsi/gomega v1.37.0 github.com/pierrec/lz4/v4 v4.1.22 - github.com/prometheus/client_golang v1.21.1 - github.com/redis/go-redis/v9 v9.7.3 - github.com/spf13/cast v1.7.1 + github.com/prometheus/client_golang v1.22.0 + github.com/redis/go-redis/v9 v9.11.0 + github.com/spf13/cast v1.9.2 github.com/spf13/pflag v1.0.6 - github.com/spf13/viper v1.19.0 + github.com/spf13/viper v1.20.1 github.com/stretchr/testify v1.10.0 github.com/vmihailenco/msgpack/v5 v5.4.1 - golang.org/x/crypto v0.36.0 - golang.org/x/net v0.38.0 - golang.org/x/oauth2 v0.28.0 - golang.org/x/sync v0.12.0 - google.golang.org/api v0.228.0 + golang.org/x/crypto v0.40.0 + golang.org/x/net v0.42.0 + golang.org/x/oauth2 v0.30.0 + golang.org/x/sync v0.16.0 + google.golang.org/api v0.241.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 - k8s.io/apimachinery v0.32.3 + k8s.io/apimachinery v0.33.2 ) require ( - cloud.google.com/go/auth v0.15.0 // indirect + cloud.google.com/go/auth v0.16.2 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect - github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/go-jose/go-jose/v4 v4.0.5 // indirect - github.com/go-logr/logr v1.4.2 // indirect + github.com/go-jose/go-jose/v4 v4.1.1 // indirect + github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-task/slim-sprig/v3 v3.0.0 // indirect - github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad // indirect + github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5 // indirect github.com/google/s2a-go v0.1.9 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect - github.com/googleapis/gax-go/v2 v2.14.1 // indirect - github.com/hashicorp/hcl v1.0.0 // indirect - github.com/klauspost/compress v1.17.11 // indirect + github.com/googleapis/gax-go/v2 v2.15.0 // indirect github.com/kylelemons/godebug v1.1.0 // indirect - github.com/magiconair/properties v1.8.7 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/pelletier/go-toml/v2 v2.2.3 // indirect + github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/prometheus/client_model v0.6.1 // indirect - github.com/prometheus/common v0.62.0 // indirect - github.com/prometheus/procfs v0.15.1 // indirect - github.com/sagikazarmark/locafero v0.7.0 // indirect - github.com/sagikazarmark/slog-shim v0.1.0 // indirect + github.com/prometheus/client_model v0.6.2 // indirect + github.com/prometheus/common v0.65.0 // indirect + github.com/prometheus/procfs v0.17.0 // indirect + github.com/rogpeppe/go-internal v1.14.1 // indirect + github.com/sagikazarmark/locafero v0.9.0 // indirect github.com/sourcegraph/conc v0.3.0 // indirect - github.com/spf13/afero v1.12.0 // indirect + github.com/spf13/afero v1.14.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/yuin/gopher-lua v1.1.1 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0 // indirect - go.opentelemetry.io/otel v1.34.0 // indirect - go.opentelemetry.io/otel/metric v1.34.0 // indirect - go.opentelemetry.io/otel/trace v1.34.0 // indirect - go.uber.org/atomic v1.9.0 // indirect - go.uber.org/multierr v1.9.0 // indirect - golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 // indirect - golang.org/x/sys v0.31.0 // indirect - golang.org/x/text v0.23.0 // indirect - golang.org/x/tools v0.31.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4 // indirect - google.golang.org/grpc v1.71.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0 // indirect + go.opentelemetry.io/otel v1.37.0 // indirect + go.opentelemetry.io/otel/metric v1.37.0 // indirect + go.opentelemetry.io/otel/trace v1.37.0 // indirect + go.uber.org/automaxprocs v1.6.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + golang.org/x/sys v0.34.0 // indirect + golang.org/x/text v0.27.0 // indirect + golang.org/x/tools v0.35.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7 // indirect + google.golang.org/grpc v1.73.0 // indirect google.golang.org/protobuf v1.36.6 // indirect - gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 77e185eb0e..22548221bb 100644 --- a/go.sum +++ b/go.sum @@ -1,21 +1,19 @@ -cloud.google.com/go/auth v0.15.0 h1:Ly0u4aA5vG/fsSsxu98qCQBemXtAtJf+95z9HK+cxps= -cloud.google.com/go/auth v0.15.0/go.mod h1:WJDGqZ1o9E9wKIL+IwStfyn/+s59zl4Bi+1KQNVXLZ8= +cloud.google.com/go/auth v0.16.2 h1:QvBAGFPLrDeoiNjyfVunhQ10HKNYuOwZ5noee0M5df4= +cloud.google.com/go/auth v0.16.2/go.mod h1:sRBas2Y1fB1vZTdurouM0AzuYQBMZinrUYL8EufhtEA= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= -cloud.google.com/go/compute/metadata v0.6.0 h1:A6hENjEsCDtC1k8byVsgwvVcioamEHvZ4j01OwKxG9I= -cloud.google.com/go/compute/metadata v0.6.0/go.mod h1:FjyFAW1MW0C203CEOMDTu3Dk1FlqW3Rga40jzHL4hfg= +cloud.google.com/go/compute/metadata v0.7.0 h1:PBWF+iiAerVNe8UCHxdOt6eHLVc3ydFeOCw78U8ytSU= +cloud.google.com/go/compute/metadata v0.7.0/go.mod h1:j5MvL9PprKL39t166CoB1uVHfQMs4tFQZZcKwksXUjo= github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb h1:ZVN4Iat3runWOFLaBCDVU5a9X/XikSRBosye++6gojw= github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb/go.mod h1:WsAABbY4HQBgd3mGuG4KMNTbHJCPvx9IVBHzysbknss= github.com/FZambia/sentinel v1.0.0 h1:KJ0ryjKTZk5WMp0dXvSdNqp3lFaW1fNFuEYfrkLOYIc= github.com/FZambia/sentinel v1.0.0/go.mod h1:ytL1Am/RLlAoAXG6Kj5LNuw/TRRQrv2rt2FT26vP5gI= -github.com/a8m/envsubst v1.4.2 h1:4yWIHXOLEJHQEFd4UjrWDrYeYlV7ncFWJOCBRLOZHQg= -github.com/a8m/envsubst v1.4.2/go.mod h1:MVUTQNGQ3tsjOOtKCNd+fl8RzhsXcDvvAEzkhGtlsbY= +github.com/a8m/envsubst v1.4.3 h1:kDF7paGK8QACWYaQo6KtyYBozY2jhQrTuNNuUxQkhJY= +github.com/a8m/envsubst v1.4.3/go.mod h1:4jjHWQlZoaXPoLQUb7H2qT4iLkZDdmEQiOUogdUmqVU= github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= -github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 h1:uvdUDbHQHO85qeSydJtItA4T55Pw6BtAejd0APRJOCE= -github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= github.com/alicebob/miniredis/v2 v2.11.1/go.mod h1:UA48pmi7aSazcGAvcdKcBB49z521IC9VjTTRz2nIaJE= -github.com/alicebob/miniredis/v2 v2.34.0 h1:mBFWMaJSNL9RwdGRyEDoAAv8OQc5UlEhLDQggTglU/0= -github.com/alicebob/miniredis/v2 v2.34.0/go.mod h1:kWShP4b58T1CW0Y5dViCd5ztzrDqRWqM3nksiyXk5s8= +github.com/alicebob/miniredis/v2 v2.35.0 h1:QwLphYqCEAo1eu1TqPRN2jgVMPBweeQcR21jeqDCONI= +github.com/alicebob/miniredis/v2 v2.35.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM= github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o= github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= @@ -35,12 +33,11 @@ github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/coreos/go-oidc/v3 v3.13.0 h1:M66zd0pcc5VxvBNM4pB331Wrsanby+QomQYjN8HamW8= -github.com/coreos/go-oidc/v3 v3.13.0/go.mod h1:HaZ3szPaZ0e4r6ebqvsLWlk2Tn+aejfmrfah6hnSYEU= +github.com/coreos/go-oidc/v3 v3.14.1 h1:9ePWwfdwC4QKRlCXsJGou56adA/owXczOzwKdOumLqk= +github.com/coreos/go-oidc/v3 v3.14.1/go.mod h1:HaZ3szPaZ0e4r6ebqvsLWlk2Tn+aejfmrfah6hnSYEU= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf h1:iW4rZ826su+pqaw19uhpSCzhj44qo35pNgKFGqzDKkU= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= @@ -49,21 +46,23 @@ github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2 github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= -github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M= -github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 h1:Arcl6UOIS/kgO2nW3A65HN+7CMjSDP/gofXL4CZt1V4= github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY= github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= -github.com/go-jose/go-jose/v4 v4.0.5 h1:M6T8+mKZl/+fNNuFHvGIzDz7BTLQPIounk/b9dw3AaE= -github.com/go-jose/go-jose/v4 v4.0.5/go.mod h1:s3P1lRrkT8igV8D9OjyL4WRyHvjB6a4JSllnOrmmBOA= +github.com/go-jose/go-jose/v4 v4.1.1 h1:JYhSgy4mXXzAdF3nUx3ygx347LRXJRrpgyU3adRmkAI= +github.com/go-jose/go-jose/v4 v4.1.1/go.mod h1:BdsZGqgdO3b6tTc6LSE56wcDbMMLuPsw5d4ZD5f94kA= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= -github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= +github.com/go-viper/mapstructure/v2 v2.3.0 h1:27XbWsHIqhbdR5TIC911OfYvgSaW93HM+dX7970Q7jk= +github.com/go-viper/mapstructure/v2 v2.3.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8= github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= @@ -73,8 +72,8 @@ github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3/go.mod h1:B4C85q github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad h1:a6HEuzUHeKH6hwfN/ZoQgRgVIWFJljSWa/zetS2WTvg= -github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= +github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5 h1:xhMrHhTJ6zxu3gA4enFM9MLn9AY7613teCdFnlUVbSQ= +github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5/go.mod h1:5hDyRhoBCxViHszMt12TnOpEI4VVi+U8Gm9iphldiMA= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -82,73 +81,68 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU9uHLo7OnF5tL52HFAgMmyrf4= github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= -github.com/googleapis/gax-go/v2 v2.14.1 h1:hb0FFeiPaQskmvakKu5EbCbpntQn48jyHuvrkurSS/Q= -github.com/googleapis/gax-go/v2 v2.14.1/go.mod h1:Hb/NubMaVM88SrNkvl8X/o8XWwDJEPqouaLeN2IUxoA= +github.com/googleapis/gax-go/v2 v2.14.2 h1:eBLnkZ9635krYIPD+ag1USrOAI0Nr0QYF3+/3GqO0k0= +github.com/googleapis/gax-go/v2 v2.14.2/go.mod h1:ON64QhlJkhVtSqp4v1uaK92VyZ2gmvDQsweuyLV+8+w= +github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81vgd/bo= +github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= -github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= -github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo= github.com/justinas/alice v1.2.0/go.mod h1:fN5HRH/reO/zrUflLfTN43t3vXvKzvZIENsNEe7i7qA= -github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc= -github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0= +github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= +github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= -github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= github.com/matryer/is v1.2.0 h1:92UTHpy8CDwaJ08GqLDzhhuixiBUUD1p3AU6PHddz4A= github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA= github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa h1:hI1uC2A3vJFjwvBn0G0a7QBRdBUp6Y048BtLAHRTKPo= github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa/go.mod h1:8vxFeeg++MqgCHwehSuwTlYCF0ALyDJbYJ1JsKi7v6s= -github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= -github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw= -github.com/onsi/ginkgo/v2 v2.23.3 h1:edHxnszytJ4lD9D5Jjc4tiDkPBZ3siDeJJkUZJJVkp0= -github.com/onsi/ginkgo/v2 v2.23.3/go.mod h1:zXTP6xIp3U8aVuXN8ENK9IXRaTjFnpVB9mGmaSRvxnM= -github.com/onsi/gomega v1.36.3 h1:hID7cr8t3Wp26+cYnfcjR6HpJ00fdogN6dqZ1t6IylU= -github.com/onsi/gomega v1.36.3/go.mod h1:8D9+Txp43QWKhM24yyOBEdpkzN8FvJyAwecBgsU4KU0= -github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= -github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= +github.com/onsi/ginkgo/v2 v2.23.4 h1:ktYTpKJAVZnDT4VjxSbiBenUjmlL/5QkBEocaWXiQus= +github.com/onsi/ginkgo/v2 v2.23.4/go.mod h1:Bt66ApGPBFzHyR+JO10Zbt0Gsp4uWxu5mIOTusL46e8= +github.com/onsi/gomega v1.37.0 h1:CdEG8g0S133B4OswTDC/5XPSzE1OeP29QOioj2PID2Y= +github.com/onsi/gomega v1.37.0/go.mod h1:8D9+Txp43QWKhM24yyOBEdpkzN8FvJyAwecBgsU4KU0= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU= github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v1.21.1 h1:DOvXXTqVzvkIewV/CDPFdejpMCGeMcbGCQ8YOmu+Ibk= -github.com/prometheus/client_golang v1.21.1/go.mod h1:U9NM32ykUErtVBxdvD3zfi+EuFkkaBvMb09mIfe0Zgg= -github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= -github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= -github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io= -github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I= -github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= -github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= -github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM= -github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA= -github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= -github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= -github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo= -github.com/sagikazarmark/locafero v0.7.0/go.mod h1:2za3Cg5rMaTMoG/2Ulr9AwtFaIppKXTRYnozin4aB5k= -github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= -github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= +github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g= +github.com/prashantv/gostub v1.1.0/go.mod h1:A5zLQHz7ieHGG7is6LLXLz7I8+3LZzsrV0P1IAHhP5U= +github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q= +github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0= +github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= +github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= +github.com/prometheus/common v0.65.0 h1:QDwzd+G1twt//Kwj/Ww6E9FQq1iVMmODnILtW1t2VzE= +github.com/prometheus/common v0.65.0/go.mod h1:0gZns+BLRQ3V6NdaerOhMbwwRbNh9hkGINtQAsP5GS8= +github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0= +github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw= +github.com/redis/go-redis/v9 v9.11.0 h1:E3S08Gl/nJNn5vkxd2i78wZxWAPNZgUNTp8WIJUAiIs= +github.com/redis/go-redis/v9 v9.11.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/sagikazarmark/locafero v0.9.0 h1:GbgQGNtTrEmddYDSAH9QLRyfAHY12md+8YFTqyMTC9k= +github.com/sagikazarmark/locafero v0.9.0/go.mod h1:UBUyz37V+EdMS3hDF3QWIiVr/2dPrx49OMO0Bn0hJqk= github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= -github.com/spf13/afero v1.12.0 h1:UcOPyRBYczmFn6yvphxkn9ZEOY65cpwGKb5mL36mrqs= -github.com/spf13/afero v1.12.0/go.mod h1:ZTlWwG4/ahT8W7T0WQ5uYmjI9duaLQGy3Q2OAl4sk/4= -github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y= -github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= +github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA= +github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo= +github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE= +github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI= -github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg= +github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4= +github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= @@ -165,31 +159,31 @@ github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.59.0 h1:rgMkmiGfix9vFJDcDi1PK8WEQP4FLQwLDfhp5ZLpFeE= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.59.0/go.mod h1:ijPqXp5P6IRRByFVVg9DY8P5HkxkHE5ARIa+86aXPf4= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0 h1:CV7UdSGJt/Ao6Gp4CXckLxVRRsRgDHoI8XjbL3PDl8s= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0/go.mod h1:FRmFuRJfag1IZ2dPkHnEoSFVgTVPUd2qf5Vi69hLb8I= -go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY= -go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI= -go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ= -go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE= -go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A= -go.opentelemetry.io/otel/sdk v1.34.0/go.mod h1:0e/pNiaMAqaykJGKbi+tSjWfNNHMTxoC9qANsCzbyxU= -go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk= -go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w= -go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k= -go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE= -go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= -go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= -go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0 h1:Hf9xI/XLML9ElpiHVDNwvqI0hIFlzV8dgIr35kV1kRU= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0/go.mod h1:NfchwuyNoMcZ5MLHwPrODwUF1HWCXWrL31s8gSAdIKY= +go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ= +go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I= +go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE= +go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E= +go.opentelemetry.io/otel/sdk v1.37.0 h1:ItB0QUqnjesGRvNcmAcU0LyvkVyGJ2xftD29bWdDvKI= +go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg= +go.opentelemetry.io/otel/sdk/metric v1.37.0 h1:90lI228XrB9jCMuSdA0673aubgRobVZFhbjxHHspCPc= +go.opentelemetry.io/otel/sdk/metric v1.37.0/go.mod h1:cNen4ZWfiD37l5NhS+Keb5RXVWZWpRE+9WyVCpbo5ps= +go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4= +go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0= +go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs= +go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= -golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= -golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= -golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw= -golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM= +golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM= +golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U= +golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM= +golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -197,15 +191,19 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= -golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= -golang.org/x/oauth2 v0.28.0 h1:CrgCKl8PPAVtLnU3c+EDw6x11699EWlsDeWNWKdIOkc= -golang.org/x/oauth2 v0.28.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= +golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw= +golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA= +golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs= +golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8= +golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= +golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw= -golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8= +golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw= +golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -215,8 +213,10 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= -golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= +golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA= +golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -228,33 +228,42 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= -golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= -golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0= -golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= +golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M= +golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA= +golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4= +golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU= +golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= +golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU= -golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ= +golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo= +golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg= +golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0= +golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.228.0 h1:X2DJ/uoWGnY5obVjewbp8icSL5U4FzuCfy9OjbLSnLs= -google.golang.org/api v0.228.0/go.mod h1:wNvRS1Pbe8r4+IfBIniV8fwCpGwTrYa+kMUDiC5z5a4= -google.golang.org/genproto v0.0.0-20241118233622-e639e219e697 h1:ToEetK57OidYuqD4Q5w+vfEnPvPpuTwedCNVohYJfNk= -google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 h1:GVIKPyP/kLIyVOgOnTwFOrvQaQUzOzGMCxgFUOEmm24= -google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422/go.mod h1:b6h1vNKhxaSoEI+5jc3PJUCustfli/mRab7295pY7rw= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4 h1:iK2jbkWL86DXjEx0qiHcRE9dE4/Ahua5k6V8OWFb//c= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4/go.mod h1:LuRYeWDFV6WOn90g357N17oMCaxpgCnbi/44qJvDn2I= -google.golang.org/grpc v1.71.0 h1:kF77BGdPTQ4/JZWMlb9VpJ5pa25aqvVqogsxNHHdeBg= -google.golang.org/grpc v1.71.0/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec= +google.golang.org/api v0.240.0 h1:PxG3AA2UIqT1ofIzWV2COM3j3JagKTKSwy7L6RHNXNU= +google.golang.org/api v0.240.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= +google.golang.org/api v0.241.0 h1:QKwqWQlkc6O895LchPEDUSYr22Xp3NCxpQRiWTB6avE= +google.golang.org/api v0.241.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= +google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2 h1:1tXaIXCracvtsRxSBsYDiSBN0cuJvM7QYW+MrpIRY78= +google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2/go.mod h1:49MsLSx0oWMOZqcpB3uL8ZOkAh1+TndpJ8ONoCBWiZk= +google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= +google.golang.org/genproto/googleapis/api v0.0.0-20250505200425-f936aa4a68b2 h1:vPV0tzlsK6EzEDHNNH5sa7Hs9bd7iXR7B1tSiPepkV0= +google.golang.org/genproto/googleapis/api v0.0.0-20250505200425-f936aa4a68b2/go.mod h1:pKLAc5OolXC3ViWGI62vvC0n10CpwAtRcTNCFwTKBEw= +google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 h1:oWVWY3NzT7KJppx2UKhKmzPq4SRe0LdCijVRwvGeikY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 h1:fc6jSaCT0vBduLYZHYrBBNY4dsWuvgyff9noRNDdBeE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7 h1:pFyd6EwwL2TqFf8emdthzeX+gZE1ElRq3iM8pui4KBY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= +google.golang.org/grpc v1.73.0 h1:VIWSmpI2MegBtTuFt5/JWy2oXxtjJ/e89Z70ImfD2ok= +google.golang.org/grpc v1.73.0/go.mod h1:50sbHOUqWoCQGI8V2HQLJM0B+LMlIUjNSZmow7EVBQc= google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= -gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -263,5 +272,5 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/apimachinery v0.32.3 h1:JmDuDarhDmA/Li7j3aPrwhpNBA94Nvk5zLeOge9HH1U= -k8s.io/apimachinery v0.32.3/go.mod h1:GpHVgxoKlTxClKcteaeuF1Ul/lDVb74KpZcxcmLDElE= +k8s.io/apimachinery v0.33.2 h1:IHFVhqg59mb8PJWTLi8m1mAoepkUNYmptHsV+Z1m5jY= +k8s.io/apimachinery v0.33.2/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= diff --git a/main_test.go b/main_test.go index 761c0c0ba0..8e40fe7faf 100644 --- a/main_test.go +++ b/main_test.go @@ -245,7 +245,7 @@ redirect_url="http://localhost:4180/oauth2/callback" Entry("with bad legacy configuration", loadConfigurationTableInput{ configContent: testCoreConfig + "unknown_field=\"something\"", expectedOptions: func() *options.Options { return nil }, - expectedErr: errors.New("failed to load config: error unmarshalling config: 1 error(s) decoding:\n\n* '' has invalid keys: unknown_field"), + expectedErr: errors.New("failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"), }), Entry("with bad alpha configuration", loadConfigurationTableInput{ configContent: testCoreConfig, @@ -257,7 +257,7 @@ redirect_url="http://localhost:4180/oauth2/callback" configContent: testCoreConfig + "unknown_field=\"something\"", alphaConfigContent: testAlphaConfig, expectedOptions: func() *options.Options { return nil }, - expectedErr: errors.New("failed to load core options: failed to load config: error unmarshalling config: 1 error(s) decoding:\n\n* '' has invalid keys: unknown_field"), + expectedErr: errors.New("failed to load core options: failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"), }), ) }) diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index 1f22dfbc9f..b198c4ffad 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -9,7 +9,7 @@ import ( "github.com/a8m/envsubst" "github.com/ghodss/yaml" - "github.com/mitchellh/mapstructure" + "github.com/go-viper/mapstructure/v2" "github.com/spf13/pflag" "github.com/spf13/viper" ) diff --git a/pkg/apis/options/load_test.go b/pkg/apis/options/load_test.go index 4265156f6f..fefbc2e795 100644 --- a/pkg/apis/options/load_test.go +++ b/pkg/apis/options/load_test.go @@ -329,7 +329,7 @@ var _ = Describe("Load", func() { Entry("with an unknown option in the config file", &testOptionsTableInput{ configFile: []byte(`unknown_option="foo"`), flagSet: func() *pflag.FlagSet { return testOptionsFlagSet }, - expectedErr: fmt.Errorf("error unmarshalling config: 1 error(s) decoding:\n\n* '' has invalid keys: unknown_option"), + expectedErr: fmt.Errorf("error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_option"), // Viper will unmarshal before returning the error, so this is the default output expectedOutput: &TestOptions{ StringOption: "default", @@ -471,7 +471,7 @@ sub: configFile: []byte(`stringSliceOption: "a"`), input: &TestOptions{}, expectedOutput: &TestOptions{}, - expectedErr: errors.New("error unmarshalling config: error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go struct field TestOptions.StringSliceOption of type []string"), + expectedErr: errors.New("error unmarshalling config: error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go struct field TestOptions.TestOptionSubStruct.StringSliceOption of type []string"), }), Entry("with a config file containing environment variable references", loadYAMLTableInput{ configFile: []byte("stringOption: ${TESTUSER}"), diff --git a/pkg/encryption/cipher.go b/pkg/encryption/cipher.go index 37e08ba85f..300bba3a22 100644 --- a/pkg/encryption/cipher.go +++ b/pkg/encryption/cipher.go @@ -66,7 +66,7 @@ func (c *cfbCipher) Encrypt(value []byte) ([]byte, error) { return nil, fmt.Errorf("failed to create initialization vector %s", err) } - stream := cipher.NewCFBEncrypter(c.Block, iv) + stream := cipher.NewCFBEncrypter(c.Block, iv) //nolint:staticcheck stream.XORKeyStream(ciphertext[aes.BlockSize:], value) return ciphertext, nil } @@ -79,7 +79,7 @@ func (c *cfbCipher) Decrypt(ciphertext []byte) ([]byte, error) { iv, ciphertext := ciphertext[:aes.BlockSize], ciphertext[aes.BlockSize:] plaintext := make([]byte, len(ciphertext)) - stream := cipher.NewCFBDecrypter(c.Block, iv) + stream := cipher.NewCFBDecrypter(c.Block, iv) //nolint:staticcheck stream.XORKeyStream(plaintext, ciphertext) return plaintext, nil diff --git a/pkg/validation/sessions_test.go b/pkg/validation/sessions_test.go index 4934b6495c..6f590ac5d8 100644 --- a/pkg/validation/sessions_test.go +++ b/pkg/validation/sessions_test.go @@ -191,8 +191,10 @@ var _ = Describe("Sessions", func() { invalidPasswordDelMsg = "unable to delete the redis initialization key: WRONGPASS invalid username-password pair" unreachableRedisSetMsg = "unable to set a redis initialization key: dial tcp 127.0.0.1:65535: connect: connection refused" unreachableRedisDelMsg = "unable to delete the redis initialization key: dial tcp 127.0.0.1:65535: connect: connection refused" - unreachableSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable" - unrechableSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable" + unreachableSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: redis: nil" + unrechableSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable: redis: nil" + refusedSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: dial tcp 127.0.0.1:65535: connect: connection refused" + refusedSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable: dial tcp 127.0.0.1:65535: connect: connection refused" ) type redisStoreTableInput struct { @@ -389,7 +391,7 @@ var _ = Describe("Sessions", func() { }, }, }, - errStrings: []string{unreachableSentinelSetMsg, unrechableSentinelDelMsg}, + errStrings: []string{refusedSentinelSetMsg, refusedSentinelDelMsg}, }), Entry("sentinel and cluster both enabled fails", &redisStoreTableInput{ opts: &options.Options{ From c4a02ecc9538f79e479b9a958becd3cf5cd82aed Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 13 Jul 2025 21:59:56 +0200 Subject: [PATCH 003/125] chore(deps): update dependency golangci/golangci-lint to v2.2.2 (#3111) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 2 +- .github/workflows/publish-release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b4061f910b..906b5eb574 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,7 +25,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.1.6 + GOLANGCI_LINT_VERSION: v2.2.2 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 61c61e322e..9ebf4b6c94 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -50,7 +50,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.1.6 + GOLANGCI_LINT_VERSION: v2.2.2 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter From d39087794559409c69e42741efa117656b070e4a Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 13 Jul 2025 22:00:12 +0200 Subject: [PATCH 004/125] chore(deps): update dependency @easyops-cn/docusaurus-search-local to ^0.51.0 (#3098) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- docs/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/package.json b/docs/package.json index 17fa43524a..33f3394bed 100644 --- a/docs/package.json +++ b/docs/package.json @@ -17,7 +17,7 @@ "@docusaurus/core": "^3.3.2", "@docusaurus/preset-classic": "^3.3.2", "@docusaurus/theme-mermaid": "^3.3.2", - "@easyops-cn/docusaurus-search-local": "^0.49.0", + "@easyops-cn/docusaurus-search-local": "^0.51.0", "@mdx-js/react": "^3.0.0", "clsx": "^2.0.0", "prism-react-renderer": "^2.3.0", From 40f3ef1ea5b0a5e78313fb6d4cb1a9aad94a00bd Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 13 Jul 2025 22:04:11 +0200 Subject: [PATCH 005/125] chore(deps): update example docker-compose files (#3096) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose-traefik.yaml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 8097a18639..ae1047c05a 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -42,7 +42,7 @@ services: - httpbin.localtest.me gitea: - image: gitea/gitea:1.23.8 + image: gitea/gitea:1.24.2 container_name: gitea environment: - USER_UID=1000 diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index d814739ca3..fb90ff28a8 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -41,7 +41,7 @@ services: depends_on: - oauth2-proxy container_name: nginx - image: nginx:1.28 + image: nginx:1.29 restart: unless-stopped ports: - 80:80/tcp diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index bdfdf785a8..65df58f0b4 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -34,7 +34,7 @@ services: # Reverse proxy gateway: container_name: traefik - image: traefik:v2.11.24 + image: traefik:v2.11.27 volumes: - "./traefik:/etc/traefik" ports: From b05bdc0fbd3f36a741326e7d705522016a263c01 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 13 Jul 2025 22:06:39 +0200 Subject: [PATCH 006/125] chore(deps): update helm examples (#2951) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/kubernetes/Chart.lock | 8 ++++---- contrib/local-environment/kubernetes/Chart.yaml | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/contrib/local-environment/kubernetes/Chart.lock b/contrib/local-environment/kubernetes/Chart.lock index 8fcaa57739..dc2ef2426a 100644 --- a/contrib/local-environment/kubernetes/Chart.lock +++ b/contrib/local-environment/kubernetes/Chart.lock @@ -1,15 +1,15 @@ dependencies: - name: dex repository: https://charts.dexidp.io - version: 0.20.0 + version: 0.23.0 - name: oauth2-proxy repository: https://oauth2-proxy.github.io/manifests - version: 7.10.2 + version: 7.12.19 - name: httpbin repository: https://conservis.github.io/helm-charts version: 1.1.0 - name: hello-world repository: https://conservis.github.io/helm-charts version: 1.1.0 -digest: sha256:d4c13dc7cfeb95a6a35d481d846fcfec23de5e7f0dc90ad8c66bba1eb8922d13 -generated: "2025-01-30T11:31:39.156062012Z" +digest: sha256:8d1d166c7c1043edd2006bb8e8d2db32a6b876febad2854253570d7ea141f064 +generated: "2025-07-13T20:04:55.152622641Z" diff --git a/contrib/local-environment/kubernetes/Chart.yaml b/contrib/local-environment/kubernetes/Chart.yaml index bc3ddbdd51..dd0938b378 100644 --- a/contrib/local-environment/kubernetes/Chart.yaml +++ b/contrib/local-environment/kubernetes/Chart.yaml @@ -3,10 +3,10 @@ description: K8S example based on https://kind.sigs.k8s.io name: kubernetes dependencies: - name: dex - version: 0.20.0 + version: 0.23.0 repository: https://charts.dexidp.io - name: oauth2-proxy - version: &chartVersion 7.10.2 + version: &chartVersion 7.12.19 repository: https://oauth2-proxy.github.io/manifests # https://github.com/postmanlabs/httpbin/issues/549 is still in progress, for now using a non-official chart - name: httpbin From 6c30a3c70b87bb8fdc86af21d3e71b7a16fb9b22 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 13 Jul 2025 22:07:21 +0200 Subject: [PATCH 007/125] chore(deps): update alpine base image to v3.22.0 (#3097) * chore(deps): update alpine docker tag to v3.22.0 * add changelog entry Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + Makefile | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 013f32b550..a9d1f52465 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - [#3072](https://github.com/oauth2-proxy/oauth2-proxy/pull/3072) feat: support for multiple github orgs #3072 (@daniel-mersch) - [#3116](https://github.com/oauth2-proxy/oauth2-proxy/pull/3116) feat: bump to go1.24.5 and full dependency update (@wardviaene / @dolmen) +- [#3097](https://github.com/oauth2-proxy/oauth2-proxy/pull/3097) chore(deps): update alpine base image to v3.22.0 # V7.9.0 diff --git a/Makefile b/Makefile index 870f1d2d68..f6128c0cd3 100644 --- a/Makefile +++ b/Makefile @@ -67,7 +67,7 @@ DOCKER_BUILDX_PUSH := $(DOCKER_BUILDX) --push DOCKER_BUILDX_PUSH_X_PLATFORM := $(DOCKER_BUILDX_PUSH) --platform ${DOCKER_BUILD_PLATFORM} DOCKER_BUILD_PLATFORM_ALPINE ?= linux/amd64,linux/arm64,linux/ppc64le,linux/arm/v6,linux/arm/v7,linux/s390x -DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.21.3 +DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.22.0 DOCKER_BUILDX_ARGS_ALPINE ?= --build-arg RUNTIME_IMAGE=${DOCKER_BUILD_RUNTIME_IMAGE_ALPINE} ${DOCKER_BUILDX_COMMON_ARGS} DOCKER_BUILDX_X_PLATFORM_ALPINE := docker buildx build ${DOCKER_BUILDX_ARGS_ALPINE} --platform ${DOCKER_BUILD_PLATFORM_ALPINE} DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE := $(DOCKER_BUILDX_X_PLATFORM_ALPINE) --push From 0e1dc9bb84a63c67d06d19e03779f74e213c0cf0 Mon Sep 17 00:00:00 2001 From: Daniel Givens <1581675+dgivens@users.noreply.github.com> Date: Thu, 17 Jul 2025 02:23:28 -0500 Subject: [PATCH 008/125] fix: return error for empty Redis URL list (#3101) * fix: return error for empty Redis URL list * add changelog entry Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + pkg/sessions/redis/redis_store.go | 4 + pkg/sessions/redis/redis_store_test.go | 279 ++++++++++++++----------- 3 files changed, 159 insertions(+), 125 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a9d1f52465..72d615e0a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - [#3072](https://github.com/oauth2-proxy/oauth2-proxy/pull/3072) feat: support for multiple github orgs #3072 (@daniel-mersch) - [#3116](https://github.com/oauth2-proxy/oauth2-proxy/pull/3116) feat: bump to go1.24.5 and full dependency update (@wardviaene / @dolmen) - [#3097](https://github.com/oauth2-proxy/oauth2-proxy/pull/3097) chore(deps): update alpine base image to v3.22.0 +- [#3101](https://github.com/oauth2-proxy/oauth2-proxy/pull/3101) fix: return error for empty Redis URL list (@dgivens) # V7.9.0 diff --git a/pkg/sessions/redis/redis_store.go b/pkg/sessions/redis/redis_store.go index e41a1e1f0e..18d79b803e 100644 --- a/pkg/sessions/redis/redis_store.go +++ b/pkg/sessions/redis/redis_store.go @@ -218,6 +218,10 @@ func setupTLSConfig(opts options.RedisStoreOptions, opt *redis.Options) error { // parseRedisURLs parses a list of redis urls and returns a list // of addresses in the form of host:port and redis.Options that can be used to connect to Redis func parseRedisURLs(urls []string) ([]string, *redis.Options, error) { + if len(urls) == 0 { + return nil, nil, fmt.Errorf("unable to parse redis urls: no redis urls provided") + } + addrs := []string{} var redisOptions *redis.Options for _, u := range urls { diff --git a/pkg/sessions/redis/redis_store_test.go b/pkg/sessions/redis/redis_store_test.go index 0c0c510600..1bff685503 100644 --- a/pkg/sessions/redis/redis_store_test.go +++ b/pkg/sessions/redis/redis_store_test.go @@ -19,116 +19,41 @@ const ( ) var _ = Describe("Redis SessionStore Tests", func() { - // helper interface to allow us to close client connections - // All non-nil redis clients should implement this - type closer interface { - Close() error - } - - var mr *miniredis.Miniredis - var ss sessionsapi.SessionStore - - BeforeEach(func() { - var err error - mr, err = miniredis.Run() - Expect(err).ToNot(HaveOccurred()) - }) - - AfterEach(func() { - mr.Close() - }) - - JustAfterEach(func() { - // Release any connections immediately after the test ends - if redisManager, ok := ss.(*persistence.Manager); ok { - if redisManager.Store.(*SessionStore).Client != nil { - Expect(redisManager.Store.(*SessionStore).Client.(closer).Close()).To(Succeed()) - } + Describe("Redis SessionStore Creation", func() { + // helper interface to allow us to close client connections + // All non-nil redis clients should implement this + type closer interface { + Close() error } - }) - const redisProtocol = "redis://" - tests.RunSessionStoreTests( - func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { - // Set the connection URL - opts.Type = options.RedisSessionStoreType - opts.Redis.ConnectionURL = redisProtocol + mr.Addr() - - // Capture the session store so that we can close the client - var err error - ss, err = NewRedisSessionStore(opts, cookieOpts) - return ss, err - }, - func(d time.Duration) error { - mr.FastForward(d) - return nil - }, - ) - - Context("with sentinel", func() { - var ms *minisentinel.Sentinel + var mr *miniredis.Miniredis + var ss sessionsapi.SessionStore BeforeEach(func() { - ms = minisentinel.NewSentinel(mr) - Expect(ms.Start()).To(Succeed()) + var err error + mr, err = miniredis.Run() + Expect(err).ToNot(HaveOccurred()) }) - tests.RunSessionStoreTests( - func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { - // Set the sentinel connection URL - sentinelAddr := redisProtocol + ms.Addr() - opts.Type = options.RedisSessionStoreType - opts.Redis.SentinelConnectionURLs = []string{sentinelAddr} - opts.Redis.UseSentinel = true - opts.Redis.SentinelMasterName = ms.MasterInfo().Name - - // Capture the session store so that we can close the client - var err error - ss, err = NewRedisSessionStore(opts, cookieOpts) - return ss, err - }, - func(d time.Duration) error { - mr.FastForward(d) - return nil - }, - ) - }) - - Context("with cluster", func() { - tests.RunSessionStoreTests( - func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { - clusterAddr := redisProtocol + mr.Addr() - opts.Type = options.RedisSessionStoreType - opts.Redis.ClusterConnectionURLs = []string{clusterAddr} - opts.Redis.UseCluster = true - - // Capture the session store so that we can close the client - var err error - ss, err = NewRedisSessionStore(opts, cookieOpts) - return ss, err - }, - func(d time.Duration) error { - mr.FastForward(d) - return nil - }, - ) - }) - - Context("with a redis password", func() { - BeforeEach(func() { - mr.RequireAuth(redisPassword) + AfterEach(func() { + mr.Close() }) - AfterEach(func() { - mr.RequireAuth("") + JustAfterEach(func() { + // Release any connections immediately after the test ends + if redisManager, ok := ss.(*persistence.Manager); ok { + if redisManager.Store.(*SessionStore).Client != nil { + Expect(redisManager.Store.(*SessionStore).Client.(closer).Close()).To(Succeed()) + } + } }) + const redisProtocol = "redis://" tests.RunSessionStoreTests( func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { // Set the connection URL opts.Type = options.RedisSessionStoreType opts.Redis.ConnectionURL = redisProtocol + mr.Addr() - opts.Redis.Password = redisPassword // Capture the session store so that we can close the client var err error @@ -157,7 +82,6 @@ var _ = Describe("Redis SessionStore Tests", func() { opts.Redis.SentinelConnectionURLs = []string{sentinelAddr} opts.Redis.UseSentinel = true opts.Redis.SentinelMasterName = ms.MasterInfo().Name - opts.Redis.Password = redisPassword // Capture the session store so that we can close the client var err error @@ -178,7 +102,6 @@ var _ = Describe("Redis SessionStore Tests", func() { opts.Type = options.RedisSessionStoreType opts.Redis.ClusterConnectionURLs = []string{clusterAddr} opts.Redis.UseCluster = true - opts.Redis.Password = redisPassword // Capture the session store so that we can close the client var err error @@ -191,43 +114,100 @@ var _ = Describe("Redis SessionStore Tests", func() { }, ) }) - }) - Context("with a redis username and password", func() { - BeforeEach(func() { - mr.RequireUserAuth(redisUsername, redisPassword) - }) + Context("with a redis password", func() { + BeforeEach(func() { + mr.RequireAuth(redisPassword) + }) - AfterEach(func() { - mr.RequireUserAuth("", "") + AfterEach(func() { + mr.RequireAuth("") + }) + + tests.RunSessionStoreTests( + func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { + // Set the connection URL + opts.Type = options.RedisSessionStoreType + opts.Redis.ConnectionURL = redisProtocol + mr.Addr() + opts.Redis.Password = redisPassword + + // Capture the session store so that we can close the client + var err error + ss, err = NewRedisSessionStore(opts, cookieOpts) + return ss, err + }, + func(d time.Duration) error { + mr.FastForward(d) + return nil + }, + ) + + Context("with sentinel", func() { + var ms *minisentinel.Sentinel + + BeforeEach(func() { + ms = minisentinel.NewSentinel(mr) + Expect(ms.Start()).To(Succeed()) + }) + + tests.RunSessionStoreTests( + func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { + // Set the sentinel connection URL + sentinelAddr := redisProtocol + ms.Addr() + opts.Type = options.RedisSessionStoreType + opts.Redis.SentinelConnectionURLs = []string{sentinelAddr} + opts.Redis.UseSentinel = true + opts.Redis.SentinelMasterName = ms.MasterInfo().Name + opts.Redis.Password = redisPassword + + // Capture the session store so that we can close the client + var err error + ss, err = NewRedisSessionStore(opts, cookieOpts) + return ss, err + }, + func(d time.Duration) error { + mr.FastForward(d) + return nil + }, + ) + }) + + Context("with cluster", func() { + tests.RunSessionStoreTests( + func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { + clusterAddr := redisProtocol + mr.Addr() + opts.Type = options.RedisSessionStoreType + opts.Redis.ClusterConnectionURLs = []string{clusterAddr} + opts.Redis.UseCluster = true + opts.Redis.Password = redisPassword + + // Capture the session store so that we can close the client + var err error + ss, err = NewRedisSessionStore(opts, cookieOpts) + return ss, err + }, + func(d time.Duration) error { + mr.FastForward(d) + return nil + }, + ) + }) }) - tests.RunSessionStoreTests( - func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { - // Set the connection URL - opts.Type = options.RedisSessionStoreType - opts.Redis.ConnectionURL = "redis://" + redisUsername + "@" + mr.Addr() - opts.Redis.Password = redisPassword + Context("with a redis username and password", func() { + BeforeEach(func() { + mr.RequireUserAuth(redisUsername, redisPassword) + }) - // Capture the session store so that we can close the client - var err error - ss, err = NewRedisSessionStore(opts, cookieOpts) - return ss, err - }, - func(d time.Duration) error { - mr.FastForward(d) - return nil - }, - ) + AfterEach(func() { + mr.RequireUserAuth("", "") + }) - Context("with cluster", func() { tests.RunSessionStoreTests( func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { - clusterAddr := "redis://" + redisUsername + "@" + mr.Addr() + // Set the connection URL opts.Type = options.RedisSessionStoreType - opts.Redis.ClusterConnectionURLs = []string{clusterAddr} - opts.Redis.UseCluster = true - opts.Redis.Username = redisUsername + opts.Redis.ConnectionURL = "redis://" + redisUsername + "@" + mr.Addr() opts.Redis.Password = redisPassword // Capture the session store so that we can close the client @@ -240,6 +220,55 @@ var _ = Describe("Redis SessionStore Tests", func() { return nil }, ) + + Context("with cluster", func() { + tests.RunSessionStoreTests( + func(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessionsapi.SessionStore, error) { + clusterAddr := "redis://" + redisUsername + "@" + mr.Addr() + opts.Type = options.RedisSessionStoreType + opts.Redis.ClusterConnectionURLs = []string{clusterAddr} + opts.Redis.UseCluster = true + opts.Redis.Username = redisUsername + opts.Redis.Password = redisPassword + + // Capture the session store so that we can close the client + var err error + ss, err = NewRedisSessionStore(opts, cookieOpts) + return ss, err + }, + func(d time.Duration) error { + mr.FastForward(d) + return nil + }, + ) + }) + }) + }) + + Describe("Redis URL Parsing", func() { + It("should parse valid redis URL", func() { + addrs, opts, err := parseRedisURLs([]string{"redis://localhost:6379"}) + Expect(err).ToNot(HaveOccurred()) + Expect(addrs).To(Equal([]string{"localhost:6379"})) + Expect(opts).ToNot(BeNil()) + Expect(opts.Addr).To(Equal("localhost:6379")) + }) + + It("should return error for invalid redis URL", func() { + addrs, opts, err := parseRedisURLs([]string{"invalid://url"}) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("unable to parse redis url")) + Expect(err.Error()).To(Not(ContainSubstring("no redis urls provided"))) + Expect(addrs).To(BeNil()) + Expect(opts).To(BeNil()) + }) + + It("should return error when no URLs provided", func() { + addrs, opts, err := parseRedisURLs([]string{}) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(Equal("unable to parse redis urls: no redis urls provided")) + Expect(addrs).To(BeNil()) + Expect(opts).To(BeNil()) }) }) }) From 07a388d17e985a3f4836f4df0aec8905e11db02f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 17 Jul 2025 07:56:01 +0000 Subject: [PATCH 009/125] add new docs version 7.10.x --- .../version-7.10.x/behaviour.md | 11 + .../version-7.10.x/community/contribution.md | 89 +++ .../version-7.10.x/community/security.md | 49 ++ .../configuration/alpha_config.md | 564 ++++++++++++++++++ .../configuration/alpha_config.md.tmpl | 139 +++++ .../configuration/integration.md | 318 ++++++++++ .../version-7.10.x/configuration/overview.md | 402 +++++++++++++ .../configuration/providers/adfs.md | 19 + .../configuration/providers/bitbucket.md | 25 + .../configuration/providers/digitalocean.md | 21 + .../configuration/providers/facebook.md | 7 + .../configuration/providers/gitea.md | 24 + .../configuration/providers/github.md | 81 +++ .../configuration/providers/gitlab.md | 49 ++ .../configuration/providers/google.md | 76 +++ .../configuration/providers/index.md | 43 ++ .../configuration/providers/keycloak.md | 36 ++ .../configuration/providers/keycloak_oidc.md | 151 +++++ .../configuration/providers/linkedin.md | 13 + .../configuration/providers/login_gov.md | 79 +++ .../configuration/providers/ms_azure_ad.md | 59 ++ .../configuration/providers/ms_entra_id.md | 197 ++++++ .../configuration/providers/nextcloud.md | 28 + .../configuration/providers/openid_connect.md | 146 +++++ .../version-7.10.x/configuration/sessions.md | 99 +++ .../configuration/systemd_socket.md | 43 ++ .../version-7.10.x/configuration/tls.md | 85 +++ .../version-7.10.x/features/endpoints.md | 47 ++ .../version-7.10.x/installation.md | 32 + docs/versioned_docs/version-7.10.x/welcome.md | 23 + .../version-7.10.x-sidebars.json | 83 +++ docs/versions.json | 1 + 32 files changed, 3039 insertions(+) create mode 100644 docs/versioned_docs/version-7.10.x/behaviour.md create mode 100644 docs/versioned_docs/version-7.10.x/community/contribution.md create mode 100644 docs/versioned_docs/version-7.10.x/community/security.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/alpha_config.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/alpha_config.md.tmpl create mode 100644 docs/versioned_docs/version-7.10.x/configuration/integration.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/overview.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/adfs.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/bitbucket.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/digitalocean.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/facebook.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/gitea.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/github.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/gitlab.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/google.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/index.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/keycloak.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/keycloak_oidc.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/linkedin.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/login_gov.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/ms_azure_ad.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/ms_entra_id.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/nextcloud.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/providers/openid_connect.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/sessions.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/systemd_socket.md create mode 100644 docs/versioned_docs/version-7.10.x/configuration/tls.md create mode 100644 docs/versioned_docs/version-7.10.x/features/endpoints.md create mode 100644 docs/versioned_docs/version-7.10.x/installation.md create mode 100644 docs/versioned_docs/version-7.10.x/welcome.md create mode 100644 docs/versioned_sidebars/version-7.10.x-sidebars.json diff --git a/docs/versioned_docs/version-7.10.x/behaviour.md b/docs/versioned_docs/version-7.10.x/behaviour.md new file mode 100644 index 0000000000..e063d4f966 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/behaviour.md @@ -0,0 +1,11 @@ +--- +id: behaviour +title: Behaviour +--- + +1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). +2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) +3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set +4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) + +Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). diff --git a/docs/versioned_docs/version-7.10.x/community/contribution.md b/docs/versioned_docs/version-7.10.x/community/contribution.md new file mode 100644 index 0000000000..2cd330ac32 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/community/contribution.md @@ -0,0 +1,89 @@ +--- +id: contribution +title: Contribution Guide +--- + +We track bugs and issues using Github. + +If you find a bug, please open an Issue. When opening an Issue or Pull Request please follow the preconfigured template and take special note of the checkboxes. + +If you want to fix a bug, add a new feature or extend existing functionality, please create a fork, create a feature branch and open a PR back to this repo. +Please mention open bug issue number(s) within your PR if applicable. + +We suggest using [Visual Studio Code](https://code.visualstudio.com/docs/languages/go) with the official [Go for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=golang.go) extension. + + +# Go version + +This project is currently still using go 1.22. You can follow the installation guide for go [here.](https://go.dev/doc/install) And you can find go version 1.22 in the archived section [here.](https://go.dev/dl/) + +# Preparing your fork +Clone your fork, create a feature branch and update the depedencies to get started. +```bash +git clone git@github.com:/oauth2-proxy +cd oauth2-proxy +git branch feature/ +git push --set-upstream origin feature/ +go mod download +``` + + +# Testing / Debugging +For starting oauth2-proxy locally open the debugging tab and create the `launch.json` and select `Go: Launch Package`. + +![Debugging Tab](/img/debug-tab.png) +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch OAuth2-Proxy with Dex", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and dex as an idetity provider + "contrib/local-environment/oauth2-proxy.cfg" + ] + }, + { + "name": "Launch OAuth2-Proxy with Keycloak", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and keycloak as an idetity provider + "contrib/local-environment/oauth2-proxy-keycloak.cfg" + ] + } + ] +} +``` + +Before you can start your local version of oauth2-proxy, you will have to use the provided docker compose files to start a local upstream service and identity provider. We suggest using [httpbin](https://hub.docker.com/r/kennethreitz/httpbin) as your upstream for testing as it allows for request and response introspection of all things HTTP. + +Inside the `contrib/local-environment` directory you can use the `Makefile` for +starting different example setups: + +- Dex as your IdP: `make up` or `make down` +- Dex as your IdP using the alpha-config: `make alpha-config-up` +- Keycloak as your IdP: `make keycloak-up` +- Dex as your IdP & nginx reverse proxy: `make nginx-up` +- and many more... + +Check out the `Makefile` to see what is available. + +The username and password for all setups is usually `admin@example.com` and `password`. + +The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me + +- OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 +- Upstream: http://httpbin.localtest.me:8080 +- Dex: http://dex.localtest.me:4190 + diff --git a/docs/versioned_docs/version-7.10.x/community/security.md b/docs/versioned_docs/version-7.10.x/community/security.md new file mode 100644 index 0000000000..c24b57d9e5 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/community/security.md @@ -0,0 +1,49 @@ +--- +id: security +title: Security +--- + +:::note +OAuth2 Proxy is a community project. +Maintainers do not work on this project full time, and as such, +while we endeavour to respond to disclosures as quickly as possible, +this may take longer than in projects with corporate sponsorship. +::: + +## Security Disclosures + +:::important +If you believe you have found a vulnerability within OAuth2 Proxy or any of its +dependencies, please do NOT open an issue or PR on GitHub, please do NOT post +any details publicly. +::: + +Security disclosures MUST be done in private. +If you have found an issue that you would like to bring to the attention of the +maintenance team for OAuth2 Proxy, please compose an email and send it to the +list of maintainers in our [MAINTAINERS](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS) file. + +Please include as much detail as possible. +Ideally, your disclosure should include: +- A reproducible case that can be used to demonstrate the exploit +- How you discovered this vulnerability +- A potential fix for the issue (if you have thought of one) +- Versions affected (if not present in master) +- Your GitHub ID + +### How will we respond to disclosures? + +We use [GitHub Security Advisories](https://docs.github.com/en/github/managing-security-vulnerabilities/about-github-security-advisories) +to privately discuss fixes for disclosed vulnerabilities. +If you include a GitHub ID with your disclosure we will add you as a collaborator +for the advisory so that you can join the discussion and validate any fixes +we may propose. + +For minor issues and previously disclosed vulnerabilities (typically for +dependencies), we may use regular PRs for fixes and forego the security advisory. + +Once a fix has been agreed upon, we will merge the fix and create a new release. +If we have multiple security issues in flight simultaneously, we may delay +merging fixes until all patches are ready. +We may also backport the fix to previous releases, +but this will be at the discretion of the maintainers. diff --git a/docs/versioned_docs/version-7.10.x/configuration/alpha_config.md b/docs/versioned_docs/version-7.10.x/configuration/alpha_config.md new file mode 100644 index 0000000000..018a29413a --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/alpha_config.md @@ -0,0 +1,564 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference + + + +### ADFSOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `skipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | + +### AlphaOptions + +AlphaOptions contains alpha structured configuration options. +Usage of these options allows users to access alpha features that are not +available as part of the primary configuration structure for OAuth2 Proxy. + +:::warning +The options within this structure are considered alpha. +They may change between releases without notice. +::: + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | +| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | + +### AzureOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | +| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | + +### BitbucketOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repository` | _string_ | Repository sets restrict logins to user with access to this repository | + +### ClaimSource + +(**Appears on:** [HeaderValue](#headervalue)) + +ClaimSource allows loading a header value from a claim within the session + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### Duration +#### (`string` alias) + +(**Appears on:** [Upstream](#upstream)) + +Duration is as string representation of a period of time. +A duration string is a is a possibly signed sequence of decimal numbers, +each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". +Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + +### GitHubOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `org` | _string_ | Org sets restrict logins to members of this organisation | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository | +| `token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | +| `users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | + +### GitLabOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Group sets restrict logins to members of this group | +| `projects` | _[]string_ | Projects restricts logins to members of these projects | + +### GoogleOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Groups sets restrict logins to members of this Google group | +| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | +| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | +| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | +| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | + +### Header + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Header represents an individual header that will be added to a request or +response header. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | +| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | + +### HeaderValue + +(**Appears on:** [Header](#header)) + +HeaderValue represents a single header value and the sources that can +make up the header value + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### KeycloakOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `groups` | _[]string_ | Group enables to restrict login to members of indicated group | +| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | + +### LoginGovOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | +| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | +| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | + +### LoginURLParameter + +(**Appears on:** [Provider](#provider)) + +LoginURLParameter is the configuration for a single query parameter that +can be passed through from the `/oauth2/start` endpoint to the IdP login +URL. The "default" option specifies the default value or values (if any) +that will be passed to the IdP for this parameter, and "allow" is a list +of options for ways in which this parameter can be set or overridden via +the query string to `/oauth2/start`. +If _only_ a default is specified and no "allow" then the parameter is +effectively fixed - the default value will always be used and anything +passed to the start URL will be ignored. If _only_ "allow" is specified +but no default then the parameter will only be passed on to the IdP if +the caller provides it, and no value will be sent otherwise. + +Examples: + +# A parameter whose value is fixed + +``` +name: organization +default: +- myorg +``` + +A parameter that is not passed by default, but may be set to one of a +fixed set of values + +``` +name: prompt +allow: +- value: login +- value: consent +- value: select_account +``` + +A parameter that is passed by default but may be overridden by one of +a fixed set of values + +``` +name: prompt +default: ["login"] +allow: +- value: consent +- value: select_account +``` + +A parameter that may be overridden, but only by values that match a +regular expression. For example to restrict `login_hint` to email +addresses in your organization's domain: + +``` +name: login_hint +allow: +- pattern: '^[^@]*@example\.com$' +# this allows at most one "@" sign, and requires "example.com" domain. +``` + +Note that the YAML rules around exactly which characters are allowed +and/or require escaping in different types of string literals are +convoluted. For regular expressions the single quoted form is simplest +as backslash is not considered to be an escape character. Alternatively +use the "chomped block" format `|-`: + +``` + - pattern: |- + ^[^@]*@example\.com$ + +``` + +The hyphen is important, a `|` block would have a trailing newline +character. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name specifies the name of the query parameter. | +| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | +| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | + +### MicrosoftEntraIDOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | +| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | + +### OIDCOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | +| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | +| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | +| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | +| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | +| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | +| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | +| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | +| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | +| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | +| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | +| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | + +### Provider + +(**Appears on:** [Providers](#providers)) + +Provider holds all configuration for a single provider + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | +| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | +| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | +| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | +| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | +| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | +| `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. | +| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | +| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | +| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | +| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | +| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | +| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | +| `id` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | +| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | +| `name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | +| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | +| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | +| `loginURL` | _string_ | LoginURL is the authentication endpoint | +| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | +| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | +| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint | +| `profileURL` | _string_ | ProfileURL is the profile access endpoint | +| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | +| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | +| `validateURL` | _string_ | ValidateURL is the access token validation endpoint | +| `scope` | _string_ | Scope is the OAuth scope specification | +| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | +| `code_challenge_method` | _string_ | The code challenge method | +| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | + +### ProviderType +#### (`string` alias) + +(**Appears on:** [Provider](#provider)) + +ProviderType is used to enumerate the different provider type options +Valid options are: adfs, azure, bitbucket, digitalocean facebook, github, +gitlab, google, keycloak, keycloak-oidc, linkedin, login.gov, nextcloud +and oidc. + +### Providers + +#### ([[]Provider](#provider) alias) + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +The provider can be selected using the `provider` configuration value, or +set in the [`providers` array using +AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). +However, [**the feature to implement multiple providers is not +complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +### SecretSource + +(**Appears on:** [ClaimSource](#claimsource), [HeaderValue](#headervalue), [TLS](#tls)) + +SecretSource references an individual secret value. +Only one source within the struct should be defined at any time. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | + +### Server + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Server represents the configuration for an HTTP(S) server + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `BindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Leave blank or set to "-" to disable. | +| `SecureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Leave blank or set to "-" to disable. | +| `TLS` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the
secure traffic and further configuration for the TLS server. | + +### TLS + +(**Appears on:** [Server](#server)) + +TLS contains the information for loading a TLS certificate and key +as well as an optional minimal TLS version that is acceptable. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `Key` | _[SecretSource](#secretsource)_ | Key is the TLS key data to use.
Typically this will come from a file. | +| `Cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.
Typically this will come from a file. | +| `MinVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.
E.g. Set to "TLS1.3" to select TLS version 1.3 | +| `CipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.
E.g.:
- TLS_RSA_WITH_RC4_128_SHA
- TLS_RSA_WITH_AES_256_GCM_SHA384
If not specified, the default Go safe cipher list is used.
List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | + +### URLParameterRule + +(**Appears on:** [LoginURLParameter](#loginurlparameter)) + +URLParameterRule represents a rule by which query parameters +passed to the `/oauth2/start` endpoint are checked to determine whether +they are valid overrides for the given parameter passed to the IdP's +login URL. Either Value or Pattern should be supplied, not both. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _string_ | A Value rule matches just this specific value | +| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | + +### Upstream + +(**Appears on:** [UpstreamConfig](#upstreamconfig)) + +Upstream represents the configuration for an upstream server. +Requests will be proxied to this upstream if the path matches the request path. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `id` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | +| `path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | +| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | +| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | +| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | +| `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | +| `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | +| `flushInterval` | _[Duration](#duration)_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | +| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | +| `timeout` | _[Duration](#duration)_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | + +### UpstreamConfig + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +UpstreamConfig is a collection of definitions for upstream servers. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | +| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | diff --git a/docs/versioned_docs/version-7.10.x/configuration/alpha_config.md.tmpl b/docs/versioned_docs/version-7.10.x/configuration/alpha_config.md.tmpl new file mode 100644 index 0000000000..8258201f2a --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/alpha_config.md.tmpl @@ -0,0 +1,139 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference diff --git a/docs/versioned_docs/version-7.10.x/configuration/integration.md b/docs/versioned_docs/version-7.10.x/configuration/integration.md new file mode 100644 index 0000000000..05d39281e5 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/integration.md @@ -0,0 +1,318 @@ +--- +id: integration +title: Integration +--- + +## Configuring for use with the Nginx `auth_request` directive + +**This option requires `--reverse-proxy` option to be set.** + +The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: + +```nginx +server { + listen 443 ssl; + server_name ...; + include ssl/ssl.conf; + + location /oauth2/ { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Auth-Request-Redirect $request_uri; + # or, if you are handling multiple domains: + # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; + } + location = /oauth2/auth { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; + # nginx auth_request includes headers but not body + proxy_set_header Content-Length ""; + proxy_pass_request_body off; + } + + location / { + auth_request /oauth2/auth; + error_page 401 =403 /oauth2/sign_in; + + # pass information via X-User and X-Email headers to backend, + # requires running with --set-xauthrequest flag + auth_request_set $user $upstream_http_x_auth_request_user; + auth_request_set $email $upstream_http_x_auth_request_email; + proxy_set_header X-User $user; + proxy_set_header X-Email $email; + + # if you enabled --pass-access-token, this will pass the token to the backend + auth_request_set $token $upstream_http_x_auth_request_access_token; + proxy_set_header X-Access-Token $token; + + # if you enabled --cookie-refresh, this is needed for it to work with auth_request + auth_request_set $auth_cookie $upstream_http_set_cookie; + add_header Set-Cookie $auth_cookie; + + # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb + # limit and so the OAuth2 Proxy splits these into multiple parts. + # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, + # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. + auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; + + # Extract the Cookie attributes from the first Set-Cookie header and append them + # to the second part ($upstream_cookie_* variables only contain the raw cookie content) + if ($auth_cookie ~* "(; .*)") { + set $auth_cookie_name_0 $auth_cookie; + set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; + } + + # Send both Set-Cookie headers now if there was a second part + if ($auth_cookie_name_upstream_1) { + add_header Set-Cookie $auth_cookie_name_0; + add_header Set-Cookie $auth_cookie_name_1; + } + + proxy_pass http://backend/; + # or "root /path/to/site;" or "fastcgi_pass ..." etc + } +} +``` + +When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`. +Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua. +Note that `nginxinc/kubernetes-ingress` does not include the Lua module. + +```yaml +nginx.ingress.kubernetes.io/auth-response-headers: Authorization +nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri +nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth +nginx.ingress.kubernetes.io/configuration-snippet: | + auth_request_set $name_upstream_1 $upstream_cookie_name_1; + + access_by_lua_block { + if ngx.var.name_upstream_1 ~= "" then + ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)") + end + } +``` +It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). + +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=". + +## Configuring for use with the Traefik (v2) `ForwardAuth` middleware + +**This option requires `--reverse-proxy` option to be set.** + +### ForwardAuth with 401 errors middleware + +The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: + +```yaml +http: + routers: + a-service: + rule: "Host(`a-service.example.com`)" + service: a-service-backend + middlewares: + - oauth-errors + - oauth-auth + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth: + rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + oauth-errors: + errors: + status: + - "401-403" + service: oauth-backend + query: "/oauth2/sign_in?rd={url}" +``` + +### ForwardAuth with static upstreams configuration + +Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint + +**Following options need to be set on `oauth2-proxy`:** +- `--upstream=static://202`: Configures a static response for authenticated sessions +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```yaml +http: + routers: + a-service-route-1: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" + service: a-service-backend + middlewares: + - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + a-service-route-2: + rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" + service: a-service-backend + middlewares: + - oauth-auth-wo-redirect # unauthenticated session will return a 401 + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + services-oauth2-route: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth2-proxy-route: + rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + b-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.3:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth-redirect: + forwardAuth: + address: https://oauth.example.com/ + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization + oauth-auth-wo-redirect: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization +``` + +## Configuring for use with the Caddy (v2) `forward_auth` directive + +The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. + +This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. + +**Following options need to be set on `oauth2-proxy`:** +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```nginx title="Caddyfile" +example.com { + # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. + # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. + handle /oauth2/* { + reverse_proxy oauth2-proxy.internal:4180 { + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. + header_up X-Real-IP {remote_host} + header_up X-Forwarded-Uri {uri} + } + } + + # Requests to other paths are first processed by oauth2-proxy for authentication. + handle { + forward_auth oauth2-proxy.internal:4180 { + uri /oauth2/auth + + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. + header_up X-Real-IP {remote_host} + + # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. + # Make sure to configure the --set-xauthrequest flag to enable this feature. + #copy_headers X-Auth-Request-User X-Auth-Request-Email + + # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. + @error status 401 + handle_response @error { + redir * /oauth2/sign_in?rd={scheme}://{host}{uri} + } + } + + # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. + reverse_proxy upstream.internal:3000 + } +} +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.10.x/configuration/overview.md b/docs/versioned_docs/version-7.10.x/configuration/overview.md new file mode 100644 index 0000000000..bea7061770 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/overview.md @@ -0,0 +1,402 @@ +--- +id: overview +title: Overview +--- + +`oauth2-proxy` can be configured via [command line options](#command-line-options), [environment variables](#environment-variables) or [config file](#config-file) (in decreasing order of precedence, i.e. command line options will overwrite environment variables and environment variables will overwrite configuration file settings). + +## Generating a Cookie Secret + +To generate a strong cookie secret use one of the below commands: + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + + +```shell +python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())' +``` + + + + +```shell +dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64 | tr -d -- '\n' | tr -- '+/' '-_' ; echo +``` + + + + +```shell +openssl rand -base64 32 | tr -- '+/' '-_' +``` + + + + +```powershell +# Add System.Web assembly to session, just in case +Add-Type -AssemblyName System.Web +[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([System.Web.Security.Membership]::GeneratePassword(32,4))).Replace("+","-").Replace("/","_") +``` + + + + +```hcl +# Valid 32 Byte Base64 URL encoding set that will decode to 24 []byte AES-192 secret +resource "random_password" "cookie_secret" { + length = 32 + override_special = "-_" +} +``` + + + + +## Config File + +Every command line argument can be specified in a config file by replacing hyphens (-) with underscores (\_). If the argument can be specified multiple times, the config option should be plural (trailing s). + +An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/oauth2-proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `--config=/etc/oauth2-proxy.cfg` + +## Config Options + +### Command Line Options + +| Flag | Description | +| ----------- | -------------------- | +| `--config` | path to config file | +| `--version` | print version string | + +### General Provider Options + +Provider specific options can be found on their respective subpages. + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| flag: `--acr-values`
toml: `acr_values` | string | optional, see [docs](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues) | `""` | +| flag: `--allowed-group`
toml: `allowed_groups` | string \| list | Restrict login to members of a group or list of groups. Furthermore, if you aren't setting the `scope` and use `allowed_groups` with the generic OIDC provider the scope `groups` gets added implicitly. | | +| flag: `--approval-prompt`
toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` | +| flag: `--backend-logout-url`
toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | | +| flag: `--client-id`
toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | | +| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret | | +| flag: `--client-secret`
toml: `client_secret` | string | the OAuth Client Secret | | +| flag: `--code-challenge-method`
toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | | +| flag: `--insecure-oidc-allow-unverified-email`
toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false | +| flag: `--insecure-oidc-skip-issuer-verification`
toml: `insecure_oidc_skip_issuer_verification` | bool | allow the OIDC issuer URL to differ from the expected (currently required for Azure multi-tenant compatibility) | false | +| flag: `--insecure-oidc-skip-nonce`
toml: `insecure_oidc_skip_nonce` | bool | skip verifying the OIDC ID Token's nonce claim | true | +| flag: `--jwt-key-file`
toml: `jwt_key_file` | string | path to the private key file in PEM format used to sign the JWT so that you can say something like `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem`: required by login.gov | | +| flag: `--jwt-key`
toml: `jwt_key` | string | private key in PEM format used to sign JWT, so that you can say something like `--jwt-key="${OAUTH2_PROXY_JWT_KEY}"`: required by login.gov | | +| flag: `--login-url`
toml: `login_url` | string | Authentication endpoint | | +| flag: `--auth-request-response-mode`
toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | | +| flag: `--oidc-audience-claim`
toml: `oidc_audience_claims` | string | which OIDC claim contains the audience | `"aud"` | +| flag: `--oidc-email-claim`
toml: `oidc_email_claim` | string | which OIDC claim contains the user's email | `"email"` | +| flag: `--oidc-extra-audience`
toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` | +| flag: `--oidc-groups-claim`
toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` | +| flag: `--oidc-issuer-url`
toml: `oidc_issuer_url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | | +| flag: `--oidc-jwks-url`
toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled and public key files are not provided | | +| flag: `--oidc-public-key-file`
toml: `oidc_public_key_files` | string | Path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times). Required if OIDC discovery is disabled na JWKS URL isn't provided | string \| list | +| flag: `--profile-url`
toml: `profile_url` | string | Profile access endpoint | | +| flag: `--prompt`
toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` | +| flag: `--provider-ca-file`
toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. | +| flag: `--provider-display-name`
toml: `provider_display_name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) | +| flag: `--provider`
toml: `provider` | string | OAuth provider | google | +| flag: `--pubjwk-url`
toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | | +| flag: `--redeem-url`
toml: `redeem_url` | string | Token redemption endpoint | | +| flag: `--scope`
toml:`scope` | string | OAuth scope specification. Every provider has a default list of scopes which will be used in case no scope is configured. | | +| flag: `--skip-claims-from-profile-url`
toml: `skip_claims_from_profile_url` | bool | skip request to Profile URL for resolving claims not present in id_token | false | +| flag: `--skip-oidc-discovery`
toml: `skip_oidc_discovery` | bool | bypass OIDC endpoint discovery. `--login-url`, `--redeem-url` and `--oidc-jwks-url` must be configured in this case | false | +| flag: `--use-system-trust-store`
toml: `use_system_trust_store` | bool | Determines if `provider-ca-file` files and the system trust store are used. If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | false | +| flag: `--validate-url`
toml: `validate_url` | string | Access token validation endpoint | | + +### Cookie Options + +| Flag / Config Field | Type | Description | Default | +| -------------------------------------------------------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | +| flag: `--cookie-csrf-expire`
toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m | +| flag: `--cookie-csrf-per-request`
toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false | +| flag: `--cookie-domain`
toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | | +| flag: `--cookie-expire`
toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s | +| flag: `--cookie-httponly`
toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true | +| flag: `--cookie-name`
toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` | +| flag: `--cookie-path`
toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` | +| flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | +| flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | +| flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | +| flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | + +[^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) + +### Header Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--basic-auth-password`
toml: `basic_auth_password` | string | the password to set when passing the HTTP Basic Auth header | | +| flag: `--set-xauthrequest`
toml: `set_xauthrequest` | bool | set X-Auth-Request-User, X-Auth-Request-Groups, X-Auth-Request-Email and X-Auth-Request-Preferred-Username response headers (useful in Nginx auth_request mode). When used with `--pass-access-token`, X-Auth-Request-Access-Token is added to response headers. | false | +| flag: `--set-authorization-header`
toml: `set_authorization_header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false | +| flag: `--set-basic-auth`
toml: `set_basic_auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false | +| flag: `--skip-auth-strip-headers`
toml: `skip_auth_strip_headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy | true | +| flag: `--pass-access-token`
toml: `pass_access_token` | bool | pass OAuth access_token to upstream via X-Forwarded-Access-Token header. When used with `--set-xauthrequest` this adds the X-Auth-Request-Access-Token header to the response | false | +| flag: `--pass-authorization-header`
toml: `pass_authorization_header` | bool | pass OIDC IDToken to upstream via Authorization Bearer header | false | +| flag: `--pass-basic-auth`
toml: `pass_basic_auth` | bool | pass HTTP Basic Auth, X-Forwarded-User, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | +| flag: `--prefer-email-to-user`
toml: `prefer_email_to_user` | bool | Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, e.g. htaccess authentication. Used in conjunction with `--pass-basic-auth` and `--pass-user-headers` | false | +| flag: `--pass-user-headers`
toml: `pass_user_headers` | bool | pass X-Forwarded-User, X-Forwarded-Groups, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | + +### Logging Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------- | --------------------------------------------------- | +| flag: `--auth-logging-format`
toml: `auth_logging_format` | string | Template for authentication log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--auth-logging`
toml: `auth_logging` | bool | Log authentication attempts | true | +| flag: `--errors-to-info-log`
toml: `errors_to_info_log` | bool | redirects error-level logging to default log channel instead of stderr | false | +| flag: `--exclude-logging-path`
toml: `exclude_logging_paths` | string | comma separated list of paths to exclude from logging, e.g. `"/ping,/path2"` | `""` (no paths excluded) | +| flag: `--logging-compress`
toml: `logging_compress` | bool | Should rotated log files be compressed using gzip | false | +| flag: `--logging-filename`
toml: `logging_filename` | string | File to log requests to, empty for `stdout` | `""` (stdout) | +| flag: `--logging-local-time`
toml: `logging_local_time` | bool | Use local time in log files and backup filenames instead of UTC | true (local time) | +| flag: `--logging-max-age`
toml: `logging_max_age` | int | Maximum number of days to retain old log files | 7 | +| flag: `--logging-max-backups`
toml: `logging_max_backups` | int | Maximum number of old log files to retain; 0 to disable | 0 | +| flag: `--logging-max-size`
toml: `logging_max_size` | int | Maximum size in megabytes of the log file before rotation | 100 | +| flag: `--request-id-header`
toml: `request_id_header` | string | Request header to use as the request ID in logging | X-Request-Id | +| flag: `--request-logging-format`
toml: `request_logging_format` | string | Template for request log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--request-logging`
toml: `request_logging` | bool | Log requests | true | +| flag: `--silence-ping-logging`
toml: `silence_ping_logging` | bool | disable logging of requests to ping & ready endpoints | false | +| flag: `--standard-logging-format`
toml: `standard_logging_format` | string | Template for standard log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--standard-logging`
toml: `standard_logging` | bool | Log standard runtime information | true | + +### Page Template Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--banner`
toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | | +| flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | +| flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | +| flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | +| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | | +| flag: `--show-debug-on-error`
toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false | + +### Probe Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------- | ------ | ---------------------------------------------------------- | ----------------------------- | +| flag: `--ping-path`
toml: `ping_path` | string | the ping endpoint that can be used for basic health checks | `"/ping"` | +| flag: `--ping-user-agent`
toml: `ping_user_agent` | string | a User-Agent that can be used for basic health checks | `""` (don't check user agent) | +| flag: `--ready-path`
toml: `ready_path` | string | the ready endpoint that can be used for deep health checks | `"/ready"` | +| flag: `--gcp-healthchecks`
toml: `gcp_healthchecks` | bool | Enable GCP/GKE healthcheck endpoints (deprecated) | false | + +### Proxy Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--bearer-token-login-fallback`
toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | + +[^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. + +### Server Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | +| flag: `--http-address`
toml: `http_address` | string | `[http://]:` or `unix://` or `fd:` (case insensitive) to listen on for HTTP clients. Square brackets are required for ipv6 address, e.g. `http://[::1]:4180` | `"127.0.0.1:4180"` | +| flag: `--https-address`
toml: `https_address` | string | `[https://]:` to listen on for HTTPS clients. Square brackets are required for ipv6 address, e.g. `https://[::1]:443` | `":443"` | +| flag: `--metrics-address`
toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` | +| flag: `--metrics-secure-address`
toml: `metrics_secure_address` | string | the address prometheus metrics will be scraped from if using HTTPS | `""` | +| flag: `--metrics-tls-cert-file`
toml: `metrics_tls_cert_file` | string | path to certificate file for secure metrics server | `""` | +| flag: `--metrics-tls-key-file`
toml: `metrics_tls_key_file` | string | path to private key file for secure metrics server | `""` | +| flag: `--tls-cert-file`
toml: `tls_cert_file` | string | path to certificate file | | +| flag: `--tls-key-file`
toml: `tls_key_file` | string | path to private key file | | +| flag: `--tls-cipher-suite`
toml: `tls_cipher_suites` | string \| list | Restricts TLS cipher suites used by server to those listed (e.g. TLS_RSA_WITH_RC4_128_SHA) (may be given multiple times). If not specified, the default Go safe cipher list is used. List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | | +| flag: `--tls-min-version`
toml: `tls_min_version` | string | minimum TLS version that is acceptable, either `"TLS1.2"` or `"TLS1.3"` | `"TLS1.2"` | + +### Session Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--session-cookie-minimal`
toml: `session_cookie_minimal` | bool | strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only) | false | +| flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | +| flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | +| flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | +| flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | +| flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | +| flag: `--redis-sentinel-master-name`
toml: `redis_sentinel_master_name` | string | Redis sentinel master name. Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-sentinel-connection-urls`
toml: `redis_sentinel_connection_urls` | string \| list | List of Redis sentinel connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-use-cluster`
toml: `redis_use_cluster` | bool | Connect to redis cluster. Must set `--redis-cluster-connection-urls` to use this feature | false | +| flag: `--redis-use-sentinel`
toml: `redis_use_sentinel` | bool | Connect to redis via sentinels. Must set `--redis-sentinel-master-name` and `--redis-sentinel-connection-urls` to use this feature | false | +| flag: `--redis-connection-idle-timeout`
toml: `redis_connection_idle_timeout` | int | Redis connection idle timeout seconds. If Redis [timeout](https://redis.io/docs/reference/clients/#client-timeouts) option is set to non-zero, the `--redis-connection-idle-timeout` must be less than Redis timeout option. Example: if either redis.conf includes `timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` | 0 | + +### Upstream Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | +| flag: `--flush-interval`
toml: `flush_interval` | duration | period between flushing response buffers when streaming responses | `"1s"` | +| flag: `--pass-host-header`
toml: `pass_host_header` | bool | pass the request Host Header to upstream | true | +| flag: `--proxy-websockets`
toml: `proxy_websockets` | bool | enables WebSocket proxying | true | +| flag: `--ssl-upstream-insecure-skip-verify`
toml: `ssl_upstream_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false | +| flag: `--upstream-timeout`
toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s | +| flag: `--upstream`
toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://` for static response. Routing is based on the path | | + +## Upstreams Configuration + +`oauth2-proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers, unix socket or serve static files from the file system. + +To configure **HTTP and HTTPS upstreams**, provide such a URL in `--upstream=URL`. The scheme+host portion and the path portion are extracted to configure proxying behavior. When processing incoming requests, the path portion becomes a lookup key for selecting the destination server of the proxied request. + +* Upstream URLs *without a trailing slash,* like in `--upstream=http://service2.internal/foo`, will match an incoming request exactly to `/foo` in `https://this.o2p.example.com/foo`, and forward the request on to service2.internal, but not match a request to `https://this.o2p.example.com/foo/more` nor ...`.com/food`. +* Upstream URLs *with a trailing slash,* like in `--upstream=http://service1.internal/foo/`, will match any incoming request to any incoming requests's path *starting with* `/foo/`, like `/foo/` and `/foo/more` and `/foo/lots/more?etc`. + +If multiple `--upstream` URLs' paths match an incoming request, the one with the longest matching path (the most specific match) takes priority over shorter (less specific) ones. + +**Unix socket upstreams** are configured as `unix:///path/to/unix.sock`. + +**Static file paths** are configured as a file:// URL. `file:///var/www/static/` will serve the files from that directory at `http://[oauth2-proxy url]/var/www/static/`, which may not be what you want. You can provide the path to where the files should be available by adding a fragment to the configured URL. The value of the fragment will then be used to specify which path the files are available at, e.g. `file:///var/www/static/#/static/` will make `/var/www/static/` available at `http://[oauth2-proxy url]/static/`. + +Multiple upstreams can either be configured by supplying a comma separated list to the `--upstream` parameter, supplying the parameter multiple times or providing a list in the [config file](#config-file). When multiple upstreams are used routing to them will be based on the path they are set up with. + +## Environment variables + +Every command line argument can be specified as an environment variable by +prefixing it with `OAUTH2_PROXY_`, capitalising it, and replacing hyphens (`-`) +with underscores (`_`). If the argument can be specified multiple times, the +environment variable should be plural (trailing `S`). + +This is particularly useful for storing secrets outside a configuration file +or the command line. + +For example, the `--cookie-secret` flag becomes `OAUTH2_PROXY_COOKIE_SECRET`. +If a flag has the type `string | list` like the `--email-domain` flag it is +available as an environment variable in plural form e.g. `OAUTH2_PROXY_EMAIL_DOMAINS` + +Values for type `string | list` usually have a plural environment variable name +and need to be seperated by `,` e.g. +`OAUTH2_PROXY_SKIP_AUTH_ROUTES="GET=^/api/status,POST=^/api/saved_objects/_import"` + +Please check the type for each [config option](#config-options) first. + +## Logging Configuration + +By default, OAuth2 Proxy logs all output to stdout. Logging can be configured to output to a rotating log file using the `--logging-filename` command. + +If logging to a file you can also configure the maximum file size (`--logging-max-size`), age (`--logging-max-age`), max backup logs (`--logging-max-backups`), and if backup logs should be compressed (`--logging-compress`). + +There are three different types of logging: standard, authentication, and HTTP requests. These can each be enabled or disabled with `--standard-logging`, `--auth-logging`, and `--request-logging`. + +Each type of logging has its own configurable format and variables. By default, these formats are similar to the Apache Combined Log. + +Logging of requests to the `/ping` endpoint (or using `--ping-user-agent`) and the `/ready` endpoint can be disabled with `--silence-ping-logging` reducing log volume. + +## Auth Log Format + +Authentication logs are logs which are guaranteed to contain a username or email address of a user attempting to authenticate. These logs are output by default in the below format: + +``` + - - [2015/03/19 17:20:19] [] +``` + +The status block will contain one of the below strings: + +- `AuthSuccess` If a user has authenticated successfully by any method +- `AuthFailure` If the user failed to authenticate explicitly +- `AuthError` If there was an unexpected error during authentication + +If you require a different format than that, you can configure it with the `--auth-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}} +``` + +Available variables for auth logging: + +| Variable | Example | Description | +| ------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Message | Authenticated via OAuth2 | The details of the auth attempt. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | +| Status | AuthSuccess | The status of the auth request. See above for details. | + +## Request Log Format + +HTTP request logs will output by default in the below format: + +``` + - - [2015/03/19 17:20:19] GET "/path/" HTTP/1.1 "" +``` + +If you require a different format than that, you can configure it with the `--request-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}} +``` + +Available variables for request logging: + +| Variable | Example | Description | +| --------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestDuration | 0.001 | The time in seconds that a request took to process. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| RequestURI | "/oauth2/auth" | The URI path of the request. | +| ResponseSize | 12 | The size in bytes of the response. | +| StatusCode | 200 | The HTTP status code of the response. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| Upstream | - | The upstream data of the HTTP request. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | + +## Standard Log Format + +All other logging that is not covered by the above two types of logging will be output in this standard logging format. This includes configuration information at startup and errors that occur outside of a session. The default format is below: + +``` +[2015/03/19 17:20:19] [main.go:40] +``` + +If you require a different format than that, you can configure it with the `--standard-logging-format` flag. The default format is configured as follows: + +``` +[{{.Timestamp}}] [{{.File}}] {{.Message}} +``` + +Available variables for standard logging: + +| Variable | Example | Description | +| --------- | --------------------------------- | -------------------------------------------------- | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| File | main.go:40 | The file and line number of the logging statement. | +| Message | HTTP: listening on 127.0.0.1:4180 | The details of the log statement. | diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/adfs.md b/docs/versioned_docs/version-7.10.x/configuration/providers/adfs.md new file mode 100644 index 0000000000..ec8d72d2af --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/adfs.md @@ -0,0 +1,19 @@ +--- +id: adfs +title: ADFS +--- + +1. Open the ADFS administration console on your Windows Server and add a new Application Group +2. Provide a name for the integration, select Server Application from the Standalone applications section and click Next +3. Follow the wizard to get the client-id, client-secret and configure the application credentials +4. Configure the proxy with + +``` + --provider=adfs + --client-id= + --client-secret= +``` + +Note: When using the ADFS Auth provider with nginx and the cookie session store you may find the cookie is too large and +doesn't get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the +[redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/bitbucket.md b/docs/versioned_docs/version-7.10.x/configuration/providers/bitbucket.md new file mode 100644 index 0000000000..e31de7526c --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/bitbucket.md @@ -0,0 +1,25 @@ +--- +id: bitbucket +title: BitBucket +--- + +1. [Add a new OAuth consumer](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html) + * In "Callback URL" use `https:///oauth2/callback`, substituting `` with the actual + hostname that oauth2-proxy is running on. + * In Permissions section select: + * Account -> Email + * Team membership -> Read + * Repositories -> Read +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=bitbucket + --client-id= + --client-secret= +``` + +The default configuration allows everyone with Bitbucket account to authenticate. To restrict the access to the team +members use additional configuration option: `--bitbucket-team=`. To restrict the access to only these users +who have access to one selected repository use `--bitbucket-repository=`. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/digitalocean.md b/docs/versioned_docs/version-7.10.x/configuration/providers/digitalocean.md new file mode 100644 index 0000000000..f6a1e89181 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/digitalocean.md @@ -0,0 +1,21 @@ +--- +id: digitalocean +title: DigitalOcean +--- + +1. [Create a new OAuth application](https://cloud.digitalocean.com/account/api/applications) + * You can fill in the name, homepage, and description however you wish. + * In the "Application callback URL" field, enter: `https://oauth-proxy/oauth2/callback`, substituting `oauth2-proxy` + with the actual hostname that oauth2-proxy is running on. The URL must match oauth2-proxy's configured redirect URL. +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=digitalocean + --client-id= + --client-secret= +``` + +Alternatively, set the equivalent options in the config file. The redirect URL defaults to +`https:///oauth2/callback`. If you need to change it, you can use the `--redirect-url` command-line option. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/facebook.md b/docs/versioned_docs/version-7.10.x/configuration/providers/facebook.md new file mode 100644 index 0000000000..352c95ce1e --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/facebook.md @@ -0,0 +1,7 @@ +--- +id: facebook +title: Facebook +--- + +1. Create a new FB App from https://developers.facebook.com/ +2. Under FB Login, set your Valid OAuth redirect URIs to `https://internal.yourcompany.com/oauth2/callback` diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/gitea.md b/docs/versioned_docs/version-7.10.x/configuration/providers/gitea.md new file mode 100644 index 0000000000..996a5ddbdb --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/gitea.md @@ -0,0 +1,24 @@ +--- +id: gitea +title: Gitea +--- + +:::note +This is not actually its own provider. For more details and options please refer to the [GitHub Provider Options](github.md) +::: + +1. Create a new application: `https://< your gitea host >/user/settings/applications` +2. Under `Redirect URI` enter the correct URL i.e. `https:///oauth2/callback` +3. Note the Client ID and Client Secret. +4. Pass the following options to the proxy: + +``` + --provider="github" + --redirect-url="https:///oauth2/callback" + --provider-display-name="Gitea" + --client-id="< client_id as generated by Gitea >" + --client-secret="< client_secret as generated by Gitea >" + --login-url="https://< your gitea host >/login/oauth/authorize" + --redeem-url="https://< your gitea host >/login/oauth/access_token" + --validate-url="https://< your gitea host >/api/v1/user/emails" +``` diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/github.md b/docs/versioned_docs/version-7.10.x/configuration/providers/github.md new file mode 100644 index 0000000000..cebca31411 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/github.md @@ -0,0 +1,81 @@ +--- +id: github +title: GitHub +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------- | ------- | +| `--github-org` | `github_org` | string | restrict logins to members of this organisation | | +| `--github-team` | `github_team` | string | restrict logins to members of any of these teams (slug) or (org:team), comma separated | | +| `--github-repo` | `github_repo` | string | restrict logins to collaborators of this repository formatted as `orgname/repo` | | +| `--github-token` | `github_token` | string | the token to use when verifying repository collaborators (must have push access to the repository) | | +| `--github-user` | `github_users` | string \| list | To allow users to login by username even if they do not belong to the specified org and team or collaborators | | + +## Usage + +1. Create a new project: https://github.com/settings/developers +2. Under `Authorization callback URL` enter the correct url ie `https://internal.yourcompany.com/oauth2/callback` + +The GitHub auth provider supports two additional ways to restrict authentication to either organization and optional +team level access, or to collaborators of a repository. Restricting by these options is normally accompanied with `--email-domain=*`. Additionally, all the organizations and teams a user belongs to are set as part of the `X-Forwarded-Groups` header. e.g. `org1:team1,org1:team2,org2:team1` + +NOTE: When `--github-user` is set, the specified users are allowed to log in even if they do not belong to the specified +org and team or collaborators. + +To restrict access to your organization: + +```shell + # restrict logins to members of this organisation + --github-org="your-org" +``` + +To restrict access to specific teams within an organization: + +```shell + --github-org="your-org" + # restrict logins to members of any of these teams (slug), comma separated + --github-team="team1,team2,team3" +``` + +To restrict to teams within different organizations, keep the organization flag empty and use `--github-team` like so: + +```shell + # keep empty + --github-org="" + # restrict logins to members to any of the following teams (format :, like octo:team1), comma separated + --github-team="org1:team1,org2:team1,org3:team42,octo:cat" +``` + +If you would rather restrict access to collaborators of a repository, those users must either have push access to a +public repository or any access to a private repository: + +```shell + # restrict logins to collaborators of this repository formatted as orgname/repo + --github-repo="" +``` + +If you'd like to allow access to users with **read only** access to a **public** repository you will need to provide a +[token](https://github.com/settings/tokens) for a user that has write access to the repository. The token must be +created with at least the `public_repo` scope: + +```shell + # the token to use when verifying repository collaborators + --github-token="" +``` + +To allow a user to log in with their username even if they do not belong to the specified org and team or collaborators: + +```shell + # allow logins by username, comma separated + --github-user="" +``` + +If you are using GitHub enterprise, make sure you set the following to the appropriate url: + +```shell + --login-url="http(s):///login/oauth/authorize" + --redeem-url="http(s):///login/oauth/access_token" + --validate-url="http(s):///api/v3" +``` diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.10.x/configuration/providers/gitlab.md new file mode 100644 index 0000000000..4cdbbbe1e0 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/gitlab.md @@ -0,0 +1,49 @@ +--- +id: gitlab +title: GitLab +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | +| `--gitlab-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 | | + +## Usage + +This auth provider has been tested against Gitlab version 12.X. Due to Gitlab API changes, it may not work for version +prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)). + +Whether you are using GitLab.com or self-hosting GitLab, follow +[these steps to add an application](https://docs.gitlab.com/integration/oauth_provider/). Make sure to enable at +least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. +https://myapp.com/oauth2/callback. + +If you need projects filtering, add the extra `read_api` scope to your application. + +The following config should be set to ensure that the oauth will work properly. To get a cookie secret follow +[these steps](../overview.md#generating-a-cookie-secret) + +``` + --provider="gitlab" + --redirect-url="https://myapp.com/oauth2/callback" // Should be the same as the redirect url for the application in gitlab + --client-id=GITLAB_CLIENT_ID + --client-secret=GITLAB_CLIENT_SECRET + --cookie-secret=COOKIE_SECRET +``` + +Restricting by group membership is possible with the following option: + +```shell + --gitlab-group="mygroup,myothergroup" # restrict logins to members of any of these groups (slug), separated by a comma +``` + +If you are using self-hosted GitLab, make sure you set the following to the appropriate URL: + +```shell + --oidc-issuer-url="" +``` + +If your self-hosted GitLab is on a subdirectory (e.g. domain.tld/gitlab), as opposed to its own subdomain +(e.g. gitlab.domain.tld), you may need to add a redirect from domain.tld/oauth pointing at e.g. domain.tld/gitlab/oauth. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/google.md b/docs/versioned_docs/version-7.10.x/configuration/providers/google.md new file mode 100644 index 0000000000..e3e819adad --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/google.md @@ -0,0 +1,76 @@ +--- +id: google +title: Google (default) +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------------------------------------- | -------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------ | -------------------------------------------------- | +| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | +| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). | | +| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | +| `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | +| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | + +## Usage + +For Google, the registration steps are: + +1. Create a new project: https://console.developers.google.com/project +2. Choose the new project from the top right project dropdown (only if another project is selected) +3. In the project Dashboard center pane, choose **"APIs & Services"** +4. In the left Nav pane, choose **"Credentials"** +5. In the center pane, choose **"OAuth consent screen"** tab. Fill in **"Product name shown to users"** and hit save. +6. In the center pane, choose **"Credentials"** tab. + - Open the **"New credentials"** drop down + - Choose **"OAuth client ID"** + - Choose **"Web application"** + - Application name is freeform, choose something appropriate + - Authorized JavaScript origins is your domain ex: `https://internal.yourcompany.com` + - Authorized redirect URIs is the location of oauth2/callback ex: `https://internal.yourcompany.com/oauth2/callback` + - Choose **"Create"** +7. Take note of the **Client ID** and **Client Secret** + +It's recommended to refresh sessions on a short interval (1h) with `cookie-refresh` setting which validates that the +account is still authorized. + +#### Restrict auth to specific Google groups on your domain. (optional) + +1. Create a [service account](https://developers.google.com/identity/protocols/OAuth2ServiceAccount) and configure it + to use [Application Default Credentials / Workload Identity / Workload Identity Federation (recommended)](#using-application-default-credentials-adc--workload-identity--workload-identity-federation-recommended) or, + alternatively download the JSON. +2. Make note of the Client ID for a future step. +3. Under "APIs & Auth", choose APIs. +4. Click on Admin SDK and then Enable API. +5. Follow the steps on https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account + and give the client id from step 2 the following oauth scopes: + + ``` + https://www.googleapis.com/auth/admin.directory.group.readonly + https://www.googleapis.com/auth/admin.directory.user.readonly + ``` + +6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access. +7. Create or choose an existing administrative email address on the Gmail domain to assign to the `google-admin-email` + flag. This email will be impersonated by this client to make calls to the Admin SDK. See the note on the link from + step 5 for the reason why. +8. Create or choose an existing email group and set that email to the `google-group` flag. You can pass multiple instances + of this flag with different groups and the user will be checked against all the provided groups. + +(Only if using a JSON file (see step 1)) + +9. Lock down the permissions on the json file downloaded from step 1 so only oauth2-proxy is able to read the file and + set the path to the file in the `google-service-account-json` flag. +10. Restart oauth2-proxy. + +Note: The user is checked against the group members list on initial authentication and every time the token is +refreshed ( about once an hour ). + +##### Using Application Default Credentials (ADC) / Workload Identity / Workload Identity Federation (recommended) +oauth2-proxy can make use of [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials). +When deployed within GCP, this means that it can automatically use the service account attached to the resource. When deployed to GKE, ADC +can be leveraged through a feature called Workload Identity. Follow Google's [guide](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity) +to set up Workload Identity. + +When deployed outside of GCP, [Workload Identity Federation](https://cloud.google.com/docs/authentication/provide-credentials-adc#wlif) might be an option. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/index.md b/docs/versioned_docs/version-7.10.x/configuration/providers/index.md new file mode 100644 index 0000000000..b947c09b7e --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/index.md @@ -0,0 +1,43 @@ +--- +id: index +title: OAuth Provider Configuration +--- + +You will need to register an OAuth application with a Provider (Google, GitHub or another provider), and configure it +with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on. + +Valid providers are : + +- [ADFS](adfs.md) +- [Bitbucket](bitbucket.md) +- [DigitalOcean](digitalocean.md) +- [Facebook](facebook.md) +- [Gitea](gitea.md) +- [GitHub](github.md) +- [GitLab](gitlab.md) +- [Google](google.md) _default_ +- [Keycloak](keycloak.md) (Deprecated) +- [Keycloak OIDC](keycloak_oidc.md) +- [LinkedIn](linkedin.md) +- [login.gov](login_gov.md) +- [Microsoft Azure](ms_azure_ad.md) (Deprecated) +- [Microsoft Entra ID](ms_entra_id.md) +- [Nextcloud](nextcloud.md) +- [OpenID Connect](openid_connect.md) + +The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the +OpenID Connect provider. + +## Email Authentication + +To authorize a specific email-domain use `--email-domain=yourcompany.com`. To authorize individual email addresses use +`--authenticated-emails-file=/path/to/file` with one email per line. To authorize all email addresses use `--email-domain=*`. + +## Adding a new Provider + +Follow the examples in the [`providers` package](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/) to define a new +`Provider` instance. Add a new `case` to +[`providers.New()`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/providers.go) to allow `oauth2-proxy` to use the +new `Provider`. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/keycloak.md b/docs/versioned_docs/version-7.10.x/configuration/providers/keycloak.md new file mode 100644 index 0000000000..11a1abca1c --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/keycloak.md @@ -0,0 +1,36 @@ +--- +id: keycloak +title: Keycloak (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Keycloak, use [Keycloak OIDC Auth Provider](keycloak_oidc.md) if possible. +::: + +1. Create new client in your Keycloak realm with **Access Type** 'confidential' and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. + +Make sure you set the following to the appropriate url: + +``` + --provider=keycloak + --client-id= + --client-secret= + --login-url="http(s):///auth/realms//protocol/openid-connect/auth" + --redeem-url="http(s):///auth/realms//protocol/openid-connect/token" + --profile-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --validate-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --keycloak-group= + --keycloak-group= +``` + +For group based authorization, the optional `--keycloak-group` (legacy) or `--allowed-group` (global standard) +flags can be used to specify which groups to limit access to. + +If these are unset but a `groups` mapper is set up above in step (3), the provider will still +populate the `X-Forwarded-Groups` header to your upstream server with the `groups` data in the +Keycloak userinfo endpoint response. + +The group management in keycloak is using a tree. If you create a group named admin in keycloak +you should define the 'keycloak-group' value to /admin. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/keycloak_oidc.md b/docs/versioned_docs/version-7.10.x/configuration/providers/keycloak_oidc.md new file mode 100644 index 0000000000..b29096e35d --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/keycloak_oidc.md @@ -0,0 +1,151 @@ +--- +id: keycloak_oidc +title: Keycloak OIDC +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------ | ------- | +| `--allowed-role` | `allowed_roles` | string \| list | restrict logins to users with this role (may be given multiple times). Only works with the keycloak-oidc provider. | | + +## Usage + +``` + --provider=keycloak-oidc + --client-id= + --client-secret= + --redirect-url=https://internal.yourcompany.com/oauth2/callback + --oidc-issuer-url=https:///realms/ // For Keycloak versions <17: --oidc-issuer-url=https:///auth/realms/ + --email-domain= // Validate email domain for users, see option documentation + --allowed-role= // Optional, required realm role + --allowed-role=: // Optional, required client role + --allowed-group= // Optional, requires group client scope + --code-challenge-method=S256 // PKCE +``` + +:::note +Keycloak has updated its admin console and as of version 19.0.0, the new admin console is enabled by default. The +legacy admin console has been announced for removal with the release of version 21.0.0. +::: + +**Keycloak legacy admin console** + +1. Create new client in your Keycloak realm with **Access Type** 'confidential', **Client protocol** 'openid-connect' + and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. +4. Create a mapper with **Mapper Type** 'Audience' and **Included Client Audience** and **Included Custom Audience** set + to your client name. + +**Keycloak new admin console (default as of v19.0.0)** + +The following example shows how to create a simple OIDC client using the new Keycloak admin2 console. However, for best +practices, it is recommended to consult the Keycloak documentation. + +The OIDC client must be configured with an _audience mapper_ to include the client's name in the `aud` claim of the JWT token. +The `aud` claim specifies the intended recipient of the token, and OAuth2 Proxy expects a match against the values of +either `--client-id` or `--oidc-extra-audience`. + +_In Keycloak, claims are added to JWT tokens through the use of mappers at either the realm level using "client scopes" or +through "dedicated" client mappers._ + +**Creating the client** + +1. Create a new OIDC client in your Keycloak realm by navigating to: + **Clients** -> **Create client** + * **Client Type** 'OpenID Connect' + * **Client ID** ``, please complete the remaining fields as appropriate and click **Next**. + * **Client authentication** 'On' + * **Authentication flow** + * **Standard flow** 'selected' + * **Direct access grants** 'deselect' + * _Save the configuration._ + * **Settings / Access settings**: + * **Valid redirect URIs** `https://internal.yourcompany.com/oauth2/callback` + * _Save the configuration._ + * Under the **Credentials** tab you will now be able to locate ``. +2. Configure a dedicated *audience mapper* for your client by navigating to **Clients** -> **\** -> **Client scopes**. +* Access the dedicated mappers pane by clicking **\-dedicated**, located under *Assigned client scope*. + _(It should have a description of "Dedicated scope and mappers for this client")_ + * Click **Configure a new mapper** and select **Audience** + * **Name** 'aud-mapper-\' + * **Included Client Audience** select `` from the dropdown. + * _OAuth2 proxy can be set up to pass both the access and ID JWT tokens to your upstream services. + If you require additional audience entries, you can use the **Included Custom Audience** field in addition + to the "Included Client Audience" dropdown. Note that the "aud" claim of a JWT token should be limited and + only specify its intended recipients._ + * **Add to ID token** 'On' + * **Add to access token** 'On' - [#1916](https://github.com/oauth2-proxy/oauth2-proxy/pull/1916) + * _Save the configuration._ +* Any subsequent dedicated client mappers can be defined by clicking **Dedicated scopes** -> **Add mapper** -> + **By configuration** -> *Select mapper* + +You should now be able to create a test user in Keycloak and get access to the OAuth2 Proxy instance, make sure to set +an email address matching `` and select _Email verified_. + +**Authorization** + +_OAuth2 Proxy will perform authorization by requiring a valid user, this authorization can be extended to take into +account a user's membership in Keycloak `groups`, `realm roles`, and `client roles` using the keycloak-oidc provider options +`--allowed-role` or `--allowed-group`_ + +**Roles** + +_A standard Keycloak installation comes with the required mappers for **realm roles** and **client roles** through the +pre-defined client scope "roles". This ensures that any roles assigned to a user are included in the `JWT` tokens when +using an OIDC client that has the "Full scope allowed" feature activated, the feature is enabled by default._ + +_Creating a realm role_ +* Navigate to **Realm roles** -> **Create role** + * **Role name**, *``* -> **save** + +_Creating a client role_ +* Navigate to **Clients** -> `` -> **Roles** -> **Create role** + * **Role name**, *``* -> **save** + + +_Assign a role to a user_ + +**Users** -> _Username_ -> **Role mapping** -> **Assign role** -> _filter by roles or clients and select_ -> **Assign**. + +Keycloak "realm roles" can be authorized using the `--allowed-role=` option, while "client roles" can be +evaluated using `--allowed-role=:`. + +You may limit the _realm roles_ included in the JWT tokens for any given client by navigating to: +**Clients** -> `` -> **Client scopes** -> _\-dedicated_ -> **Scope** +Disabling **Full scope allowed** activates the **Assign role** option, allowing you to select which roles, if assigned +to a user, will be included in the user's JWT tokens. This can be useful when a user has many associated roles, and you +want to reduce the size and impact of the JWT token. + + +**Groups** + +You may also do authorization on group memberships by using the OAuth2 Proxy option `--allowed-group`. +We will only do a brief description of creating the required _client scope_ **groups** and refer you to read the Keycloak +documentation. + +To summarize, the steps required to authorize Keycloak group membership with OAuth2 Proxy are as follows: + +* Create a new Client Scope with the name **groups** in Keycloak. + * Include a mapper of type **Group Membership**. + * Set the "Token Claim Name" to **groups** or customize by matching it to the `--oidc-groups-claim` option of OAuth2 Proxy. + * If the "Full group path" option is selected, you need to include a "/" separator in the group names defined in the + `--allowed-group` option of OAuth2 Proxy. Example: "/groupname" or "/groupname/child_group". + +After creating the _Client Scope_ named _groups_ you will need to attach it to your client. +**Clients** -> `` -> **Client scopes** -> **Add client scope** -> Select **groups** and choose Optional +and you should now have a client that maps group memberships into the JWT tokens so that Oauth2 Proxy may evaluate them. + +Create a group by navigating to **Groups** -> **Create group** and _add_ your test user as a member. + +The OAuth2 Proxy option `--allowed-group=/groupname` will now allow you to filter on group membership + +Keycloak also has the option of attaching roles to groups, please refer to the Keycloak documentation for more information. + +**Tip** + +To check if roles or groups are added to JWT tokens, you can preview a users token in the Keycloak console by following +these steps: **Clients** -> `` -> **Client scopes** -> **Evaluate**. +Select a _realm user_ and optional _scope parameters_ such as groups, and generate the JSON representation of an access +or id token to examine its contents. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/linkedin.md b/docs/versioned_docs/version-7.10.x/configuration/providers/linkedin.md new file mode 100644 index 0000000000..7d26ec4334 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/linkedin.md @@ -0,0 +1,13 @@ +--- +id: linkedin +title: LinkedIn +--- + +For LinkedIn, the registration steps are: + +1. Create a new project: https://www.linkedin.com/secure/developer +2. In the OAuth User Agreement section: + - In default scope, select r_basicprofile and r_emailaddress. + - In "OAuth 2.0 Redirect URLs", enter `https://internal.yourcompany.com/oauth2/callback` +3. Fill in the remaining required fields and Save. +4. Take note of the **Consumer Key / API Key** and **Consumer Secret / Secret Key** diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/login_gov.md b/docs/versioned_docs/version-7.10.x/configuration/providers/login_gov.md new file mode 100644 index 0000000000..badbe48e69 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/login_gov.md @@ -0,0 +1,79 @@ +--- +id: login_gov +title: Login.gov +--- + +login.gov is an OIDC provider for the US Government. +If you are a US Government agency, you can contact the login.gov team through the contact information +that you can find on https://login.gov/developers/ and work with them to understand how to get login.gov +accounts for integration/test and production access. + +A developer guide is available here: https://developers.login.gov/, though this proxy handles everything +but the data you need to create to register your application in the login.gov dashboard. + +As a demo, we will assume that you are running your application that you want to secure locally on +http://localhost:3000/, that you will be starting your proxy up on http://localhost:4180/, and that +you have an agency integration account for testing. + +First, register your application in the dashboard. The important bits are: +* Identity protocol: make this `Openid connect` +* Issuer: do what they say for OpenID Connect. We will refer to this string as `${LOGINGOV_ISSUER}`. +* Public key: This is a self-signed certificate in .pem format generated from a 2048-bit RSA private key. + A quick way to do this is + `openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -nodes -subj '/C=US/ST=Washington/L=DC/O=GSA/OU=18F/CN=localhost'`. + The contents of the `key.pem` shall be referred to as `${OAUTH2_PROXY_JWT_KEY}`. +* Return to App URL: Make this be `http://localhost:4180/` +* Redirect URIs: Make this be `http://localhost:4180/oauth2/callback`. +* Attribute Bundle: Make sure that email is selected. + +Now start the proxy up with the following options: +``` +./oauth2-proxy -provider login.gov \ + -client-id=${LOGINGOV_ISSUER} \ + -redirect-url=http://localhost:4180/oauth2/callback \ + -oidc-issuer-url=https://idp.int.identitysandbox.gov/ \ + -cookie-secure=false \ + -email-domain=gsa.gov \ + -upstream=http://localhost:3000/ \ + -cookie-secret=somerandomstring12341234567890AB \ + -cookie-domain=localhost \ + -skip-provider-button=true \ + -pubjwk-url=https://idp.int.identitysandbox.gov/api/openid_connect/certs \ + -profile-url=https://idp.int.identitysandbox.gov/api/openid_connect/userinfo \ + -jwt-key="${OAUTH2_PROXY_JWT_KEY}" +``` +You can also set all these options with environment variables, for use in cloud/docker environments. +One tricky thing that you may encounter is that some cloud environments will pass in environment +variables in a docker env-file, which does not allow multiline variables like a PEM file. +If you encounter this, then you can create a `jwt_signing_key.pem` file in the top level +directory of the repo which contains the key in PEM format and then do your docker build. +The docker build process will copy that file into your image which you can then access by +setting the `OAUTH2_PROXY_JWT_KEY_FILE=/etc/ssl/private/jwt_signing_key.pem` +environment variable, or by setting `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem` on the commandline. + +Once it is running, you should be able to go to `http://localhost:4180/` in your browser, +get authenticated by the login.gov integration server, and then get proxied on to your +application running on `http://localhost:3000/`. In a real deployment, you would secure +your application with a firewall or something so that it was only accessible from the +proxy, and you would use real hostnames everywhere. + +#### Skip OIDC discovery + +Some providers do not support OIDC discovery via their issuer URL, so oauth2-proxy cannot simply grab the authorization, +token and jwks URI endpoints from the provider's metadata. + +In this case, you can set the `--skip-oidc-discovery` option, and supply those required endpoints manually: + +``` + -provider oidc + -client-id oauth2-proxy + -client-secret proxy + -redirect-url http://127.0.0.1:4180/oauth2/callback + -oidc-issuer-url http://127.0.0.1:5556 + -skip-oidc-discovery + -login-url http://127.0.0.1:5556/authorize + -redeem-url http://127.0.0.1:5556/token + -oidc-jwks-url http://127.0.0.1:5556/keys + -cookie-secure=false + -email-domain example.com +``` diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/ms_azure_ad.md b/docs/versioned_docs/version-7.10.x/configuration/providers/ms_azure_ad.md new file mode 100644 index 0000000000..4feefc6800 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/ms_azure_ad.md @@ -0,0 +1,59 @@ +--- +id: azure +title: Azure (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Azure, use [Microsoft Entra ID](ms_entra_id.md) if possible. +::: + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | ------ | ---------------------------------------------------------------- | ---------- | +| `--azure-tenant` | `azure_tenant` | string | go to a tenant-specific or common (tenant-independent) endpoint. | `"common"` | +| `--resource` | `resource` | string | The resource that is protected (Azure AD only) | | + +## Usage + +1. Add an application: go to [https://portal.azure.com](https://portal.azure.com), choose **Azure Active Directory**, select + **App registrations** and then click on **New registration**. +2. Pick a name, check the supported account type(single-tenant, multi-tenant, etc). In the **Redirect URI** section create a new + **Web** platform entry for each app that you want to protect by the oauth2 proxy(e.g. + https://internal.yourcompanycom/oauth2/callback). Click **Register**. +3. Next we need to add group read permissions for the app registration, on the **API Permissions** page of the app, click on + **Add a permission**, select **Microsoft Graph**, then select **Application permissions**, then click on **Group** and select + **Group.Read.All**. Hit **Add permissions** and then on **Grant admin consent** (you might need an admin to do this). +
**IMPORTANT**: Even if this permission is listed with **"Admin consent required=No"** the consent might actually + be required, due to AAD policies you won't be able to see. If you get a **"Need admin approval"** during login, + most likely this is what you're missing! +4. Next, if you are planning to use v2.0 Azure Auth endpoint, go to the **Manifest** page and set `"accessTokenAcceptedVersion": 2` + in the App registration manifest file. +5. On the **Certificates & secrets** page of the app, add a new client secret and note down the value after hitting **Add**. +6. Configure the proxy with: +- for V1 Azure Auth endpoint (Azure Active Directory Endpoints - https://login.microsoftonline.com/common/oauth2/authorize) + +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://sts.windows.net/{tenant-id}/ +``` + +- for V2 Azure Auth endpoint (Microsoft Identity Platform Endpoints - https://login.microsoftonline.com/common/oauth2/v2.0/authorize) +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://login.microsoftonline.com/{tenant-id}/v2.0 +``` + +***Notes***: +- When using v2.0 Azure Auth endpoint (`https://login.microsoftonline.com/{tenant-id}/v2.0`) as `--oidc_issuer_url`, in conjunction + with `--resource` flag, be sure to append `/.default` at the end of the resource name. See + https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope for more details. +- When using the Azure Auth provider with nginx and the cookie session store you may find the cookie is too large and doesn't + get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the + [redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.10.x/configuration/providers/ms_entra_id.md new file mode 100644 index 0000000000..c5d9594edd --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/ms_entra_id.md @@ -0,0 +1,197 @@ +--- +id: ms_entra_id +title: Microsoft Entra ID +--- + +Provider for Microsoft Entra ID. Fully compliant with OIDC, with support for group overage and multi-tenant apps. + +## Config Options + +The provider is OIDC-compliant, so all the OIDC parameters are honored. Additional provider-specific configuration parameters are: + +| Flag | Toml Field | Type | Description | Default | +| --------------------------- | -------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--entra-id-allowed-tenant` | `entra_id_allowed_tenants` | string \| list | List of allowed tenants. In case of multi-tenant apps, incoming tokens are issued by different issuers and OIDC issuer verification needs to be disabled. When not specified, all tenants are allowed. Redundant for single-tenant apps (regular ID token validation matches the issuer). | | +| `--entra-id-federated-token-auth` | `entra_id_federated_token_auth` | boolean | Enable oAuth2 client authentication with federated token projected by Entra Workload Identity plugin, instead of client secret. | false | + +## Configure App registration +To begin, create an App registration, set a redirect URI, and generate a secret. All account types are supported, including single-tenant, multi-tenant, multi-tenant with Microsoft accounts, and Microsoft accounts only. + +
+ See Azure Portal example +
+ +
+
+ +
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" # Others are also supported + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + // We don't specify any required API permissions - we allow user consent only + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Configure groups +If you want to make use of groups, you can configure *groups claim* to be present in ID Tokens issued by the App registration. +
+ See Azure Portal example +
+
+ +
+
+
+
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" + + group_membership_claims = [ + "SecurityGroup" + ] + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Scopes and claims +For single-tenant and multi-tenant apps without groups, the only required scope is `openid` (See: [Scopes and permissions](https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#the-openid-scope)). + +To make use of groups - for example use `allowed_groups` setting or authorize based on groups inside your service - you need to enable *groups claims* in the App Registration. When enabled, list of groups is present in the issued ID token. No additional scopes are required besides `openid`. This works up to 200 groups. + +When user has more than 200 group memberships, OAuth2-Proxy attempts to retrieve the complete list from Microsoft Graph API's [`transitiveMemberOf`](https://learn.microsoft.com/en-us/graph/api/user-list-transitivememberof). Endpoint requires `User.Read` scope (delegated permission). This permission can be by default consented by user during first login. Set scope to `openid User.Read` to request user consent. Without proper scope, user with 200+ groups will authenticate with 0 groups. See: [group overages](https://learn.microsoft.com/en-us/security/zero-trust/develop/configure-tokens-group-claims-app-roles#group-overages). + +Alternatively to user consent, both `openid` and `User.Read` permissions can be consented by admistrator. Then, user is not asked for consent on the first login, and group overage works with `openid` scope only. Admin consent can also be required for some tenants. It can be granted with [azuread_service_principal_delegated_permission_grant](https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/service_principal_delegated_permission_grant) terraform resource. + +For personal microsoft accounts, required scope is `openid profile email`. + +See: [Overview of permissions and consent in the Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview). + +### Multi-tenant apps +To authenticate apps from multiple tenants (including personal Microsoft accounts), set the common OIDC issuer url and disable verification: +```toml +oidc_issuer_url=https://login.microsoftonline.com/common/v2.0 +insecure_oidc_skip_issuer_verification=true +``` +`insecure_oidc_skip_issuer_verification` setting is required to disable following checks: +* Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). + +To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. + +### Workload Identity +Provider supports authentication with federated token, without need of using client secret. Following conditions have to be met: + +* Cluster has public OIDC provider URL. For major cloud providers, it can be enabled with a single flag, for example for [Azure Kubernetes Service deployed with Terraform](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster), it's `oidc_issuer_enabled`. +* Workload Identity admission webhook is deployed on the cluster. For AKS, it can be enabled with a flag (`workload_identity_enabled` in Terraform resource), for clusters outside of Azure, it can be installed from [helm chart](https://github.com/Azure/azure-workload-identity). +* Appropriate federated credential is added to application registration. +
+ See federated credential terraform example +``` + resource "azuread_application_federated_identity_credential" "fedcred" { + application_id = azuread_application.application.id # ID of your application + display_name = "federation-cred" + description = "Workload identity for oauth2-proxy" + audiences = ["api://AzureADTokenExchange"] # Fixed value + issuer = "https://cluster-oidc-issuer-url..." + subject = "system:serviceaccount:oauth2-proxy-namespace-name:oauth2-proxy-sa-name" # set proper NS and SA name + } +``` +
+ +* Kubernetes service account associated with oauth2-proxy deployment, is annotated with `azure.workload.identity/client-id: ` +* oauth2-proxy pod is labeled with `azure.workload.identity/use: "true"` +* oauth2-proxy is configured with `entra_id_federated_token_auth` set to `true`. + +`client_secret` setting can be omitted when using federated token authentication. + +See: [Azure Workload Identity documentation](https://azure.github.io/azure-workload-identity/docs/). + +### Example configurations +Single-tenant app without groups (*groups claim* not enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +``` + +Single-tenant app with up to 200 groups (*groups claim* enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +allowed_groups=["ac51800c-2679-4ecb-8130-636380a3b491"] +``` + +Single-tenant app with more than 200 groups: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +``` + +Single-tenant app with more than 200 groups and workload identity enabled: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +entra_id_federated_token_auth=true +``` + +Multi-tenant app with Microsoft personal accounts & one Entra tenant allowed, with group overage considered: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com/common/v2.0" +client_id="" +client_secret="" +insecure_oidc_skip_issuer_verification=true +scope="openid profile email User.Read" +entra_id_allowed_tenants=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant +email_domains="*" +``` diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/nextcloud.md b/docs/versioned_docs/version-7.10.x/configuration/providers/nextcloud.md new file mode 100644 index 0000000000..85ebff0398 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/nextcloud.md @@ -0,0 +1,28 @@ +--- +id: nextcloud +title: NextCloud +--- + +The Nextcloud provider allows you to authenticate against users in your +Nextcloud instance. + +When you are using the Nextcloud provider, you must specify the urls via +configuration, environment variable, or command line argument. Depending +on whether your Nextcloud instance is using pretty urls your urls may be of the +form `/index.php/apps/oauth2/*` or `/apps/oauth2/*`. + +Refer to the [OAuth2 +documentation](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/oauth2.html) +to set up the client id and client secret. Your "Redirection URI" will be +`https://internalapp.yourcompany.com/oauth2/callback`. + +``` + -provider nextcloud + -client-id + -client-secret + -login-url="/index.php/apps/oauth2/authorize" + -redeem-url="/index.php/apps/oauth2/api/v1/token" + -validate-url="/ocs/v2.php/cloud/user?format=json" +``` + +Note: in *all* cases the validate-url will *not* have the `index.php`. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/openid_connect.md b/docs/versioned_docs/version-7.10.x/configuration/providers/openid_connect.md new file mode 100644 index 0000000000..de17005808 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/openid_connect.md @@ -0,0 +1,146 @@ +--- +id: openid_connect +title: OpenID Connect +--- + +OpenID Connect is a spec for OAUTH 2.0 + identity that is implemented by many major providers and several open source projects. + +This provider was originally built against CoreOS Dex, and we will use it as an example. +The OpenID Connect Provider (OIDC) can also be used to connect to other Identity Providers such as Okta, an example can be found below. + +#### Dex + +To configure the OIDC provider for Dex, perform the following steps: + +1. Download Dex: + + ``` + go get github.com/dexidp/dex + ``` + + See the [getting started guide](https://dexidp.io/docs/getting-started/) for more details. + +2. Setup oauth2-proxy with the correct provider and using the default ports and callbacks. Add a configuration block to + the `staticClients` section of `examples/config-dev.yaml`: + + ``` + - id: oauth2-proxy + redirectURIs: + - 'http://127.0.0.1:4180/oauth2/callback' + name: 'oauth2-proxy' + secret: proxy + ``` + +3. Launch Dex: from `$GOPATH/github.com/dexidp/dex`, run: + + ``` + bin/dex serve examples/config-dev.yaml + ``` + +4. In a second terminal, run the oauth2-proxy with the following args: + + ```shell + --provider oidc + --provider-display-name "My OIDC Provider" + --client-id oauth2-proxy + --client-secret proxy + --redirect-url http://127.0.0.1:4180/oauth2/callback + --oidc-issuer-url http://127.0.0.1:5556/dex + --cookie-secure=false + --cookie-secret=secret + --email-domain kilgore.trout + ``` + + To serve the current working directory as a website under the `/static` endpoint, add: + + ```shell + --upstream file://$PWD/#/static/ + ``` + +5. Test the setup by visiting http://127.0.0.1:4180 or http://127.0.0.1:4180/static . + +See also [our local testing environment](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/local-environment) for a self-contained example using Docker and etcd as storage for Dex. + +#### Okta + +To configure the OIDC provider for Okta, perform the following steps: + +1. Log in to Okta using an administrative account. It is suggested you try this in preview first, `example.oktapreview.com` +2. (OPTIONAL) If you want to configure authorization scopes and claims to be passed on to multiple applications, + you may wish to configure an authorization server for each application. Otherwise, the provided `default` will work. + * Navigate to **Security** then select **API** + * Click **Add Authorization Server**, if this option is not available you may require an additional license for a custom + authorization server. + * Fill out the **Name** with something to describe the application you are protecting. e.g. 'Example App'. + * For **Audience**, pick the URL of the application you wish to protect: https://example.corp.com + * Fill out a **Description** + * Add any **Access Policies** you wish to configure to limit application access. + * The default settings will work for other options. + [See Okta documentation for more information on Authorization Servers](https://developer.okta.com/docs/guides/customize-authz-server/overview/) +3. Navigate to **Applications** then select **Add Application**. + * Select **Web** for the **Platform** setting. + * Select **OpenID Connect** and click **Create** + * Pick an **Application Name** such as `Example App`. + * Set the **Login redirect URI** to `https://example.corp.com`. + * Under **General** set the **Allowed grant types** to `Authorization Code` and `Refresh Token`. + * Leave the rest as default, taking note of the `Client ID` and `Client Secret`. + * Under **Assignments** select the users or groups you wish to access your application. +4. Create a configuration file like the following: + + ``` + provider = "oidc" + redirect_url = "https://example.corp.com/oauth2/callback" + oidc_issuer_url = "https://corp.okta.com/oauth2/abCd1234" + upstreams = [ + "https://example.corp.com" + ] + email_domains = [ + "corp.com" + ] + client_id = "XXXXX" + client_secret = "YYYYY" + pass_access_token = true + cookie_secret = "ZZZZZ" + skip_provider_button = true + ``` + +The `oidc_issuer_url` is based on URL from your **Authorization Server**'s **Issuer** field in step 2, or simply +https://corp.okta.com. The `client_id` and `client_secret` are configured in the application settings. +Generate a unique `cookie_secret` to encrypt the cookie. + +Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/example.cfg` + +#### Okta - localhost + +1. Signup for developer account: https://developer.okta.com/signup/ +2. Create New `Web` Application: https://$\{your-okta-domain\}/dev/console/apps/new +3. Example Application Settings for localhost: + * **Name:** My Web App + * **Base URIs:** http://localhost:4180/ + * **Login redirect URIs:** http://localhost:4180/oauth2/callback + * **Logout redirect URIs:** http://localhost:4180/ + * **Group assignments:** `Everyone` + * **Grant type allowed:** `Authorization Code` and `Refresh Token` +4. Make note of the `Client ID` and `Client secret`, they are needed in a future step +5. Make note of the **default** Authorization Server Issuer URI from: https://$\{your-okta-domain\}/admin/oauth2/as +6. Example config file `/etc/localhost.cfg` + ```shell + provider = "oidc" + redirect_url = "http://localhost:4180/oauth2/callback" + oidc_issuer_url = "https://$\{your-okta-domain\}/oauth2/default" + upstreams = [ + "http://0.0.0.0:8080" + ] + email_domains = [ + "*" + ] + client_id = "XXX" + client_secret = "YYY" + pass_access_token = true + cookie_secret = "ZZZ" + cookie_secure = false + skip_provider_button = true + # Note: use the following for testing within a container + # http_address = "0.0.0.0:4180" + ``` +7. Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/localhost.cfg` diff --git a/docs/versioned_docs/version-7.10.x/configuration/sessions.md b/docs/versioned_docs/version-7.10.x/configuration/sessions.md new file mode 100644 index 0000000000..e20378170a --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/sessions.md @@ -0,0 +1,99 @@ +--- +id: session_storage +title: Session Storage +--- + +Sessions allow a user's authentication to be tracked between multiple HTTP +requests to a service. + +The OAuth2 Proxy uses a Cookie to track user sessions and will store the session +data in one of the available session storage backends. + +At present the available backends are (as passed to `--session-store-type`): +- [cookie](#cookie-storage) (default) +- [redis](#redis-storage) + +### Cookie Storage + +The Cookie storage backend is the default backend implementation and has +been used in the OAuth2 Proxy historically. + +With the Cookie storage backend, all session information is stored in client +side cookies and transferred with each and every request. + +The following should be known when using this implementation: +- Since all state is stored client side, this storage backend means that the OAuth2 Proxy is completely stateless +- Cookies are signed server side to prevent modification client-side +- It is mandatory to set a `cookie-secret` which will ensure data is encrypted within the cookie data. +- Since multiple requests can be made concurrently to the OAuth2 Proxy, this session implementation +cannot lock sessions and while updating and refreshing sessions, there can be conflicts which force +users to re-authenticate + + +### Redis Storage + +The Redis Storage backend stores encrypted sessions in redis. Instead of sending all the information +back the client for storage, as in the [Cookie storage](#cookie-storage), a ticket is sent back +to the user as the cookie value instead. + +A ticket is composed as the following: + +`{CookieName}-{ticketID}.{secret}` + +Where: + +- The `CookieName` is the OAuth2 cookie name (_oauth2_proxy by default) +- The `ticketID` is a 128-bit random number, hex-encoded +- The `secret` is a 128-bit random number, base64url encoded (no padding). The secret is unique for every session. +- The pair of `{CookieName}-{ticketID}` comprises a ticket handle, and thus, the redis key +to which the session is stored. The encoded session is encrypted with the secret and stored +in redis via the `SETEX` command. + +Encrypting every session uniquely protects the refresh/access/id tokens stored in the session from +disclosure. Additionally, the browser only has to send a short Cookie with every request and not the whole JWT, +which can get quite big. + +Two settings are used to configure the OAuth2 Proxy cookie lifetime: + + --cookie-refresh duration refresh the cookie after this duration; 0 to disable + --cookie-expire duration expire timeframe for cookie 168h0m0s + +The "cookie-expire" value should be equal to the lifetime of the Refresh-Token that is issued by the OAuth2 authorization server. +If it expires earlier and is deleted by the browser, OAuth2 Proxy cannot find the stored Refresh-Tokens in Redis and thus cannot start +the refresh flow to get a new Access-Token. If it is longer, it might be that the old Refresh-Token will be found in Redis but has already +expired. + +The "cookie-refresh" value controls when OAuth2 Proxy tries to refresh an Access-Token. If it is set to "0", the +Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2-Proxy will +refresh the Access-Token after this many seconds whether it is still valid or not. According to the official OAuth2.0 specification +Access-Tokens are not required to follow a specific format. Therefore OAuth2-Proxy cannot check for any expiry date without an +introspection endpoint. If an Access-Token expires and you have not set a corresponding "cookie-refresh" value, you will likely +encounter expiry issues. + +Caveat: It can happen that the Access-Token is valid for e.g. "1m" and a request happens after exactly "59s". +It would pass OAuth2 Proxy and be forwarded to the backend but is just expired when the backend tries to validate +it. This is especially relevant if the backend uses the JWT to make requests to other backends. +For this reason, it's advised to set the cookie-refresh a couple of seconds less than the Access-Token lifespan. + +Recommended settings: + +* cookie_refresh := Access-Token lifespan - 1m +* cookie_expire := Refresh-Token lifespan (i.e. Keycloak client_session_idle) + +#### Usage + +When using the redis store, specify `--session-store-type=redis` as well as the Redis connection URL, via +`--redis-connection-url=redis://host[:port][/db-number]`. + +You may also configure the store for Redis Sentinel. In this case, you will want to use the +`--redis-use-sentinel=true` flag, as well as configure the flags `--redis-sentinel-master-name` +and `--redis-sentinel-connection-urls` appropriately. + +Redis Cluster is available to be the backend store as well. To leverage it, you will need to set the +`--redis-use-cluster=true` flag, and configure the flags `--redis-cluster-connection-urls` appropriately. + +Note that flags `--redis-use-sentinel=true` and `--redis-use-cluster=true` are mutually exclusive. + +Note, if Redis timeout option is set to non-zero, the `--redis-connection-idle-timeout` +must be less than [Redis timeout option](https://redis.io/docs/reference/clients/#client-timeouts). For example: if either redis.conf includes +`timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` diff --git a/docs/versioned_docs/version-7.10.x/configuration/systemd_socket.md b/docs/versioned_docs/version-7.10.x/configuration/systemd_socket.md new file mode 100644 index 0000000000..642e6f3f7b --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/systemd_socket.md @@ -0,0 +1,43 @@ +--- +id: systemd_socket +title: Systemd Socket Activation +--- + +Pass an existing listener created by systemd.socket to oauth2-proxy. + +To do this create a socket: + +oauth2-proxy.socket +``` +[Socket] +ListenStream=%t/oauth2.sock +SocketGroup=www-data +SocketMode=0660 +``` + +Now it's possible to call this socket from e.g. nginx: +``` +server { + location /oauth2/ { + proxy_pass http://unix:/run/oauth2-proxy/oauth2.sock; +} +``` + +The oauth2-proxy should have `--http-address=fd:3` as a parameter. +Here fd is case insensitive and means file descriptor. The number 3 refers to the first non-stdin/stdout/stderr file descriptor, +systemd-socket-activate (which is what systemd.socket uses), listens to what it is told and passes +the listener it created onto the process, starting with file descriptor 3. + +``` +./oauth2-proxy \ + --http-address="fd:3" \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... +``` + +Currently TLS is not supported (but it's doable). diff --git a/docs/versioned_docs/version-7.10.x/configuration/tls.md b/docs/versioned_docs/version-7.10.x/configuration/tls.md new file mode 100644 index 0000000000..68344b22d5 --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/configuration/tls.md @@ -0,0 +1,85 @@ +--- +id: tls +title: TLS Configuration +--- + +There are two recommended configurations: +- [At OAuth2 Proxy](#terminate-tls-at-oauth2-proxy) +- [At Reverse Proxy](#terminate-tls-at-reverse-proxy-eg-nginx) + +### Terminate TLS at OAuth2 Proxy + +1. Configure SSL Termination with OAuth2 Proxy by providing a `--tls-cert-file=/path/to/cert.pem` and `--tls-key-file=/path/to/cert.key`. + + The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --tls-cert-file=/path/to/cert.pem \ + --tls-key-file=/path/to/cert.key \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... + ``` + +2. With this configuration approach the customization of the TLS settings is limited. + + The minimal acceptable TLS version can be set with `--tls-min-version=TLS1.3`. + The defaults set `TLS1.2` as the minimal version. + Regardless of the minimum version configured, `TLS1.3` is currently always used as the maximal version. + + TLS server side cipher suites can be specified with `--tls-cipher-suite=TLS_RSA_WITH_RC4_128_SHA`. + If not specified, the defaults from [`crypto/tls`](https://pkg.go.dev/crypto/tls#CipherSuites) of the currently used `go` version for building `oauth2-proxy` will be used. + A complete list of valid TLS cipher suite names can be found in [`crypto/tls`](https://pkg.go.dev/crypto/tls#pkg-constants). + +### Terminate TLS at Reverse Proxy, e.g. Nginx + +1. Configure SSL Termination with [Nginx](http://nginx.org/) (example config below), Amazon ELB, Google Cloud Platform Load Balancing, or ... + + Because `oauth2-proxy` listens on `127.0.0.1:4180` by default, to listen on all interfaces (needed when using an + external load balancer like Amazon ELB or Google Platform Load Balancing) use `--http-address="0.0.0.0:4180"` or + `--http-address="http://:4180"`. + + Nginx will listen on port `443` and handle SSL connections while proxying to `oauth2-proxy` on port `4180`. + `oauth2-proxy` will then authenticate requests for an upstream application. The external endpoint for this example + would be `https://internal.yourcompany.com/`. + + An example Nginx config follows. Note the use of `Strict-Transport-Security` header to pin requests to SSL + via [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security): + + ``` + server { + listen 443 default ssl; + server_name internal.yourcompany.com; + ssl_certificate /path/to/cert.pem; + ssl_certificate_key /path/to/cert.key; + add_header Strict-Transport-Security max-age=2592000; + + location / { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_connect_timeout 1; + proxy_send_timeout 30; + proxy_read_timeout 30; + } + } + ``` + +2. The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --reverse-proxy=true \ + --client-id=... \ + --client-secret=... + ``` diff --git a/docs/versioned_docs/version-7.10.x/features/endpoints.md b/docs/versioned_docs/version-7.10.x/features/endpoints.md new file mode 100644 index 0000000000..3ec1e2aa8a --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/features/endpoints.md @@ -0,0 +1,47 @@ +--- +id: endpoints +title: Endpoints +--- + +OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable. + +- /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info +- /ping - returns a 200 OK response, which is intended for use with health checks +- /ready - returns a 200 OK response if all the underlying connections (e.g., Redis store) are connected +- /metrics - Metrics endpoint for Prometheus to scrape, serve on the address specified by `--metrics-address`, disabled by default +- /oauth2/sign_in - the login page, which also doubles as a sign-out page (it clears cookies) +- /oauth2/sign_out - this URL is used to clear the session cookie +- /oauth2/start - a URL that will redirect to start the OAuth cycle +- /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url. +- /oauth2/userinfo - the URL is used to return user's email from the session in JSON format. +- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integration#configuring-for-use-with-the-nginx-auth_request-directive) +- /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages + +### Sign out + +To sign the user out, redirect them to `/oauth2/sign_out`. This endpoint only removes oauth2-proxy's own cookies, i.e. the user is still logged in with the authentication provider and may automatically re-login when accessing the application again. You will also need to redirect the user to the authentication provider's sign-out page afterward using the `rd` query parameter, i.e. redirect the user to something like (notice the url-encoding!): + +``` +/oauth2/sign_out?rd=https%3A%2F%2Fmy-oidc-provider.example.com%2Fsign_out_page +``` + +Alternatively, include the redirect URL in the `X-Auth-Request-Redirect` header: + +``` +GET /oauth2/sign_out HTTP/1.1 +X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page +... +``` + +(The "sign_out_page" should be the [`end_session_endpoint`](https://openid.net/specs/openid-connect-session-1_0.html#rfc.section.2.1) from [the metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) if your OIDC provider supports Session Management and Discovery.) + +BEWARE that the domain you want to redirect to (`my-oidc-provider.example.com` in the example) must be added to the [`--whitelist-domain`](../configuration/overview) configuration option otherwise the redirect will be ignored. Make sure to include the actual domain and port (if needed) and not the URL (e.g "localhost:8081" instead of "http://localhost:8081"). + +### Auth + +This endpoint returns 202 Accepted response or a 401 Unauthorized response. + +It can be configured using the following query parameters: +- `allowed_groups`: comma separated list of allowed groups +- `allowed_email_domains`: comma separated list of allowed email domains +- `allowed_emails`: comma separated list of allowed emails diff --git a/docs/versioned_docs/version-7.10.x/installation.md b/docs/versioned_docs/version-7.10.x/installation.md new file mode 100644 index 0000000000..3b6919d89c --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/installation.md @@ -0,0 +1,32 @@ +--- +id: installation +title: Installation +--- + +1. Choose how to deploy: + + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.9.0`) + + b. Using Go to install the latest release + ```bash + $ go install github.com/oauth2-proxy/oauth2-proxy/v7@latest + ``` + This will install the binary into `$GOPATH/bin`. Make sure you include `$GOPATH` in your `$PATH`. Otherwise your system won't find binaries installed via `go install` + + c. Using a [Prebuilt Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy) (AMD64, PPC64LE, S390x, ARMv6, ARMv7, and ARM64 available) + + d. Using a [Pre-Release Nightly Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy-nightly) (AMD64, PPC64LE, ARMv6, ARMv7, and ARM64 available) + + e. Using the official [Kubernetes manifest](https://github.com/oauth2-proxy/manifests) (Helm) + + Prebuilt binaries can be validated by extracting the file and verifying it against the `sha256sum.txt` checksum file provided for each release starting with version `v3.0.0`. + + ``` + $ sha256sum -c sha256sum.txt + oauth2-proxy-x.y.z.linux-amd64: OK + ``` + +2. [Select a Provider and Register an OAuth Application with a Provider](configuration/providers/index.md) +3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration/overview.md) +4. [Configure SSL or Deploy behind an SSL endpoint](configuration/tls.md) (example provided for Nginx) +5. [Configure OAuth2 Proxy using systemd.socket](configuration/systemd_socket.md) (example provided for Nginx/Systemd) diff --git a/docs/versioned_docs/version-7.10.x/welcome.md b/docs/versioned_docs/version-7.10.x/welcome.md new file mode 100644 index 0000000000..7bceadd80e --- /dev/null +++ b/docs/versioned_docs/version-7.10.x/welcome.md @@ -0,0 +1,23 @@ +--- +id: welcome +title: Welcome +hide_table_of_contents: true +slug: / +--- + +![OAuth2 Proxy](/img/logos/OAuth2_Proxy_horizontal.svg) + +A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others) +to validate accounts by email, domain or group. + +:::note +This repository was forked from [bitly/OAuth2_Proxy](https://github.com/bitly/oauth2_proxy) on 27/11/2018. +Versions v3.0.0 and up are from this fork and will have diverged from any changes in the original fork. +A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/CHANGELOG.md). +::: + +![Sign In Page](/img/sign-in-page.png) + +## Architecture + +![OAuth2 Proxy Architecture](/img/simplified-architecture.svg) diff --git a/docs/versioned_sidebars/version-7.10.x-sidebars.json b/docs/versioned_sidebars/version-7.10.x-sidebars.json new file mode 100644 index 0000000000..0dbf04bd44 --- /dev/null +++ b/docs/versioned_sidebars/version-7.10.x-sidebars.json @@ -0,0 +1,83 @@ +{ + "docs": [ + { + "type": "doc", + "id": "welcome" + }, + { + "type": "doc", + "id": "installation" + }, + { + "type": "doc", + "id": "behaviour" + }, + { + "type": "category", + "label": "Configuration", + "link": { + "type": "doc", + "id": "configuration/overview" + }, + "collapsed": false, + "items": [ + "configuration/overview", + "configuration/integration", + { + "type": "category", + "label": "OAuth Provider Configuration", + "link": { + "type": "doc", + "id": "configuration/providers/index" + }, + "items": [ + "configuration/providers/adfs", + "configuration/providers/azure", + "configuration/providers/bitbucket", + "configuration/providers/digitalocean", + "configuration/providers/facebook", + "configuration/providers/gitea", + "configuration/providers/github", + "configuration/providers/gitlab", + "configuration/providers/google", + "configuration/providers/keycloak", + "configuration/providers/keycloak_oidc", + "configuration/providers/linkedin", + "configuration/providers/login_gov", + "configuration/providers/ms_entra_id", + "configuration/providers/nextcloud", + "configuration/providers/openid_connect" + ] + }, + "configuration/session_storage", + "configuration/tls", + "configuration/alpha-config" + ] + }, + { + "type": "category", + "label": "Features", + "link": { + "type": "doc", + "id": "features/endpoints" + }, + "collapsed": false, + "items": [ + "features/endpoints" + ] + }, + { + "type": "category", + "label": "Community", + "link": { + "type": "doc", + "id": "community/security" + }, + "collapsed": false, + "items": [ + "community/contribution", + "community/security" + ] + } + ] +} diff --git a/docs/versions.json b/docs/versions.json index bdabb049cd..2b55679560 100644 --- a/docs/versions.json +++ b/docs/versions.json @@ -1,4 +1,5 @@ [ + "7.10.x", "7.9.x", "7.8.x", "7.7.x", From 5808f5376a3d141df88ad57e18e341d7d0af5bdc Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 17 Jul 2025 07:56:01 +0000 Subject: [PATCH 010/125] update to release version v7.10.0 --- CHANGELOG.md | 10 ++++++++++ .../local-environment/docker-compose-alpha-config.yaml | 2 +- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-keycloak.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/installation.md | 2 +- docs/versioned_docs/version-7.10.x/installation.md | 2 +- 9 files changed, 18 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 72d615e0a1..756f1bf19c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,16 @@ ## Breaking Changes +## Changes since v7.10.0 + +# V7.10.0 + +## Release Highlights + +## Important Notes + +## Breaking Changes + ## Changes since v7.9.0 - [#3072](https://github.com/oauth2-proxy/oauth2-proxy/pull/3072) feat: support for multiple github orgs #3072 (@daniel-mersch) diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index 35608eb899..3acc01bf80 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml volumes: - "./oauth2-proxy-alpha-config.cfg:/oauth2-proxy.cfg" diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index ae1047c05a..66a09b6164 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index 7d99a1e218..3a5a391467 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index fb90ff28a8..f9ec9f3d7c 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,7 +22,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 65df58f0b4..e22c633d22 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index ed79eab564..6f2321b74b 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.9.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/installation.md b/docs/docs/installation.md index 3b6919d89c..95da82da27 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.9.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.10.0`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.10.x/installation.md b/docs/versioned_docs/version-7.10.x/installation.md index 3b6919d89c..95da82da27 100644 --- a/docs/versioned_docs/version-7.10.x/installation.md +++ b/docs/versioned_docs/version-7.10.x/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.9.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.10.0`) b. Using Go to install the latest release ```bash From e25f9ec9d789e40c032fae9f99a197a4bf144f52 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Thu, 17 Jul 2025 10:01:37 +0200 Subject: [PATCH 011/125] add changelog entry Signed-off-by: Jan Larwig --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 756f1bf19c..479ab4ce7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,14 @@ # V7.10.0 ## Release Highlights +- 🏢 Support for multiple orgs using the GitHub / Gitea provider +- 🔵 Golang version upgrade to v1.24.5 +- 🕵️‍♀️ Vulnerabilities have been addressed + - [CVE-2025-4673](https://access.redhat.com/security/cve/CVE-2025-4673) + - [CVE-2025-22872](https://access.redhat.com/security/cve/CVE-2025-22872) + - [CVE-2025-09130](https://nvd.nist.gov/vuln/detail/CVE-2025-09130) + - [CVE-2025-22871](https://access.redhat.com/security/cve/CVE-2025-22871) +- 🐛 Squashed some bugs ## Important Notes From 313a2cb38ba31891fda1e42e7aeb663437662211 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 20 Jul 2025 11:07:35 +0200 Subject: [PATCH 012/125] chore(deps): update dependency @easyops-cn/docusaurus-search-local to ^0.52.0 (#3131) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- docs/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/package.json b/docs/package.json index 33f3394bed..bfedb21e69 100644 --- a/docs/package.json +++ b/docs/package.json @@ -17,7 +17,7 @@ "@docusaurus/core": "^3.3.2", "@docusaurus/preset-classic": "^3.3.2", "@docusaurus/theme-mermaid": "^3.3.2", - "@easyops-cn/docusaurus-search-local": "^0.51.0", + "@easyops-cn/docusaurus-search-local": "^0.52.0", "@mdx-js/react": "^3.0.0", "clsx": "^2.0.0", "prism-react-renderer": "^2.3.0", From 658256d5665080ef6ad890481e313ca35e039161 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 20 Jul 2025 11:08:02 +0200 Subject: [PATCH 013/125] chore(deps): update gomod (#3132) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- go.mod | 10 +++++----- go.sum | 10 ++++++++++ 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index 087dad8afa..044f2c2374 100644 --- a/go.mod +++ b/go.mod @@ -15,8 +15,8 @@ require ( github.com/fsnotify/fsnotify v1.9.0 github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 github.com/go-jose/go-jose/v3 v3.0.4 - github.com/go-viper/mapstructure/v2 v2.3.0 - github.com/golang-jwt/jwt/v5 v5.2.2 + github.com/go-viper/mapstructure/v2 v2.4.0 + github.com/golang-jwt/jwt/v5 v5.2.3 github.com/google/go-cmp v0.7.0 github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 @@ -29,7 +29,7 @@ require ( github.com/prometheus/client_golang v1.22.0 github.com/redis/go-redis/v9 v9.11.0 github.com/spf13/cast v1.9.2 - github.com/spf13/pflag v1.0.6 + github.com/spf13/pflag v1.0.7 github.com/spf13/viper v1.20.1 github.com/stretchr/testify v1.10.0 github.com/vmihailenco/msgpack/v5 v5.4.1 @@ -37,9 +37,9 @@ require ( golang.org/x/net v0.42.0 golang.org/x/oauth2 v0.30.0 golang.org/x/sync v0.16.0 - google.golang.org/api v0.241.0 + google.golang.org/api v0.242.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 - k8s.io/apimachinery v0.33.2 + k8s.io/apimachinery v0.33.3 ) require ( diff --git a/go.sum b/go.sum index 22548221bb..caa8e2a0b0 100644 --- a/go.sum +++ b/go.sum @@ -63,8 +63,12 @@ github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1v github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/go-viper/mapstructure/v2 v2.3.0 h1:27XbWsHIqhbdR5TIC911OfYvgSaW93HM+dX7970Q7jk= github.com/go-viper/mapstructure/v2 v2.3.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= +github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8= github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/golang-jwt/jwt/v5 v5.2.3 h1:kkGXqQOBSDDWRhWNXTFpqGSCMyh/PLnqUvMGJPDJDs0= +github.com/golang-jwt/jwt/v5 v5.2.3/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3 h1:6amM4HsNPOvMLVc2ZnyqrjeQ92YAVWn7T4WBKK87inY= @@ -140,6 +144,8 @@ github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE= github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/pflag v1.0.7 h1:vN6T9TfwStFPFM5XzjsvmzZkLuaLX+HS+0SeFLRgU6M= +github.com/spf13/pflag v1.0.7/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4= github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -247,6 +253,8 @@ google.golang.org/api v0.240.0 h1:PxG3AA2UIqT1ofIzWV2COM3j3JagKTKSwy7L6RHNXNU= google.golang.org/api v0.240.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= google.golang.org/api v0.241.0 h1:QKwqWQlkc6O895LchPEDUSYr22Xp3NCxpQRiWTB6avE= google.golang.org/api v0.241.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= +google.golang.org/api v0.242.0 h1:7Lnb1nfnpvbkCiZek6IXKdJ0MFuAZNAJKQfA1ws62xg= +google.golang.org/api v0.242.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2 h1:1tXaIXCracvtsRxSBsYDiSBN0cuJvM7QYW+MrpIRY78= google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2/go.mod h1:49MsLSx0oWMOZqcpB3uL8ZOkAh1+TndpJ8ONoCBWiZk= google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= @@ -274,3 +282,5 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= k8s.io/apimachinery v0.33.2 h1:IHFVhqg59mb8PJWTLi8m1mAoepkUNYmptHsV+Z1m5jY= k8s.io/apimachinery v0.33.2/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= +k8s.io/apimachinery v0.33.3 h1:4ZSrmNa0c/ZpZJhAgRdcsFcZOw1PQU1bALVQ0B3I5LA= +k8s.io/apimachinery v0.33.3/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= From c403d61d73edb2eb39ec3a9787254b5d0216008a Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 20 Jul 2025 11:08:23 +0200 Subject: [PATCH 014/125] chore(deps): update helm release oauth2-proxy to v7.14.1 (#3133) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/kubernetes/Chart.lock | 6 +++--- contrib/local-environment/kubernetes/Chart.yaml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/contrib/local-environment/kubernetes/Chart.lock b/contrib/local-environment/kubernetes/Chart.lock index dc2ef2426a..e6774fb24b 100644 --- a/contrib/local-environment/kubernetes/Chart.lock +++ b/contrib/local-environment/kubernetes/Chart.lock @@ -4,12 +4,12 @@ dependencies: version: 0.23.0 - name: oauth2-proxy repository: https://oauth2-proxy.github.io/manifests - version: 7.12.19 + version: 7.14.1 - name: httpbin repository: https://conservis.github.io/helm-charts version: 1.1.0 - name: hello-world repository: https://conservis.github.io/helm-charts version: 1.1.0 -digest: sha256:8d1d166c7c1043edd2006bb8e8d2db32a6b876febad2854253570d7ea141f064 -generated: "2025-07-13T20:04:55.152622641Z" +digest: sha256:9b18e072db6863053c2967d023929ab4b9c03b6bd84f6529d90fe7a9ec5e315f +generated: "2025-07-20T08:56:43.559585022Z" diff --git a/contrib/local-environment/kubernetes/Chart.yaml b/contrib/local-environment/kubernetes/Chart.yaml index dd0938b378..3d224378a0 100644 --- a/contrib/local-environment/kubernetes/Chart.yaml +++ b/contrib/local-environment/kubernetes/Chart.yaml @@ -6,7 +6,7 @@ dependencies: version: 0.23.0 repository: https://charts.dexidp.io - name: oauth2-proxy - version: &chartVersion 7.12.19 + version: &chartVersion 7.14.1 repository: https://oauth2-proxy.github.io/manifests # https://github.com/postmanlabs/httpbin/issues/549 is still in progress, for now using a non-official chart - name: httpbin From 20f561cf70a82fba586954b097efe95cc03010f7 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 20 Jul 2025 11:08:44 +0200 Subject: [PATCH 015/125] chore(deps): update docker-compose (#3130) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 66a09b6164..454d012368 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -42,7 +42,7 @@ services: - httpbin.localtest.me gitea: - image: gitea/gitea:1.24.2 + image: gitea/gitea:1.24.3 container_name: gitea environment: - USER_UID=1000 diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index f9ec9f3d7c..45dcad84df 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -81,7 +81,7 @@ services: - httpbin.localtest.me etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.0 + image: gcr.io/etcd-development/etcd:v3.6.2 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 6f2321b74b..d79ee292c7 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -55,7 +55,7 @@ services: - httpbin.localtest.me etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.0 + image: gcr.io/etcd-development/etcd:v3.6.2 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 From d5f8507cc863c1ba4d699f635c6340078dda4857 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 20 Jul 2025 11:37:45 +0200 Subject: [PATCH 016/125] chore(deps): update alpine docker tag to v3.22.1 (#3129) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index f6128c0cd3..091ca726e8 100644 --- a/Makefile +++ b/Makefile @@ -67,7 +67,7 @@ DOCKER_BUILDX_PUSH := $(DOCKER_BUILDX) --push DOCKER_BUILDX_PUSH_X_PLATFORM := $(DOCKER_BUILDX_PUSH) --platform ${DOCKER_BUILD_PLATFORM} DOCKER_BUILD_PLATFORM_ALPINE ?= linux/amd64,linux/arm64,linux/ppc64le,linux/arm/v6,linux/arm/v7,linux/s390x -DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.22.0 +DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.22.1 DOCKER_BUILDX_ARGS_ALPINE ?= --build-arg RUNTIME_IMAGE=${DOCKER_BUILD_RUNTIME_IMAGE_ALPINE} ${DOCKER_BUILDX_COMMON_ARGS} DOCKER_BUILDX_X_PLATFORM_ALPINE := docker buildx build ${DOCKER_BUILDX_ARGS_ALPINE} --platform ${DOCKER_BUILD_PLATFORM_ALPINE} DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE := $(DOCKER_BUILDX_X_PLATFORM_ALPINE) --push From b57c82181d8d626d91ab72b42abea01e2049138a Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sun, 20 Jul 2025 16:44:42 +0200 Subject: [PATCH 017/125] feat(cookie) csrf per request limit (#3134) * Allow setting maximum number of csrf cookies, deleting the oldest if necessary * Add a test for multiple CSRF cookies to remove the old cookie * Add docs/changelog * If limit is <=0 do not clear Signed-off-by: test * Better docs Co-authored-by: Jan Larwig * direct check of option value Co-authored-by: Jan Larwig * direct use of option value Co-authored-by: Jan Larwig * sort based on clock compare vs time compare Co-authored-by: Jan Larwig * clock.Clock does not implement Compare, fix csrf cookie extraction after rename Signed-off-by: Bert Helderman * Linter fix * add method signature documentation and slight formatting Signed-off-by: Jan Larwig * fix: test case for csrf cookie limit and flag Signed-off-by: Jan Larwig --------- Signed-off-by: Bert Helderman Signed-off-by: Jan Larwig Co-authored-by: test Co-authored-by: bh-tt <71650427+bh-tt@users.noreply.github.com> --- CHANGELOG.md | 2 + docs/docs/configuration/overview.md | 84 ++++++++++++++-------------- oauthproxy.go | 3 +- pkg/apis/options/cookie.go | 24 ++++---- pkg/cookies/csrf.go | 50 ++++++++++++++++- pkg/cookies/csrf_per_request_test.go | 79 ++++++++++++++++++++++++++ 6 files changed, 186 insertions(+), 56 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 479ab4ce7d..d8cd18651a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ ## Changes since v7.10.0 +- [#2615](https://github.com/oauth2-proxy/oauth2-proxy/pull/2615) feat(cookies): add option to set a limit on the number of per-request CSRF cookies oauth2-proxy sets (@bh-tt) + # V7.10.0 ## Release Highlights diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index bea7061770..6a8f52e536 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -71,6 +71,7 @@ An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/ | `--config` | path to config file | | `--version` | print version string | + ### General Provider Options Provider specific options can be found on their respective subpages. @@ -91,7 +92,7 @@ Provider specific options can be found on their respective subpages. | flag: `--jwt-key-file`
toml: `jwt_key_file` | string | path to the private key file in PEM format used to sign the JWT so that you can say something like `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem`: required by login.gov | | | flag: `--jwt-key`
toml: `jwt_key` | string | private key in PEM format used to sign JWT, so that you can say something like `--jwt-key="${OAUTH2_PROXY_JWT_KEY}"`: required by login.gov | | | flag: `--login-url`
toml: `login_url` | string | Authentication endpoint | | -| flag: `--auth-request-response-mode`
toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | | +| flag: `--auth-request-response-mode`
toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | | | flag: `--oidc-audience-claim`
toml: `oidc_audience_claims` | string | which OIDC claim contains the audience | `"aud"` | | flag: `--oidc-email-claim`
toml: `oidc_email_claim` | string | which OIDC claim contains the user's email | `"email"` | | flag: `--oidc-extra-audience`
toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` | @@ -114,19 +115,20 @@ Provider specific options can be found on their respective subpages. ### Cookie Options -| Flag / Config Field | Type | Description | Default | -| -------------------------------------------------------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | -| flag: `--cookie-csrf-expire`
toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m | -| flag: `--cookie-csrf-per-request`
toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false | -| flag: `--cookie-domain`
toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | | -| flag: `--cookie-expire`
toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s | -| flag: `--cookie-httponly`
toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true | -| flag: `--cookie-name`
toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` | -| flag: `--cookie-path`
toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` | -| flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | -| flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | -| flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | -| flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | +| flag: `--cookie-csrf-expire`
toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m | +| flag: `--cookie-csrf-per-request`
toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false | +| flag: `--cookie-csrf-per-request-limit`
toml: `cookie_csrf_per_request_limit` | int | Sets a limit on the number of CSRF requests cookies that oauth2-proxy will create. The oldest cookie will be removed. Useful if users end up with 431 Request headers too large status codes. Only effective if --cookie-csrf-per-request is true | "infinite" | +| flag: `--cookie-domain`
toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | | +| flag: `--cookie-expire`
toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s | +| flag: `--cookie-httponly`
toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true | +| flag: `--cookie-name`
toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` | +| flag: `--cookie-path`
toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` | +| flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | +| flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | +| flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | +| flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | [^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) @@ -188,33 +190,33 @@ Provider specific options can be found on their respective subpages. ### Proxy Options -| Flag / Config Field | Type | Description | Default | -| ------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | -| flag: `--api-route`
toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | | -| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | -| flag: `--bearer-token-login-fallback`
toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true | -| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | -| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | -| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | -| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | -| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | -| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | -| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | -| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | -| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | -| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | -| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | -| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | -| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | -| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | -| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | -| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | -| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | -| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | -| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | -| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | -| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--bearer-token-login-fallback`
toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | [^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. diff --git a/oauthproxy.go b/oauthproxy.go index b85c89b486..a35e08acdb 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -845,13 +845,12 @@ func (p *OAuthProxy) doOAuthStart(rw http.ResponseWriter, req *http.Request, ove csrf.HashOIDCNonce(), extraParams, ) - + cookies.ClearExtraCsrfCookies(p.CookieOptions, rw, req) if _, err := csrf.SetCookie(rw, req); err != nil { logger.Errorf("Error setting CSRF cookie: %v", err) p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error()) return } - http.Redirect(rw, req, loginURL, http.StatusFound) } diff --git a/pkg/apis/options/cookie.go b/pkg/apis/options/cookie.go index 6917bdc570..22b74a6c54 100644 --- a/pkg/apis/options/cookie.go +++ b/pkg/apis/options/cookie.go @@ -8,17 +8,18 @@ import ( // Cookie contains configuration options relating to Cookie configuration type Cookie struct { - Name string `flag:"cookie-name" cfg:"cookie_name"` - Secret string `flag:"cookie-secret" cfg:"cookie_secret"` - Domains []string `flag:"cookie-domain" cfg:"cookie_domains"` - Path string `flag:"cookie-path" cfg:"cookie_path"` - Expire time.Duration `flag:"cookie-expire" cfg:"cookie_expire"` - Refresh time.Duration `flag:"cookie-refresh" cfg:"cookie_refresh"` - Secure bool `flag:"cookie-secure" cfg:"cookie_secure"` - HTTPOnly bool `flag:"cookie-httponly" cfg:"cookie_httponly"` - SameSite string `flag:"cookie-samesite" cfg:"cookie_samesite"` - CSRFPerRequest bool `flag:"cookie-csrf-per-request" cfg:"cookie_csrf_per_request"` - CSRFExpire time.Duration `flag:"cookie-csrf-expire" cfg:"cookie_csrf_expire"` + Name string `flag:"cookie-name" cfg:"cookie_name"` + Secret string `flag:"cookie-secret" cfg:"cookie_secret"` + Domains []string `flag:"cookie-domain" cfg:"cookie_domains"` + Path string `flag:"cookie-path" cfg:"cookie_path"` + Expire time.Duration `flag:"cookie-expire" cfg:"cookie_expire"` + Refresh time.Duration `flag:"cookie-refresh" cfg:"cookie_refresh"` + Secure bool `flag:"cookie-secure" cfg:"cookie_secure"` + HTTPOnly bool `flag:"cookie-httponly" cfg:"cookie_httponly"` + SameSite string `flag:"cookie-samesite" cfg:"cookie_samesite"` + CSRFPerRequest bool `flag:"cookie-csrf-per-request" cfg:"cookie_csrf_per_request"` + CSRFExpire time.Duration `flag:"cookie-csrf-expire" cfg:"cookie_csrf_expire"` + CSRFPerRequestLimit int `flag:"cookie-csrf-per-request-limit" cfg:"cookie_csrf_per_request_limit"` } func cookieFlagSet() *pflag.FlagSet { @@ -34,6 +35,7 @@ func cookieFlagSet() *pflag.FlagSet { flagSet.Bool("cookie-httponly", true, "set HttpOnly cookie flag") flagSet.String("cookie-samesite", "", "set SameSite cookie attribute (ie: \"lax\", \"strict\", \"none\", or \"\"). ") flagSet.Bool("cookie-csrf-per-request", false, "When this property is set to true, then the CSRF cookie name is built based on the state and varies per request. If property is set to false, then CSRF cookie has the same name for all requests.") + flagSet.Int("cookie-csrf-per-request-limit", 0, "Sets a limit on the number of CSRF requests cookies that oauth2-proxy will create. The oldest cookies will be removed. Useful if users end up with 431 Request headers too large status codes.") flagSet.Duration("cookie-csrf-expire", time.Duration(15)*time.Minute, "expire timeframe for CSRF cookie") return flagSet } diff --git a/pkg/cookies/csrf.go b/pkg/cookies/csrf.go index 698a7c8d45..eab87869e4 100644 --- a/pkg/cookies/csrf.go +++ b/pkg/cookies/csrf.go @@ -4,6 +4,8 @@ import ( "errors" "fmt" "net/http" + "slices" + "strings" "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" @@ -151,6 +153,48 @@ func (c *csrf) SetCookie(rw http.ResponseWriter, req *http.Request) (*http.Cooki return cookie, nil } +// ClearExtraCsrfCookies limits the amount of existing CSRF cookies by deleting +// an excess of cookies controlled through the option CSRFPerRequestLimit +func ClearExtraCsrfCookies(opts *options.Cookie, rw http.ResponseWriter, req *http.Request) { + if !opts.CSRFPerRequest || opts.CSRFPerRequestLimit <= 0 { + return + } + + cookies := req.Cookies() + existingCsrfCookies := []*http.Cookie{} + startsWith := fmt.Sprintf("%v_", opts.Name) + + // determine how many csrf cookies we have + for _, cookie := range cookies { + if strings.HasPrefix(cookie.Name, startsWith) && strings.HasSuffix(cookie.Name, "_csrf") { + existingCsrfCookies = append(existingCsrfCookies, cookie) + } + } + + // short circuit return + if len(existingCsrfCookies) <= opts.CSRFPerRequestLimit { + return + } + + decodedCookies := []*csrf{} + for _, cookie := range existingCsrfCookies { + decodedCookie, err := decodeCSRFCookie(cookie, opts) + if err != nil { + continue + } + decodedCookies = append(decodedCookies, decodedCookie) + } + + // delete the X oldest cookies + slices.SortStableFunc(decodedCookies, func(a, b *csrf) int { + return a.time.Now().Compare(b.time.Now()) + }) + + for i := 0; i < len(decodedCookies)-opts.CSRFPerRequestLimit; i++ { + decodedCookies[i].ClearCookie(rw, req) + } +} + // ClearCookie removes the CSRF cookie func (c *csrf) ClearCookie(rw http.ResponseWriter, req *http.Request) { http.SetCookie(rw, MakeCookieFromOptions( @@ -181,7 +225,7 @@ func (c *csrf) encodeCookie() (string, error) { // decodeCSRFCookie validates the signature then decrypts and decodes a CSRF // cookie into a CSRF struct func decodeCSRFCookie(cookie *http.Cookie, opts *options.Cookie) (*csrf, error) { - val, _, ok := encryption.Validate(cookie, opts.Secret, opts.Expire) + val, t, ok := encryption.Validate(cookie, opts.Secret, opts.Expire) if !ok { return nil, errors.New("CSRF cookie failed validation") } @@ -192,7 +236,9 @@ func decodeCSRFCookie(cookie *http.Cookie, opts *options.Cookie) (*csrf, error) } // Valid cookie, Unmarshal the CSRF - csrf := &csrf{cookieOpts: opts} + clock := clock.Clock{} + clock.Set(t) + csrf := &csrf{cookieOpts: opts, time: clock} err = msgpack.Unmarshal(decrypted, csrf) if err != nil { return nil, fmt.Errorf("error unmarshalling data to CSRF: %v", err) diff --git a/pkg/cookies/csrf_per_request_test.go b/pkg/cookies/csrf_per_request_test.go index 28e2e29607..9b7d4e592d 100644 --- a/pkg/cookies/csrf_per_request_test.go +++ b/pkg/cookies/csrf_per_request_test.go @@ -190,5 +190,84 @@ var _ = Describe("CSRF Cookie with non-fixed name Tests", func() { Expect(privateCSRF.cookieName()).To(ContainSubstring(cookieName)) }) }) + + Context("CSRF per request limit", func() { + It("clears cookies based on the limit", func() { + //needs to be now as pkg/encryption/utils.go uses time.Now() + testNow := time.Now() + cookieOpts.CSRFPerRequestLimit = 1 + + publicCSRF1, err := NewCSRF(cookieOpts, "verifier") + Expect(err).ToNot(HaveOccurred()) + privateCSRF1 := publicCSRF1.(*csrf) + privateCSRF1.time.Set(testNow) + + publicCSRF2, err := NewCSRF(cookieOpts, "verifier") + Expect(err).ToNot(HaveOccurred()) + privateCSRF2 := publicCSRF2.(*csrf) + privateCSRF2.time.Set(testNow.Add(time.Minute)) + + publicCSRF3, err := NewCSRF(cookieOpts, "verifier") + Expect(err).ToNot(HaveOccurred()) + privateCSRF3 := publicCSRF3.(*csrf) + privateCSRF3.time.Set(testNow.Add(time.Minute * 2)) + + cookies := []string{} + for _, csrf := range []*csrf{privateCSRF1, privateCSRF2, privateCSRF3} { + encoded, err := csrf.encodeCookie() + Expect(err).ToNot(HaveOccurred()) + cookie := MakeCookieFromOptions( + req, + csrf.cookieName(), + encoded, + csrf.cookieOpts, + csrf.cookieOpts.CSRFExpire, + ) + cookies = append(cookies, fmt.Sprintf("%v=%v", cookie.Name, cookie.Value)) + } + + header := make(map[string][]string, 1) + header["Cookie"] = cookies + req = &http.Request{ + Method: http.MethodGet, + Proto: "HTTP/1.1", + Host: cookieDomain, + + URL: &url.URL{ + Scheme: "https", + Host: cookieDomain, + Path: cookiePath, + }, + Header: header, + } + + // when setting the limit to one csrf cookie but configuring three csrf cookies + // then two cookies should be removed / set to expired on the response + + // for this test case we have set all the cookies on a single request, + // but in reality this will be multiple requests after another + rw := httptest.NewRecorder() + ClearExtraCsrfCookies(cookieOpts, rw, req) + + clearedCookies := rw.Header()["Set-Cookie"] + Expect(clearedCookies).To(HaveLen(2)) + Expect(clearedCookies[0]).To(Equal( + fmt.Sprintf( + "%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure", + privateCSRF1.cookieName(), + cookiePath, + cookieDomain, + ), + )) + Expect(clearedCookies[1]).To(Equal( + fmt.Sprintf( + "%s=; Path=%s; Domain=%s; Max-Age=0; HttpOnly; Secure", + privateCSRF2.cookieName(), + cookiePath, + cookieDomain, + ), + )) + }) + }) }) }) From 5e7f14bdcbbd22702c7b5de907398e94012bab2a Mon Sep 17 00:00:00 2001 From: Johann <76482511+Primexz@users.noreply.github.com> Date: Sun, 20 Jul 2025 17:17:24 +0200 Subject: [PATCH 018/125] fix: show login page on broken session cookie (#2605) * fix: redirect on invalid cookie * docs: update changelog * chore: remove duplicated code * fix: status code handling if wrong http method is used --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + oauthproxy.go | 10 ++++------ 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d8cd18651a..35685b7a8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ## Changes since v7.10.0 - [#2615](https://github.com/oauth2-proxy/oauth2-proxy/pull/2615) feat(cookies): add option to set a limit on the number of per-request CSRF cookies oauth2-proxy sets (@bh-tt) +- [#2605](https://github.com/oauth2-proxy/oauth2-proxy/pull/2605) fix: show login page on broken cookie (@Primexz) # V7.10.0 diff --git a/oauthproxy.go b/oauthproxy.go index a35e08acdb..d8984cde7c 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -633,12 +633,6 @@ func (p *OAuthProxy) isTrustedIP(req *http.Request) bool { // SignInPage writes the sign in template to the response func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code int) { prepareNoCache(rw) - err := p.ClearSessionCookie(rw, req) - if err != nil { - logger.Printf("Error clearing session cookie: %v", err) - p.ErrorPage(rw, req, http.StatusInternalServerError, err.Error()) - return - } rw.WriteHeader(code) redirectURL, err := p.appDirector.GetRedirect(req) @@ -652,6 +646,10 @@ func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code redirectURL = "/" } + if err := p.ClearSessionCookie(rw, req); err != nil { + logger.Printf("Error clearing session cookie: %v", err) + } + p.pageWriter.WriteSignInPage(rw, req, redirectURL, code) } From 3ac834dbcfbb06de1b5168eb6397835f6f6538bb Mon Sep 17 00:00:00 2001 From: Simmo Saan Date: Sun, 20 Jul 2025 21:32:50 +0300 Subject: [PATCH 019/125] Fix local-environment ports (#3136) * Change Dex port in local-environment from 4190 to 5556 Port 4190 is blocked by standards-compliant browsers (e.g. Firefox), as per https://fetch.spec.whatwg.org/#port-blocking. Port 5556 is used by Dex in its example config files: https://github.com/dexidp/dex/blob/745e1114f341e849f3b0edde45b39c14017deaf8/examples/config-dev.yaml#L50 * Fix upstream in local-environment/oauth2-proxy.cfg http://httpbin.localtest.me:8080 is only exposed to the host, not to httpbin Docker network. Causes Bad Gateway before. * Do not expose unauthenticated httpbin service in local-environment This defeats the point of having oauth2-proxy. It has already been misleading by causing the bug fixed in cafc6af48fc38f6fe4395fb0c7e2638bc84e6091. It serves as a bad example: users might accidentally expose the service they're trying to protect in the first place. * Remove unnecessary httpbin.localtest.me alias from local-environment --- contrib/local-environment/dex.yaml | 6 +++--- contrib/local-environment/docker-compose-gitea.yaml | 7 ++----- contrib/local-environment/docker-compose-keycloak.yaml | 7 ++----- contrib/local-environment/docker-compose-nginx.yaml | 9 +++------ contrib/local-environment/docker-compose.yaml | 9 +++------ contrib/local-environment/oauth2-proxy-alpha-config.yaml | 2 +- contrib/local-environment/oauth2-proxy-keycloak.cfg | 2 +- contrib/local-environment/oauth2-proxy-nginx.cfg | 2 +- contrib/local-environment/oauth2-proxy-traefik.cfg | 4 ++-- contrib/local-environment/oauth2-proxy.cfg | 4 ++-- docs/docs/community/contribution.md | 2 +- .../version-7.10.x/community/contribution.md | 2 +- 12 files changed, 22 insertions(+), 34 deletions(-) diff --git a/contrib/local-environment/dex.yaml b/contrib/local-environment/dex.yaml index fd64152b23..f0a2ead422 100644 --- a/contrib/local-environment/dex.yaml +++ b/contrib/local-environment/dex.yaml @@ -1,7 +1,7 @@ # This configuration is intended to be used with the docker-compose testing # environment. -# This should configure Dex to run on port 4190 and provides a static login -issuer: http://dex.localtest.me:4190/dex +# This should configure Dex to run on port 5556 and provides a static login +issuer: http://dex.localtest.me:5556/dex storage: type: etcd config: @@ -9,7 +9,7 @@ storage: - http://etcd:2379 namespace: dex/ web: - http: 0.0.0.0:4190 + http: 0.0.0.0:5556 oauth2: skipApprovalScreen: true expiry: diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 454d012368..c32360840f 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -34,12 +34,9 @@ services: container_name: httpbin image: kennethreitz/httpbin:latest hostname: httpbin - ports: - - 8080:80 + ports: [] networks: - httpbin: - aliases: - - httpbin.localtest.me + httpbin: {} gitea: image: gitea/gitea:1.24.3 diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index 3a5a391467..66a2d011ff 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -34,12 +34,9 @@ services: container_name: httpbin image: kennethreitz/httpbin:latest hostname: httpbin - ports: - - 8080:80/tcp + ports: [] networks: - httpbin: - aliases: - - httpbin.localtest.me + httpbin: {} keycloak: container_name: keycloak diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 45dcad84df..72f9d97a7c 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -62,7 +62,7 @@ services: - "./dex.yaml:/dex.yaml" restart: unless-stopped ports: - - 4190:4190/tcp + - 5556:4181/tcp networks: dex: aliases: @@ -73,12 +73,9 @@ services: httpbin: container_name: httpbin image: kennethreitz/httpbin - ports: - - 8080:80/tcp + ports: [] networks: - httpbin: - aliases: - - httpbin.localtest.me + httpbin: {} etcd: container_name: etcd image: gcr.io/etcd-development/etcd:v3.6.2 diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index d79ee292c7..3da4a9a63b 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -36,7 +36,7 @@ services: - "./dex.yaml:/dex.yaml" restart: unless-stopped ports: - - 4190:4190/tcp + - 5556:4181/tcp networks: dex: aliases: @@ -47,12 +47,9 @@ services: httpbin: container_name: httpbin image: kennethreitz/httpbin - ports: - - 8080:80/tcp + ports: [] networks: - httpbin: - aliases: - - httpbin.localtest.me + httpbin: {} etcd: container_name: etcd image: gcr.io/etcd-development/etcd:v3.6.2 diff --git a/contrib/local-environment/oauth2-proxy-alpha-config.yaml b/contrib/local-environment/oauth2-proxy-alpha-config.yaml index 6a46e1b1fe..b2c9f6a89e 100644 --- a/contrib/local-environment/oauth2-proxy-alpha-config.yaml +++ b/contrib/local-environment/oauth2-proxy-alpha-config.yaml @@ -20,4 +20,4 @@ providers: clientSecret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK clientID: oauth2-proxy oidcConfig: - issuerURL: http://dex.localhost:4190/dex + issuerURL: http://dex.localhost:5556/dex diff --git a/contrib/local-environment/oauth2-proxy-keycloak.cfg b/contrib/local-environment/oauth2-proxy-keycloak.cfg index 391ad331d0..8491b28640 100644 --- a/contrib/local-environment/oauth2-proxy-keycloak.cfg +++ b/contrib/local-environment/oauth2-proxy-keycloak.cfg @@ -3,7 +3,7 @@ cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w=" email_domains="example.com" cookie_secure="false" upstreams="http://httpbin" -cookie_domains=["oauth2-proxy.localtest.me:4080", "httpbin.localtest.me:8080", "keycloak.localtest.me:9080"] # Required so cookie can be read on all subdomains. +cookie_domains=["oauth2-proxy.localtest.me:4080", "keycloak.localtest.me:9080"] # Required so cookie can be read on all subdomains. whitelist_domains=[".localtest.me"] # Required to allow redirection back to original requested target. # keycloak provider diff --git a/contrib/local-environment/oauth2-proxy-nginx.cfg b/contrib/local-environment/oauth2-proxy-nginx.cfg index e17eb31182..01b64a55f6 100644 --- a/contrib/local-environment/oauth2-proxy-nginx.cfg +++ b/contrib/local-environment/oauth2-proxy-nginx.cfg @@ -2,7 +2,7 @@ http_address="0.0.0.0:4180" cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w=" provider="oidc" email_domains="example.com" -oidc_issuer_url="http://dex.localtest.me:4190/dex" +oidc_issuer_url="http://dex.localtest.me:5556/dex" client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK" client_id="oauth2-proxy" cookie_secure="false" diff --git a/contrib/local-environment/oauth2-proxy-traefik.cfg b/contrib/local-environment/oauth2-proxy-traefik.cfg index 6357c383a6..8dce675276 100644 --- a/contrib/local-environment/oauth2-proxy-traefik.cfg +++ b/contrib/local-environment/oauth2-proxy-traefik.cfg @@ -2,7 +2,7 @@ http_address="0.0.0.0:4180" cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w=" provider="oidc" email_domains=["example.com"] -oidc_issuer_url="http://dex.localhost:4190/dex" +oidc_issuer_url="http://dex.localhost:5556/dex" client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK" client_id="oauth2-proxy" cookie_secure="false" @@ -13,7 +13,7 @@ whitelist_domains=".oauth2-proxy.localhost" # Required to allow redirection back # Mandatory option when using oauth2-proxy with traefik reverse_proxy="true" -# Required for traefik with ForwardAuth and static upstream configuration +# Required for traefik with ForwardAuth and static upstream configuration upstreams="static://202" # The following option skip the page requesting the user # to click on a button to be redirected to the identity provider diff --git a/contrib/local-environment/oauth2-proxy.cfg b/contrib/local-environment/oauth2-proxy.cfg index ee58e14583..dfa8b34184 100644 --- a/contrib/local-environment/oauth2-proxy.cfg +++ b/contrib/local-environment/oauth2-proxy.cfg @@ -2,7 +2,7 @@ http_address="0.0.0.0:4180" cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w=" email_domains="example.com" cookie_secure="false" -upstreams="http://httpbin.localtest.me:8080" +upstreams="http://httpbin" cookie_domains=[".localtest.me"] # Required so cookie can be read on all subdomains. whitelist_domains=[".localtest.me"] # Required to allow redirection back to original requested target. @@ -11,6 +11,6 @@ client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK" client_id="oauth2-proxy" redirect_url="http://oauth2-proxy.localtest.me:4180/oauth2/callback" -oidc_issuer_url="http://dex.localtest.me:4190/dex" +oidc_issuer_url="http://dex.localtest.me:5556/dex" provider="oidc" provider_display_name="Dex" diff --git a/docs/docs/community/contribution.md b/docs/docs/community/contribution.md index 2cd330ac32..92255eda17 100644 --- a/docs/docs/community/contribution.md +++ b/docs/docs/community/contribution.md @@ -85,5 +85,5 @@ The docker compose setups expose the services with a dynamic reverse DNS resolve - OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 - Upstream: http://httpbin.localtest.me:8080 -- Dex: http://dex.localtest.me:4190 +- Dex: http://dex.localtest.me:5556 diff --git a/docs/versioned_docs/version-7.10.x/community/contribution.md b/docs/versioned_docs/version-7.10.x/community/contribution.md index 2cd330ac32..92255eda17 100644 --- a/docs/versioned_docs/version-7.10.x/community/contribution.md +++ b/docs/versioned_docs/version-7.10.x/community/contribution.md @@ -85,5 +85,5 @@ The docker compose setups expose the services with a dynamic reverse DNS resolve - OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 - Upstream: http://httpbin.localtest.me:8080 -- Dex: http://dex.localtest.me:4190 +- Dex: http://dex.localtest.me:5556 From 4d17bc1d6834b62c49548b88eff3f8d2a666ef8d Mon Sep 17 00:00:00 2001 From: Bob Du Date: Mon, 21 Jul 2025 15:06:17 +0800 Subject: [PATCH 020/125] feat: allow use more possible google admin-sdk api scopes (#2743) * feat: Allow use more possible google admin-sdk api scopes. * reduce cognitive complexity Signed-off-by: Bob Du * remove unnecessary else block / indentation Signed-off-by: Jan Larwig * add changelog entry Signed-off-by: Jan Larwig * slight formatting and error message rephrasing Signed-off-by: Jan Larwig --------- Signed-off-by: Bob Du Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- .gitignore | 1 + CHANGELOG.md | 1 + docs/docs/configuration/providers/google.md | 7 +- providers/google.go | 79 ++++++++++++++++----- 4 files changed, 65 insertions(+), 23 deletions(-) diff --git a/.gitignore b/.gitignore index e40acd5217..a7ee4162b5 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,7 @@ c.out # Folders _obj _test +.DS_Store .idea/ .vscode/* !/.vscode/tasks.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 35685b7a8c..2aa456e211 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - [#2615](https://github.com/oauth2-proxy/oauth2-proxy/pull/2615) feat(cookies): add option to set a limit on the number of per-request CSRF cookies oauth2-proxy sets (@bh-tt) - [#2605](https://github.com/oauth2-proxy/oauth2-proxy/pull/2605) fix: show login page on broken cookie (@Primexz) +- [#2743](https://github.com/oauth2-proxy/oauth2-proxy/pull/2743) feat: allow use more possible google admin-sdk api scopes (@BobDu) # V7.10.0 diff --git a/docs/docs/configuration/providers/google.md b/docs/docs/configuration/providers/google.md index e3e819adad..26af87ab5c 100644 --- a/docs/docs/configuration/providers/google.md +++ b/docs/docs/configuration/providers/google.md @@ -37,18 +37,17 @@ account is still authorized. #### Restrict auth to specific Google groups on your domain. (optional) -1. Create a [service account](https://developers.google.com/identity/protocols/OAuth2ServiceAccount) and configure it +1. Create a [service account](https://developers.google.com/identity/protocols/oauth2/service-account) and configure it to use [Application Default Credentials / Workload Identity / Workload Identity Federation (recommended)](#using-application-default-credentials-adc--workload-identity--workload-identity-federation-recommended) or, alternatively download the JSON. 2. Make note of the Client ID for a future step. 3. Under "APIs & Auth", choose APIs. 4. Click on Admin SDK and then Enable API. -5. Follow the steps on https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account +5. Follow the steps on [Set up domain-wide delegation for a service account](https://developers.google.com/workspace/guides/create-credentials#optional_set_up_domain-wide_delegation_for_a_service_account) and give the client id from step 2 the following oauth scopes: ``` - https://www.googleapis.com/auth/admin.directory.group.readonly - https://www.googleapis.com/auth/admin.directory.user.readonly + https://www.googleapis.com/auth/admin.directory.group.member.readonly ``` 6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access. diff --git a/providers/google.go b/providers/google.go index 8b17d090d2..0e1e215661 100644 --- a/providers/google.go +++ b/providers/google.go @@ -229,38 +229,79 @@ func (p *GoogleProvider) setGroupRestriction(opts options.GoogleOptions) { } } -func getAdminService(opts options.GoogleOptions) *admin.Service { - ctx := context.Background() - var client *http.Client +// https://developers.google.com/admin-sdk/directory/reference/rest/v1/members/hasMember#authorization-scopes +var possibleScopesList = [...]string{ + admin.AdminDirectoryGroupMemberReadonlyScope, + admin.AdminDirectoryGroupReadonlyScope, + admin.AdminDirectoryGroupMemberScope, + admin.AdminDirectoryGroupScope, +} + +func getOauth2TokenSource(ctx context.Context, opts options.GoogleOptions, scope string) oauth2.TokenSource { if opts.UseApplicationDefaultCredentials { ts, err := impersonate.CredentialsTokenSource(ctx, impersonate.CredentialsConfig{ TargetPrincipal: getTargetPrincipal(ctx, opts), - Scopes: []string{admin.AdminDirectoryGroupReadonlyScope, admin.AdminDirectoryUserReadonlyScope}, + Scopes: []string{scope}, Subject: opts.AdminEmail, }) if err != nil { logger.Fatal("failed to fetch application default credentials: ", err) } - client = oauth2.NewClient(ctx, ts) - } else { - credentialsReader, err := os.Open(opts.ServiceAccountJSON) - if err != nil { - logger.Fatal("couldn't open Google credentials file: ", err) - return nil - } + return ts + } - data, err := io.ReadAll(credentialsReader) - if err != nil { - logger.Fatal("can't read Google credentials file:", err) + credentialsReader, err := os.Open(opts.ServiceAccountJSON) + if err != nil { + logger.Fatal("couldn't open Google credentials file: ", err) + } + + data, err := io.ReadAll(credentialsReader) + if err != nil { + logger.Fatal("can't read Google credentials file:", err) + } + + conf, err := google.JWTConfigFromJSON(data, scope) + if err != nil { + logger.Fatal("can't load Google credentials file:", err) + } + + conf.Subject = opts.AdminEmail + return conf.TokenSource(ctx) +} + +func getAdminService(opts options.GoogleOptions) *admin.Service { + ctx := context.Background() + var client *http.Client + + for _, scope := range possibleScopesList { + + ts := getOauth2TokenSource(ctx, opts, scope) + _, err := ts.Token() + + if err == nil { + client = oauth2.NewClient(ctx, ts) + break } - conf, err := google.JWTConfigFromJSON(data, admin.AdminDirectoryUserReadonlyScope, admin.AdminDirectoryGroupReadonlyScope) - if err != nil { - logger.Fatal("can't load Google credentials file:", err) + if retrieveErr, ok := err.(*oauth2.RetrieveError); ok { + retrieveErrBody := map[string]interface{}{} + + if err := json.Unmarshal(retrieveErr.Body, &retrieveErrBody); err != nil { + logger.Fatal("error unmarshalling retrieveErr body:", err) + } + + if retrieveErrBody["error"] == "unauthorized_client" && retrieveErrBody["error_description"] == "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested." { + continue + } + + logger.Fatal("error retrieving token:", err) } - conf.Subject = opts.AdminEmail - client = conf.Client(ctx) } + + if client == nil { + logger.Fatal("error: google credentials do not have enough permissions to access admin API scope") + } + adminService, err := admin.NewService(ctx, option.WithHTTPClient(client)) if err != nil { logger.Fatal(err) From a88306be980a4866edae676f8c976ab94f23eec6 Mon Sep 17 00:00:00 2001 From: Conrad Hoffmann <1226676+bitfehler@users.noreply.github.com> Date: Tue, 22 Jul 2025 08:16:32 +0200 Subject: [PATCH 021/125] feat: add SourceHut (sr.ht) provider (#2359) * Add SourceHut (sr.ht) provider * fix changelog entry Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + .../docs/configuration/providers/sourcehut.md | 25 ++++ pkg/apis/options/providers.go | 3 + providers/providers.go | 5 +- providers/srht.go | 108 ++++++++++++++++++ providers/srht_test.go | 77 +++++++++++++ 6 files changed, 218 insertions(+), 1 deletion(-) create mode 100644 docs/docs/configuration/providers/sourcehut.md create mode 100644 providers/srht.go create mode 100644 providers/srht_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 2aa456e211..b2ffc50dff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - [#2615](https://github.com/oauth2-proxy/oauth2-proxy/pull/2615) feat(cookies): add option to set a limit on the number of per-request CSRF cookies oauth2-proxy sets (@bh-tt) - [#2605](https://github.com/oauth2-proxy/oauth2-proxy/pull/2605) fix: show login page on broken cookie (@Primexz) - [#2743](https://github.com/oauth2-proxy/oauth2-proxy/pull/2743) feat: allow use more possible google admin-sdk api scopes (@BobDu) +- [#2359](https://github.com/oauth2-proxy/oauth2-proxy/pull/2359) feat: add SourceHut (sr.ht) provider(@bitfehler) # V7.10.0 diff --git a/docs/docs/configuration/providers/sourcehut.md b/docs/docs/configuration/providers/sourcehut.md new file mode 100644 index 0000000000..88d14622bd --- /dev/null +++ b/docs/docs/configuration/providers/sourcehut.md @@ -0,0 +1,25 @@ +--- +id: sourcehut +title: SourceHut +--- + +1. Create a new OAuth client: https://meta.sr.ht/oauth2 +2. Under `Redirection URI` enter the correct URL, i.e. + `https://internal.yourcompany.com/oauth2/callback` + +To use the provider, start with `--provider=sourcehut`. + +If you are hosting your own SourceHut instance, make sure you set the following +to the appropriate URLs: + +```shell + --login-url="https:///oauth2/authorize" + --redeem-url="https:///oauth2/access-token" + --profile-url="https:///query" + --validate-url="https:///profile" +``` + +The default configuration allows everyone with an account to authenticate. +Restricting access is currently only supported by +[email](#email-authentication). + diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 280b1ce0fa..ac5652cabb 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -147,6 +147,9 @@ const ( // OIDCProvider is the provider type for OIDC OIDCProvider ProviderType = "oidc" + + // SourceHutProvider is the provider type for SourceHut + SourceHutProvider ProviderType = "sourcehut" ) type KeycloakOptions struct { diff --git a/providers/providers.go b/providers/providers.go index 3a125a24cd..8bc5ff8867 100644 --- a/providers/providers.go +++ b/providers/providers.go @@ -67,6 +67,8 @@ func NewProvider(providerConfig options.Provider) (Provider, error) { return NewNextcloudProvider(providerData), nil case options.OIDCProvider: return NewOIDCProvider(providerData, providerConfig.OIDCConfig), nil + case options.SourceHutProvider: + return NewSourceHutProvider(providerData), nil default: return nil, fmt.Errorf("unknown provider type %q", providerConfig.Type) } @@ -183,7 +185,8 @@ func parseCodeChallengeMethod(providerConfig options.Provider) string { func providerRequiresOIDCProviderVerifier(providerType options.ProviderType) (bool, error) { switch providerType { case options.BitbucketProvider, options.DigitalOceanProvider, options.FacebookProvider, options.GitHubProvider, - options.GoogleProvider, options.KeycloakProvider, options.LinkedInProvider, options.LoginGovProvider, options.NextCloudProvider: + options.GoogleProvider, options.KeycloakProvider, options.LinkedInProvider, options.LoginGovProvider, + options.NextCloudProvider, options.SourceHutProvider: return false, nil case options.ADFSProvider, options.AzureProvider, options.GitLabProvider, options.KeycloakOIDCProvider, options.OIDCProvider, options.MicrosoftEntraIDProvider: return true, nil diff --git a/providers/srht.go b/providers/srht.go new file mode 100644 index 0000000000..aa72229cb0 --- /dev/null +++ b/providers/srht.go @@ -0,0 +1,108 @@ +package providers + +import ( + "bytes" + "context" + "fmt" + "net/url" + + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" +) + +type SourceHutProvider struct { + *ProviderData +} + +var _ Provider = (*SourceHutProvider)(nil) + +const ( + SourceHutProviderName = "SourceHut" + SourceHutDefaultScope = "meta.sr.ht/PROFILE:RO" +) + +var ( + // Default Login URL for SourceHut. + // Pre-parsed URL of https://meta.sr.ht/oauth2/authorize. + SourceHutDefaultLoginURL = &url.URL{ + Scheme: "https", + Host: "meta.sr.ht", + Path: "/oauth2/authorize", + } + + // Default Redeem URL for SourceHut. + // Pre-parsed URL of https://meta.sr.ht/oauth2/access-token. + SourceHutDefaultRedeemURL = &url.URL{ + Scheme: "https", + Host: "meta.sr.ht", + Path: "/oauth2/access-token", + } + + // Default Profile URL for SourceHut. + // Pre-parsed URL of https://meta.sr.ht/query. + SourceHutDefaultProfileURL = &url.URL{ + Scheme: "https", + Host: "meta.sr.ht", + Path: "/query", + } + + // Default Validation URL for SourceHut. + // Pre-parsed URL of https://meta.sr.ht/profile. + SourceHutDefaultValidateURL = &url.URL{ + Scheme: "https", + Host: "meta.sr.ht", + Path: "/profile", + } +) + +// NewSourceHutProvider creates a SourceHutProvider using the passed ProviderData +func NewSourceHutProvider(p *ProviderData) *SourceHutProvider { + p.setProviderDefaults(providerDefaults{ + name: SourceHutProviderName, + loginURL: SourceHutDefaultLoginURL, + redeemURL: SourceHutDefaultRedeemURL, + profileURL: SourceHutDefaultProfileURL, + validateURL: SourceHutDefaultValidateURL, + scope: SourceHutDefaultScope, + }) + + return &SourceHutProvider{ProviderData: p} +} + +// EnrichSession uses the SourceHut userinfo endpoint to populate the session's +// email and username. +func (p *SourceHutProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error { + json, err := requests.New(p.ProfileURL.String()). + WithContext(ctx). + WithMethod("POST"). + SetHeader("Content-Type", "application/json"). + SetHeader("Authorization", "Bearer "+s.AccessToken). + WithBody(bytes.NewBufferString(`{"query": "{ me { username, email } }"}`)). + Do(). + UnmarshalSimpleJSON() + if err != nil { + logger.Errorf("failed making request %v", err) + return err + } + + email, err := json.GetPath("data", "me", "email").String() + if err != nil { + return fmt.Errorf("unable to extract email from userinfo endpoint: %v", err) + } + s.Email = email + + username, err := json.GetPath("data", "me", "username").String() + if err != nil { + return fmt.Errorf("unable to extract username from userinfo endpoint: %v", err) + } + s.PreferredUsername = username + s.User = username + + return nil +} + +// ValidateSession validates the AccessToken +func (p *SourceHutProvider) ValidateSession(ctx context.Context, s *sessions.SessionState) bool { + return validateToken(ctx, p, s.AccessToken, makeOIDCHeader(s.AccessToken)) +} diff --git a/providers/srht_test.go b/providers/srht_test.go new file mode 100644 index 0000000000..fd51bf7ff2 --- /dev/null +++ b/providers/srht_test.go @@ -0,0 +1,77 @@ +package providers + +import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/stretchr/testify/assert" +) + +func testSourceHutProvider(hostname string) *SourceHutProvider { + p := NewSourceHutProvider( + &ProviderData{ + ProviderName: "SourceHut", + LoginURL: &url.URL{}, + RedeemURL: &url.URL{}, + ProfileURL: &url.URL{}, + ValidateURL: &url.URL{}, + Scope: ""}, + ) + p.ProviderName = "SourceHut" + + if hostname != "" { + updateURL(p.Data().LoginURL, hostname) + updateURL(p.Data().RedeemURL, hostname) + updateURL(p.Data().ProfileURL, hostname) + updateURL(p.Data().ValidateURL, hostname) + } + return p +} + +func testSourceHutBackend(payloads map[string][]string) *httptest.Server { + return httptest.NewServer(http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + index := 0 + payload, ok := payloads[r.URL.Path] + if !ok { + w.WriteHeader(404) + } else if payload[index] == "" { + w.WriteHeader(204) + } else { + w.WriteHeader(200) + w.Write([]byte(payload[index])) + } + })) +} + +func TestSourceHutProvider_ValidateSessionWithBaseUrl(t *testing.T) { + b := testSourceHutBackend(map[string][]string{}) + defer b.Close() + + bURL, _ := url.Parse(b.URL) + p := testSourceHutProvider(bURL.Host) + + session := CreateAuthorizedSession() + + valid := p.ValidateSession(context.Background(), session) + assert.False(t, valid) +} + +func TestSourceHutProvider_ValidateSessionWithUserEmails(t *testing.T) { + b := testSourceHutBackend(map[string][]string{ + "/query": {`{"data":{"me":{"username":"bitfehler","email":"ch@bitfehler.net"}}}`}, + "/profile": {`ok`}, + }) + defer b.Close() + + bURL, _ := url.Parse(b.URL) + p := testSourceHutProvider(bURL.Host) + + session := CreateAuthorizedSession() + + valid := p.ValidateSession(context.Background(), session) + assert.True(t, valid) +} From 137e59d52668e3fc5d670dfbb6c3d667739e22e3 Mon Sep 17 00:00:00 2001 From: Ashkan Daie <1415513+dashkan@users.noreply.github.com> Date: Mon, 21 Jul 2025 23:52:23 -0700 Subject: [PATCH 022/125] fix: regex substitution for $ signs in upstream path handling before running envsubst (#2524) * Perform a regex replace of $NUM to $$NUM before running envsubst * Perform a regex replace of $NUM to $$NUM before running envsubst * add test case; fix linter warnings; add method documentation Signed-off-by: Jan Larwig * add changelog entry Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + pkg/apis/options/load.go | 22 +++++++++++++++++++--- pkg/apis/options/load_test.go | 25 +++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b2ffc50dff..50dbc9b915 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - [#2605](https://github.com/oauth2-proxy/oauth2-proxy/pull/2605) fix: show login page on broken cookie (@Primexz) - [#2743](https://github.com/oauth2-proxy/oauth2-proxy/pull/2743) feat: allow use more possible google admin-sdk api scopes (@BobDu) - [#2359](https://github.com/oauth2-proxy/oauth2-proxy/pull/2359) feat: add SourceHut (sr.ht) provider(@bitfehler) +-[#2524](https://github.com/oauth2-proxy/oauth2-proxy/pull/2524) fix: regex substitution for $ signs in upstream path handling before running envsubst (@dashkan / @tuunit) # V7.10.0 diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index b198c4ffad..c302e8e775 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -5,6 +5,7 @@ import ( "fmt" "os" "reflect" + "regexp" "strings" "github.com/a8m/envsubst" @@ -155,7 +156,8 @@ func LoadYAML(configFileName string, into interface{}) error { return nil } -// Performs the heavy lifting of the LoadYaml function +// loadAndParseYaml reads the config from the filesystem and +// execute the environment variable substitution func loadAndParseYaml(configFileName string) ([]byte, error) { if configFileName == "" { return nil, errors.New("no configuration file provided") @@ -166,12 +168,26 @@ func loadAndParseYaml(configFileName string) ([]byte, error) { return nil, fmt.Errorf("unable to load config file: %w", err) } - // We now parse over the yaml with env substring, and fill in the ENV's - buffer, err := envsubst.Bytes(unparsedBuffer) + modifiedBuffer, err := normalizeSubstitution(unparsedBuffer) + if err != nil { + return nil, fmt.Errorf("error normalizing substitution string : %w", err) + } + + buffer, err := envsubst.Bytes(modifiedBuffer) if err != nil { return nil, fmt.Errorf("error in substituting env variables : %w", err) } return buffer, nil +} + +// normalizeSubstitution normalizes dollar signs ($) with numerals like +// $1 or $2 properly by correctly escaping them +func normalizeSubstitution(unparsedBuffer []byte) ([]byte, error) { + unparsedString := string(unparsedBuffer) + + regexPattern := regexp.MustCompile(`\$(\d+)`) + substitutedString := regexPattern.ReplaceAllString(unparsedString, `$$$$1`) + return []byte(substitutedString), nil } diff --git a/pkg/apis/options/load_test.go b/pkg/apis/options/load_test.go index fefbc2e795..06123c37f0 100644 --- a/pkg/apis/options/load_test.go +++ b/pkg/apis/options/load_test.go @@ -487,6 +487,31 @@ sub: StringOption: "Bob", }, }), + Entry("with a config file containing $ signs for things other than environment variables", loadYAMLTableInput{ + configFile: []byte(` +stringOption: /$1 +stringSliceOption: +- /$1 +- ^/(.*)$ +- api/$1 +- api/(.*)$ +- ^/api/(.*)$ +- /api/$1`), + input: &TestOptions{}, + expectedOutput: &TestOptions{ + StringOption: "/$1", + TestOptionSubStruct: TestOptionSubStruct{ + StringSliceOption: []string{ + "/$1", + "^/(.*)$", + "api/$1", + "api/(.*)$", + "^/api/(.*)$", + "/api/$1", + }, + }, + }, + }), ) }) From dc8b1623a26a2537a8d0119e087f2048234c9843 Mon Sep 17 00:00:00 2001 From: Sandy Chen Date: Wed, 23 Jul 2025 01:59:55 +0900 Subject: [PATCH 023/125] feat(cookie): add feature support for cookie-secret-file (#3104) * feat: add feature support for cookie-secret-file --------- Signed-off-by: Jan Larwig Co-Authored-By: Sandy Chen Co-authored-by: Jan Larwig --- CHANGELOG.md | 3 +- docs/docs/configuration/overview.md | 1 + pkg/apis/options/cookie.go | 46 +++++++++++++----- pkg/apis/options/cookie_test.go | 70 ++++++++++++++++++++++++++++ pkg/cookies/csrf.go | 32 +++++++++---- pkg/sessions/cookie/session_store.go | 26 +++++++---- pkg/sessions/persistence/ticket.go | 6 ++- pkg/validation/cookie.go | 27 +++++++++-- pkg/validation/cookie_test.go | 49 ++++++++++++++++++- pkg/validation/options_test.go | 2 +- 10 files changed, 226 insertions(+), 36 deletions(-) create mode 100644 pkg/apis/options/cookie_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 50dbc9b915..ea7b0b094b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,8 @@ - [#2605](https://github.com/oauth2-proxy/oauth2-proxy/pull/2605) fix: show login page on broken cookie (@Primexz) - [#2743](https://github.com/oauth2-proxy/oauth2-proxy/pull/2743) feat: allow use more possible google admin-sdk api scopes (@BobDu) - [#2359](https://github.com/oauth2-proxy/oauth2-proxy/pull/2359) feat: add SourceHut (sr.ht) provider(@bitfehler) --[#2524](https://github.com/oauth2-proxy/oauth2-proxy/pull/2524) fix: regex substitution for $ signs in upstream path handling before running envsubst (@dashkan / @tuunit) +- [#2524](https://github.com/oauth2-proxy/oauth2-proxy/pull/2524) fix: regex substitution for $ signs in upstream path handling before running envsubst (@dashkan / @tuunit) +- [#3104](https://github.com/oauth2-proxy/oauth2-proxy/pull/3104) feat(cookie): add feature support for cookie-secret-file (@sandy2008) # V7.10.0 diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index 6a8f52e536..7c216dfb1f 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -128,6 +128,7 @@ Provider specific options can be found on their respective subpages. | flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | | flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | | flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | +| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | For defining a separate cookie secret file to read the encryption key from | | | flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | [^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) diff --git a/pkg/apis/options/cookie.go b/pkg/apis/options/cookie.go index 22b74a6c54..3653b7d076 100644 --- a/pkg/apis/options/cookie.go +++ b/pkg/apis/options/cookie.go @@ -1,8 +1,11 @@ package options import ( + "errors" + "os" "time" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" "github.com/spf13/pflag" ) @@ -10,6 +13,7 @@ import ( type Cookie struct { Name string `flag:"cookie-name" cfg:"cookie_name"` Secret string `flag:"cookie-secret" cfg:"cookie_secret"` + SecretFile string `flag:"cookie-secret-file" cfg:"cookie_secret_file"` Domains []string `flag:"cookie-domain" cfg:"cookie_domains"` Path string `flag:"cookie-path" cfg:"cookie_path"` Expire time.Duration `flag:"cookie-expire" cfg:"cookie_expire"` @@ -18,8 +22,8 @@ type Cookie struct { HTTPOnly bool `flag:"cookie-httponly" cfg:"cookie_httponly"` SameSite string `flag:"cookie-samesite" cfg:"cookie_samesite"` CSRFPerRequest bool `flag:"cookie-csrf-per-request" cfg:"cookie_csrf_per_request"` - CSRFExpire time.Duration `flag:"cookie-csrf-expire" cfg:"cookie_csrf_expire"` CSRFPerRequestLimit int `flag:"cookie-csrf-per-request-limit" cfg:"cookie_csrf_per_request_limit"` + CSRFExpire time.Duration `flag:"cookie-csrf-expire" cfg:"cookie_csrf_expire"` } func cookieFlagSet() *pflag.FlagSet { @@ -27,6 +31,7 @@ func cookieFlagSet() *pflag.FlagSet { flagSet.String("cookie-name", "_oauth2_proxy", "the name of the cookie that the oauth_proxy creates") flagSet.String("cookie-secret", "", "the seed string for secure cookies (optionally base64 encoded)") + flagSet.String("cookie-secret-file", "", "For defining a separate cookie secret file to read the encryption key from") flagSet.StringSlice("cookie-domain", []string{}, "Optional cookie domains to force cookies to (ie: `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match).") flagSet.String("cookie-path", "/", "an optional cookie path to force cookies to (ie: /poc/)*") flagSet.Duration("cookie-expire", time.Duration(168)*time.Hour, "expire timeframe for cookie") @@ -43,16 +48,33 @@ func cookieFlagSet() *pflag.FlagSet { // cookieDefaults creates a Cookie populating each field with its default value func cookieDefaults() Cookie { return Cookie{ - Name: "_oauth2_proxy", - Secret: "", - Domains: nil, - Path: "/", - Expire: time.Duration(168) * time.Hour, - Refresh: time.Duration(0), - Secure: true, - HTTPOnly: true, - SameSite: "", - CSRFPerRequest: false, - CSRFExpire: time.Duration(15) * time.Minute, + Name: "_oauth2_proxy", + Secret: "", + SecretFile: "", + Domains: nil, + Path: "/", + Expire: time.Duration(168) * time.Hour, + Refresh: time.Duration(0), + Secure: true, + HTTPOnly: true, + SameSite: "", + CSRFPerRequest: false, + CSRFPerRequestLimit: 0, + CSRFExpire: time.Duration(15) * time.Minute, + } +} + +// GetSecret returns the cookie secret, reading from file if SecretFile is set +func (c *Cookie) GetSecret() (secret string, err error) { + if c.Secret != "" || c.SecretFile == "" { + return c.Secret, nil + } + + fileSecret, err := os.ReadFile(c.SecretFile) + if err != nil { + logger.Errorf("error reading cookie secret file %s: %s", c.SecretFile, err) + return "", errors.New("could not read cookie secret file") } + + return string(fileSecret), nil } diff --git a/pkg/apis/options/cookie_test.go b/pkg/apis/options/cookie_test.go new file mode 100644 index 0000000000..a1486fede0 --- /dev/null +++ b/pkg/apis/options/cookie_test.go @@ -0,0 +1,70 @@ +package options + +import ( + "os" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestCookieGetSecret(t *testing.T) { + t.Run("returns secret when Secret is set", func(t *testing.T) { + c := &Cookie{ + Secret: "my-secret", + SecretFile: "", + } + secret, err := c.GetSecret() + assert.NoError(t, err) + assert.Equal(t, "my-secret", secret) + }) + + t.Run("returns secret when both Secret and SecretFile are set", func(t *testing.T) { + c := &Cookie{ + Secret: "my-secret", + SecretFile: "/some/file", + } + secret, err := c.GetSecret() + assert.NoError(t, err) + assert.Equal(t, "my-secret", secret) + }) + + t.Run("reads from file when only SecretFile is set", func(t *testing.T) { + // Create a temporary file + tmpfile, err := os.CreateTemp("", "cookie-secret-test") + assert.NoError(t, err) + defer os.Remove(tmpfile.Name()) + + _, err = tmpfile.Write([]byte("file-secret")) + assert.NoError(t, err) + tmpfile.Close() + + c := &Cookie{ + Secret: "", + SecretFile: tmpfile.Name(), + } + secret, err := c.GetSecret() + assert.NoError(t, err) + assert.Equal(t, "file-secret", secret) + }) + + t.Run("returns error when file does not exist", func(t *testing.T) { + c := &Cookie{ + Secret: "", + SecretFile: "/nonexistent/file", + } + secret, err := c.GetSecret() + assert.Error(t, err) + assert.Equal(t, "", secret) + assert.Contains(t, err.Error(), "could not read cookie secret file") + }) + + t.Run("returns empty when both Secret and SecretFile are empty", func(t *testing.T) { + c := &Cookie{ + Secret: "", + SecretFile: "", + } + secret, err := c.GetSecret() + assert.NoError(t, err) + assert.Equal(t, "", secret) + }) +} diff --git a/pkg/cookies/csrf.go b/pkg/cookies/csrf.go index eab87869e4..3b8efaf306 100644 --- a/pkg/cookies/csrf.go +++ b/pkg/cookies/csrf.go @@ -219,13 +219,22 @@ func (c *csrf) encodeCookie() (string, error) { return "", err } - return encryption.SignedValue(c.cookieOpts.Secret, c.cookieName(), encrypted, c.time.Now()) + secret, err := c.cookieOpts.GetSecret() + if err != nil { + return "", fmt.Errorf("error getting cookie secret: %v", err) + } + return encryption.SignedValue(secret, c.cookieName(), encrypted, c.time.Now()) } // decodeCSRFCookie validates the signature then decrypts and decodes a CSRF // cookie into a CSRF struct func decodeCSRFCookie(cookie *http.Cookie, opts *options.Cookie) (*csrf, error) { - val, t, ok := encryption.Validate(cookie, opts.Secret, opts.Expire) + secret, err := opts.GetSecret() + if err != nil { + return nil, fmt.Errorf("error getting cookie secret: %v", err) + } + + val, t, ok := encryption.Validate(cookie, secret, opts.Expire) if !ok { return nil, errors.New("CSRF cookie failed validation") } @@ -235,15 +244,18 @@ func decodeCSRFCookie(cookie *http.Cookie, opts *options.Cookie) (*csrf, error) return nil, err } - // Valid cookie, Unmarshal the CSRF + return unmarshalCSRF(decrypted, opts, t) +} + +// unmarshalCSRF unmarshals decrypted data into a CSRF struct +func unmarshalCSRF(decrypted []byte, opts *options.Cookie, csrfTime time.Time) (*csrf, error) { clock := clock.Clock{} - clock.Set(t) + clock.Set(csrfTime) + csrf := &csrf{cookieOpts: opts, time: clock} - err = msgpack.Unmarshal(decrypted, csrf) - if err != nil { + if err := msgpack.Unmarshal(decrypted, csrf); err != nil { return nil, fmt.Errorf("error unmarshalling data to CSRF: %v", err) } - return csrf, nil } @@ -290,5 +302,9 @@ func decrypt(data []byte, opts *options.Cookie) ([]byte, error) { } func makeCipher(opts *options.Cookie) (encryption.Cipher, error) { - return encryption.NewCFBCipher(encryption.SecretBytes(opts.Secret)) + secret, err := opts.GetSecret() + if err != nil { + return nil, fmt.Errorf("error getting cookie secret: %v", err) + } + return encryption.NewCFBCipher(encryption.SecretBytes(secret)) } diff --git a/pkg/sessions/cookie/session_store.go b/pkg/sessions/cookie/session_store.go index 3947177f1f..095bc0e779 100644 --- a/pkg/sessions/cookie/session_store.go +++ b/pkg/sessions/cookie/session_store.go @@ -54,16 +54,18 @@ func (s *SessionStore) Load(req *http.Request) (*sessions.SessionState, error) { // always http.ErrNoCookie return nil, err } - val, _, ok := encryption.Validate(c, s.Cookie.Secret, s.Cookie.Expire) + + secret, err := s.Cookie.GetSecret() + if err != nil { + return nil, fmt.Errorf("error getting cookie secret: %v", err) + } + + val, _, ok := encryption.Validate(c, secret, s.Cookie.Expire) if !ok { return nil, errors.New("cookie signature not valid") } - session, err := sessions.DecodeSessionState(val, s.CookieCipher, true) - if err != nil { - return nil, err - } - return session, nil + return sessions.DecodeSessionState(val, s.CookieCipher, true) } // Clear clears any saved session information by writing a cookie to @@ -121,7 +123,11 @@ func (s *SessionStore) makeSessionCookie(req *http.Request, value []byte, now ti strValue := string(value) if strValue != "" { var err error - strValue, err = encryption.SignedValue(s.Cookie.Secret, s.Cookie.Name, value, now) + secret, err := s.Cookie.GetSecret() + if err != nil { + return nil, fmt.Errorf("error getting cookie secret: %v", err) + } + strValue, err = encryption.SignedValue(secret, s.Cookie.Name, value, now) if err != nil { return nil, err } @@ -146,7 +152,11 @@ func (s *SessionStore) makeCookie(req *http.Request, name string, value string, // NewCookieSessionStore initialises a new instance of the SessionStore from // the configuration given func NewCookieSessionStore(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessions.SessionStore, error) { - cipher, err := encryption.NewCFBCipher(encryption.SecretBytes(cookieOpts.Secret)) + secret, err := cookieOpts.GetSecret() + if err != nil { + return nil, fmt.Errorf("error getting cookie secret: %v", err) + } + cipher, err := encryption.NewCFBCipher(encryption.SecretBytes(secret)) if err != nil { return nil, fmt.Errorf("error initialising cipher: %v", err) } diff --git a/pkg/sessions/persistence/ticket.go b/pkg/sessions/persistence/ticket.go index 581a7f456f..7855db4556 100644 --- a/pkg/sessions/persistence/ticket.go +++ b/pkg/sessions/persistence/ticket.go @@ -146,7 +146,11 @@ func decodeTicketFromRequest(req *http.Request, cookieOpts *options.Cookie) (*ti } // An existing cookie exists, try to retrieve the ticket - val, _, ok := encryption.Validate(requestCookie, cookieOpts.Secret, cookieOpts.Expire) + secret, err := cookieOpts.GetSecret() + if err != nil { + return nil, fmt.Errorf("error getting cookie secret: %v", err) + } + val, _, ok := encryption.Validate(requestCookie, secret, cookieOpts.Expire) if !ok { return nil, fmt.Errorf("session ticket cookie failed validation: %v", err) } diff --git a/pkg/validation/cookie.go b/pkg/validation/cookie.go index b515809d18..5f2dd8ac9d 100644 --- a/pkg/validation/cookie.go +++ b/pkg/validation/cookie.go @@ -3,6 +3,7 @@ package validation import ( "fmt" "net/http" + "os" "sort" "time" @@ -11,7 +12,7 @@ import ( ) func validateCookie(o options.Cookie) []string { - msgs := validateCookieSecret(o.Secret) + msgs := validateCookieSecret(o.Secret, o.SecretFile) if o.Expire != time.Duration(0) && o.Refresh >= o.Expire { msgs = append(msgs, fmt.Sprintf( @@ -49,9 +50,27 @@ func validateCookieName(name string) []string { return msgs } -func validateCookieSecret(secret string) []string { - if secret == "" { - return []string{"missing setting: cookie-secret"} +func validateCookieSecret(secret string, secretFile string) []string { + if secret == "" && secretFile == "" { + return []string{"missing setting: cookie-secret or cookie-secret-file"} + } + if secret == "" && secretFile != "" { + fileData, err := os.ReadFile(secretFile) + if err != nil { + return []string{"could not read cookie secret file: " + secretFile} + } + // Validate the file content as a secret + secretBytes := encryption.SecretBytes(string(fileData)) + switch len(secretBytes) { + case 16, 24, 32: + // Valid secret size found + return []string{} + } + // Invalid secret size found, return a message + return []string{fmt.Sprintf( + "cookie_secret from file must be 16, 24, or 32 bytes to create an AES cipher, but is %d bytes", + len(secretBytes)), + } } secretBytes := encryption.SecretBytes(secret) diff --git a/pkg/validation/cookie_test.go b/pkg/validation/cookie_test.go index 1f0dc5cdd8..d11134da85 100644 --- a/pkg/validation/cookie_test.go +++ b/pkg/validation/cookie_test.go @@ -1,6 +1,7 @@ package validation import ( + "os" "strings" "testing" "time" @@ -29,9 +30,23 @@ func TestValidateCookie(t *testing.T) { "a.cba.localhost", } + // Create a temporary file for the valid secret file test + tmpfile, err := os.CreateTemp("", "cookie-secret-test") + if err != nil { + t.Fatalf("Failed to create temporary file: %v", err) + } + defer os.Remove(tmpfile.Name()) + + // Write a valid 32-byte secret to the file + _, err = tmpfile.Write([]byte(validSecret)) + if err != nil { + t.Fatalf("Failed to write to temporary file: %v", err) + } + tmpfile.Close() + invalidNameMsg := "invalid cookie name: \"_oauth2;proxy\"" longNameMsg := "cookie name should be under 256 characters: cookie name is 260 characters" - missingSecretMsg := "missing setting: cookie-secret" + missingSecretMsg := "missing setting: cookie-secret or cookie-secret-file" invalidSecretMsg := "cookie_secret must be 16, 24, or 32 bytes to create an AES cipher, but is 6 bytes" invalidBase64SecretMsg := "cookie_secret must be 16, 24, or 32 bytes to create an AES cipher, but is 10 bytes" refreshLongerThanExpireMsg := "cookie_refresh (\"1h0m0s\") must be less than cookie_expire (\"15m0s\")" @@ -271,6 +286,38 @@ func TestValidateCookie(t *testing.T) { }, errStrings: []string{}, }, + { + name: "with valid secret file", + cookie: options.Cookie{ + Name: validName, + Secret: "", + SecretFile: tmpfile.Name(), + Domains: domains, + Path: "", + Expire: 24 * time.Hour, + Refresh: 0, + Secure: true, + HTTPOnly: true, + SameSite: "", + }, + errStrings: []string{}, + }, + { + name: "with nonexistent secret file", + cookie: options.Cookie{ + Name: validName, + Secret: "", + SecretFile: "/nonexistent/file.txt", + Domains: domains, + Path: "", + Expire: 24 * time.Hour, + Refresh: 0, + Secure: true, + HTTPOnly: true, + SameSite: "", + }, + errStrings: []string{"could not read cookie secret file: /nonexistent/file.txt"}, + }, } for _, tc := range testCases { diff --git a/pkg/validation/options_test.go b/pkg/validation/options_test.go index 2d5e956027..5c242e027b 100644 --- a/pkg/validation/options_test.go +++ b/pkg/validation/options_test.go @@ -48,7 +48,7 @@ func TestNewOptions(t *testing.T) { assert.NotEqual(t, nil, err) expected := errorMsg([]string{ - "missing setting: cookie-secret", + "missing setting: cookie-secret or cookie-secret-file", "provider has empty id: ids are required for all providers", "provider missing setting: client-id", "missing setting: client-secret or client-secret-file"}) From b905f2cd934315100dadc5c64203533fa4c9aa70 Mon Sep 17 00:00:00 2001 From: Michael Cornel Date: Wed, 23 Jul 2025 22:40:12 +0200 Subject: [PATCH 024/125] feat: use non-default authorization request response mode in OIDC providers (#3055) * fix: OIDC sets response mode * Update CHANGELOG --- CHANGELOG.md | 1 + providers/oidc.go | 5 +++++ providers/oidc_test.go | 29 +++++++++++++++++++++++++++++ 3 files changed, 35 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea7b0b094b..78718cc3cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ - [#2359](https://github.com/oauth2-proxy/oauth2-proxy/pull/2359) feat: add SourceHut (sr.ht) provider(@bitfehler) - [#2524](https://github.com/oauth2-proxy/oauth2-proxy/pull/2524) fix: regex substitution for $ signs in upstream path handling before running envsubst (@dashkan / @tuunit) - [#3104](https://github.com/oauth2-proxy/oauth2-proxy/pull/3104) feat(cookie): add feature support for cookie-secret-file (@sandy2008) +- [#3055](https://github.com/oauth2-proxy/oauth2-proxy/pull/3055) feat: support non-default authorization request response mode also for OIDC providers (@stieler-it) # V7.10.0 diff --git a/providers/oidc.go b/providers/oidc.go index 43b5227e9a..15598aba58 100644 --- a/providers/oidc.go +++ b/providers/oidc.go @@ -61,6 +61,11 @@ func (p *OIDCProvider) GetLoginURL(redirectURI, state, nonce string, extraParams if !p.SkipNonce { extraParams.Add("nonce", nonce) } + // Response mode should only be set if a non default mode is requested + if p.AuthRequestResponseMode != "" { + extraParams.Add("response_mode", p.AuthRequestResponseMode) + } + loginURL := makeLoginURL(p.Data(), redirectURI, state, extraParams) return loginURL.String() } diff --git a/providers/oidc_test.go b/providers/oidc_test.go index 6a49f8ff8f..81a70eb410 100644 --- a/providers/oidc_test.go +++ b/providers/oidc_test.go @@ -275,3 +275,32 @@ func TestOIDCProviderCreateSessionFromToken(t *testing.T) { }) } } + +func TestOIDCProviderResponseModeConfigured(t *testing.T) { + providerData := &ProviderData{ + LoginURL: &url.URL{ + Scheme: "http", + Host: "my.test.idp", + Path: "/oauth/authorize", + }, + AuthRequestResponseMode: "form_post", + } + p := NewOIDCProvider(providerData, options.OIDCOptions{}) + + result := p.GetLoginURL("https://my.test.app/oauth", "", "", url.Values{}) + assert.Contains(t, result, "response_mode=form_post") +} + +func TestOIDCProviderResponseModeNotConfigured(t *testing.T) { + providerData := &ProviderData{ + LoginURL: &url.URL{ + Scheme: "http", + Host: "my.test.idp", + Path: "/oauth/authorize", + }, + } + p := NewOIDCProvider(providerData, options.OIDCOptions{}) + + result := p.GetLoginURL("https://my.test.app/oauth", "", "", url.Values{}) + assert.NotContains(t, result, "response_mode") +} From e75a258299ec3db633450dd48a6df54b38988916 Mon Sep 17 00:00:00 2001 From: Sourav Agrawal <146818014+sourava01@users.noreply.github.com> Date: Thu, 24 Jul 2025 11:25:54 +0530 Subject: [PATCH 025/125] feat: make google-groups argument optional (#3138) add test cases update documentation refactor code and some cleanup update changelog Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + docs/docs/configuration/providers/google.md | 2 +- pkg/validation/options_test.go | 26 +++++- pkg/validation/providers.go | 6 +- providers/google.go | 89 +++++++++++++++++---- providers/google_test.go | 36 +++++++++ 6 files changed, 135 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78718cc3cc..0c11712951 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ - [#2524](https://github.com/oauth2-proxy/oauth2-proxy/pull/2524) fix: regex substitution for $ signs in upstream path handling before running envsubst (@dashkan / @tuunit) - [#3104](https://github.com/oauth2-proxy/oauth2-proxy/pull/3104) feat(cookie): add feature support for cookie-secret-file (@sandy2008) - [#3055](https://github.com/oauth2-proxy/oauth2-proxy/pull/3055) feat: support non-default authorization request response mode also for OIDC providers (@stieler-it) +- [#3138](https://github.com/oauth2-proxy/oauth2-proxy/pull/3138) feat: make google_groups argument optional when using google provider (@sourava01) # V7.10.0 diff --git a/docs/docs/configuration/providers/google.md b/docs/docs/configuration/providers/google.md index 26af87ab5c..ac2a7dfaaf 100644 --- a/docs/docs/configuration/providers/google.md +++ b/docs/docs/configuration/providers/google.md @@ -8,7 +8,7 @@ title: Google (default) | Flag | Toml Field | Type | Description | Default | | ---------------------------------------------- | -------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------ | -------------------------------------------------- | | `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | -| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). | | +| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). If not specified and service account or default credentials are configured, all user groups will be allowed. | | | `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | | `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | | `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | diff --git a/pkg/validation/options_test.go b/pkg/validation/options_test.go index 5c242e027b..5c28354593 100644 --- a/pkg/validation/options_test.go +++ b/pkg/validation/options_test.go @@ -55,18 +55,38 @@ func TestNewOptions(t *testing.T) { assert.Equal(t, expected, err.Error()) } -func TestGoogleGroupOptions(t *testing.T) { +func TestGoogleGroupOptionsWithoutServiceAccountJSON(t *testing.T) { o := testOptions() - o.Providers[0].GoogleConfig.Groups = []string{"googlegroup"} + o.Providers[0].GoogleConfig.AdminEmail = "admin@example.com" err := Validate(o) assert.NotEqual(t, nil, err) expected := errorMsg([]string{ - "missing setting: google-admin-email", "missing setting: google-service-account-json or google-use-application-default-credentials"}) assert.Equal(t, expected, err.Error()) } +func TestGoogleGroupOptionsWithoutAdminEmail(t *testing.T) { + o := testOptions() + o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = true + err := Validate(o) + assert.NotEqual(t, nil, err) + + expected := errorMsg([]string{ + "missing setting: google-admin-email"}) + assert.Equal(t, expected, err.Error()) +} + +func TestGoogleGroupOptionsWithoutGroups(t *testing.T) { + o := testOptions() + // Set admin email and application default credentials but no groups - should still require them + o.Providers[0].GoogleConfig.AdminEmail = "admin@example.com" + o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = true + err := Validate(o) + // Should pass validation since google-group is now optional + assert.Equal(t, nil, err) +} + func TestGoogleGroupInvalidFile(t *testing.T) { o := testOptions() o.Providers[0].GoogleConfig.Groups = []string{"test_group"} diff --git a/pkg/validation/providers.go b/pkg/validation/providers.go index b1106b3502..4527b84160 100644 --- a/pkg/validation/providers.go +++ b/pkg/validation/providers.go @@ -94,18 +94,14 @@ func validateClientSecret(provider options.Provider) []string { func validateGoogleConfig(provider options.Provider) []string { msgs := []string{} - hasGoogleGroups := len(provider.GoogleConfig.Groups) >= 1 hasAdminEmail := provider.GoogleConfig.AdminEmail != "" hasSAJSON := provider.GoogleConfig.ServiceAccountJSON != "" useADC := provider.GoogleConfig.UseApplicationDefaultCredentials - if !hasGoogleGroups && !hasAdminEmail && !hasSAJSON && !useADC { + if !hasAdminEmail && !hasSAJSON && !useADC { return msgs } - if !hasGoogleGroups { - msgs = append(msgs, "missing setting: google-group") - } if !hasAdminEmail { msgs = append(msgs, "missing setting: google-admin-email") } diff --git a/providers/google.go b/providers/google.go index 0e1e215661..097e35670d 100644 --- a/providers/google.go +++ b/providers/google.go @@ -103,17 +103,24 @@ func NewGoogleProvider(p *ProviderData, opts options.GoogleOptions) (*GoogleProv } if opts.ServiceAccountJSON != "" || opts.UseApplicationDefaultCredentials { - // Backwards compatibility with `--google-group` option - if len(opts.Groups) > 0 { - provider.setAllowedGroups(opts.Groups) - } - - provider.setGroupRestriction(opts) + provider.configureGroups(opts) } return provider, nil } +func (p *GoogleProvider) configureGroups(opts options.GoogleOptions) { + adminService := getAdminService(opts) + // Backwards compatibility with `--google-group` option + if len(opts.Groups) > 0 { + p.setAllowedGroups(opts.Groups) + p.groupValidator = p.setGroupRestriction(opts.Groups, adminService) + return + } + + p.groupValidator = p.populateAllGroups(adminService) +} + func claimsFromIDToken(idToken string) (*claims, error) { // id_token is a base64 encode ID token payload @@ -209,18 +216,13 @@ func (p *GoogleProvider) EnrichSession(_ context.Context, s *sessions.SessionSta } // SetGroupRestriction configures the GoogleProvider to restrict access to the -// specified group(s). AdminEmail has to be an administrative email on the domain that is -// checked. CredentialsFile is the path to a json file containing a Google service -// account credentials. -// -// TODO (@NickMeves) - Unit Test this OR refactor away from groupValidator func -func (p *GoogleProvider) setGroupRestriction(opts options.GoogleOptions) { - adminService := getAdminService(opts) - p.groupValidator = func(s *sessions.SessionState) bool { +// specified group(s). +func (p *GoogleProvider) setGroupRestriction(groups []string, adminService *admin.Service) func(*sessions.SessionState) bool { + return func(s *sessions.SessionState) bool { // Reset our saved Groups in case membership changed // This is used by `Authorize` on every request - s.Groups = make([]string, 0, len(opts.Groups)) - for _, group := range opts.Groups { + s.Groups = make([]string, 0, len(groups)) + for _, group := range groups { if userInGroup(adminService, group, s.Email) { s.Groups = append(s.Groups, group) } @@ -229,6 +231,25 @@ func (p *GoogleProvider) setGroupRestriction(opts options.GoogleOptions) { } } +// populateAllGroups configures the GoogleProvider to allow access with all +// groups and populate session with all groups of the user when no specific +// groups are configured. +func (p *GoogleProvider) populateAllGroups(adminService *admin.Service) func(s *sessions.SessionState) bool { + return func(s *sessions.SessionState) bool { + // Get all groups of the user + groups, err := getUserGroups(adminService, s.Email) + if err != nil { + logger.Errorf("Failed to get user groups for %s: %v", s.Email, err) + s.Groups = []string{} + return true // Allow access even if we can't get groups + } + + // Populate session with all user groups + s.Groups = groups + return true // Always allow access when no specific groups are configured + } +} + // https://developers.google.com/admin-sdk/directory/reference/rest/v1/members/hasMember#authorization-scopes var possibleScopesList = [...]string{ admin.AdminDirectoryGroupMemberReadonlyScope, @@ -269,6 +290,10 @@ func getOauth2TokenSource(ctx context.Context, opts options.GoogleOptions, scope return conf.TokenSource(ctx) } +// getAdminService retrieves an oauth token for the admin api of Google +// AdminEmail has to be an administrative email on the domain that is +// checked. CredentialsFile is the path to a json file containing a Google service +// account credentials. func getAdminService(opts options.GoogleOptions) *admin.Service { ctx := context.Background() var client *http.Client @@ -339,6 +364,38 @@ func getTargetPrincipal(ctx context.Context, opts options.GoogleOptions) (target return targetPrincipal } +// getUserGroups retrieves all groups that a user is a member of using the Google Admin Directory API +func getUserGroups(service *admin.Service, email string) ([]string, error) { + var allGroups []string + var pageToken string + + for { + req := service.Groups.List().UserKey(email).MaxResults(200) + if pageToken != "" { + req = req.PageToken(pageToken) + } + + groupsResp, err := req.Do() + if err != nil { + return nil, fmt.Errorf("failed to list groups for user %s: %v", email, err) + } + + for _, group := range groupsResp.Groups { + if group.Email != "" { + allGroups = append(allGroups, group.Email) + } + } + + // Check if there are more pages + if groupsResp.NextPageToken == "" { + break + } + pageToken = groupsResp.NextPageToken + } + + return allGroups, nil +} + func userInGroup(service *admin.Service, group string, email string) bool { // Use the HasMember API to checking for the user's presence in each group or nested subgroups req := service.Members.HasMember(group, email) diff --git a/providers/google_test.go b/providers/google_test.go index 23bca7ea91..dc061203fc 100644 --- a/providers/google_test.go +++ b/providers/google_test.go @@ -289,3 +289,39 @@ func TestGoogleProvider_userInGroup(t *testing.T) { result = userInGroup(service, "group@example.com", "non-member-out-of-domain@otherexample.com") assert.False(t, result) } + +func TestGoogleProvider_getUserGroups(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/admin/directory/v1/groups" && r.URL.Query().Get("userKey") == "test@example.com" { + response := `{ + "kind": "admin#directory#groups", + "groups": [ + { + "kind": "admin#directory#group", + "id": "1", + "email": "group1@example.com", + "name": "Group 1" + }, + { + "kind": "admin#directory#group", + "id": "2", + "email": "group2@example.com", + "name": "Group 2" + } + ] + }` + fmt.Fprintln(w, response) + } else { + http.NotFound(w, r) + } + })) + defer ts.Close() + + client := &http.Client{} + adminService, err := admin.NewService(context.Background(), option.WithHTTPClient(client), option.WithEndpoint(ts.URL)) + assert.NoError(t, err) + + groups, err := getUserGroups(adminService, "test@example.com") + assert.NoError(t, err) + assert.Equal(t, []string{"group1@example.com", "group2@example.com"}, groups) +} From f4b33b64bd66ad28e9b0d63bea51837b83c00ca1 Mon Sep 17 00:00:00 2001 From: nobletrout Date: Thu, 24 Jul 2025 02:33:06 -0400 Subject: [PATCH 026/125] feat: differentiate between "no available key" and error for redis sessions (#3093) * add some better error handling * add changelog entry Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 2 ++ pkg/sessions/redis/redis_store.go | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c11712951..ed30ea57c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,8 @@ - [#3104](https://github.com/oauth2-proxy/oauth2-proxy/pull/3104) feat(cookie): add feature support for cookie-secret-file (@sandy2008) - [#3055](https://github.com/oauth2-proxy/oauth2-proxy/pull/3055) feat: support non-default authorization request response mode also for OIDC providers (@stieler-it) - [#3138](https://github.com/oauth2-proxy/oauth2-proxy/pull/3138) feat: make google_groups argument optional when using google provider (@sourava01) +- [#3093](https://github.com/oauth2-proxy/oauth2-proxy/pull/3093) feat: differentiate between "no available key" and error for redis sessions (@nobletrout) + # V7.10.0 diff --git a/pkg/sessions/redis/redis_store.go b/pkg/sessions/redis/redis_store.go index 18d79b803e..4e846e9bd9 100644 --- a/pkg/sessions/redis/redis_store.go +++ b/pkg/sessions/redis/redis_store.go @@ -49,9 +49,12 @@ func (store *SessionStore) Save(ctx context.Context, key string, value []byte, e // cookie within the HTTP request object func (store *SessionStore) Load(ctx context.Context, key string) ([]byte, error) { value, err := store.Client.Get(ctx, key) - if err != nil { + if err == redis.Nil { + return nil, fmt.Errorf("session does not exist") + } else if err != nil { return nil, fmt.Errorf("error loading redis session: %v", err) } + return value, nil } From 9ffafad4b2d2f9f7668e5504565f356a7c047b77 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Wed, 30 Jul 2025 19:46:58 +0200 Subject: [PATCH 027/125] Merge commit from fork Signed-off-by: Jan Larwig --- CHANGELOG.md | 15 +++++++++ oauthproxy.go | 2 +- pkg/requests/util/util.go | 21 ++++++++++++ pkg/requests/util/util_test.go | 61 ++++++++++++++++++++++++++-------- 4 files changed, 85 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed30ea57c6..2b751d9f11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,22 @@ ## Important Notes +Fixed critical vulnerability where `skip_auth_routes` regex patterns matched against the full request URI (path + query parameters) instead of just the path, allowing authentication bypass attacks. + ## Breaking Changes +If your configuration relies on matching query parameters in `skip_auth_routes` patterns, you must update your regex patterns to match paths only. Review all `skip_auth_routes` entries for potential impact. + +**Example of affected configuration:** +```yaml +# This pattern previously matched both: +# - /api/foo/status (intended) +# - /api/private/sensitive?path=/status (bypass - now fixed) +skip_auth_routes: ["^/api/.*/status"] +``` + +For detailed information, migration guidance, and security implications, see the [security advisory](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-7rh7-c77v-6434). + ## Changes since v7.10.0 - [#2615](https://github.com/oauth2-proxy/oauth2-proxy/pull/2615) feat(cookies): add option to set a limit on the number of per-request CSRF cookies oauth2-proxy sets (@bh-tt) @@ -17,6 +31,7 @@ - [#3055](https://github.com/oauth2-proxy/oauth2-proxy/pull/3055) feat: support non-default authorization request response mode also for OIDC providers (@stieler-it) - [#3138](https://github.com/oauth2-proxy/oauth2-proxy/pull/3138) feat: make google_groups argument optional when using google provider (@sourava01) - [#3093](https://github.com/oauth2-proxy/oauth2-proxy/pull/3093) feat: differentiate between "no available key" and error for redis sessions (@nobletrout) +- [GHSA-7rh7-c77v-6434](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-7rh7-c77v-6434) fix: skip_auth_routes bypass through query parameter inclusion # V7.10.0 diff --git a/oauthproxy.go b/oauthproxy.go index d8984cde7c..7526d6417a 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -580,7 +580,7 @@ func isAllowedMethod(req *http.Request, route allowedRoute) bool { } func isAllowedPath(req *http.Request, route allowedRoute) bool { - matches := route.pathRegex.MatchString(requestutil.GetRequestURI(req)) + matches := route.pathRegex.MatchString(requestutil.GetRequestPath(req)) if route.negate { return !matches diff --git a/pkg/requests/util/util.go b/pkg/requests/util/util.go index 44e1ab0e91..290f805937 100644 --- a/pkg/requests/util/util.go +++ b/pkg/requests/util/util.go @@ -2,6 +2,8 @@ package util import ( "net/http" + "net/url" + "strings" middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" ) @@ -43,6 +45,25 @@ func GetRequestURI(req *http.Request) string { return uri } +// GetRequestPath returns the request URI or X-Forwarded-Uri if present and the +// request is proxied but always strips the query parameters and only returns +// the pure path +func GetRequestPath(req *http.Request) string { + uri := GetRequestURI(req) + + // Parse URI and return only the path component + if parsedURL, err := url.Parse(uri); err == nil { + return parsedURL.Path + } + + // Fallback: strip query parameters manually + if idx := strings.Index(uri, "?"); idx != -1 { + return uri[:idx] + } + + return uri +} + // IsProxied determines if a request was from a proxy based on the RequestScope // ReverseProxy tracker. func IsProxied(req *http.Request) bool { diff --git a/pkg/requests/util/util_test.go b/pkg/requests/util/util_test.go index f1153d87a9..ba72c66dcf 100644 --- a/pkg/requests/util/util_test.go +++ b/pkg/requests/util/util_test.go @@ -13,16 +13,17 @@ import ( var _ = Describe("Util Suite", func() { const ( - proto = "http" - host = "www.oauth2proxy.test" - uri = "/test/endpoint" + proto = "http" + host = "www.oauth2proxy.test" + uriWithQueryParams = "/test/endpoint?query=param" + uriNoQueryParams = "/test/endpoint" ) var req *http.Request BeforeEach(func() { req = httptest.NewRequest( http.MethodGet, - fmt.Sprintf("%s://%s%s", proto, host, uri), + fmt.Sprintf("%s://%s%s", proto, host, uriWithQueryParams), nil, ) }) @@ -101,13 +102,13 @@ var _ = Describe("Util Suite", func() { req = middleware.AddRequestScope(req, &middleware.RequestScope{}) }) - It("returns the URI", func() { - Expect(util.GetRequestURI(req)).To(Equal(uri)) + It("returns the URI (with query params)", func() { + Expect(util.GetRequestURI(req)).To(Equal(uriWithQueryParams)) }) - It("ignores X-Forwarded-Uri and returns the URI", func() { + It("ignores X-Forwarded-Uri and returns the URI (with query params)", func() { req.Header.Add("X-Forwarded-Uri", "/some/other/path") - Expect(util.GetRequestURI(req)).To(Equal(uri)) + Expect(util.GetRequestURI(req)).To(Equal(uriWithQueryParams)) }) }) @@ -118,13 +119,47 @@ var _ = Describe("Util Suite", func() { }) }) - It("returns the URI if X-Forwarded-Uri is not present", func() { - Expect(util.GetRequestURI(req)).To(Equal(uri)) + It("returns the URI if X-Forwarded-Uri is not present (with query params)", func() { + Expect(util.GetRequestURI(req)).To(Equal(uriWithQueryParams)) }) - It("returns the X-Forwarded-Uri when present", func() { - req.Header.Add("X-Forwarded-Uri", "/some/other/path") - Expect(util.GetRequestURI(req)).To(Equal("/some/other/path")) + It("returns the X-Forwarded-Uri when present (with query params)", func() { + req.Header.Add("X-Forwarded-Uri", "/some/other/path?query=param") + Expect(util.GetRequestURI(req)).To(Equal("/some/other/path?query=param")) + }) + }) + }) + + Context("GetRequestPath", func() { + Context("IsProxied is false", func() { + BeforeEach(func() { + req = middleware.AddRequestScope(req, &middleware.RequestScope{}) + }) + + It("returns the URI (without query params)", func() { + Expect(util.GetRequestPath(req)).To(Equal(uriNoQueryParams)) + }) + + It("ignores X-Forwarded-Uri and returns the URI (without query params)", func() { + req.Header.Add("X-Forwarded-Uri", "/some/other/path?query=param") + Expect(util.GetRequestPath(req)).To(Equal(uriNoQueryParams)) + }) + }) + + Context("IsProxied is true", func() { + BeforeEach(func() { + req = middleware.AddRequestScope(req, &middleware.RequestScope{ + ReverseProxy: true, + }) + }) + + It("returns the URI if X-Forwarded-Uri is not present (without query params)", func() { + Expect(util.GetRequestPath(req)).To(Equal(uriNoQueryParams)) + }) + + It("returns the X-Forwarded-Uri when present (without query params)", func() { + req.Header.Add("X-Forwarded-Uri", "/some/other/path?query=param") + Expect(util.GetRequestPath(req)).To(Equal("/some/other/path")) }) }) }) From c0a928ededa40391baeedf8c5f3e104c047bfb6e Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 30 Jul 2025 20:09:33 +0200 Subject: [PATCH 028/125] release v7.11.0 (#3145) * add new docs version 7.11.x * update to release version v7.11.0 * add changelog entry for v7.11.0 Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Jan Larwig --- CHANGELOG.md | 34 +- .../docker-compose-alpha-config.yaml | 2 +- .../docker-compose-gitea.yaml | 2 +- .../docker-compose-keycloak.yaml | 2 +- .../docker-compose-nginx.yaml | 2 +- .../docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/installation.md | 2 +- .../version-7.11.x/behaviour.md | 11 + .../version-7.11.x/community/contribution.md | 89 +++ .../version-7.11.x/community/security.md | 49 ++ .../configuration/alpha_config.md | 564 ++++++++++++++++++ .../configuration/alpha_config.md.tmpl | 139 +++++ .../configuration/integration.md | 318 ++++++++++ .../version-7.11.x/configuration/overview.md | 405 +++++++++++++ .../configuration/providers/adfs.md | 19 + .../configuration/providers/bitbucket.md | 25 + .../configuration/providers/digitalocean.md | 21 + .../configuration/providers/facebook.md | 7 + .../configuration/providers/gitea.md | 24 + .../configuration/providers/github.md | 81 +++ .../configuration/providers/gitlab.md | 49 ++ .../configuration/providers/google.md | 75 +++ .../configuration/providers/index.md | 43 ++ .../configuration/providers/keycloak.md | 36 ++ .../configuration/providers/keycloak_oidc.md | 151 +++++ .../configuration/providers/linkedin.md | 13 + .../configuration/providers/login_gov.md | 79 +++ .../configuration/providers/ms_azure_ad.md | 59 ++ .../configuration/providers/ms_entra_id.md | 197 ++++++ .../configuration/providers/nextcloud.md | 28 + .../configuration/providers/openid_connect.md | 146 +++++ .../configuration/providers/sourcehut.md | 25 + .../version-7.11.x/configuration/sessions.md | 99 +++ .../configuration/systemd_socket.md | 43 ++ .../version-7.11.x/configuration/tls.md | 85 +++ .../version-7.11.x/features/endpoints.md | 47 ++ .../version-7.11.x/installation.md | 32 + docs/versioned_docs/version-7.11.x/welcome.md | 23 + .../version-7.11.x-sidebars.json | 83 +++ docs/versions.json | 1 + 41 files changed, 3106 insertions(+), 8 deletions(-) create mode 100644 docs/versioned_docs/version-7.11.x/behaviour.md create mode 100644 docs/versioned_docs/version-7.11.x/community/contribution.md create mode 100644 docs/versioned_docs/version-7.11.x/community/security.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/alpha_config.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/alpha_config.md.tmpl create mode 100644 docs/versioned_docs/version-7.11.x/configuration/integration.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/overview.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/adfs.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/bitbucket.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/digitalocean.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/facebook.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/gitea.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/github.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/gitlab.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/google.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/index.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/keycloak.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/keycloak_oidc.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/linkedin.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/login_gov.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/ms_azure_ad.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/ms_entra_id.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/nextcloud.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/openid_connect.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/providers/sourcehut.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/sessions.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/systemd_socket.md create mode 100644 docs/versioned_docs/version-7.11.x/configuration/tls.md create mode 100644 docs/versioned_docs/version-7.11.x/features/endpoints.md create mode 100644 docs/versioned_docs/version-7.11.x/installation.md create mode 100644 docs/versioned_docs/version-7.11.x/welcome.md create mode 100644 docs/versioned_sidebars/version-7.11.x-sidebars.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b751d9f11..c830117089 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,39 @@ ## Important Notes -Fixed critical vulnerability where `skip_auth_routes` regex patterns matched against the full request URI (path + query parameters) instead of just the path, allowing authentication bypass attacks. +## Breaking Changes + +## Changes since v7.11.0 + +# V7.11.0 + +## Release Highlights + +- 🏢 Support for SourceHut (sr.ht) provider +- 🔍️ Support for more fine-grained control over the google admin-sdk scopes and optional google groups +- 🐛 Squashed some bugs + + +## Important Notes + +Firstly, fixed critical vulnerability where `skip_auth_routes` regex patterns matched against the full request URI (path + query parameters) instead of just the path, allowing authentication bypass attacks. + +Secondly, fixed double-escaping of `$` in regexes for Alpha Config upstreams path and rewriteTargets: + +```yaml +# Before +upstreams: + - id: web + path: ^/(.*)$$ + rewriteTarget: /$$1 + +# After +upstreams: + - id: web + path: ^/(.*)$ + rewriteTarget: /$1 +``` + ## Breaking Changes diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index 3acc01bf80..55b4649ede 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml volumes: - "./oauth2-proxy-alpha-config.cfg:/oauth2-proxy.cfg" diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index c32360840f..f3f4f900e7 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index 66a2d011ff..1796b65cd9 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 72f9d97a7c..3875eda979 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,7 +22,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index e22c633d22..d9d4897a77 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 3da4a9a63b..3940f4757a 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.10.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/installation.md b/docs/docs/installation.md index 95da82da27..b6fc9d011a 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.10.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.11.0`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.11.x/behaviour.md b/docs/versioned_docs/version-7.11.x/behaviour.md new file mode 100644 index 0000000000..e063d4f966 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/behaviour.md @@ -0,0 +1,11 @@ +--- +id: behaviour +title: Behaviour +--- + +1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). +2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) +3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set +4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) + +Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). diff --git a/docs/versioned_docs/version-7.11.x/community/contribution.md b/docs/versioned_docs/version-7.11.x/community/contribution.md new file mode 100644 index 0000000000..92255eda17 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/community/contribution.md @@ -0,0 +1,89 @@ +--- +id: contribution +title: Contribution Guide +--- + +We track bugs and issues using Github. + +If you find a bug, please open an Issue. When opening an Issue or Pull Request please follow the preconfigured template and take special note of the checkboxes. + +If you want to fix a bug, add a new feature or extend existing functionality, please create a fork, create a feature branch and open a PR back to this repo. +Please mention open bug issue number(s) within your PR if applicable. + +We suggest using [Visual Studio Code](https://code.visualstudio.com/docs/languages/go) with the official [Go for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=golang.go) extension. + + +# Go version + +This project is currently still using go 1.22. You can follow the installation guide for go [here.](https://go.dev/doc/install) And you can find go version 1.22 in the archived section [here.](https://go.dev/dl/) + +# Preparing your fork +Clone your fork, create a feature branch and update the depedencies to get started. +```bash +git clone git@github.com:/oauth2-proxy +cd oauth2-proxy +git branch feature/ +git push --set-upstream origin feature/ +go mod download +``` + + +# Testing / Debugging +For starting oauth2-proxy locally open the debugging tab and create the `launch.json` and select `Go: Launch Package`. + +![Debugging Tab](/img/debug-tab.png) +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch OAuth2-Proxy with Dex", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and dex as an idetity provider + "contrib/local-environment/oauth2-proxy.cfg" + ] + }, + { + "name": "Launch OAuth2-Proxy with Keycloak", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and keycloak as an idetity provider + "contrib/local-environment/oauth2-proxy-keycloak.cfg" + ] + } + ] +} +``` + +Before you can start your local version of oauth2-proxy, you will have to use the provided docker compose files to start a local upstream service and identity provider. We suggest using [httpbin](https://hub.docker.com/r/kennethreitz/httpbin) as your upstream for testing as it allows for request and response introspection of all things HTTP. + +Inside the `contrib/local-environment` directory you can use the `Makefile` for +starting different example setups: + +- Dex as your IdP: `make up` or `make down` +- Dex as your IdP using the alpha-config: `make alpha-config-up` +- Keycloak as your IdP: `make keycloak-up` +- Dex as your IdP & nginx reverse proxy: `make nginx-up` +- and many more... + +Check out the `Makefile` to see what is available. + +The username and password for all setups is usually `admin@example.com` and `password`. + +The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me + +- OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 +- Upstream: http://httpbin.localtest.me:8080 +- Dex: http://dex.localtest.me:5556 + diff --git a/docs/versioned_docs/version-7.11.x/community/security.md b/docs/versioned_docs/version-7.11.x/community/security.md new file mode 100644 index 0000000000..c24b57d9e5 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/community/security.md @@ -0,0 +1,49 @@ +--- +id: security +title: Security +--- + +:::note +OAuth2 Proxy is a community project. +Maintainers do not work on this project full time, and as such, +while we endeavour to respond to disclosures as quickly as possible, +this may take longer than in projects with corporate sponsorship. +::: + +## Security Disclosures + +:::important +If you believe you have found a vulnerability within OAuth2 Proxy or any of its +dependencies, please do NOT open an issue or PR on GitHub, please do NOT post +any details publicly. +::: + +Security disclosures MUST be done in private. +If you have found an issue that you would like to bring to the attention of the +maintenance team for OAuth2 Proxy, please compose an email and send it to the +list of maintainers in our [MAINTAINERS](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS) file. + +Please include as much detail as possible. +Ideally, your disclosure should include: +- A reproducible case that can be used to demonstrate the exploit +- How you discovered this vulnerability +- A potential fix for the issue (if you have thought of one) +- Versions affected (if not present in master) +- Your GitHub ID + +### How will we respond to disclosures? + +We use [GitHub Security Advisories](https://docs.github.com/en/github/managing-security-vulnerabilities/about-github-security-advisories) +to privately discuss fixes for disclosed vulnerabilities. +If you include a GitHub ID with your disclosure we will add you as a collaborator +for the advisory so that you can join the discussion and validate any fixes +we may propose. + +For minor issues and previously disclosed vulnerabilities (typically for +dependencies), we may use regular PRs for fixes and forego the security advisory. + +Once a fix has been agreed upon, we will merge the fix and create a new release. +If we have multiple security issues in flight simultaneously, we may delay +merging fixes until all patches are ready. +We may also backport the fix to previous releases, +but this will be at the discretion of the maintainers. diff --git a/docs/versioned_docs/version-7.11.x/configuration/alpha_config.md b/docs/versioned_docs/version-7.11.x/configuration/alpha_config.md new file mode 100644 index 0000000000..018a29413a --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/alpha_config.md @@ -0,0 +1,564 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference + + + +### ADFSOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `skipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | + +### AlphaOptions + +AlphaOptions contains alpha structured configuration options. +Usage of these options allows users to access alpha features that are not +available as part of the primary configuration structure for OAuth2 Proxy. + +:::warning +The options within this structure are considered alpha. +They may change between releases without notice. +::: + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | +| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | + +### AzureOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | +| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | + +### BitbucketOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repository` | _string_ | Repository sets restrict logins to user with access to this repository | + +### ClaimSource + +(**Appears on:** [HeaderValue](#headervalue)) + +ClaimSource allows loading a header value from a claim within the session + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### Duration +#### (`string` alias) + +(**Appears on:** [Upstream](#upstream)) + +Duration is as string representation of a period of time. +A duration string is a is a possibly signed sequence of decimal numbers, +each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". +Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + +### GitHubOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `org` | _string_ | Org sets restrict logins to members of this organisation | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository | +| `token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | +| `users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | + +### GitLabOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Group sets restrict logins to members of this group | +| `projects` | _[]string_ | Projects restricts logins to members of these projects | + +### GoogleOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Groups sets restrict logins to members of this Google group | +| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | +| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | +| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | +| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | + +### Header + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Header represents an individual header that will be added to a request or +response header. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | +| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | + +### HeaderValue + +(**Appears on:** [Header](#header)) + +HeaderValue represents a single header value and the sources that can +make up the header value + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### KeycloakOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `groups` | _[]string_ | Group enables to restrict login to members of indicated group | +| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | + +### LoginGovOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | +| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | +| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | + +### LoginURLParameter + +(**Appears on:** [Provider](#provider)) + +LoginURLParameter is the configuration for a single query parameter that +can be passed through from the `/oauth2/start` endpoint to the IdP login +URL. The "default" option specifies the default value or values (if any) +that will be passed to the IdP for this parameter, and "allow" is a list +of options for ways in which this parameter can be set or overridden via +the query string to `/oauth2/start`. +If _only_ a default is specified and no "allow" then the parameter is +effectively fixed - the default value will always be used and anything +passed to the start URL will be ignored. If _only_ "allow" is specified +but no default then the parameter will only be passed on to the IdP if +the caller provides it, and no value will be sent otherwise. + +Examples: + +# A parameter whose value is fixed + +``` +name: organization +default: +- myorg +``` + +A parameter that is not passed by default, but may be set to one of a +fixed set of values + +``` +name: prompt +allow: +- value: login +- value: consent +- value: select_account +``` + +A parameter that is passed by default but may be overridden by one of +a fixed set of values + +``` +name: prompt +default: ["login"] +allow: +- value: consent +- value: select_account +``` + +A parameter that may be overridden, but only by values that match a +regular expression. For example to restrict `login_hint` to email +addresses in your organization's domain: + +``` +name: login_hint +allow: +- pattern: '^[^@]*@example\.com$' +# this allows at most one "@" sign, and requires "example.com" domain. +``` + +Note that the YAML rules around exactly which characters are allowed +and/or require escaping in different types of string literals are +convoluted. For regular expressions the single quoted form is simplest +as backslash is not considered to be an escape character. Alternatively +use the "chomped block" format `|-`: + +``` + - pattern: |- + ^[^@]*@example\.com$ + +``` + +The hyphen is important, a `|` block would have a trailing newline +character. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name specifies the name of the query parameter. | +| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | +| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | + +### MicrosoftEntraIDOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | +| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | + +### OIDCOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | +| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | +| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | +| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | +| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | +| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | +| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | +| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | +| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | +| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | +| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | +| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | + +### Provider + +(**Appears on:** [Providers](#providers)) + +Provider holds all configuration for a single provider + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | +| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | +| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | +| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | +| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | +| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | +| `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. | +| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | +| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | +| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | +| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | +| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | +| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | +| `id` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | +| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | +| `name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | +| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | +| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | +| `loginURL` | _string_ | LoginURL is the authentication endpoint | +| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | +| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | +| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint | +| `profileURL` | _string_ | ProfileURL is the profile access endpoint | +| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | +| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | +| `validateURL` | _string_ | ValidateURL is the access token validation endpoint | +| `scope` | _string_ | Scope is the OAuth scope specification | +| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | +| `code_challenge_method` | _string_ | The code challenge method | +| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | + +### ProviderType +#### (`string` alias) + +(**Appears on:** [Provider](#provider)) + +ProviderType is used to enumerate the different provider type options +Valid options are: adfs, azure, bitbucket, digitalocean facebook, github, +gitlab, google, keycloak, keycloak-oidc, linkedin, login.gov, nextcloud +and oidc. + +### Providers + +#### ([[]Provider](#provider) alias) + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +The provider can be selected using the `provider` configuration value, or +set in the [`providers` array using +AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). +However, [**the feature to implement multiple providers is not +complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +### SecretSource + +(**Appears on:** [ClaimSource](#claimsource), [HeaderValue](#headervalue), [TLS](#tls)) + +SecretSource references an individual secret value. +Only one source within the struct should be defined at any time. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | + +### Server + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Server represents the configuration for an HTTP(S) server + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `BindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Leave blank or set to "-" to disable. | +| `SecureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Leave blank or set to "-" to disable. | +| `TLS` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the
secure traffic and further configuration for the TLS server. | + +### TLS + +(**Appears on:** [Server](#server)) + +TLS contains the information for loading a TLS certificate and key +as well as an optional minimal TLS version that is acceptable. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `Key` | _[SecretSource](#secretsource)_ | Key is the TLS key data to use.
Typically this will come from a file. | +| `Cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.
Typically this will come from a file. | +| `MinVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.
E.g. Set to "TLS1.3" to select TLS version 1.3 | +| `CipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.
E.g.:
- TLS_RSA_WITH_RC4_128_SHA
- TLS_RSA_WITH_AES_256_GCM_SHA384
If not specified, the default Go safe cipher list is used.
List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | + +### URLParameterRule + +(**Appears on:** [LoginURLParameter](#loginurlparameter)) + +URLParameterRule represents a rule by which query parameters +passed to the `/oauth2/start` endpoint are checked to determine whether +they are valid overrides for the given parameter passed to the IdP's +login URL. Either Value or Pattern should be supplied, not both. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _string_ | A Value rule matches just this specific value | +| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | + +### Upstream + +(**Appears on:** [UpstreamConfig](#upstreamconfig)) + +Upstream represents the configuration for an upstream server. +Requests will be proxied to this upstream if the path matches the request path. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `id` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | +| `path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | +| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | +| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | +| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | +| `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | +| `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | +| `flushInterval` | _[Duration](#duration)_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | +| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | +| `timeout` | _[Duration](#duration)_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | + +### UpstreamConfig + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +UpstreamConfig is a collection of definitions for upstream servers. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | +| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | diff --git a/docs/versioned_docs/version-7.11.x/configuration/alpha_config.md.tmpl b/docs/versioned_docs/version-7.11.x/configuration/alpha_config.md.tmpl new file mode 100644 index 0000000000..8258201f2a --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/alpha_config.md.tmpl @@ -0,0 +1,139 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference diff --git a/docs/versioned_docs/version-7.11.x/configuration/integration.md b/docs/versioned_docs/version-7.11.x/configuration/integration.md new file mode 100644 index 0000000000..05d39281e5 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/integration.md @@ -0,0 +1,318 @@ +--- +id: integration +title: Integration +--- + +## Configuring for use with the Nginx `auth_request` directive + +**This option requires `--reverse-proxy` option to be set.** + +The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: + +```nginx +server { + listen 443 ssl; + server_name ...; + include ssl/ssl.conf; + + location /oauth2/ { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Auth-Request-Redirect $request_uri; + # or, if you are handling multiple domains: + # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; + } + location = /oauth2/auth { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; + # nginx auth_request includes headers but not body + proxy_set_header Content-Length ""; + proxy_pass_request_body off; + } + + location / { + auth_request /oauth2/auth; + error_page 401 =403 /oauth2/sign_in; + + # pass information via X-User and X-Email headers to backend, + # requires running with --set-xauthrequest flag + auth_request_set $user $upstream_http_x_auth_request_user; + auth_request_set $email $upstream_http_x_auth_request_email; + proxy_set_header X-User $user; + proxy_set_header X-Email $email; + + # if you enabled --pass-access-token, this will pass the token to the backend + auth_request_set $token $upstream_http_x_auth_request_access_token; + proxy_set_header X-Access-Token $token; + + # if you enabled --cookie-refresh, this is needed for it to work with auth_request + auth_request_set $auth_cookie $upstream_http_set_cookie; + add_header Set-Cookie $auth_cookie; + + # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb + # limit and so the OAuth2 Proxy splits these into multiple parts. + # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, + # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. + auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; + + # Extract the Cookie attributes from the first Set-Cookie header and append them + # to the second part ($upstream_cookie_* variables only contain the raw cookie content) + if ($auth_cookie ~* "(; .*)") { + set $auth_cookie_name_0 $auth_cookie; + set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; + } + + # Send both Set-Cookie headers now if there was a second part + if ($auth_cookie_name_upstream_1) { + add_header Set-Cookie $auth_cookie_name_0; + add_header Set-Cookie $auth_cookie_name_1; + } + + proxy_pass http://backend/; + # or "root /path/to/site;" or "fastcgi_pass ..." etc + } +} +``` + +When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`. +Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua. +Note that `nginxinc/kubernetes-ingress` does not include the Lua module. + +```yaml +nginx.ingress.kubernetes.io/auth-response-headers: Authorization +nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri +nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth +nginx.ingress.kubernetes.io/configuration-snippet: | + auth_request_set $name_upstream_1 $upstream_cookie_name_1; + + access_by_lua_block { + if ngx.var.name_upstream_1 ~= "" then + ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)") + end + } +``` +It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). + +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=". + +## Configuring for use with the Traefik (v2) `ForwardAuth` middleware + +**This option requires `--reverse-proxy` option to be set.** + +### ForwardAuth with 401 errors middleware + +The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: + +```yaml +http: + routers: + a-service: + rule: "Host(`a-service.example.com`)" + service: a-service-backend + middlewares: + - oauth-errors + - oauth-auth + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth: + rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + oauth-errors: + errors: + status: + - "401-403" + service: oauth-backend + query: "/oauth2/sign_in?rd={url}" +``` + +### ForwardAuth with static upstreams configuration + +Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint + +**Following options need to be set on `oauth2-proxy`:** +- `--upstream=static://202`: Configures a static response for authenticated sessions +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```yaml +http: + routers: + a-service-route-1: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" + service: a-service-backend + middlewares: + - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + a-service-route-2: + rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" + service: a-service-backend + middlewares: + - oauth-auth-wo-redirect # unauthenticated session will return a 401 + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + services-oauth2-route: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth2-proxy-route: + rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + b-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.3:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth-redirect: + forwardAuth: + address: https://oauth.example.com/ + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization + oauth-auth-wo-redirect: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization +``` + +## Configuring for use with the Caddy (v2) `forward_auth` directive + +The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. + +This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. + +**Following options need to be set on `oauth2-proxy`:** +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```nginx title="Caddyfile" +example.com { + # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. + # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. + handle /oauth2/* { + reverse_proxy oauth2-proxy.internal:4180 { + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. + header_up X-Real-IP {remote_host} + header_up X-Forwarded-Uri {uri} + } + } + + # Requests to other paths are first processed by oauth2-proxy for authentication. + handle { + forward_auth oauth2-proxy.internal:4180 { + uri /oauth2/auth + + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. + header_up X-Real-IP {remote_host} + + # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. + # Make sure to configure the --set-xauthrequest flag to enable this feature. + #copy_headers X-Auth-Request-User X-Auth-Request-Email + + # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. + @error status 401 + handle_response @error { + redir * /oauth2/sign_in?rd={scheme}://{host}{uri} + } + } + + # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. + reverse_proxy upstream.internal:3000 + } +} +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.11.x/configuration/overview.md b/docs/versioned_docs/version-7.11.x/configuration/overview.md new file mode 100644 index 0000000000..7c216dfb1f --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/overview.md @@ -0,0 +1,405 @@ +--- +id: overview +title: Overview +--- + +`oauth2-proxy` can be configured via [command line options](#command-line-options), [environment variables](#environment-variables) or [config file](#config-file) (in decreasing order of precedence, i.e. command line options will overwrite environment variables and environment variables will overwrite configuration file settings). + +## Generating a Cookie Secret + +To generate a strong cookie secret use one of the below commands: + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + + +```shell +python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())' +``` + + + + +```shell +dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64 | tr -d -- '\n' | tr -- '+/' '-_' ; echo +``` + + + + +```shell +openssl rand -base64 32 | tr -- '+/' '-_' +``` + + + + +```powershell +# Add System.Web assembly to session, just in case +Add-Type -AssemblyName System.Web +[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([System.Web.Security.Membership]::GeneratePassword(32,4))).Replace("+","-").Replace("/","_") +``` + + + + +```hcl +# Valid 32 Byte Base64 URL encoding set that will decode to 24 []byte AES-192 secret +resource "random_password" "cookie_secret" { + length = 32 + override_special = "-_" +} +``` + + + + +## Config File + +Every command line argument can be specified in a config file by replacing hyphens (-) with underscores (\_). If the argument can be specified multiple times, the config option should be plural (trailing s). + +An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/oauth2-proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `--config=/etc/oauth2-proxy.cfg` + +## Config Options + +### Command Line Options + +| Flag | Description | +| ----------- | -------------------- | +| `--config` | path to config file | +| `--version` | print version string | + + +### General Provider Options + +Provider specific options can be found on their respective subpages. + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| flag: `--acr-values`
toml: `acr_values` | string | optional, see [docs](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues) | `""` | +| flag: `--allowed-group`
toml: `allowed_groups` | string \| list | Restrict login to members of a group or list of groups. Furthermore, if you aren't setting the `scope` and use `allowed_groups` with the generic OIDC provider the scope `groups` gets added implicitly. | | +| flag: `--approval-prompt`
toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` | +| flag: `--backend-logout-url`
toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | | +| flag: `--client-id`
toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | | +| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret | | +| flag: `--client-secret`
toml: `client_secret` | string | the OAuth Client Secret | | +| flag: `--code-challenge-method`
toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | | +| flag: `--insecure-oidc-allow-unverified-email`
toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false | +| flag: `--insecure-oidc-skip-issuer-verification`
toml: `insecure_oidc_skip_issuer_verification` | bool | allow the OIDC issuer URL to differ from the expected (currently required for Azure multi-tenant compatibility) | false | +| flag: `--insecure-oidc-skip-nonce`
toml: `insecure_oidc_skip_nonce` | bool | skip verifying the OIDC ID Token's nonce claim | true | +| flag: `--jwt-key-file`
toml: `jwt_key_file` | string | path to the private key file in PEM format used to sign the JWT so that you can say something like `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem`: required by login.gov | | +| flag: `--jwt-key`
toml: `jwt_key` | string | private key in PEM format used to sign JWT, so that you can say something like `--jwt-key="${OAUTH2_PROXY_JWT_KEY}"`: required by login.gov | | +| flag: `--login-url`
toml: `login_url` | string | Authentication endpoint | | +| flag: `--auth-request-response-mode`
toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | | +| flag: `--oidc-audience-claim`
toml: `oidc_audience_claims` | string | which OIDC claim contains the audience | `"aud"` | +| flag: `--oidc-email-claim`
toml: `oidc_email_claim` | string | which OIDC claim contains the user's email | `"email"` | +| flag: `--oidc-extra-audience`
toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` | +| flag: `--oidc-groups-claim`
toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` | +| flag: `--oidc-issuer-url`
toml: `oidc_issuer_url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | | +| flag: `--oidc-jwks-url`
toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled and public key files are not provided | | +| flag: `--oidc-public-key-file`
toml: `oidc_public_key_files` | string | Path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times). Required if OIDC discovery is disabled na JWKS URL isn't provided | string \| list | +| flag: `--profile-url`
toml: `profile_url` | string | Profile access endpoint | | +| flag: `--prompt`
toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` | +| flag: `--provider-ca-file`
toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. | +| flag: `--provider-display-name`
toml: `provider_display_name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) | +| flag: `--provider`
toml: `provider` | string | OAuth provider | google | +| flag: `--pubjwk-url`
toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | | +| flag: `--redeem-url`
toml: `redeem_url` | string | Token redemption endpoint | | +| flag: `--scope`
toml:`scope` | string | OAuth scope specification. Every provider has a default list of scopes which will be used in case no scope is configured. | | +| flag: `--skip-claims-from-profile-url`
toml: `skip_claims_from_profile_url` | bool | skip request to Profile URL for resolving claims not present in id_token | false | +| flag: `--skip-oidc-discovery`
toml: `skip_oidc_discovery` | bool | bypass OIDC endpoint discovery. `--login-url`, `--redeem-url` and `--oidc-jwks-url` must be configured in this case | false | +| flag: `--use-system-trust-store`
toml: `use_system_trust_store` | bool | Determines if `provider-ca-file` files and the system trust store are used. If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | false | +| flag: `--validate-url`
toml: `validate_url` | string | Access token validation endpoint | | + +### Cookie Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | +| flag: `--cookie-csrf-expire`
toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m | +| flag: `--cookie-csrf-per-request`
toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false | +| flag: `--cookie-csrf-per-request-limit`
toml: `cookie_csrf_per_request_limit` | int | Sets a limit on the number of CSRF requests cookies that oauth2-proxy will create. The oldest cookie will be removed. Useful if users end up with 431 Request headers too large status codes. Only effective if --cookie-csrf-per-request is true | "infinite" | +| flag: `--cookie-domain`
toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | | +| flag: `--cookie-expire`
toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s | +| flag: `--cookie-httponly`
toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true | +| flag: `--cookie-name`
toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` | +| flag: `--cookie-path`
toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` | +| flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | +| flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | +| flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | +| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | For defining a separate cookie secret file to read the encryption key from | | +| flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | + +[^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) + +### Header Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--basic-auth-password`
toml: `basic_auth_password` | string | the password to set when passing the HTTP Basic Auth header | | +| flag: `--set-xauthrequest`
toml: `set_xauthrequest` | bool | set X-Auth-Request-User, X-Auth-Request-Groups, X-Auth-Request-Email and X-Auth-Request-Preferred-Username response headers (useful in Nginx auth_request mode). When used with `--pass-access-token`, X-Auth-Request-Access-Token is added to response headers. | false | +| flag: `--set-authorization-header`
toml: `set_authorization_header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false | +| flag: `--set-basic-auth`
toml: `set_basic_auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false | +| flag: `--skip-auth-strip-headers`
toml: `skip_auth_strip_headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy | true | +| flag: `--pass-access-token`
toml: `pass_access_token` | bool | pass OAuth access_token to upstream via X-Forwarded-Access-Token header. When used with `--set-xauthrequest` this adds the X-Auth-Request-Access-Token header to the response | false | +| flag: `--pass-authorization-header`
toml: `pass_authorization_header` | bool | pass OIDC IDToken to upstream via Authorization Bearer header | false | +| flag: `--pass-basic-auth`
toml: `pass_basic_auth` | bool | pass HTTP Basic Auth, X-Forwarded-User, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | +| flag: `--prefer-email-to-user`
toml: `prefer_email_to_user` | bool | Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, e.g. htaccess authentication. Used in conjunction with `--pass-basic-auth` and `--pass-user-headers` | false | +| flag: `--pass-user-headers`
toml: `pass_user_headers` | bool | pass X-Forwarded-User, X-Forwarded-Groups, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | + +### Logging Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------- | --------------------------------------------------- | +| flag: `--auth-logging-format`
toml: `auth_logging_format` | string | Template for authentication log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--auth-logging`
toml: `auth_logging` | bool | Log authentication attempts | true | +| flag: `--errors-to-info-log`
toml: `errors_to_info_log` | bool | redirects error-level logging to default log channel instead of stderr | false | +| flag: `--exclude-logging-path`
toml: `exclude_logging_paths` | string | comma separated list of paths to exclude from logging, e.g. `"/ping,/path2"` | `""` (no paths excluded) | +| flag: `--logging-compress`
toml: `logging_compress` | bool | Should rotated log files be compressed using gzip | false | +| flag: `--logging-filename`
toml: `logging_filename` | string | File to log requests to, empty for `stdout` | `""` (stdout) | +| flag: `--logging-local-time`
toml: `logging_local_time` | bool | Use local time in log files and backup filenames instead of UTC | true (local time) | +| flag: `--logging-max-age`
toml: `logging_max_age` | int | Maximum number of days to retain old log files | 7 | +| flag: `--logging-max-backups`
toml: `logging_max_backups` | int | Maximum number of old log files to retain; 0 to disable | 0 | +| flag: `--logging-max-size`
toml: `logging_max_size` | int | Maximum size in megabytes of the log file before rotation | 100 | +| flag: `--request-id-header`
toml: `request_id_header` | string | Request header to use as the request ID in logging | X-Request-Id | +| flag: `--request-logging-format`
toml: `request_logging_format` | string | Template for request log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--request-logging`
toml: `request_logging` | bool | Log requests | true | +| flag: `--silence-ping-logging`
toml: `silence_ping_logging` | bool | disable logging of requests to ping & ready endpoints | false | +| flag: `--standard-logging-format`
toml: `standard_logging_format` | string | Template for standard log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--standard-logging`
toml: `standard_logging` | bool | Log standard runtime information | true | + +### Page Template Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--banner`
toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | | +| flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | +| flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | +| flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | +| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | | +| flag: `--show-debug-on-error`
toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false | + +### Probe Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------- | ------ | ---------------------------------------------------------- | ----------------------------- | +| flag: `--ping-path`
toml: `ping_path` | string | the ping endpoint that can be used for basic health checks | `"/ping"` | +| flag: `--ping-user-agent`
toml: `ping_user_agent` | string | a User-Agent that can be used for basic health checks | `""` (don't check user agent) | +| flag: `--ready-path`
toml: `ready_path` | string | the ready endpoint that can be used for deep health checks | `"/ready"` | +| flag: `--gcp-healthchecks`
toml: `gcp_healthchecks` | bool | Enable GCP/GKE healthcheck endpoints (deprecated) | false | + +### Proxy Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--bearer-token-login-fallback`
toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | + +[^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. + +### Server Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | +| flag: `--http-address`
toml: `http_address` | string | `[http://]:` or `unix://` or `fd:` (case insensitive) to listen on for HTTP clients. Square brackets are required for ipv6 address, e.g. `http://[::1]:4180` | `"127.0.0.1:4180"` | +| flag: `--https-address`
toml: `https_address` | string | `[https://]:` to listen on for HTTPS clients. Square brackets are required for ipv6 address, e.g. `https://[::1]:443` | `":443"` | +| flag: `--metrics-address`
toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` | +| flag: `--metrics-secure-address`
toml: `metrics_secure_address` | string | the address prometheus metrics will be scraped from if using HTTPS | `""` | +| flag: `--metrics-tls-cert-file`
toml: `metrics_tls_cert_file` | string | path to certificate file for secure metrics server | `""` | +| flag: `--metrics-tls-key-file`
toml: `metrics_tls_key_file` | string | path to private key file for secure metrics server | `""` | +| flag: `--tls-cert-file`
toml: `tls_cert_file` | string | path to certificate file | | +| flag: `--tls-key-file`
toml: `tls_key_file` | string | path to private key file | | +| flag: `--tls-cipher-suite`
toml: `tls_cipher_suites` | string \| list | Restricts TLS cipher suites used by server to those listed (e.g. TLS_RSA_WITH_RC4_128_SHA) (may be given multiple times). If not specified, the default Go safe cipher list is used. List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | | +| flag: `--tls-min-version`
toml: `tls_min_version` | string | minimum TLS version that is acceptable, either `"TLS1.2"` or `"TLS1.3"` | `"TLS1.2"` | + +### Session Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--session-cookie-minimal`
toml: `session_cookie_minimal` | bool | strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only) | false | +| flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | +| flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | +| flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | +| flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | +| flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | +| flag: `--redis-sentinel-master-name`
toml: `redis_sentinel_master_name` | string | Redis sentinel master name. Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-sentinel-connection-urls`
toml: `redis_sentinel_connection_urls` | string \| list | List of Redis sentinel connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-use-cluster`
toml: `redis_use_cluster` | bool | Connect to redis cluster. Must set `--redis-cluster-connection-urls` to use this feature | false | +| flag: `--redis-use-sentinel`
toml: `redis_use_sentinel` | bool | Connect to redis via sentinels. Must set `--redis-sentinel-master-name` and `--redis-sentinel-connection-urls` to use this feature | false | +| flag: `--redis-connection-idle-timeout`
toml: `redis_connection_idle_timeout` | int | Redis connection idle timeout seconds. If Redis [timeout](https://redis.io/docs/reference/clients/#client-timeouts) option is set to non-zero, the `--redis-connection-idle-timeout` must be less than Redis timeout option. Example: if either redis.conf includes `timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` | 0 | + +### Upstream Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | +| flag: `--flush-interval`
toml: `flush_interval` | duration | period between flushing response buffers when streaming responses | `"1s"` | +| flag: `--pass-host-header`
toml: `pass_host_header` | bool | pass the request Host Header to upstream | true | +| flag: `--proxy-websockets`
toml: `proxy_websockets` | bool | enables WebSocket proxying | true | +| flag: `--ssl-upstream-insecure-skip-verify`
toml: `ssl_upstream_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false | +| flag: `--upstream-timeout`
toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s | +| flag: `--upstream`
toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://` for static response. Routing is based on the path | | + +## Upstreams Configuration + +`oauth2-proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers, unix socket or serve static files from the file system. + +To configure **HTTP and HTTPS upstreams**, provide such a URL in `--upstream=URL`. The scheme+host portion and the path portion are extracted to configure proxying behavior. When processing incoming requests, the path portion becomes a lookup key for selecting the destination server of the proxied request. + +* Upstream URLs *without a trailing slash,* like in `--upstream=http://service2.internal/foo`, will match an incoming request exactly to `/foo` in `https://this.o2p.example.com/foo`, and forward the request on to service2.internal, but not match a request to `https://this.o2p.example.com/foo/more` nor ...`.com/food`. +* Upstream URLs *with a trailing slash,* like in `--upstream=http://service1.internal/foo/`, will match any incoming request to any incoming requests's path *starting with* `/foo/`, like `/foo/` and `/foo/more` and `/foo/lots/more?etc`. + +If multiple `--upstream` URLs' paths match an incoming request, the one with the longest matching path (the most specific match) takes priority over shorter (less specific) ones. + +**Unix socket upstreams** are configured as `unix:///path/to/unix.sock`. + +**Static file paths** are configured as a file:// URL. `file:///var/www/static/` will serve the files from that directory at `http://[oauth2-proxy url]/var/www/static/`, which may not be what you want. You can provide the path to where the files should be available by adding a fragment to the configured URL. The value of the fragment will then be used to specify which path the files are available at, e.g. `file:///var/www/static/#/static/` will make `/var/www/static/` available at `http://[oauth2-proxy url]/static/`. + +Multiple upstreams can either be configured by supplying a comma separated list to the `--upstream` parameter, supplying the parameter multiple times or providing a list in the [config file](#config-file). When multiple upstreams are used routing to them will be based on the path they are set up with. + +## Environment variables + +Every command line argument can be specified as an environment variable by +prefixing it with `OAUTH2_PROXY_`, capitalising it, and replacing hyphens (`-`) +with underscores (`_`). If the argument can be specified multiple times, the +environment variable should be plural (trailing `S`). + +This is particularly useful for storing secrets outside a configuration file +or the command line. + +For example, the `--cookie-secret` flag becomes `OAUTH2_PROXY_COOKIE_SECRET`. +If a flag has the type `string | list` like the `--email-domain` flag it is +available as an environment variable in plural form e.g. `OAUTH2_PROXY_EMAIL_DOMAINS` + +Values for type `string | list` usually have a plural environment variable name +and need to be seperated by `,` e.g. +`OAUTH2_PROXY_SKIP_AUTH_ROUTES="GET=^/api/status,POST=^/api/saved_objects/_import"` + +Please check the type for each [config option](#config-options) first. + +## Logging Configuration + +By default, OAuth2 Proxy logs all output to stdout. Logging can be configured to output to a rotating log file using the `--logging-filename` command. + +If logging to a file you can also configure the maximum file size (`--logging-max-size`), age (`--logging-max-age`), max backup logs (`--logging-max-backups`), and if backup logs should be compressed (`--logging-compress`). + +There are three different types of logging: standard, authentication, and HTTP requests. These can each be enabled or disabled with `--standard-logging`, `--auth-logging`, and `--request-logging`. + +Each type of logging has its own configurable format and variables. By default, these formats are similar to the Apache Combined Log. + +Logging of requests to the `/ping` endpoint (or using `--ping-user-agent`) and the `/ready` endpoint can be disabled with `--silence-ping-logging` reducing log volume. + +## Auth Log Format + +Authentication logs are logs which are guaranteed to contain a username or email address of a user attempting to authenticate. These logs are output by default in the below format: + +``` + - - [2015/03/19 17:20:19] [] +``` + +The status block will contain one of the below strings: + +- `AuthSuccess` If a user has authenticated successfully by any method +- `AuthFailure` If the user failed to authenticate explicitly +- `AuthError` If there was an unexpected error during authentication + +If you require a different format than that, you can configure it with the `--auth-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}} +``` + +Available variables for auth logging: + +| Variable | Example | Description | +| ------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Message | Authenticated via OAuth2 | The details of the auth attempt. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | +| Status | AuthSuccess | The status of the auth request. See above for details. | + +## Request Log Format + +HTTP request logs will output by default in the below format: + +``` + - - [2015/03/19 17:20:19] GET "/path/" HTTP/1.1 "" +``` + +If you require a different format than that, you can configure it with the `--request-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}} +``` + +Available variables for request logging: + +| Variable | Example | Description | +| --------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestDuration | 0.001 | The time in seconds that a request took to process. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| RequestURI | "/oauth2/auth" | The URI path of the request. | +| ResponseSize | 12 | The size in bytes of the response. | +| StatusCode | 200 | The HTTP status code of the response. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| Upstream | - | The upstream data of the HTTP request. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | + +## Standard Log Format + +All other logging that is not covered by the above two types of logging will be output in this standard logging format. This includes configuration information at startup and errors that occur outside of a session. The default format is below: + +``` +[2015/03/19 17:20:19] [main.go:40] +``` + +If you require a different format than that, you can configure it with the `--standard-logging-format` flag. The default format is configured as follows: + +``` +[{{.Timestamp}}] [{{.File}}] {{.Message}} +``` + +Available variables for standard logging: + +| Variable | Example | Description | +| --------- | --------------------------------- | -------------------------------------------------- | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| File | main.go:40 | The file and line number of the logging statement. | +| Message | HTTP: listening on 127.0.0.1:4180 | The details of the log statement. | diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/adfs.md b/docs/versioned_docs/version-7.11.x/configuration/providers/adfs.md new file mode 100644 index 0000000000..ec8d72d2af --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/adfs.md @@ -0,0 +1,19 @@ +--- +id: adfs +title: ADFS +--- + +1. Open the ADFS administration console on your Windows Server and add a new Application Group +2. Provide a name for the integration, select Server Application from the Standalone applications section and click Next +3. Follow the wizard to get the client-id, client-secret and configure the application credentials +4. Configure the proxy with + +``` + --provider=adfs + --client-id= + --client-secret= +``` + +Note: When using the ADFS Auth provider with nginx and the cookie session store you may find the cookie is too large and +doesn't get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the +[redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/bitbucket.md b/docs/versioned_docs/version-7.11.x/configuration/providers/bitbucket.md new file mode 100644 index 0000000000..e31de7526c --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/bitbucket.md @@ -0,0 +1,25 @@ +--- +id: bitbucket +title: BitBucket +--- + +1. [Add a new OAuth consumer](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html) + * In "Callback URL" use `https:///oauth2/callback`, substituting `` with the actual + hostname that oauth2-proxy is running on. + * In Permissions section select: + * Account -> Email + * Team membership -> Read + * Repositories -> Read +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=bitbucket + --client-id= + --client-secret= +``` + +The default configuration allows everyone with Bitbucket account to authenticate. To restrict the access to the team +members use additional configuration option: `--bitbucket-team=`. To restrict the access to only these users +who have access to one selected repository use `--bitbucket-repository=`. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/digitalocean.md b/docs/versioned_docs/version-7.11.x/configuration/providers/digitalocean.md new file mode 100644 index 0000000000..f6a1e89181 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/digitalocean.md @@ -0,0 +1,21 @@ +--- +id: digitalocean +title: DigitalOcean +--- + +1. [Create a new OAuth application](https://cloud.digitalocean.com/account/api/applications) + * You can fill in the name, homepage, and description however you wish. + * In the "Application callback URL" field, enter: `https://oauth-proxy/oauth2/callback`, substituting `oauth2-proxy` + with the actual hostname that oauth2-proxy is running on. The URL must match oauth2-proxy's configured redirect URL. +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=digitalocean + --client-id= + --client-secret= +``` + +Alternatively, set the equivalent options in the config file. The redirect URL defaults to +`https:///oauth2/callback`. If you need to change it, you can use the `--redirect-url` command-line option. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/facebook.md b/docs/versioned_docs/version-7.11.x/configuration/providers/facebook.md new file mode 100644 index 0000000000..352c95ce1e --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/facebook.md @@ -0,0 +1,7 @@ +--- +id: facebook +title: Facebook +--- + +1. Create a new FB App from https://developers.facebook.com/ +2. Under FB Login, set your Valid OAuth redirect URIs to `https://internal.yourcompany.com/oauth2/callback` diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/gitea.md b/docs/versioned_docs/version-7.11.x/configuration/providers/gitea.md new file mode 100644 index 0000000000..996a5ddbdb --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/gitea.md @@ -0,0 +1,24 @@ +--- +id: gitea +title: Gitea +--- + +:::note +This is not actually its own provider. For more details and options please refer to the [GitHub Provider Options](github.md) +::: + +1. Create a new application: `https://< your gitea host >/user/settings/applications` +2. Under `Redirect URI` enter the correct URL i.e. `https:///oauth2/callback` +3. Note the Client ID and Client Secret. +4. Pass the following options to the proxy: + +``` + --provider="github" + --redirect-url="https:///oauth2/callback" + --provider-display-name="Gitea" + --client-id="< client_id as generated by Gitea >" + --client-secret="< client_secret as generated by Gitea >" + --login-url="https://< your gitea host >/login/oauth/authorize" + --redeem-url="https://< your gitea host >/login/oauth/access_token" + --validate-url="https://< your gitea host >/api/v1/user/emails" +``` diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/github.md b/docs/versioned_docs/version-7.11.x/configuration/providers/github.md new file mode 100644 index 0000000000..cebca31411 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/github.md @@ -0,0 +1,81 @@ +--- +id: github +title: GitHub +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------- | ------- | +| `--github-org` | `github_org` | string | restrict logins to members of this organisation | | +| `--github-team` | `github_team` | string | restrict logins to members of any of these teams (slug) or (org:team), comma separated | | +| `--github-repo` | `github_repo` | string | restrict logins to collaborators of this repository formatted as `orgname/repo` | | +| `--github-token` | `github_token` | string | the token to use when verifying repository collaborators (must have push access to the repository) | | +| `--github-user` | `github_users` | string \| list | To allow users to login by username even if they do not belong to the specified org and team or collaborators | | + +## Usage + +1. Create a new project: https://github.com/settings/developers +2. Under `Authorization callback URL` enter the correct url ie `https://internal.yourcompany.com/oauth2/callback` + +The GitHub auth provider supports two additional ways to restrict authentication to either organization and optional +team level access, or to collaborators of a repository. Restricting by these options is normally accompanied with `--email-domain=*`. Additionally, all the organizations and teams a user belongs to are set as part of the `X-Forwarded-Groups` header. e.g. `org1:team1,org1:team2,org2:team1` + +NOTE: When `--github-user` is set, the specified users are allowed to log in even if they do not belong to the specified +org and team or collaborators. + +To restrict access to your organization: + +```shell + # restrict logins to members of this organisation + --github-org="your-org" +``` + +To restrict access to specific teams within an organization: + +```shell + --github-org="your-org" + # restrict logins to members of any of these teams (slug), comma separated + --github-team="team1,team2,team3" +``` + +To restrict to teams within different organizations, keep the organization flag empty and use `--github-team` like so: + +```shell + # keep empty + --github-org="" + # restrict logins to members to any of the following teams (format :, like octo:team1), comma separated + --github-team="org1:team1,org2:team1,org3:team42,octo:cat" +``` + +If you would rather restrict access to collaborators of a repository, those users must either have push access to a +public repository or any access to a private repository: + +```shell + # restrict logins to collaborators of this repository formatted as orgname/repo + --github-repo="" +``` + +If you'd like to allow access to users with **read only** access to a **public** repository you will need to provide a +[token](https://github.com/settings/tokens) for a user that has write access to the repository. The token must be +created with at least the `public_repo` scope: + +```shell + # the token to use when verifying repository collaborators + --github-token="" +``` + +To allow a user to log in with their username even if they do not belong to the specified org and team or collaborators: + +```shell + # allow logins by username, comma separated + --github-user="" +``` + +If you are using GitHub enterprise, make sure you set the following to the appropriate url: + +```shell + --login-url="http(s):///login/oauth/authorize" + --redeem-url="http(s):///login/oauth/access_token" + --validate-url="http(s):///api/v3" +``` diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.11.x/configuration/providers/gitlab.md new file mode 100644 index 0000000000..4cdbbbe1e0 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/gitlab.md @@ -0,0 +1,49 @@ +--- +id: gitlab +title: GitLab +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | +| `--gitlab-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 | | + +## Usage + +This auth provider has been tested against Gitlab version 12.X. Due to Gitlab API changes, it may not work for version +prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)). + +Whether you are using GitLab.com or self-hosting GitLab, follow +[these steps to add an application](https://docs.gitlab.com/integration/oauth_provider/). Make sure to enable at +least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. +https://myapp.com/oauth2/callback. + +If you need projects filtering, add the extra `read_api` scope to your application. + +The following config should be set to ensure that the oauth will work properly. To get a cookie secret follow +[these steps](../overview.md#generating-a-cookie-secret) + +``` + --provider="gitlab" + --redirect-url="https://myapp.com/oauth2/callback" // Should be the same as the redirect url for the application in gitlab + --client-id=GITLAB_CLIENT_ID + --client-secret=GITLAB_CLIENT_SECRET + --cookie-secret=COOKIE_SECRET +``` + +Restricting by group membership is possible with the following option: + +```shell + --gitlab-group="mygroup,myothergroup" # restrict logins to members of any of these groups (slug), separated by a comma +``` + +If you are using self-hosted GitLab, make sure you set the following to the appropriate URL: + +```shell + --oidc-issuer-url="" +``` + +If your self-hosted GitLab is on a subdirectory (e.g. domain.tld/gitlab), as opposed to its own subdomain +(e.g. gitlab.domain.tld), you may need to add a redirect from domain.tld/oauth pointing at e.g. domain.tld/gitlab/oauth. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/google.md b/docs/versioned_docs/version-7.11.x/configuration/providers/google.md new file mode 100644 index 0000000000..ac2a7dfaaf --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/google.md @@ -0,0 +1,75 @@ +--- +id: google +title: Google (default) +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------------------------------------- | -------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------ | -------------------------------------------------- | +| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | +| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). If not specified and service account or default credentials are configured, all user groups will be allowed. | | +| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | +| `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | +| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | + +## Usage + +For Google, the registration steps are: + +1. Create a new project: https://console.developers.google.com/project +2. Choose the new project from the top right project dropdown (only if another project is selected) +3. In the project Dashboard center pane, choose **"APIs & Services"** +4. In the left Nav pane, choose **"Credentials"** +5. In the center pane, choose **"OAuth consent screen"** tab. Fill in **"Product name shown to users"** and hit save. +6. In the center pane, choose **"Credentials"** tab. + - Open the **"New credentials"** drop down + - Choose **"OAuth client ID"** + - Choose **"Web application"** + - Application name is freeform, choose something appropriate + - Authorized JavaScript origins is your domain ex: `https://internal.yourcompany.com` + - Authorized redirect URIs is the location of oauth2/callback ex: `https://internal.yourcompany.com/oauth2/callback` + - Choose **"Create"** +7. Take note of the **Client ID** and **Client Secret** + +It's recommended to refresh sessions on a short interval (1h) with `cookie-refresh` setting which validates that the +account is still authorized. + +#### Restrict auth to specific Google groups on your domain. (optional) + +1. Create a [service account](https://developers.google.com/identity/protocols/oauth2/service-account) and configure it + to use [Application Default Credentials / Workload Identity / Workload Identity Federation (recommended)](#using-application-default-credentials-adc--workload-identity--workload-identity-federation-recommended) or, + alternatively download the JSON. +2. Make note of the Client ID for a future step. +3. Under "APIs & Auth", choose APIs. +4. Click on Admin SDK and then Enable API. +5. Follow the steps on [Set up domain-wide delegation for a service account](https://developers.google.com/workspace/guides/create-credentials#optional_set_up_domain-wide_delegation_for_a_service_account) + and give the client id from step 2 the following oauth scopes: + + ``` + https://www.googleapis.com/auth/admin.directory.group.member.readonly + ``` + +6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access. +7. Create or choose an existing administrative email address on the Gmail domain to assign to the `google-admin-email` + flag. This email will be impersonated by this client to make calls to the Admin SDK. See the note on the link from + step 5 for the reason why. +8. Create or choose an existing email group and set that email to the `google-group` flag. You can pass multiple instances + of this flag with different groups and the user will be checked against all the provided groups. + +(Only if using a JSON file (see step 1)) + +9. Lock down the permissions on the json file downloaded from step 1 so only oauth2-proxy is able to read the file and + set the path to the file in the `google-service-account-json` flag. +10. Restart oauth2-proxy. + +Note: The user is checked against the group members list on initial authentication and every time the token is +refreshed ( about once an hour ). + +##### Using Application Default Credentials (ADC) / Workload Identity / Workload Identity Federation (recommended) +oauth2-proxy can make use of [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials). +When deployed within GCP, this means that it can automatically use the service account attached to the resource. When deployed to GKE, ADC +can be leveraged through a feature called Workload Identity. Follow Google's [guide](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity) +to set up Workload Identity. + +When deployed outside of GCP, [Workload Identity Federation](https://cloud.google.com/docs/authentication/provide-credentials-adc#wlif) might be an option. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/index.md b/docs/versioned_docs/version-7.11.x/configuration/providers/index.md new file mode 100644 index 0000000000..b947c09b7e --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/index.md @@ -0,0 +1,43 @@ +--- +id: index +title: OAuth Provider Configuration +--- + +You will need to register an OAuth application with a Provider (Google, GitHub or another provider), and configure it +with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on. + +Valid providers are : + +- [ADFS](adfs.md) +- [Bitbucket](bitbucket.md) +- [DigitalOcean](digitalocean.md) +- [Facebook](facebook.md) +- [Gitea](gitea.md) +- [GitHub](github.md) +- [GitLab](gitlab.md) +- [Google](google.md) _default_ +- [Keycloak](keycloak.md) (Deprecated) +- [Keycloak OIDC](keycloak_oidc.md) +- [LinkedIn](linkedin.md) +- [login.gov](login_gov.md) +- [Microsoft Azure](ms_azure_ad.md) (Deprecated) +- [Microsoft Entra ID](ms_entra_id.md) +- [Nextcloud](nextcloud.md) +- [OpenID Connect](openid_connect.md) + +The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the +OpenID Connect provider. + +## Email Authentication + +To authorize a specific email-domain use `--email-domain=yourcompany.com`. To authorize individual email addresses use +`--authenticated-emails-file=/path/to/file` with one email per line. To authorize all email addresses use `--email-domain=*`. + +## Adding a new Provider + +Follow the examples in the [`providers` package](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/) to define a new +`Provider` instance. Add a new `case` to +[`providers.New()`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/providers.go) to allow `oauth2-proxy` to use the +new `Provider`. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/keycloak.md b/docs/versioned_docs/version-7.11.x/configuration/providers/keycloak.md new file mode 100644 index 0000000000..11a1abca1c --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/keycloak.md @@ -0,0 +1,36 @@ +--- +id: keycloak +title: Keycloak (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Keycloak, use [Keycloak OIDC Auth Provider](keycloak_oidc.md) if possible. +::: + +1. Create new client in your Keycloak realm with **Access Type** 'confidential' and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. + +Make sure you set the following to the appropriate url: + +``` + --provider=keycloak + --client-id= + --client-secret= + --login-url="http(s):///auth/realms//protocol/openid-connect/auth" + --redeem-url="http(s):///auth/realms//protocol/openid-connect/token" + --profile-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --validate-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --keycloak-group= + --keycloak-group= +``` + +For group based authorization, the optional `--keycloak-group` (legacy) or `--allowed-group` (global standard) +flags can be used to specify which groups to limit access to. + +If these are unset but a `groups` mapper is set up above in step (3), the provider will still +populate the `X-Forwarded-Groups` header to your upstream server with the `groups` data in the +Keycloak userinfo endpoint response. + +The group management in keycloak is using a tree. If you create a group named admin in keycloak +you should define the 'keycloak-group' value to /admin. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/keycloak_oidc.md b/docs/versioned_docs/version-7.11.x/configuration/providers/keycloak_oidc.md new file mode 100644 index 0000000000..b29096e35d --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/keycloak_oidc.md @@ -0,0 +1,151 @@ +--- +id: keycloak_oidc +title: Keycloak OIDC +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------ | ------- | +| `--allowed-role` | `allowed_roles` | string \| list | restrict logins to users with this role (may be given multiple times). Only works with the keycloak-oidc provider. | | + +## Usage + +``` + --provider=keycloak-oidc + --client-id= + --client-secret= + --redirect-url=https://internal.yourcompany.com/oauth2/callback + --oidc-issuer-url=https:///realms/ // For Keycloak versions <17: --oidc-issuer-url=https:///auth/realms/ + --email-domain= // Validate email domain for users, see option documentation + --allowed-role= // Optional, required realm role + --allowed-role=: // Optional, required client role + --allowed-group= // Optional, requires group client scope + --code-challenge-method=S256 // PKCE +``` + +:::note +Keycloak has updated its admin console and as of version 19.0.0, the new admin console is enabled by default. The +legacy admin console has been announced for removal with the release of version 21.0.0. +::: + +**Keycloak legacy admin console** + +1. Create new client in your Keycloak realm with **Access Type** 'confidential', **Client protocol** 'openid-connect' + and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. +4. Create a mapper with **Mapper Type** 'Audience' and **Included Client Audience** and **Included Custom Audience** set + to your client name. + +**Keycloak new admin console (default as of v19.0.0)** + +The following example shows how to create a simple OIDC client using the new Keycloak admin2 console. However, for best +practices, it is recommended to consult the Keycloak documentation. + +The OIDC client must be configured with an _audience mapper_ to include the client's name in the `aud` claim of the JWT token. +The `aud` claim specifies the intended recipient of the token, and OAuth2 Proxy expects a match against the values of +either `--client-id` or `--oidc-extra-audience`. + +_In Keycloak, claims are added to JWT tokens through the use of mappers at either the realm level using "client scopes" or +through "dedicated" client mappers._ + +**Creating the client** + +1. Create a new OIDC client in your Keycloak realm by navigating to: + **Clients** -> **Create client** + * **Client Type** 'OpenID Connect' + * **Client ID** ``, please complete the remaining fields as appropriate and click **Next**. + * **Client authentication** 'On' + * **Authentication flow** + * **Standard flow** 'selected' + * **Direct access grants** 'deselect' + * _Save the configuration._ + * **Settings / Access settings**: + * **Valid redirect URIs** `https://internal.yourcompany.com/oauth2/callback` + * _Save the configuration._ + * Under the **Credentials** tab you will now be able to locate ``. +2. Configure a dedicated *audience mapper* for your client by navigating to **Clients** -> **\** -> **Client scopes**. +* Access the dedicated mappers pane by clicking **\-dedicated**, located under *Assigned client scope*. + _(It should have a description of "Dedicated scope and mappers for this client")_ + * Click **Configure a new mapper** and select **Audience** + * **Name** 'aud-mapper-\' + * **Included Client Audience** select `` from the dropdown. + * _OAuth2 proxy can be set up to pass both the access and ID JWT tokens to your upstream services. + If you require additional audience entries, you can use the **Included Custom Audience** field in addition + to the "Included Client Audience" dropdown. Note that the "aud" claim of a JWT token should be limited and + only specify its intended recipients._ + * **Add to ID token** 'On' + * **Add to access token** 'On' - [#1916](https://github.com/oauth2-proxy/oauth2-proxy/pull/1916) + * _Save the configuration._ +* Any subsequent dedicated client mappers can be defined by clicking **Dedicated scopes** -> **Add mapper** -> + **By configuration** -> *Select mapper* + +You should now be able to create a test user in Keycloak and get access to the OAuth2 Proxy instance, make sure to set +an email address matching `` and select _Email verified_. + +**Authorization** + +_OAuth2 Proxy will perform authorization by requiring a valid user, this authorization can be extended to take into +account a user's membership in Keycloak `groups`, `realm roles`, and `client roles` using the keycloak-oidc provider options +`--allowed-role` or `--allowed-group`_ + +**Roles** + +_A standard Keycloak installation comes with the required mappers for **realm roles** and **client roles** through the +pre-defined client scope "roles". This ensures that any roles assigned to a user are included in the `JWT` tokens when +using an OIDC client that has the "Full scope allowed" feature activated, the feature is enabled by default._ + +_Creating a realm role_ +* Navigate to **Realm roles** -> **Create role** + * **Role name**, *``* -> **save** + +_Creating a client role_ +* Navigate to **Clients** -> `` -> **Roles** -> **Create role** + * **Role name**, *``* -> **save** + + +_Assign a role to a user_ + +**Users** -> _Username_ -> **Role mapping** -> **Assign role** -> _filter by roles or clients and select_ -> **Assign**. + +Keycloak "realm roles" can be authorized using the `--allowed-role=` option, while "client roles" can be +evaluated using `--allowed-role=:`. + +You may limit the _realm roles_ included in the JWT tokens for any given client by navigating to: +**Clients** -> `` -> **Client scopes** -> _\-dedicated_ -> **Scope** +Disabling **Full scope allowed** activates the **Assign role** option, allowing you to select which roles, if assigned +to a user, will be included in the user's JWT tokens. This can be useful when a user has many associated roles, and you +want to reduce the size and impact of the JWT token. + + +**Groups** + +You may also do authorization on group memberships by using the OAuth2 Proxy option `--allowed-group`. +We will only do a brief description of creating the required _client scope_ **groups** and refer you to read the Keycloak +documentation. + +To summarize, the steps required to authorize Keycloak group membership with OAuth2 Proxy are as follows: + +* Create a new Client Scope with the name **groups** in Keycloak. + * Include a mapper of type **Group Membership**. + * Set the "Token Claim Name" to **groups** or customize by matching it to the `--oidc-groups-claim` option of OAuth2 Proxy. + * If the "Full group path" option is selected, you need to include a "/" separator in the group names defined in the + `--allowed-group` option of OAuth2 Proxy. Example: "/groupname" or "/groupname/child_group". + +After creating the _Client Scope_ named _groups_ you will need to attach it to your client. +**Clients** -> `` -> **Client scopes** -> **Add client scope** -> Select **groups** and choose Optional +and you should now have a client that maps group memberships into the JWT tokens so that Oauth2 Proxy may evaluate them. + +Create a group by navigating to **Groups** -> **Create group** and _add_ your test user as a member. + +The OAuth2 Proxy option `--allowed-group=/groupname` will now allow you to filter on group membership + +Keycloak also has the option of attaching roles to groups, please refer to the Keycloak documentation for more information. + +**Tip** + +To check if roles or groups are added to JWT tokens, you can preview a users token in the Keycloak console by following +these steps: **Clients** -> `` -> **Client scopes** -> **Evaluate**. +Select a _realm user_ and optional _scope parameters_ such as groups, and generate the JSON representation of an access +or id token to examine its contents. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/linkedin.md b/docs/versioned_docs/version-7.11.x/configuration/providers/linkedin.md new file mode 100644 index 0000000000..7d26ec4334 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/linkedin.md @@ -0,0 +1,13 @@ +--- +id: linkedin +title: LinkedIn +--- + +For LinkedIn, the registration steps are: + +1. Create a new project: https://www.linkedin.com/secure/developer +2. In the OAuth User Agreement section: + - In default scope, select r_basicprofile and r_emailaddress. + - In "OAuth 2.0 Redirect URLs", enter `https://internal.yourcompany.com/oauth2/callback` +3. Fill in the remaining required fields and Save. +4. Take note of the **Consumer Key / API Key** and **Consumer Secret / Secret Key** diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/login_gov.md b/docs/versioned_docs/version-7.11.x/configuration/providers/login_gov.md new file mode 100644 index 0000000000..badbe48e69 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/login_gov.md @@ -0,0 +1,79 @@ +--- +id: login_gov +title: Login.gov +--- + +login.gov is an OIDC provider for the US Government. +If you are a US Government agency, you can contact the login.gov team through the contact information +that you can find on https://login.gov/developers/ and work with them to understand how to get login.gov +accounts for integration/test and production access. + +A developer guide is available here: https://developers.login.gov/, though this proxy handles everything +but the data you need to create to register your application in the login.gov dashboard. + +As a demo, we will assume that you are running your application that you want to secure locally on +http://localhost:3000/, that you will be starting your proxy up on http://localhost:4180/, and that +you have an agency integration account for testing. + +First, register your application in the dashboard. The important bits are: +* Identity protocol: make this `Openid connect` +* Issuer: do what they say for OpenID Connect. We will refer to this string as `${LOGINGOV_ISSUER}`. +* Public key: This is a self-signed certificate in .pem format generated from a 2048-bit RSA private key. + A quick way to do this is + `openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -nodes -subj '/C=US/ST=Washington/L=DC/O=GSA/OU=18F/CN=localhost'`. + The contents of the `key.pem` shall be referred to as `${OAUTH2_PROXY_JWT_KEY}`. +* Return to App URL: Make this be `http://localhost:4180/` +* Redirect URIs: Make this be `http://localhost:4180/oauth2/callback`. +* Attribute Bundle: Make sure that email is selected. + +Now start the proxy up with the following options: +``` +./oauth2-proxy -provider login.gov \ + -client-id=${LOGINGOV_ISSUER} \ + -redirect-url=http://localhost:4180/oauth2/callback \ + -oidc-issuer-url=https://idp.int.identitysandbox.gov/ \ + -cookie-secure=false \ + -email-domain=gsa.gov \ + -upstream=http://localhost:3000/ \ + -cookie-secret=somerandomstring12341234567890AB \ + -cookie-domain=localhost \ + -skip-provider-button=true \ + -pubjwk-url=https://idp.int.identitysandbox.gov/api/openid_connect/certs \ + -profile-url=https://idp.int.identitysandbox.gov/api/openid_connect/userinfo \ + -jwt-key="${OAUTH2_PROXY_JWT_KEY}" +``` +You can also set all these options with environment variables, for use in cloud/docker environments. +One tricky thing that you may encounter is that some cloud environments will pass in environment +variables in a docker env-file, which does not allow multiline variables like a PEM file. +If you encounter this, then you can create a `jwt_signing_key.pem` file in the top level +directory of the repo which contains the key in PEM format and then do your docker build. +The docker build process will copy that file into your image which you can then access by +setting the `OAUTH2_PROXY_JWT_KEY_FILE=/etc/ssl/private/jwt_signing_key.pem` +environment variable, or by setting `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem` on the commandline. + +Once it is running, you should be able to go to `http://localhost:4180/` in your browser, +get authenticated by the login.gov integration server, and then get proxied on to your +application running on `http://localhost:3000/`. In a real deployment, you would secure +your application with a firewall or something so that it was only accessible from the +proxy, and you would use real hostnames everywhere. + +#### Skip OIDC discovery + +Some providers do not support OIDC discovery via their issuer URL, so oauth2-proxy cannot simply grab the authorization, +token and jwks URI endpoints from the provider's metadata. + +In this case, you can set the `--skip-oidc-discovery` option, and supply those required endpoints manually: + +``` + -provider oidc + -client-id oauth2-proxy + -client-secret proxy + -redirect-url http://127.0.0.1:4180/oauth2/callback + -oidc-issuer-url http://127.0.0.1:5556 + -skip-oidc-discovery + -login-url http://127.0.0.1:5556/authorize + -redeem-url http://127.0.0.1:5556/token + -oidc-jwks-url http://127.0.0.1:5556/keys + -cookie-secure=false + -email-domain example.com +``` diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/ms_azure_ad.md b/docs/versioned_docs/version-7.11.x/configuration/providers/ms_azure_ad.md new file mode 100644 index 0000000000..4feefc6800 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/ms_azure_ad.md @@ -0,0 +1,59 @@ +--- +id: azure +title: Azure (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Azure, use [Microsoft Entra ID](ms_entra_id.md) if possible. +::: + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | ------ | ---------------------------------------------------------------- | ---------- | +| `--azure-tenant` | `azure_tenant` | string | go to a tenant-specific or common (tenant-independent) endpoint. | `"common"` | +| `--resource` | `resource` | string | The resource that is protected (Azure AD only) | | + +## Usage + +1. Add an application: go to [https://portal.azure.com](https://portal.azure.com), choose **Azure Active Directory**, select + **App registrations** and then click on **New registration**. +2. Pick a name, check the supported account type(single-tenant, multi-tenant, etc). In the **Redirect URI** section create a new + **Web** platform entry for each app that you want to protect by the oauth2 proxy(e.g. + https://internal.yourcompanycom/oauth2/callback). Click **Register**. +3. Next we need to add group read permissions for the app registration, on the **API Permissions** page of the app, click on + **Add a permission**, select **Microsoft Graph**, then select **Application permissions**, then click on **Group** and select + **Group.Read.All**. Hit **Add permissions** and then on **Grant admin consent** (you might need an admin to do this). +
**IMPORTANT**: Even if this permission is listed with **"Admin consent required=No"** the consent might actually + be required, due to AAD policies you won't be able to see. If you get a **"Need admin approval"** during login, + most likely this is what you're missing! +4. Next, if you are planning to use v2.0 Azure Auth endpoint, go to the **Manifest** page and set `"accessTokenAcceptedVersion": 2` + in the App registration manifest file. +5. On the **Certificates & secrets** page of the app, add a new client secret and note down the value after hitting **Add**. +6. Configure the proxy with: +- for V1 Azure Auth endpoint (Azure Active Directory Endpoints - https://login.microsoftonline.com/common/oauth2/authorize) + +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://sts.windows.net/{tenant-id}/ +``` + +- for V2 Azure Auth endpoint (Microsoft Identity Platform Endpoints - https://login.microsoftonline.com/common/oauth2/v2.0/authorize) +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://login.microsoftonline.com/{tenant-id}/v2.0 +``` + +***Notes***: +- When using v2.0 Azure Auth endpoint (`https://login.microsoftonline.com/{tenant-id}/v2.0`) as `--oidc_issuer_url`, in conjunction + with `--resource` flag, be sure to append `/.default` at the end of the resource name. See + https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope for more details. +- When using the Azure Auth provider with nginx and the cookie session store you may find the cookie is too large and doesn't + get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the + [redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.11.x/configuration/providers/ms_entra_id.md new file mode 100644 index 0000000000..c5d9594edd --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/ms_entra_id.md @@ -0,0 +1,197 @@ +--- +id: ms_entra_id +title: Microsoft Entra ID +--- + +Provider for Microsoft Entra ID. Fully compliant with OIDC, with support for group overage and multi-tenant apps. + +## Config Options + +The provider is OIDC-compliant, so all the OIDC parameters are honored. Additional provider-specific configuration parameters are: + +| Flag | Toml Field | Type | Description | Default | +| --------------------------- | -------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--entra-id-allowed-tenant` | `entra_id_allowed_tenants` | string \| list | List of allowed tenants. In case of multi-tenant apps, incoming tokens are issued by different issuers and OIDC issuer verification needs to be disabled. When not specified, all tenants are allowed. Redundant for single-tenant apps (regular ID token validation matches the issuer). | | +| `--entra-id-federated-token-auth` | `entra_id_federated_token_auth` | boolean | Enable oAuth2 client authentication with federated token projected by Entra Workload Identity plugin, instead of client secret. | false | + +## Configure App registration +To begin, create an App registration, set a redirect URI, and generate a secret. All account types are supported, including single-tenant, multi-tenant, multi-tenant with Microsoft accounts, and Microsoft accounts only. + +
+ See Azure Portal example +
+ +
+
+ +
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" # Others are also supported + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + // We don't specify any required API permissions - we allow user consent only + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Configure groups +If you want to make use of groups, you can configure *groups claim* to be present in ID Tokens issued by the App registration. +
+ See Azure Portal example +
+
+ +
+
+
+
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" + + group_membership_claims = [ + "SecurityGroup" + ] + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Scopes and claims +For single-tenant and multi-tenant apps without groups, the only required scope is `openid` (See: [Scopes and permissions](https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#the-openid-scope)). + +To make use of groups - for example use `allowed_groups` setting or authorize based on groups inside your service - you need to enable *groups claims* in the App Registration. When enabled, list of groups is present in the issued ID token. No additional scopes are required besides `openid`. This works up to 200 groups. + +When user has more than 200 group memberships, OAuth2-Proxy attempts to retrieve the complete list from Microsoft Graph API's [`transitiveMemberOf`](https://learn.microsoft.com/en-us/graph/api/user-list-transitivememberof). Endpoint requires `User.Read` scope (delegated permission). This permission can be by default consented by user during first login. Set scope to `openid User.Read` to request user consent. Without proper scope, user with 200+ groups will authenticate with 0 groups. See: [group overages](https://learn.microsoft.com/en-us/security/zero-trust/develop/configure-tokens-group-claims-app-roles#group-overages). + +Alternatively to user consent, both `openid` and `User.Read` permissions can be consented by admistrator. Then, user is not asked for consent on the first login, and group overage works with `openid` scope only. Admin consent can also be required for some tenants. It can be granted with [azuread_service_principal_delegated_permission_grant](https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/service_principal_delegated_permission_grant) terraform resource. + +For personal microsoft accounts, required scope is `openid profile email`. + +See: [Overview of permissions and consent in the Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview). + +### Multi-tenant apps +To authenticate apps from multiple tenants (including personal Microsoft accounts), set the common OIDC issuer url and disable verification: +```toml +oidc_issuer_url=https://login.microsoftonline.com/common/v2.0 +insecure_oidc_skip_issuer_verification=true +``` +`insecure_oidc_skip_issuer_verification` setting is required to disable following checks: +* Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). + +To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. + +### Workload Identity +Provider supports authentication with federated token, without need of using client secret. Following conditions have to be met: + +* Cluster has public OIDC provider URL. For major cloud providers, it can be enabled with a single flag, for example for [Azure Kubernetes Service deployed with Terraform](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster), it's `oidc_issuer_enabled`. +* Workload Identity admission webhook is deployed on the cluster. For AKS, it can be enabled with a flag (`workload_identity_enabled` in Terraform resource), for clusters outside of Azure, it can be installed from [helm chart](https://github.com/Azure/azure-workload-identity). +* Appropriate federated credential is added to application registration. +
+ See federated credential terraform example +``` + resource "azuread_application_federated_identity_credential" "fedcred" { + application_id = azuread_application.application.id # ID of your application + display_name = "federation-cred" + description = "Workload identity for oauth2-proxy" + audiences = ["api://AzureADTokenExchange"] # Fixed value + issuer = "https://cluster-oidc-issuer-url..." + subject = "system:serviceaccount:oauth2-proxy-namespace-name:oauth2-proxy-sa-name" # set proper NS and SA name + } +``` +
+ +* Kubernetes service account associated with oauth2-proxy deployment, is annotated with `azure.workload.identity/client-id: ` +* oauth2-proxy pod is labeled with `azure.workload.identity/use: "true"` +* oauth2-proxy is configured with `entra_id_federated_token_auth` set to `true`. + +`client_secret` setting can be omitted when using federated token authentication. + +See: [Azure Workload Identity documentation](https://azure.github.io/azure-workload-identity/docs/). + +### Example configurations +Single-tenant app without groups (*groups claim* not enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +``` + +Single-tenant app with up to 200 groups (*groups claim* enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +allowed_groups=["ac51800c-2679-4ecb-8130-636380a3b491"] +``` + +Single-tenant app with more than 200 groups: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +``` + +Single-tenant app with more than 200 groups and workload identity enabled: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +entra_id_federated_token_auth=true +``` + +Multi-tenant app with Microsoft personal accounts & one Entra tenant allowed, with group overage considered: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com/common/v2.0" +client_id="" +client_secret="" +insecure_oidc_skip_issuer_verification=true +scope="openid profile email User.Read" +entra_id_allowed_tenants=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant +email_domains="*" +``` diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/nextcloud.md b/docs/versioned_docs/version-7.11.x/configuration/providers/nextcloud.md new file mode 100644 index 0000000000..85ebff0398 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/nextcloud.md @@ -0,0 +1,28 @@ +--- +id: nextcloud +title: NextCloud +--- + +The Nextcloud provider allows you to authenticate against users in your +Nextcloud instance. + +When you are using the Nextcloud provider, you must specify the urls via +configuration, environment variable, or command line argument. Depending +on whether your Nextcloud instance is using pretty urls your urls may be of the +form `/index.php/apps/oauth2/*` or `/apps/oauth2/*`. + +Refer to the [OAuth2 +documentation](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/oauth2.html) +to set up the client id and client secret. Your "Redirection URI" will be +`https://internalapp.yourcompany.com/oauth2/callback`. + +``` + -provider nextcloud + -client-id + -client-secret + -login-url="/index.php/apps/oauth2/authorize" + -redeem-url="/index.php/apps/oauth2/api/v1/token" + -validate-url="/ocs/v2.php/cloud/user?format=json" +``` + +Note: in *all* cases the validate-url will *not* have the `index.php`. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/openid_connect.md b/docs/versioned_docs/version-7.11.x/configuration/providers/openid_connect.md new file mode 100644 index 0000000000..de17005808 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/openid_connect.md @@ -0,0 +1,146 @@ +--- +id: openid_connect +title: OpenID Connect +--- + +OpenID Connect is a spec for OAUTH 2.0 + identity that is implemented by many major providers and several open source projects. + +This provider was originally built against CoreOS Dex, and we will use it as an example. +The OpenID Connect Provider (OIDC) can also be used to connect to other Identity Providers such as Okta, an example can be found below. + +#### Dex + +To configure the OIDC provider for Dex, perform the following steps: + +1. Download Dex: + + ``` + go get github.com/dexidp/dex + ``` + + See the [getting started guide](https://dexidp.io/docs/getting-started/) for more details. + +2. Setup oauth2-proxy with the correct provider and using the default ports and callbacks. Add a configuration block to + the `staticClients` section of `examples/config-dev.yaml`: + + ``` + - id: oauth2-proxy + redirectURIs: + - 'http://127.0.0.1:4180/oauth2/callback' + name: 'oauth2-proxy' + secret: proxy + ``` + +3. Launch Dex: from `$GOPATH/github.com/dexidp/dex`, run: + + ``` + bin/dex serve examples/config-dev.yaml + ``` + +4. In a second terminal, run the oauth2-proxy with the following args: + + ```shell + --provider oidc + --provider-display-name "My OIDC Provider" + --client-id oauth2-proxy + --client-secret proxy + --redirect-url http://127.0.0.1:4180/oauth2/callback + --oidc-issuer-url http://127.0.0.1:5556/dex + --cookie-secure=false + --cookie-secret=secret + --email-domain kilgore.trout + ``` + + To serve the current working directory as a website under the `/static` endpoint, add: + + ```shell + --upstream file://$PWD/#/static/ + ``` + +5. Test the setup by visiting http://127.0.0.1:4180 or http://127.0.0.1:4180/static . + +See also [our local testing environment](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/local-environment) for a self-contained example using Docker and etcd as storage for Dex. + +#### Okta + +To configure the OIDC provider for Okta, perform the following steps: + +1. Log in to Okta using an administrative account. It is suggested you try this in preview first, `example.oktapreview.com` +2. (OPTIONAL) If you want to configure authorization scopes and claims to be passed on to multiple applications, + you may wish to configure an authorization server for each application. Otherwise, the provided `default` will work. + * Navigate to **Security** then select **API** + * Click **Add Authorization Server**, if this option is not available you may require an additional license for a custom + authorization server. + * Fill out the **Name** with something to describe the application you are protecting. e.g. 'Example App'. + * For **Audience**, pick the URL of the application you wish to protect: https://example.corp.com + * Fill out a **Description** + * Add any **Access Policies** you wish to configure to limit application access. + * The default settings will work for other options. + [See Okta documentation for more information on Authorization Servers](https://developer.okta.com/docs/guides/customize-authz-server/overview/) +3. Navigate to **Applications** then select **Add Application**. + * Select **Web** for the **Platform** setting. + * Select **OpenID Connect** and click **Create** + * Pick an **Application Name** such as `Example App`. + * Set the **Login redirect URI** to `https://example.corp.com`. + * Under **General** set the **Allowed grant types** to `Authorization Code` and `Refresh Token`. + * Leave the rest as default, taking note of the `Client ID` and `Client Secret`. + * Under **Assignments** select the users or groups you wish to access your application. +4. Create a configuration file like the following: + + ``` + provider = "oidc" + redirect_url = "https://example.corp.com/oauth2/callback" + oidc_issuer_url = "https://corp.okta.com/oauth2/abCd1234" + upstreams = [ + "https://example.corp.com" + ] + email_domains = [ + "corp.com" + ] + client_id = "XXXXX" + client_secret = "YYYYY" + pass_access_token = true + cookie_secret = "ZZZZZ" + skip_provider_button = true + ``` + +The `oidc_issuer_url` is based on URL from your **Authorization Server**'s **Issuer** field in step 2, or simply +https://corp.okta.com. The `client_id` and `client_secret` are configured in the application settings. +Generate a unique `cookie_secret` to encrypt the cookie. + +Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/example.cfg` + +#### Okta - localhost + +1. Signup for developer account: https://developer.okta.com/signup/ +2. Create New `Web` Application: https://$\{your-okta-domain\}/dev/console/apps/new +3. Example Application Settings for localhost: + * **Name:** My Web App + * **Base URIs:** http://localhost:4180/ + * **Login redirect URIs:** http://localhost:4180/oauth2/callback + * **Logout redirect URIs:** http://localhost:4180/ + * **Group assignments:** `Everyone` + * **Grant type allowed:** `Authorization Code` and `Refresh Token` +4. Make note of the `Client ID` and `Client secret`, they are needed in a future step +5. Make note of the **default** Authorization Server Issuer URI from: https://$\{your-okta-domain\}/admin/oauth2/as +6. Example config file `/etc/localhost.cfg` + ```shell + provider = "oidc" + redirect_url = "http://localhost:4180/oauth2/callback" + oidc_issuer_url = "https://$\{your-okta-domain\}/oauth2/default" + upstreams = [ + "http://0.0.0.0:8080" + ] + email_domains = [ + "*" + ] + client_id = "XXX" + client_secret = "YYY" + pass_access_token = true + cookie_secret = "ZZZ" + cookie_secure = false + skip_provider_button = true + # Note: use the following for testing within a container + # http_address = "0.0.0.0:4180" + ``` +7. Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/localhost.cfg` diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/sourcehut.md b/docs/versioned_docs/version-7.11.x/configuration/providers/sourcehut.md new file mode 100644 index 0000000000..88d14622bd --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/sourcehut.md @@ -0,0 +1,25 @@ +--- +id: sourcehut +title: SourceHut +--- + +1. Create a new OAuth client: https://meta.sr.ht/oauth2 +2. Under `Redirection URI` enter the correct URL, i.e. + `https://internal.yourcompany.com/oauth2/callback` + +To use the provider, start with `--provider=sourcehut`. + +If you are hosting your own SourceHut instance, make sure you set the following +to the appropriate URLs: + +```shell + --login-url="https:///oauth2/authorize" + --redeem-url="https:///oauth2/access-token" + --profile-url="https:///query" + --validate-url="https:///profile" +``` + +The default configuration allows everyone with an account to authenticate. +Restricting access is currently only supported by +[email](#email-authentication). + diff --git a/docs/versioned_docs/version-7.11.x/configuration/sessions.md b/docs/versioned_docs/version-7.11.x/configuration/sessions.md new file mode 100644 index 0000000000..e20378170a --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/sessions.md @@ -0,0 +1,99 @@ +--- +id: session_storage +title: Session Storage +--- + +Sessions allow a user's authentication to be tracked between multiple HTTP +requests to a service. + +The OAuth2 Proxy uses a Cookie to track user sessions and will store the session +data in one of the available session storage backends. + +At present the available backends are (as passed to `--session-store-type`): +- [cookie](#cookie-storage) (default) +- [redis](#redis-storage) + +### Cookie Storage + +The Cookie storage backend is the default backend implementation and has +been used in the OAuth2 Proxy historically. + +With the Cookie storage backend, all session information is stored in client +side cookies and transferred with each and every request. + +The following should be known when using this implementation: +- Since all state is stored client side, this storage backend means that the OAuth2 Proxy is completely stateless +- Cookies are signed server side to prevent modification client-side +- It is mandatory to set a `cookie-secret` which will ensure data is encrypted within the cookie data. +- Since multiple requests can be made concurrently to the OAuth2 Proxy, this session implementation +cannot lock sessions and while updating and refreshing sessions, there can be conflicts which force +users to re-authenticate + + +### Redis Storage + +The Redis Storage backend stores encrypted sessions in redis. Instead of sending all the information +back the client for storage, as in the [Cookie storage](#cookie-storage), a ticket is sent back +to the user as the cookie value instead. + +A ticket is composed as the following: + +`{CookieName}-{ticketID}.{secret}` + +Where: + +- The `CookieName` is the OAuth2 cookie name (_oauth2_proxy by default) +- The `ticketID` is a 128-bit random number, hex-encoded +- The `secret` is a 128-bit random number, base64url encoded (no padding). The secret is unique for every session. +- The pair of `{CookieName}-{ticketID}` comprises a ticket handle, and thus, the redis key +to which the session is stored. The encoded session is encrypted with the secret and stored +in redis via the `SETEX` command. + +Encrypting every session uniquely protects the refresh/access/id tokens stored in the session from +disclosure. Additionally, the browser only has to send a short Cookie with every request and not the whole JWT, +which can get quite big. + +Two settings are used to configure the OAuth2 Proxy cookie lifetime: + + --cookie-refresh duration refresh the cookie after this duration; 0 to disable + --cookie-expire duration expire timeframe for cookie 168h0m0s + +The "cookie-expire" value should be equal to the lifetime of the Refresh-Token that is issued by the OAuth2 authorization server. +If it expires earlier and is deleted by the browser, OAuth2 Proxy cannot find the stored Refresh-Tokens in Redis and thus cannot start +the refresh flow to get a new Access-Token. If it is longer, it might be that the old Refresh-Token will be found in Redis but has already +expired. + +The "cookie-refresh" value controls when OAuth2 Proxy tries to refresh an Access-Token. If it is set to "0", the +Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2-Proxy will +refresh the Access-Token after this many seconds whether it is still valid or not. According to the official OAuth2.0 specification +Access-Tokens are not required to follow a specific format. Therefore OAuth2-Proxy cannot check for any expiry date without an +introspection endpoint. If an Access-Token expires and you have not set a corresponding "cookie-refresh" value, you will likely +encounter expiry issues. + +Caveat: It can happen that the Access-Token is valid for e.g. "1m" and a request happens after exactly "59s". +It would pass OAuth2 Proxy and be forwarded to the backend but is just expired when the backend tries to validate +it. This is especially relevant if the backend uses the JWT to make requests to other backends. +For this reason, it's advised to set the cookie-refresh a couple of seconds less than the Access-Token lifespan. + +Recommended settings: + +* cookie_refresh := Access-Token lifespan - 1m +* cookie_expire := Refresh-Token lifespan (i.e. Keycloak client_session_idle) + +#### Usage + +When using the redis store, specify `--session-store-type=redis` as well as the Redis connection URL, via +`--redis-connection-url=redis://host[:port][/db-number]`. + +You may also configure the store for Redis Sentinel. In this case, you will want to use the +`--redis-use-sentinel=true` flag, as well as configure the flags `--redis-sentinel-master-name` +and `--redis-sentinel-connection-urls` appropriately. + +Redis Cluster is available to be the backend store as well. To leverage it, you will need to set the +`--redis-use-cluster=true` flag, and configure the flags `--redis-cluster-connection-urls` appropriately. + +Note that flags `--redis-use-sentinel=true` and `--redis-use-cluster=true` are mutually exclusive. + +Note, if Redis timeout option is set to non-zero, the `--redis-connection-idle-timeout` +must be less than [Redis timeout option](https://redis.io/docs/reference/clients/#client-timeouts). For example: if either redis.conf includes +`timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` diff --git a/docs/versioned_docs/version-7.11.x/configuration/systemd_socket.md b/docs/versioned_docs/version-7.11.x/configuration/systemd_socket.md new file mode 100644 index 0000000000..642e6f3f7b --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/systemd_socket.md @@ -0,0 +1,43 @@ +--- +id: systemd_socket +title: Systemd Socket Activation +--- + +Pass an existing listener created by systemd.socket to oauth2-proxy. + +To do this create a socket: + +oauth2-proxy.socket +``` +[Socket] +ListenStream=%t/oauth2.sock +SocketGroup=www-data +SocketMode=0660 +``` + +Now it's possible to call this socket from e.g. nginx: +``` +server { + location /oauth2/ { + proxy_pass http://unix:/run/oauth2-proxy/oauth2.sock; +} +``` + +The oauth2-proxy should have `--http-address=fd:3` as a parameter. +Here fd is case insensitive and means file descriptor. The number 3 refers to the first non-stdin/stdout/stderr file descriptor, +systemd-socket-activate (which is what systemd.socket uses), listens to what it is told and passes +the listener it created onto the process, starting with file descriptor 3. + +``` +./oauth2-proxy \ + --http-address="fd:3" \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... +``` + +Currently TLS is not supported (but it's doable). diff --git a/docs/versioned_docs/version-7.11.x/configuration/tls.md b/docs/versioned_docs/version-7.11.x/configuration/tls.md new file mode 100644 index 0000000000..68344b22d5 --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/configuration/tls.md @@ -0,0 +1,85 @@ +--- +id: tls +title: TLS Configuration +--- + +There are two recommended configurations: +- [At OAuth2 Proxy](#terminate-tls-at-oauth2-proxy) +- [At Reverse Proxy](#terminate-tls-at-reverse-proxy-eg-nginx) + +### Terminate TLS at OAuth2 Proxy + +1. Configure SSL Termination with OAuth2 Proxy by providing a `--tls-cert-file=/path/to/cert.pem` and `--tls-key-file=/path/to/cert.key`. + + The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --tls-cert-file=/path/to/cert.pem \ + --tls-key-file=/path/to/cert.key \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... + ``` + +2. With this configuration approach the customization of the TLS settings is limited. + + The minimal acceptable TLS version can be set with `--tls-min-version=TLS1.3`. + The defaults set `TLS1.2` as the minimal version. + Regardless of the minimum version configured, `TLS1.3` is currently always used as the maximal version. + + TLS server side cipher suites can be specified with `--tls-cipher-suite=TLS_RSA_WITH_RC4_128_SHA`. + If not specified, the defaults from [`crypto/tls`](https://pkg.go.dev/crypto/tls#CipherSuites) of the currently used `go` version for building `oauth2-proxy` will be used. + A complete list of valid TLS cipher suite names can be found in [`crypto/tls`](https://pkg.go.dev/crypto/tls#pkg-constants). + +### Terminate TLS at Reverse Proxy, e.g. Nginx + +1. Configure SSL Termination with [Nginx](http://nginx.org/) (example config below), Amazon ELB, Google Cloud Platform Load Balancing, or ... + + Because `oauth2-proxy` listens on `127.0.0.1:4180` by default, to listen on all interfaces (needed when using an + external load balancer like Amazon ELB or Google Platform Load Balancing) use `--http-address="0.0.0.0:4180"` or + `--http-address="http://:4180"`. + + Nginx will listen on port `443` and handle SSL connections while proxying to `oauth2-proxy` on port `4180`. + `oauth2-proxy` will then authenticate requests for an upstream application. The external endpoint for this example + would be `https://internal.yourcompany.com/`. + + An example Nginx config follows. Note the use of `Strict-Transport-Security` header to pin requests to SSL + via [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security): + + ``` + server { + listen 443 default ssl; + server_name internal.yourcompany.com; + ssl_certificate /path/to/cert.pem; + ssl_certificate_key /path/to/cert.key; + add_header Strict-Transport-Security max-age=2592000; + + location / { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_connect_timeout 1; + proxy_send_timeout 30; + proxy_read_timeout 30; + } + } + ``` + +2. The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --reverse-proxy=true \ + --client-id=... \ + --client-secret=... + ``` diff --git a/docs/versioned_docs/version-7.11.x/features/endpoints.md b/docs/versioned_docs/version-7.11.x/features/endpoints.md new file mode 100644 index 0000000000..3ec1e2aa8a --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/features/endpoints.md @@ -0,0 +1,47 @@ +--- +id: endpoints +title: Endpoints +--- + +OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable. + +- /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info +- /ping - returns a 200 OK response, which is intended for use with health checks +- /ready - returns a 200 OK response if all the underlying connections (e.g., Redis store) are connected +- /metrics - Metrics endpoint for Prometheus to scrape, serve on the address specified by `--metrics-address`, disabled by default +- /oauth2/sign_in - the login page, which also doubles as a sign-out page (it clears cookies) +- /oauth2/sign_out - this URL is used to clear the session cookie +- /oauth2/start - a URL that will redirect to start the OAuth cycle +- /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url. +- /oauth2/userinfo - the URL is used to return user's email from the session in JSON format. +- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integration#configuring-for-use-with-the-nginx-auth_request-directive) +- /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages + +### Sign out + +To sign the user out, redirect them to `/oauth2/sign_out`. This endpoint only removes oauth2-proxy's own cookies, i.e. the user is still logged in with the authentication provider and may automatically re-login when accessing the application again. You will also need to redirect the user to the authentication provider's sign-out page afterward using the `rd` query parameter, i.e. redirect the user to something like (notice the url-encoding!): + +``` +/oauth2/sign_out?rd=https%3A%2F%2Fmy-oidc-provider.example.com%2Fsign_out_page +``` + +Alternatively, include the redirect URL in the `X-Auth-Request-Redirect` header: + +``` +GET /oauth2/sign_out HTTP/1.1 +X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page +... +``` + +(The "sign_out_page" should be the [`end_session_endpoint`](https://openid.net/specs/openid-connect-session-1_0.html#rfc.section.2.1) from [the metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) if your OIDC provider supports Session Management and Discovery.) + +BEWARE that the domain you want to redirect to (`my-oidc-provider.example.com` in the example) must be added to the [`--whitelist-domain`](../configuration/overview) configuration option otherwise the redirect will be ignored. Make sure to include the actual domain and port (if needed) and not the URL (e.g "localhost:8081" instead of "http://localhost:8081"). + +### Auth + +This endpoint returns 202 Accepted response or a 401 Unauthorized response. + +It can be configured using the following query parameters: +- `allowed_groups`: comma separated list of allowed groups +- `allowed_email_domains`: comma separated list of allowed email domains +- `allowed_emails`: comma separated list of allowed emails diff --git a/docs/versioned_docs/version-7.11.x/installation.md b/docs/versioned_docs/version-7.11.x/installation.md new file mode 100644 index 0000000000..b6fc9d011a --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/installation.md @@ -0,0 +1,32 @@ +--- +id: installation +title: Installation +--- + +1. Choose how to deploy: + + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.11.0`) + + b. Using Go to install the latest release + ```bash + $ go install github.com/oauth2-proxy/oauth2-proxy/v7@latest + ``` + This will install the binary into `$GOPATH/bin`. Make sure you include `$GOPATH` in your `$PATH`. Otherwise your system won't find binaries installed via `go install` + + c. Using a [Prebuilt Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy) (AMD64, PPC64LE, S390x, ARMv6, ARMv7, and ARM64 available) + + d. Using a [Pre-Release Nightly Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy-nightly) (AMD64, PPC64LE, ARMv6, ARMv7, and ARM64 available) + + e. Using the official [Kubernetes manifest](https://github.com/oauth2-proxy/manifests) (Helm) + + Prebuilt binaries can be validated by extracting the file and verifying it against the `sha256sum.txt` checksum file provided for each release starting with version `v3.0.0`. + + ``` + $ sha256sum -c sha256sum.txt + oauth2-proxy-x.y.z.linux-amd64: OK + ``` + +2. [Select a Provider and Register an OAuth Application with a Provider](configuration/providers/index.md) +3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration/overview.md) +4. [Configure SSL or Deploy behind an SSL endpoint](configuration/tls.md) (example provided for Nginx) +5. [Configure OAuth2 Proxy using systemd.socket](configuration/systemd_socket.md) (example provided for Nginx/Systemd) diff --git a/docs/versioned_docs/version-7.11.x/welcome.md b/docs/versioned_docs/version-7.11.x/welcome.md new file mode 100644 index 0000000000..7bceadd80e --- /dev/null +++ b/docs/versioned_docs/version-7.11.x/welcome.md @@ -0,0 +1,23 @@ +--- +id: welcome +title: Welcome +hide_table_of_contents: true +slug: / +--- + +![OAuth2 Proxy](/img/logos/OAuth2_Proxy_horizontal.svg) + +A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others) +to validate accounts by email, domain or group. + +:::note +This repository was forked from [bitly/OAuth2_Proxy](https://github.com/bitly/oauth2_proxy) on 27/11/2018. +Versions v3.0.0 and up are from this fork and will have diverged from any changes in the original fork. +A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/CHANGELOG.md). +::: + +![Sign In Page](/img/sign-in-page.png) + +## Architecture + +![OAuth2 Proxy Architecture](/img/simplified-architecture.svg) diff --git a/docs/versioned_sidebars/version-7.11.x-sidebars.json b/docs/versioned_sidebars/version-7.11.x-sidebars.json new file mode 100644 index 0000000000..0dbf04bd44 --- /dev/null +++ b/docs/versioned_sidebars/version-7.11.x-sidebars.json @@ -0,0 +1,83 @@ +{ + "docs": [ + { + "type": "doc", + "id": "welcome" + }, + { + "type": "doc", + "id": "installation" + }, + { + "type": "doc", + "id": "behaviour" + }, + { + "type": "category", + "label": "Configuration", + "link": { + "type": "doc", + "id": "configuration/overview" + }, + "collapsed": false, + "items": [ + "configuration/overview", + "configuration/integration", + { + "type": "category", + "label": "OAuth Provider Configuration", + "link": { + "type": "doc", + "id": "configuration/providers/index" + }, + "items": [ + "configuration/providers/adfs", + "configuration/providers/azure", + "configuration/providers/bitbucket", + "configuration/providers/digitalocean", + "configuration/providers/facebook", + "configuration/providers/gitea", + "configuration/providers/github", + "configuration/providers/gitlab", + "configuration/providers/google", + "configuration/providers/keycloak", + "configuration/providers/keycloak_oidc", + "configuration/providers/linkedin", + "configuration/providers/login_gov", + "configuration/providers/ms_entra_id", + "configuration/providers/nextcloud", + "configuration/providers/openid_connect" + ] + }, + "configuration/session_storage", + "configuration/tls", + "configuration/alpha-config" + ] + }, + { + "type": "category", + "label": "Features", + "link": { + "type": "doc", + "id": "features/endpoints" + }, + "collapsed": false, + "items": [ + "features/endpoints" + ] + }, + { + "type": "category", + "label": "Community", + "link": { + "type": "doc", + "id": "community/security" + }, + "collapsed": false, + "items": [ + "community/contribution", + "community/security" + ] + } + ] +} diff --git a/docs/versions.json b/docs/versions.json index 2b55679560..b4f8a9f55d 100644 --- a/docs/versions.json +++ b/docs/versions.json @@ -1,4 +1,5 @@ [ + "7.11.x", "7.10.x", "7.9.x", "7.8.x", From 4eaa1bcfd5774fc534d81ca715d1fade07345a5b Mon Sep 17 00:00:00 2001 From: Theron Boerner Date: Fri, 1 Aug 2025 17:36:45 -0500 Subject: [PATCH 029/125] fix: port for local-environment (#3148) --- contrib/local-environment/docker-compose.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 3940f4757a..02c8a16579 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -36,7 +36,7 @@ services: - "./dex.yaml:/dex.yaml" restart: unless-stopped ports: - - 5556:4181/tcp + - 5556:5556/tcp networks: dex: aliases: From 9667bce094bd4e322ce882cd7d3e132822aa3763 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Tue, 12 Aug 2025 08:11:00 +0200 Subject: [PATCH 030/125] feat(e2e): add workflow to trigger e2e test suite through PR comments (#3153) * feat(e2e): add workflow to trigger e2e test suite through PR comments * add empty line --- .github/workflows/e2e.yml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .github/workflows/e2e.yml diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml new file mode 100644 index 0000000000..97f43c7ca1 --- /dev/null +++ b/.github/workflows/e2e.yml @@ -0,0 +1,14 @@ +name: E2E + +on: + issue_comment: + types: [created] + +jobs: + e2e: + uses: oauth2-proxy/e2e-suite/.github/workflows/e2e.yml@main + permissions: + contents: read + statuses: write + issues: write + pull-requests: write From 4c86a4d574952ffa829dbe1f5a32c48b3f2e1ddc Mon Sep 17 00:00:00 2001 From: Kevin Kreitner Date: Tue, 12 Aug 2025 17:41:45 +0200 Subject: [PATCH 031/125] feat: add Cidaas provider (#2273) * Add sensible logging flag to default setup for logger * Fix default value flag for sensitive logging * Remove sensitive logging changes * Add Cidaas provider * Update CHANGELOG.md * Add required groups scope to defaults * Fix tests * Remove if block with protected resource * Fix linting * Adjust provider sorting, fixes * Directly handle error return Co-authored-by: Jan Larwig * Use less deep nesting Co-authored-by: Jan Larwig * Directly handle returned error Co-authored-by: Jan Larwig * Pass provider options to Cidaas provider Co-authored-by: Jan Larwig * Add import for provider options * Fix tests * Fix linting * Add Cidaas doc page * Add Cidaas provider doc page to overview * Fix link in docs * Fix link in docs * Add link to Cidaas * fix provider order in docs and changelog position Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Teko012 <112829523+Teko012@users.noreply.github.com> Co-authored-by: Jan Larwig Co-authored-by: Kevin Kreitner --- CHANGELOG.md | 2 + docs/docs/configuration/providers/cidaas.md | 37 ++ docs/docs/configuration/providers/index.md | 1 + pkg/apis/options/providers.go | 3 + providers/cidaas.go | 144 ++++++ providers/cidaas_test.go | 493 ++++++++++++++++++++ providers/providers.go | 5 +- 7 files changed, 684 insertions(+), 1 deletion(-) create mode 100644 docs/docs/configuration/providers/cidaas.md create mode 100644 providers/cidaas.go create mode 100644 providers/cidaas_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index c830117089..a690916381 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ ## Changes since v7.11.0 +- [#2273](https://github.com/oauth2-proxy/oauth2-proxy/pull/2273) feat: add Cidaas provider (@Bibob7, @Teko012) + # V7.11.0 ## Release Highlights diff --git a/docs/docs/configuration/providers/cidaas.md b/docs/docs/configuration/providers/cidaas.md new file mode 100644 index 0000000000..7a9870181f --- /dev/null +++ b/docs/docs/configuration/providers/cidaas.md @@ -0,0 +1,37 @@ +--- +id: cidaas +title: Cidaas +--- + +[Cidaas](https://www.cidaas.com/) is an Identity as a Service (IDaaS) solution that provides authentication and authorization services. +It supports various protocols including OpenID Connect, OAuth 2.0, and SAML. + +However, Cidaas provides groups and their roles as hierarchical claims, which are not supported by oauth2-proxy yet. +The Cidaas provider transforms the hierarchical claims into a flat list of groups, which can be used by oauth2-proxy. + +Example of groups and roles in Cidaas: + +```json +{ + "groups": [ + { + "groupId": "group1", + "roles": ["role1", "role2"] + }, + { + "groupId": "group2", + "roles": ["role3"] + } + ] +} +``` + +This will be transformed into a flat list of groups: + +```json +{ + "groups": ["group1:role1", "group2:role2", "group2:role3"] +} +``` + +Apart from that the Cidaas provider inherits all the features of the [OpenID Connect provider](openid_connect.md). \ No newline at end of file diff --git a/docs/docs/configuration/providers/index.md b/docs/docs/configuration/providers/index.md index b947c09b7e..713b5cb95e 100644 --- a/docs/docs/configuration/providers/index.md +++ b/docs/docs/configuration/providers/index.md @@ -10,6 +10,7 @@ Valid providers are : - [ADFS](adfs.md) - [Bitbucket](bitbucket.md) +- [Cidaas](cidaas.md) - [DigitalOcean](digitalocean.md) - [Facebook](facebook.md) - [Gitea](gitea.md) diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index ac5652cabb..0f25457585 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -115,6 +115,9 @@ const ( // BitbucketProvider is the provider type for Bitbucket BitbucketProvider ProviderType = "bitbucket" + // CidaasProvider is the provider type for Cidaas IDP + CidaasProvider ProviderType = "cidaas" + // DigitalOceanProvider is the provider type for DigitalOcean DigitalOceanProvider ProviderType = "digitalocean" diff --git a/providers/cidaas.go b/providers/cidaas.go new file mode 100644 index 0000000000..1d526dfc81 --- /dev/null +++ b/providers/cidaas.go @@ -0,0 +1,144 @@ +package providers + +import ( + "context" + "encoding/json" + "errors" + "fmt" + + "github.com/bitly/go-simplejson" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" +) + +type GroupsClaimList []GroupClaimEntry + +type GroupClaimEntry struct { + GroupID string `json:"groupId"` + Roles []string `json:"roles"` +} + +// CIDAASProvider represents an CIDAAS based Identity Provider +type CIDAASProvider struct { + *OIDCProvider +} + +var _ Provider = (*CIDAASProvider)(nil) + +const ( + CidaasProviderName = "CIDAAS" + CidaasGroupName = "cidaas" + CidaasDefaultScope = "openid email profile roles groups" +) + +// NewCIDAASProvider initiates a new CIDAASProvider +func NewCIDAASProvider(p *ProviderData, opts options.Provider) *CIDAASProvider { + p.setProviderDefaults(providerDefaults{ + name: CidaasProviderName, + scope: CidaasDefaultScope, + }) + + return &CIDAASProvider{ + OIDCProvider: NewOIDCProvider(p, opts.OIDCConfig), + } +} + +// RefreshSession uses the RefreshToken to fetch new Access and ID Tokens +func (p *CIDAASProvider) RefreshSession(ctx context.Context, s *sessions.SessionState) (bool, error) { + if s == nil || s.RefreshToken == "" { + return false, nil + } + + if err := p.redeemRefreshToken(ctx, s); err != nil { + return false, fmt.Errorf("unable to redeem refresh token: %w", err) + } + + if err := p.EnrichSession(ctx, s); err != nil { + return false, fmt.Errorf("unable to enrich session data after refresh: %w %v", err, s) + } + + return true, nil +} + +// EnrichSession data to add email an groups +func (p *CIDAASProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error { + if p.ProfileURL.String() == "" && s.Email == "" { + return errors.New("id_token did not contain an email and profileURL is not defined") + } else if p.ProfileURL.String() == "" { + return nil + } + + // Try to get missing emails or groups from a profileURL + if err := p.enrichFromUserinfoEndpoint(ctx, s); err != nil { + logger.Errorf("Warning: Profile URL request failed: %s", err) + } + + // If a mandatory email wasn't set, error at this point. + if s.Email == "" { + return errors.New("neither the id_token nor the profileURL set an email") + } + return nil +} + +// enrichFromUserinfoEndpoint enriches a session's Email & Groups via the JSON response of +// an OIDC profile URL +func (p *CIDAASProvider) enrichFromUserinfoEndpoint(ctx context.Context, s *sessions.SessionState) error { + // profile url is userinfo url in case of Cidaas + respJSON, err := requests.New(p.ProfileURL.String()). + WithContext(ctx). + WithHeaders(makeOIDCHeader(s.AccessToken)). + Do(). + UnmarshalSimpleJSON() + if err != nil { + return err + } + + email, err := respJSON.Get(p.EmailClaim).String() + if err == nil && s.Email == "" { + s.Email = email + } + + groups, err := p.extractGroups(respJSON) + if err != nil { + return fmt.Errorf("extracting groups failed: %w", err) + } + + s.Groups = groups + return nil +} + +func (p *CIDAASProvider) extractGroups(respJSON *simplejson.Json) ([]string, error) { + rawGroupsClaim, err := respJSON.Get(p.GroupsClaim).MarshalJSON() + if err != nil { + return nil, err + } + + var groupsClaimList GroupsClaimList + err = json.Unmarshal(rawGroupsClaim, &groupsClaimList) + if err != nil { + return nil, err + } + + var groups []string + for _, group := range groupsClaimList { + for _, role := range group.Roles { + groups = append(groups, fmt.Sprintf("%s:%s", group.GroupID, role)) + } + } + + // Cidaas specific roles + if rolesVal, rolesClaimExists := respJSON.CheckGet("roles"); rolesClaimExists { + cidaasRoles, err := rolesVal.StringArray() + if err != nil { + return nil, fmt.Errorf("unmarshal roles failed: %w", err) + } + + for _, role := range cidaasRoles { + groups = append(groups, fmt.Sprintf("%s:%s", CidaasGroupName, role)) + } + } + + return groups, nil +} diff --git a/providers/cidaas_test.go b/providers/cidaas_test.go new file mode 100644 index 0000000000..a9ee4e9733 --- /dev/null +++ b/providers/cidaas_test.go @@ -0,0 +1,493 @@ +package providers + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + + "github.com/coreos/go-oidc/v3/oidc" + "github.com/stretchr/testify/assert" + + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" +) + +func newCidaasProvider(serverURL *url.URL) *CIDAASProvider { + providerData := &ProviderData{ + ProviderName: "cidaas", + ClientID: oidcClientID, + ClientSecret: oidcSecret, + LoginURL: &url.URL{ + Scheme: serverURL.Scheme, + Host: serverURL.Host, + Path: "/login/oauth/authorize"}, + RedeemURL: &url.URL{ + Scheme: serverURL.Scheme, + Host: serverURL.Host, + Path: "/login/oauth/access_token"}, + ProfileURL: &url.URL{ + Scheme: serverURL.Scheme, + Host: serverURL.Host, + Path: "/profile"}, + ValidateURL: &url.URL{ + Scheme: serverURL.Scheme, + Host: serverURL.Host, + Path: "/api"}, + Scope: "openid profile offline_access roles groups", + EmailClaim: "email", + GroupsClaim: "groups", + Verifier: oidc.NewVerifier( + oidcIssuer, + mockJWKS{}, + &oidc.Config{ClientID: oidcClientID}, + ), + } + cfg := options.Provider{ + Type: options.CidaasProvider, + } + + p := NewCIDAASProvider(providerData, cfg) + + return p +} + +func newCidaasServer(pathBodyMap map[string][]byte) (*url.URL, *httptest.Server) { + s := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + body, ok := pathBodyMap[r.URL.Path] + if !ok { + rw.WriteHeader(404) + return + } + rw.Header().Add("content-type", "application/json") + _, _ = rw.Write(body) + })) + u, _ := url.Parse(s.URL) + return u, s +} + +func newTestCidaasSetup(pathToBodyMap map[string][]byte) (*httptest.Server, *CIDAASProvider) { + redeemURL, server := newCidaasServer(pathToBodyMap) + provider := newCidaasProvider(redeemURL) + return server, provider +} + +func TestCidaasProvider_EnrichSession(t *testing.T) { + testCases := map[string]struct { + ExistingSession *sessions.SessionState + EmailClaim string + GroupsClaim string + ProfileJSON map[string]interface{} + ExpectedError error + ExpectedSession *sessions.SessionState + }{ + "Missing Email Only in Profile URL": { + ExistingSession: &sessions.SessionState{ + User: "missing.email", + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "email", + GroupsClaim: "groups", + ProfileJSON: map[string]interface{}{ + "email": "found@email.com", + }, + ExpectedError: nil, + ExpectedSession: &sessions.SessionState{ + User: "missing.email", + Email: "found@email.com", + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + "Missing Email with Custom Claim": { + ExistingSession: &sessions.SessionState{ + User: "missing.email", + Groups: []string{"already", "populated"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "weird", + GroupsClaim: "groups", + ProfileJSON: map[string]interface{}{ + "weird": "weird@claim.com", + "groups": []map[string]interface{}{ + { + "groupId": "CIDAAS_USERS", + "roles": []string{"USER"}, + }, + }, + "roles": []string{"USER"}, + }, + ExpectedError: nil, + ExpectedSession: &sessions.SessionState{ + User: "missing.email", + Email: "weird@claim.com", + Groups: []string{"CIDAAS_USERS:USER", "cidaas:USER"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + "Missing Email not in Profile URL": { + ExistingSession: &sessions.SessionState{ + User: "missing.email", + Groups: []string{"already", "populated"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "email", + GroupsClaim: "groups", + ProfileJSON: map[string]interface{}{ + "groups": []map[string]interface{}{ + { + "groupId": "CIDAAS_USERS", + "roles": []string{"USER"}, + }, + }, + "roles": []string{"USER"}, + }, + ExpectedError: errors.New("neither the id_token nor the profileURL set an email"), + ExpectedSession: &sessions.SessionState{ + User: "missing.email", + Groups: []string{"CIDAAS_USERS:USER", "cidaas:USER"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + "Missing Groups": { + ExistingSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: nil, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "email", + GroupsClaim: "groups", + ProfileJSON: map[string]interface{}{ + "email": "new@thing.com", + "groups": []map[string]interface{}{ + { + "groupId": "CIDAAS_USERS", + "roles": []string{"USER"}, + }, + }, + "roles": []string{"USER"}, + }, + ExpectedError: nil, + ExpectedSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: []string{"CIDAAS_USERS:USER", "cidaas:USER"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + "Empty Groups Claims": { + ExistingSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: []string{}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "email", + GroupsClaim: "groups", + ProfileJSON: map[string]interface{}{ + "email": "new@thing.com", + "groups": []map[string]interface{}{ + { + "groupId": "CIDAAS_USERS", + "roles": []string{"USER"}, + }, + }, + "roles": []string{"USER"}, + }, + ExpectedError: nil, + ExpectedSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: []string{"CIDAAS_USERS:USER", "cidaas:USER"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + "Missing Groups with Custom Claim": { + ExistingSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: nil, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "email", + GroupsClaim: "groups2", + ProfileJSON: map[string]interface{}{ + "email": "already@populated.com", + "groups2": []map[string]interface{}{ + { + "sub": "aa5181ea-0841-4ea7-b67f-81882f153d40", + "groupId": "CIDAAS_ADMINS", + "path": "/CIDAAS_ADMINS/", + "roles": []string{"ADMIN"}, + }, + { + "sub": "aa5181ea-0841-4ea7-b67f-81882f153d39", + "groupId": "customers", + "groupType": "Customers", + "path": "/customers/", + "roles": []string{ + "CUSTOMER_ACCOUNT_LOGIN", + "GROUP_ADMIN", + }, + }, + { + "groupId": "CIDAAS_USERS", + "roles": []string{"USER"}, + }, + }, + "roles": []string{"USER"}, + }, + ExpectedError: nil, + ExpectedSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: []string{"CIDAAS_ADMINS:ADMIN", "customers:CUSTOMER_ACCOUNT_LOGIN", "customers:GROUP_ADMIN", "CIDAAS_USERS:USER", "cidaas:USER"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + "Just format Groups": { + ExistingSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: nil, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "email", + GroupsClaim: "groups2", + ProfileJSON: map[string]interface{}{ + "email": "already@populated.com", + "groups2": []map[string]interface{}{ + { + "sub": "aa5181ea-0841-4ea7-b67f-81882f153d39", + "groupId": "customers", + "groupType": "Customers", + "path": "/customers/", + "roles": []string{ + "CUSTOMER_ACCOUNT_LOGIN", + "GROUP_ADMIN", + }, + }, + { + "groupId": "CIDAAS_USERS", + "roles": []string{"USER"}, + }, + }, + "roles": []string{"USER"}, + }, + ExpectedError: nil, + ExpectedSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: []string{"customers:CUSTOMER_ACCOUNT_LOGIN", "customers:GROUP_ADMIN", "CIDAAS_USERS:USER", "cidaas:USER"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + "Missing Groups String Profile URL Response": { + ExistingSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: nil, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "email", + GroupsClaim: "groups", + ProfileJSON: map[string]interface{}{ + "groups": []map[string]interface{}{ + { + "sub": "aa5181ea-0841-4ea7-b67f-81882f153d40", + "groupId": "CIDAAS_ADMINS", + "path": "/CIDAAS_ADMINS/", + "roles": []string{"ADMIN"}, + }, + { + "sub": "aa5181ea-0841-4ea7-b67f-81882f153d39", + "groupId": "customers", + "groupType": "Customers", + "path": "/customers/", + "roles": []string{ + "CUSTOMER_ACCOUNT_LOGIN", + "GROUP_ADMIN", + }, + }, + { + "groupId": "CIDAAS_USERS", + "roles": []string{"USER"}, + }, + }, + "roles": []string{"USER"}, + }, + ExpectedError: nil, + ExpectedSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + Groups: []string{"CIDAAS_ADMINS:ADMIN", "customers:CUSTOMER_ACCOUNT_LOGIN", "customers:GROUP_ADMIN", "CIDAAS_USERS:USER", "cidaas:USER"}, + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + "Missing Groups in both Claims and Profile URL": { + ExistingSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + EmailClaim: "email", + GroupsClaim: "groups", + ProfileJSON: map[string]interface{}{ + "email": "new@thing.com", + }, + ExpectedError: nil, + ExpectedSession: &sessions.SessionState{ + User: "already", + Email: "already@populated.com", + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + }, + } + for testName, tc := range testCases { + t.Run(testName, func(t *testing.T) { + path := "/userinfo/" + jsonResp, err := json.Marshal(tc.ProfileJSON) + assert.NoError(t, err) + + server, provider := newTestCidaasSetup(map[string][]byte{path: jsonResp}) + provider.ProfileURL, err = url.Parse(fmt.Sprintf("%s%s", server.URL, path)) + assert.NoError(t, err) + + provider.EmailClaim = tc.EmailClaim + provider.GroupsClaim = tc.GroupsClaim + defer server.Close() + + err = provider.EnrichSession(context.Background(), tc.ExistingSession) + if tc.ExpectedError != nil { + assert.EqualError(t, err, tc.ExpectedError.Error()) + } else { + assert.NoError(t, err) + } + assert.Equal(t, *tc.ExpectedSession, *tc.ExistingSession) + }) + } +} + +func TestCidaasProvider_RefreshSession(t *testing.T) { + testCases := map[string]struct { + ExistingSession *sessions.SessionState + EmailClaim string + GroupsClaim string + ProfileJSON map[string]interface{} + RedeemJSON redeemTokenResponse + ExpectedRefreshed bool + ExpectedError error + ExpectedEmail string + ExpectedUser string + }{ + "Refresh session successfully": { + ExistingSession: &sessions.SessionState{ + User: "session.is.not.locked", + Email: "found@email.com", + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + RedeemJSON: redeemTokenResponse{ + AccessToken: accessToken, + ExpiresIn: 10, + TokenType: "Bearer", + RefreshToken: refreshToken, + }, + ExpectedRefreshed: true, + ExpectedError: nil, + ExpectedEmail: defaultIDToken.Email, + ExpectedUser: defaultIDToken.Subject, + }, + "Unable to refresh session": { + ExistingSession: &sessions.SessionState{ + User: "session.is.unable.to.refresh", + Email: "found@email.com", + IDToken: idToken, + AccessToken: accessToken, + RefreshToken: refreshToken, + }, + ExpectedRefreshed: false, + ExpectedError: fmt.Errorf("unable to redeem refresh token: failed to get token: oauth2: server response missing access_token"), + ExpectedUser: "session.is.unable.to.refresh", + ExpectedEmail: "found@email.com", + }, + } + for testName, tc := range testCases { + t.Run(testName, func(t *testing.T) { + idToken, _ := newSignedTestIDToken(defaultIDToken) + tc.RedeemJSON.IDToken = idToken + redeemPath := "/token/" + redeemJSONResp, err := json.Marshal(tc.RedeemJSON) + assert.NoError(t, err) + + serverURL, server := newCidaasServer( + map[string][]byte{ + redeemPath: redeemJSONResp, + }) + provider := newCidaasProvider(serverURL) + + // Disable session enrichment, because we want to focus on refreshing logic + provider.ProfileURL, err = url.Parse("") + assert.NoError(t, err) + provider.RedeemURL, err = url.Parse(fmt.Sprintf("%s%s", server.URL, redeemPath)) + assert.NoError(t, err) + + provider.GroupsClaim = tc.GroupsClaim + defer server.Close() + + var refreshed bool + refreshed, err = provider.RefreshSession(context.Background(), tc.ExistingSession) + + if tc.ExpectedError != nil { + assert.EqualError(t, err, tc.ExpectedError.Error()) + } else { + assert.NoError(t, err) + } + assert.Equal(t, tc.ExpectedRefreshed, refreshed) + assert.Equal(t, tc.ExpectedEmail, tc.ExistingSession.Email) + assert.Equal(t, tc.ExpectedUser, tc.ExistingSession.User) + }) + } +} diff --git a/providers/providers.go b/providers/providers.go index 8bc5ff8867..ec00f41265 100644 --- a/providers/providers.go +++ b/providers/providers.go @@ -45,6 +45,8 @@ func NewProvider(providerConfig options.Provider) (Provider, error) { return NewMicrosoftEntraIDProvider(providerData, providerConfig), nil case options.BitbucketProvider: return NewBitbucketProvider(providerData, providerConfig.BitbucketConfig), nil + case options.CidaasProvider: + return NewCIDAASProvider(providerData, providerConfig), nil case options.DigitalOceanProvider: return NewDigitalOceanProvider(providerData), nil case options.FacebookProvider: @@ -188,7 +190,8 @@ func providerRequiresOIDCProviderVerifier(providerType options.ProviderType) (bo options.GoogleProvider, options.KeycloakProvider, options.LinkedInProvider, options.LoginGovProvider, options.NextCloudProvider, options.SourceHutProvider: return false, nil - case options.ADFSProvider, options.AzureProvider, options.GitLabProvider, options.KeycloakOIDCProvider, options.OIDCProvider, options.MicrosoftEntraIDProvider: + case options.OIDCProvider, options.ADFSProvider, options.AzureProvider, options.CidaasProvider, + options.GitLabProvider, options.KeycloakOIDCProvider, options.MicrosoftEntraIDProvider: return true, nil default: return false, fmt.Errorf("unknown provider type: %s", providerType) From 744b31a2c6d6338b09935f7ce0946f2b5f830075 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Mon, 18 Aug 2025 14:27:19 +0200 Subject: [PATCH 032/125] chore(dep): upgrade to latest golang 1.24.6 (#3166) Signed-off-by: Jan Larwig --- CHANGELOG.md | 4 ++++ go.mod | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a690916381..7bcc843bde 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Release Highlights +- 🕵️‍♀️ Vulnerabilities have been addressed + - [CVE-2025-47907](https://pkg.go.dev/vuln/GO-2025-3849) + ## Important Notes ## Breaking Changes @@ -9,6 +12,7 @@ ## Changes since v7.11.0 - [#2273](https://github.com/oauth2-proxy/oauth2-proxy/pull/2273) feat: add Cidaas provider (@Bibob7, @Teko012) +- [#3166](https://github.com/oauth2-proxy/oauth2-proxy/pull/3166) chore(dep): upgrade to latest golang 1.24.6 (@tuunit) # V7.11.0 diff --git a/go.mod b/go.mod index 044f2c2374..24f316e406 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/oauth2-proxy/oauth2-proxy/v7 -go 1.24.5 +go 1.24.6 require ( cloud.google.com/go/compute/metadata v0.7.0 From 82e016954caf174adbe573dafc41108d2efb076f Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 18 Aug 2025 14:27:29 +0200 Subject: [PATCH 033/125] chore(deps): update actions/checkout action to v5 (#3164) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 4 ++-- .github/workflows/codeql.yml | 2 +- .github/workflows/create-release.yml | 2 +- .github/workflows/docs.yml | 4 ++-- .github/workflows/nightly.yml | 2 +- .github/workflows/publish-release.yml | 4 ++-- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 906b5eb574..e33c922954 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,7 +14,7 @@ jobs: COVER: true steps: - name: Check out code - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Set up Go uses: actions/setup-go@v5 @@ -60,7 +60,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out code - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Set up QEMU uses: docker/setup-qemu-action@v3 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index df63060c80..d3ebda1d75 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -32,7 +32,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL diff --git a/.github/workflows/create-release.yml b/.github/workflows/create-release.yml index 8a0008bc54..9ab0d79fd9 100644 --- a/.github/workflows/create-release.yml +++ b/.github/workflows/create-release.yml @@ -17,7 +17,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out code - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: ref: master fetch-depth: 0 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index a60f035977..81ab689a0c 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -14,7 +14,7 @@ jobs: if: github.event_name == 'pull_request' runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Setup Pages id: pages @@ -35,7 +35,7 @@ jobs: if: github.event_name == 'push' || github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - uses: actions/setup-node@v4 with: diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index b2a69d95a1..8b14174b2e 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -12,7 +12,7 @@ jobs: if: github.repository == 'oauth2-proxy/oauth2-proxy' steps: - name: Check out code - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: ref: master fetch-depth: 0 diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 9ebf4b6c94..0aeff2378a 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -20,7 +20,7 @@ jobs: tag: ${{ steps.tag.outputs.version }} steps: - name: Check out code - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: ref: ${{ github.event.pull_request.merge_commit_sha }} fetch-depth: 0 @@ -100,7 +100,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out code - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: ref: ${{ needs.publish.outputs.tag }} fetch-depth: 0 From 26813d3cddafc37c6997f75c7a5e1dfb4a400f39 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 18 Aug 2025 14:27:37 +0200 Subject: [PATCH 034/125] chore(deps): update dependency golangci/golangci-lint to v2.4.0 (#3161) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 2 +- .github/workflows/publish-release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e33c922954..b8bcd58080 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,7 +25,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.2.2 + GOLANGCI_LINT_VERSION: v2.4.0 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 0aeff2378a..f45debabd2 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -50,7 +50,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.2.2 + GOLANGCI_LINT_VERSION: v2.4.0 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter From 3978b2f27fd4af09ae2103aa337768ab0bc5a809 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 18 Aug 2025 14:27:46 +0200 Subject: [PATCH 035/125] chore(deps): update docker-compose (#3160) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index f3f4f900e7..92c1dedf19 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -39,7 +39,7 @@ services: httpbin: {} gitea: - image: gitea/gitea:1.24.3 + image: gitea/gitea:1.24.5 container_name: gitea environment: - USER_UID=1000 diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 3875eda979..91374fbb76 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -78,7 +78,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.2 + image: gcr.io/etcd-development/etcd:v3.6.4 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index d9d4897a77..8636340008 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -34,7 +34,7 @@ services: # Reverse proxy gateway: container_name: traefik - image: traefik:v2.11.27 + image: traefik:v2.11.28 volumes: - "./traefik:/etc/traefik" ports: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 02c8a16579..aaae15515e 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -52,7 +52,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.2 + image: gcr.io/etcd-development/etcd:v3.6.4 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 From f18a0b7b0744eac3c0696764aa6ccdcc08856b0c Mon Sep 17 00:00:00 2001 From: jet <71936688+jet-go@users.noreply.github.com> Date: Tue, 19 Aug 2025 14:56:16 +0900 Subject: [PATCH 036/125] feat: allow disable-keep-alives configuration in upstream (#3156) Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + docs/docs/configuration/alpha_config.md | 1 + docs/docs/configuration/overview.md | 1 + pkg/apis/options/legacy_options.go | 13 +++++++++---- pkg/apis/options/legacy_options_test.go | 11 +++++++++++ pkg/apis/options/upstreams.go | 4 ++++ pkg/upstream/http.go | 4 ++++ pkg/upstream/http_test.go | 26 +++++++++++++++++++------ 8 files changed, 51 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bcc843bde..dce52ba73d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ - [#2273](https://github.com/oauth2-proxy/oauth2-proxy/pull/2273) feat: add Cidaas provider (@Bibob7, @Teko012) - [#3166](https://github.com/oauth2-proxy/oauth2-proxy/pull/3166) chore(dep): upgrade to latest golang 1.24.6 (@tuunit) +- [#3156](https://github.com/oauth2-proxy/oauth2-proxy/pull/3156) feat: allow disable-keep-alives configuration for upstream (@jet-go) # V7.11.0 diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index 018a29413a..28645ceba1 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -551,6 +551,7 @@ Requests will be proxied to this upstream if the path matches the request path. | `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | | `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | | `timeout` | _[Duration](#duration)_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | +| `disableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | ### UpstreamConfig diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index 7c216dfb1f..b159df09cc 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -261,6 +261,7 @@ Provider specific options can be found on their respective subpages. | flag: `--pass-host-header`
toml: `pass_host_header` | bool | pass the request Host Header to upstream | true | | flag: `--proxy-websockets`
toml: `proxy_websockets` | bool | enables WebSocket proxying | true | | flag: `--ssl-upstream-insecure-skip-verify`
toml: `ssl_upstream_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false | +| flag: `--disable-keep-alives`
toml: `disable_keep_alives` | bool | disable HTTP keep-alive connections to the upstream server | false | | flag: `--upstream-timeout`
toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s | | flag: `--upstream`
toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://` for static response. Routing is based on the path | | diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index a2c5f4e3e9..1297522520 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -31,10 +31,11 @@ type LegacyOptions struct { func NewLegacyOptions() *LegacyOptions { return &LegacyOptions{ LegacyUpstreams: LegacyUpstreams{ - PassHostHeader: true, - ProxyWebSockets: true, - FlushInterval: DefaultUpstreamFlushInterval, - Timeout: DefaultUpstreamTimeout, + PassHostHeader: true, + ProxyWebSockets: true, + FlushInterval: DefaultUpstreamFlushInterval, + Timeout: DefaultUpstreamTimeout, + DisableKeepAlives: false, }, LegacyHeaders: LegacyHeaders{ @@ -105,6 +106,7 @@ type LegacyUpstreams struct { SSLUpstreamInsecureSkipVerify bool `flag:"ssl-upstream-insecure-skip-verify" cfg:"ssl_upstream_insecure_skip_verify"` Upstreams []string `flag:"upstream" cfg:"upstreams"` Timeout time.Duration `flag:"upstream-timeout" cfg:"upstream_timeout"` + DisableKeepAlives bool `flag:"disable-keep-alives" cfg:"disable_keep_alives"` } func legacyUpstreamsFlagSet() *pflag.FlagSet { @@ -116,6 +118,7 @@ func legacyUpstreamsFlagSet() *pflag.FlagSet { flagSet.Bool("ssl-upstream-insecure-skip-verify", false, "skip validation of certificates presented when using HTTPS upstreams") flagSet.StringSlice("upstream", []string{}, "the http url(s) of the upstream endpoint, file:// paths for static files or static:// for static response. Routing is based on the path") flagSet.Duration("upstream-timeout", DefaultUpstreamTimeout, "maximum amount of time the server will wait for a response from the upstream") + flagSet.Bool("disable-keep-alives", false, "disable HTTP keep-alive connections to the upstream server") return flagSet } @@ -144,6 +147,7 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { ProxyWebSockets: &l.ProxyWebSockets, FlushInterval: &flushInterval, Timeout: &timeout, + DisableKeepAlives: l.DisableKeepAlives, } switch u.Scheme { @@ -176,6 +180,7 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { upstream.ProxyWebSockets = nil upstream.FlushInterval = nil upstream.Timeout = nil + upstream.DisableKeepAlives = false case "unix": upstream.Path = "/" } diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index 84d7661f7d..9481cf9526 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -24,6 +24,7 @@ var _ = Describe("Legacy Options", func() { legacyOpts.LegacyUpstreams.SSLUpstreamInsecureSkipVerify = true legacyOpts.LegacyUpstreams.Upstreams = []string{"http://foo.bar/baz", "file:///var/lib/website#/bar", "static://204"} legacyOpts.LegacyProvider.ClientID = "oauth-proxy" + legacyOpts.LegacyUpstreams.DisableKeepAlives = false truth := true staticCode := 204 @@ -38,6 +39,7 @@ var _ = Describe("Legacy Options", func() { PassHostHeader: &truth, ProxyWebSockets: &truth, Timeout: &timeout, + DisableKeepAlives: legacyOpts.LegacyUpstreams.DisableKeepAlives, }, { ID: "/bar", @@ -48,6 +50,7 @@ var _ = Describe("Legacy Options", func() { PassHostHeader: &truth, ProxyWebSockets: &truth, Timeout: &timeout, + DisableKeepAlives: legacyOpts.LegacyUpstreams.DisableKeepAlives, }, { ID: "static://204", @@ -60,6 +63,7 @@ var _ = Describe("Legacy Options", func() { PassHostHeader: nil, ProxyWebSockets: nil, Timeout: nil, + DisableKeepAlives: legacyOpts.LegacyUpstreams.DisableKeepAlives, }, }, } @@ -145,6 +149,7 @@ var _ = Describe("Legacy Options", func() { proxyWebSockets := true flushInterval := Duration(5 * time.Second) timeout := Duration(5 * time.Second) + disableKeepAlives := true // Test cases and expected outcomes validHTTP := "http://foo.bar/baz" @@ -157,6 +162,7 @@ var _ = Describe("Legacy Options", func() { ProxyWebSockets: &proxyWebSockets, FlushInterval: &flushInterval, Timeout: &timeout, + DisableKeepAlives: disableKeepAlives, } // Test cases and expected outcomes @@ -170,6 +176,7 @@ var _ = Describe("Legacy Options", func() { ProxyWebSockets: &proxyWebSockets, FlushInterval: &flushInterval, Timeout: &timeout, + DisableKeepAlives: disableKeepAlives, } validFileWithFragment := "file:///var/lib/website#/bar" @@ -182,6 +189,7 @@ var _ = Describe("Legacy Options", func() { ProxyWebSockets: &proxyWebSockets, FlushInterval: &flushInterval, Timeout: &timeout, + DisableKeepAlives: disableKeepAlives, } validStatic := "static://204" @@ -197,6 +205,7 @@ var _ = Describe("Legacy Options", func() { ProxyWebSockets: nil, FlushInterval: nil, Timeout: nil, + DisableKeepAlives: false, } invalidStatic := "static://abc" @@ -212,6 +221,7 @@ var _ = Describe("Legacy Options", func() { ProxyWebSockets: nil, FlushInterval: nil, Timeout: nil, + DisableKeepAlives: false, } invalidHTTP := ":foo" @@ -226,6 +236,7 @@ var _ = Describe("Legacy Options", func() { ProxyWebSockets: proxyWebSockets, FlushInterval: time.Duration(flushInterval), Timeout: time.Duration(timeout), + DisableKeepAlives: disableKeepAlives, } upstreams, err := legacyUpstreams.convert() diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index 971d151e51..b3c7195f97 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -93,4 +93,8 @@ type Upstream struct { // Timeout is the maximum duration the server will wait for a response from the upstream server. // Defaults to 30 seconds. Timeout *Duration `json:"timeout,omitempty"` + + // DisableKeepAlives disables HTTP keep-alive connections to the upstream server. + // Defaults to false. + DisableKeepAlives bool `json:"disableKeepAlives,omitempty"` } diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index 56fcc23e79..7a0e6e847e 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -166,6 +166,10 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr proxy.ErrorHandler = errorHandler } + // Pass on DisableKeepAlives to the transport settings + // to allow for disabling HTTP keep-alive connections + transport.DisableKeepAlives = upstream.DisableKeepAlives + // Apply the customized transport to our proxy before returning it proxy.Transport = transport diff --git a/pkg/upstream/http_test.go b/pkg/upstream/http_test.go index 16f75f2dc6..31476df01a 100644 --- a/pkg/upstream/http_test.go +++ b/pkg/upstream/http_test.go @@ -372,12 +372,13 @@ var _ = Describe("HTTP Upstream Suite", func() { }) type newUpstreamTableInput struct { - proxyWebSockets bool - flushInterval options.Duration - skipVerify bool - sigData *options.SignatureData - errorHandler func(http.ResponseWriter, *http.Request, error) - timeout options.Duration + proxyWebSockets bool + flushInterval options.Duration + skipVerify bool + sigData *options.SignatureData + errorHandler func(http.ResponseWriter, *http.Request, error) + timeout options.Duration + disableKeepAlives bool } DescribeTable("newHTTPUpstreamProxy", @@ -391,6 +392,7 @@ var _ = Describe("HTTP Upstream Suite", func() { InsecureSkipTLSVerify: in.skipVerify, ProxyWebSockets: &in.proxyWebSockets, Timeout: &in.timeout, + DisableKeepAlives: in.disableKeepAlives, } handler := newHTTPUpstreamProxy(upstream, u, in.sigData, in.errorHandler) @@ -412,6 +414,9 @@ var _ = Describe("HTTP Upstream Suite", func() { if in.skipVerify { Expect(transport.TLSClientConfig.InsecureSkipVerify).To(Equal(true)) } + if in.disableKeepAlives { + Expect(transport.DisableKeepAlives).To(Equal(true)) + } }, Entry("with proxy websockets", &newUpstreamTableInput{ proxyWebSockets: true, @@ -463,6 +468,15 @@ var _ = Describe("HTTP Upstream Suite", func() { errorHandler: nil, timeout: options.Duration(5 * time.Second), }), + Entry("with a DisableKeepAlives", &newUpstreamTableInput{ + proxyWebSockets: false, + flushInterval: defaultFlushInterval, + skipVerify: false, + sigData: nil, + errorHandler: nil, + timeout: defaultTimeout, + disableKeepAlives: true, + }), ) Context("with a websocket proxy", func() { From 8c1b2b63bfdba1118f55464a1554a672be9637d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Richard=20Bre=C5=BE=C3=A1k?= Date: Tue, 19 Aug 2025 08:40:36 +0200 Subject: [PATCH 037/125] fix: Gitea team membership (#3150) * bugfix: Gitaa team membership Gitea doesn't properly fill in all the fields like GitHub, so implement a series of fallbacks. Signed-off-by: magic_rb * add changelog, documentation and fix groups list Signed-off-by: Jan Larwig --------- Signed-off-by: magic_rb Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + docs/docs/configuration/providers/gitea.md | 4 +-- providers/github.go | 36 ++++++++++++++++++---- 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dce52ba73d..faecde024d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ - [#2273](https://github.com/oauth2-proxy/oauth2-proxy/pull/2273) feat: add Cidaas provider (@Bibob7, @Teko012) - [#3166](https://github.com/oauth2-proxy/oauth2-proxy/pull/3166) chore(dep): upgrade to latest golang 1.24.6 (@tuunit) - [#3156](https://github.com/oauth2-proxy/oauth2-proxy/pull/3156) feat: allow disable-keep-alives configuration for upstream (@jet-go) +- [#3150](https://github.com/oauth2-proxy/oauth2-proxy/pull/3150) fix: Gitea team membership (@MagicRB, @tuunit) # V7.11.0 diff --git a/docs/docs/configuration/providers/gitea.md b/docs/docs/configuration/providers/gitea.md index 996a5ddbdb..6c679dd0f4 100644 --- a/docs/docs/configuration/providers/gitea.md +++ b/docs/docs/configuration/providers/gitea.md @@ -1,10 +1,10 @@ --- id: gitea -title: Gitea +title: Gitea / Forgejo --- :::note -This is not actually its own provider. For more details and options please refer to the [GitHub Provider Options](github.md) +This is not actually a fully serparate provider. For more details and options please refer to the [GitHub Provider Options](github.md) ::: 1. Create a new application: `https://< your gitea host >/user/settings/applications` diff --git a/providers/github.go b/providers/github.go index 749fcc0377..09f10083e1 100644 --- a/providers/github.go +++ b/providers/github.go @@ -460,10 +460,14 @@ func (p *GitHubProvider) getOrgAndTeam(ctx context.Context, s *sessions.SessionS } func (p *GitHubProvider) getOrgs(ctx context.Context, s *sessions.SessionState) error { - // https://docs.github.com/en/rest/orgs/orgs#list-organizations-for-the-authenticated-user type Organization struct { - Login string `json:"login"` + // Support for Github organizations + // https://docs.github.com/en/rest/orgs/orgs#list-organizations-for-the-authenticated-user + Login string `json:"login,omitempty"` + // Support for Gitea organizations + // https://docs.gitea.com/api/1.24/#tag/organization/operation/orgGetAll + Name string `json:"name,omitempty"` } pn := 1 @@ -490,8 +494,16 @@ func (p *GitHubProvider) getOrgs(ctx context.Context, s *sessions.SessionState) } for _, org := range orgs { - logger.Printf("Member of Github Organization:%q", org.Login) - s.Groups = append(s.Groups, org.Login) + var orgName string + if len(org.Login) > 0 { + orgName = org.Login + logger.Printf("Member of Github Organization: %q", orgName) + } else { + orgName = org.Name + logger.Printf("Member of Gitea Organization: %q", orgName) + } + + s.Groups = append(s.Groups, orgName) } pn++ } @@ -506,6 +518,7 @@ func (p *GitHubProvider) getTeams(ctx context.Context, s *sessions.SessionState) Slug string `json:"slug"` Org struct { Login string `json:"login"` + Name string `json:"name"` } `json:"organization"` } @@ -533,8 +546,19 @@ func (p *GitHubProvider) getTeams(ctx context.Context, s *sessions.SessionState) } for _, team := range teams { - logger.Printf("Member of Github Organization/Team: %q/%q", team.Org.Login, team.Slug) - s.Groups = append(s.Groups, fmt.Sprintf("%s%s%s", team.Org.Login, orgTeamSeparator, team.Slug)) + var orgName, teamName string + + if len(team.Org.Login) > 0 { + orgName = team.Org.Login + teamName = team.Slug + logger.Printf("Member of Github Organization/Team: %q/%q", orgName, teamName) + } else { + orgName = team.Org.Name + teamName = team.Name + logger.Printf("Member of Gitea Organization/Team: %q/%q", orgName, teamName) + } + + s.Groups = append(s.Groups, fmt.Sprintf("%s%s%s", orgName, orgTeamSeparator, teamName)) } pn++ From 413d4f697632a270516a482910a157470b58f28f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 19 Aug 2025 05:58:41 +0000 Subject: [PATCH 038/125] add new docs version 7.12.x Signed-off-by: Jan Larwig --- .../version-7.12.x/behaviour.md | 11 + .../version-7.12.x/community/contribution.md | 89 +++ .../version-7.12.x/community/security.md | 49 ++ .../configuration/alpha_config.md | 565 ++++++++++++++++++ .../configuration/alpha_config.md.tmpl | 139 +++++ .../configuration/integration.md | 318 ++++++++++ .../version-7.12.x/configuration/overview.md | 406 +++++++++++++ .../configuration/providers/adfs.md | 19 + .../configuration/providers/bitbucket.md | 25 + .../configuration/providers/cidaas.md | 37 ++ .../configuration/providers/digitalocean.md | 21 + .../configuration/providers/facebook.md | 7 + .../configuration/providers/gitea.md | 24 + .../configuration/providers/github.md | 81 +++ .../configuration/providers/gitlab.md | 49 ++ .../configuration/providers/google.md | 75 +++ .../configuration/providers/index.md | 44 ++ .../configuration/providers/keycloak.md | 36 ++ .../configuration/providers/keycloak_oidc.md | 151 +++++ .../configuration/providers/linkedin.md | 13 + .../configuration/providers/login_gov.md | 79 +++ .../configuration/providers/ms_azure_ad.md | 59 ++ .../configuration/providers/ms_entra_id.md | 197 ++++++ .../configuration/providers/nextcloud.md | 28 + .../configuration/providers/openid_connect.md | 146 +++++ .../configuration/providers/sourcehut.md | 25 + .../version-7.12.x/configuration/sessions.md | 99 +++ .../configuration/systemd_socket.md | 43 ++ .../version-7.12.x/configuration/tls.md | 85 +++ .../version-7.12.x/features/endpoints.md | 47 ++ .../version-7.12.x/installation.md | 32 + docs/versioned_docs/version-7.12.x/welcome.md | 23 + .../version-7.12.x-sidebars.json | 83 +++ docs/versions.json | 1 + 34 files changed, 3106 insertions(+) create mode 100644 docs/versioned_docs/version-7.12.x/behaviour.md create mode 100644 docs/versioned_docs/version-7.12.x/community/contribution.md create mode 100644 docs/versioned_docs/version-7.12.x/community/security.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/alpha_config.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/alpha_config.md.tmpl create mode 100644 docs/versioned_docs/version-7.12.x/configuration/integration.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/overview.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/adfs.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/bitbucket.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/cidaas.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/digitalocean.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/facebook.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/gitea.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/github.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/gitlab.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/google.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/index.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/keycloak.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/keycloak_oidc.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/linkedin.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/login_gov.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/ms_azure_ad.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/ms_entra_id.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/nextcloud.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/openid_connect.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/providers/sourcehut.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/sessions.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/systemd_socket.md create mode 100644 docs/versioned_docs/version-7.12.x/configuration/tls.md create mode 100644 docs/versioned_docs/version-7.12.x/features/endpoints.md create mode 100644 docs/versioned_docs/version-7.12.x/installation.md create mode 100644 docs/versioned_docs/version-7.12.x/welcome.md create mode 100644 docs/versioned_sidebars/version-7.12.x-sidebars.json diff --git a/docs/versioned_docs/version-7.12.x/behaviour.md b/docs/versioned_docs/version-7.12.x/behaviour.md new file mode 100644 index 0000000000..e063d4f966 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/behaviour.md @@ -0,0 +1,11 @@ +--- +id: behaviour +title: Behaviour +--- + +1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). +2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) +3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set +4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) + +Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). diff --git a/docs/versioned_docs/version-7.12.x/community/contribution.md b/docs/versioned_docs/version-7.12.x/community/contribution.md new file mode 100644 index 0000000000..92255eda17 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/community/contribution.md @@ -0,0 +1,89 @@ +--- +id: contribution +title: Contribution Guide +--- + +We track bugs and issues using Github. + +If you find a bug, please open an Issue. When opening an Issue or Pull Request please follow the preconfigured template and take special note of the checkboxes. + +If you want to fix a bug, add a new feature or extend existing functionality, please create a fork, create a feature branch and open a PR back to this repo. +Please mention open bug issue number(s) within your PR if applicable. + +We suggest using [Visual Studio Code](https://code.visualstudio.com/docs/languages/go) with the official [Go for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=golang.go) extension. + + +# Go version + +This project is currently still using go 1.22. You can follow the installation guide for go [here.](https://go.dev/doc/install) And you can find go version 1.22 in the archived section [here.](https://go.dev/dl/) + +# Preparing your fork +Clone your fork, create a feature branch and update the depedencies to get started. +```bash +git clone git@github.com:/oauth2-proxy +cd oauth2-proxy +git branch feature/ +git push --set-upstream origin feature/ +go mod download +``` + + +# Testing / Debugging +For starting oauth2-proxy locally open the debugging tab and create the `launch.json` and select `Go: Launch Package`. + +![Debugging Tab](/img/debug-tab.png) +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch OAuth2-Proxy with Dex", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and dex as an idetity provider + "contrib/local-environment/oauth2-proxy.cfg" + ] + }, + { + "name": "Launch OAuth2-Proxy with Keycloak", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and keycloak as an idetity provider + "contrib/local-environment/oauth2-proxy-keycloak.cfg" + ] + } + ] +} +``` + +Before you can start your local version of oauth2-proxy, you will have to use the provided docker compose files to start a local upstream service and identity provider. We suggest using [httpbin](https://hub.docker.com/r/kennethreitz/httpbin) as your upstream for testing as it allows for request and response introspection of all things HTTP. + +Inside the `contrib/local-environment` directory you can use the `Makefile` for +starting different example setups: + +- Dex as your IdP: `make up` or `make down` +- Dex as your IdP using the alpha-config: `make alpha-config-up` +- Keycloak as your IdP: `make keycloak-up` +- Dex as your IdP & nginx reverse proxy: `make nginx-up` +- and many more... + +Check out the `Makefile` to see what is available. + +The username and password for all setups is usually `admin@example.com` and `password`. + +The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me + +- OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 +- Upstream: http://httpbin.localtest.me:8080 +- Dex: http://dex.localtest.me:5556 + diff --git a/docs/versioned_docs/version-7.12.x/community/security.md b/docs/versioned_docs/version-7.12.x/community/security.md new file mode 100644 index 0000000000..c24b57d9e5 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/community/security.md @@ -0,0 +1,49 @@ +--- +id: security +title: Security +--- + +:::note +OAuth2 Proxy is a community project. +Maintainers do not work on this project full time, and as such, +while we endeavour to respond to disclosures as quickly as possible, +this may take longer than in projects with corporate sponsorship. +::: + +## Security Disclosures + +:::important +If you believe you have found a vulnerability within OAuth2 Proxy or any of its +dependencies, please do NOT open an issue or PR on GitHub, please do NOT post +any details publicly. +::: + +Security disclosures MUST be done in private. +If you have found an issue that you would like to bring to the attention of the +maintenance team for OAuth2 Proxy, please compose an email and send it to the +list of maintainers in our [MAINTAINERS](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS) file. + +Please include as much detail as possible. +Ideally, your disclosure should include: +- A reproducible case that can be used to demonstrate the exploit +- How you discovered this vulnerability +- A potential fix for the issue (if you have thought of one) +- Versions affected (if not present in master) +- Your GitHub ID + +### How will we respond to disclosures? + +We use [GitHub Security Advisories](https://docs.github.com/en/github/managing-security-vulnerabilities/about-github-security-advisories) +to privately discuss fixes for disclosed vulnerabilities. +If you include a GitHub ID with your disclosure we will add you as a collaborator +for the advisory so that you can join the discussion and validate any fixes +we may propose. + +For minor issues and previously disclosed vulnerabilities (typically for +dependencies), we may use regular PRs for fixes and forego the security advisory. + +Once a fix has been agreed upon, we will merge the fix and create a new release. +If we have multiple security issues in flight simultaneously, we may delay +merging fixes until all patches are ready. +We may also backport the fix to previous releases, +but this will be at the discretion of the maintainers. diff --git a/docs/versioned_docs/version-7.12.x/configuration/alpha_config.md b/docs/versioned_docs/version-7.12.x/configuration/alpha_config.md new file mode 100644 index 0000000000..28645ceba1 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/alpha_config.md @@ -0,0 +1,565 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference + + + +### ADFSOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `skipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | + +### AlphaOptions + +AlphaOptions contains alpha structured configuration options. +Usage of these options allows users to access alpha features that are not +available as part of the primary configuration structure for OAuth2 Proxy. + +:::warning +The options within this structure are considered alpha. +They may change between releases without notice. +::: + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | +| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | + +### AzureOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | +| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | + +### BitbucketOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repository` | _string_ | Repository sets restrict logins to user with access to this repository | + +### ClaimSource + +(**Appears on:** [HeaderValue](#headervalue)) + +ClaimSource allows loading a header value from a claim within the session + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### Duration +#### (`string` alias) + +(**Appears on:** [Upstream](#upstream)) + +Duration is as string representation of a period of time. +A duration string is a is a possibly signed sequence of decimal numbers, +each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". +Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + +### GitHubOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `org` | _string_ | Org sets restrict logins to members of this organisation | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository | +| `token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | +| `users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | + +### GitLabOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Group sets restrict logins to members of this group | +| `projects` | _[]string_ | Projects restricts logins to members of these projects | + +### GoogleOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Groups sets restrict logins to members of this Google group | +| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | +| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | +| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | +| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | + +### Header + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Header represents an individual header that will be added to a request or +response header. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | +| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | + +### HeaderValue + +(**Appears on:** [Header](#header)) + +HeaderValue represents a single header value and the sources that can +make up the header value + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### KeycloakOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `groups` | _[]string_ | Group enables to restrict login to members of indicated group | +| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | + +### LoginGovOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | +| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | +| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | + +### LoginURLParameter + +(**Appears on:** [Provider](#provider)) + +LoginURLParameter is the configuration for a single query parameter that +can be passed through from the `/oauth2/start` endpoint to the IdP login +URL. The "default" option specifies the default value or values (if any) +that will be passed to the IdP for this parameter, and "allow" is a list +of options for ways in which this parameter can be set or overridden via +the query string to `/oauth2/start`. +If _only_ a default is specified and no "allow" then the parameter is +effectively fixed - the default value will always be used and anything +passed to the start URL will be ignored. If _only_ "allow" is specified +but no default then the parameter will only be passed on to the IdP if +the caller provides it, and no value will be sent otherwise. + +Examples: + +# A parameter whose value is fixed + +``` +name: organization +default: +- myorg +``` + +A parameter that is not passed by default, but may be set to one of a +fixed set of values + +``` +name: prompt +allow: +- value: login +- value: consent +- value: select_account +``` + +A parameter that is passed by default but may be overridden by one of +a fixed set of values + +``` +name: prompt +default: ["login"] +allow: +- value: consent +- value: select_account +``` + +A parameter that may be overridden, but only by values that match a +regular expression. For example to restrict `login_hint` to email +addresses in your organization's domain: + +``` +name: login_hint +allow: +- pattern: '^[^@]*@example\.com$' +# this allows at most one "@" sign, and requires "example.com" domain. +``` + +Note that the YAML rules around exactly which characters are allowed +and/or require escaping in different types of string literals are +convoluted. For regular expressions the single quoted form is simplest +as backslash is not considered to be an escape character. Alternatively +use the "chomped block" format `|-`: + +``` + - pattern: |- + ^[^@]*@example\.com$ + +``` + +The hyphen is important, a `|` block would have a trailing newline +character. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name specifies the name of the query parameter. | +| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | +| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | + +### MicrosoftEntraIDOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | +| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | + +### OIDCOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | +| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | +| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | +| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | +| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | +| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | +| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | +| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | +| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | +| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | +| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | +| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | + +### Provider + +(**Appears on:** [Providers](#providers)) + +Provider holds all configuration for a single provider + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | +| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | +| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | +| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | +| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | +| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | +| `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. | +| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | +| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | +| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | +| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | +| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | +| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | +| `id` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | +| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | +| `name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | +| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | +| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | +| `loginURL` | _string_ | LoginURL is the authentication endpoint | +| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | +| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | +| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint | +| `profileURL` | _string_ | ProfileURL is the profile access endpoint | +| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | +| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | +| `validateURL` | _string_ | ValidateURL is the access token validation endpoint | +| `scope` | _string_ | Scope is the OAuth scope specification | +| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | +| `code_challenge_method` | _string_ | The code challenge method | +| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | + +### ProviderType +#### (`string` alias) + +(**Appears on:** [Provider](#provider)) + +ProviderType is used to enumerate the different provider type options +Valid options are: adfs, azure, bitbucket, digitalocean facebook, github, +gitlab, google, keycloak, keycloak-oidc, linkedin, login.gov, nextcloud +and oidc. + +### Providers + +#### ([[]Provider](#provider) alias) + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +The provider can be selected using the `provider` configuration value, or +set in the [`providers` array using +AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). +However, [**the feature to implement multiple providers is not +complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +### SecretSource + +(**Appears on:** [ClaimSource](#claimsource), [HeaderValue](#headervalue), [TLS](#tls)) + +SecretSource references an individual secret value. +Only one source within the struct should be defined at any time. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | + +### Server + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Server represents the configuration for an HTTP(S) server + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `BindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Leave blank or set to "-" to disable. | +| `SecureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Leave blank or set to "-" to disable. | +| `TLS` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the
secure traffic and further configuration for the TLS server. | + +### TLS + +(**Appears on:** [Server](#server)) + +TLS contains the information for loading a TLS certificate and key +as well as an optional minimal TLS version that is acceptable. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `Key` | _[SecretSource](#secretsource)_ | Key is the TLS key data to use.
Typically this will come from a file. | +| `Cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.
Typically this will come from a file. | +| `MinVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.
E.g. Set to "TLS1.3" to select TLS version 1.3 | +| `CipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.
E.g.:
- TLS_RSA_WITH_RC4_128_SHA
- TLS_RSA_WITH_AES_256_GCM_SHA384
If not specified, the default Go safe cipher list is used.
List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | + +### URLParameterRule + +(**Appears on:** [LoginURLParameter](#loginurlparameter)) + +URLParameterRule represents a rule by which query parameters +passed to the `/oauth2/start` endpoint are checked to determine whether +they are valid overrides for the given parameter passed to the IdP's +login URL. Either Value or Pattern should be supplied, not both. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _string_ | A Value rule matches just this specific value | +| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | + +### Upstream + +(**Appears on:** [UpstreamConfig](#upstreamconfig)) + +Upstream represents the configuration for an upstream server. +Requests will be proxied to this upstream if the path matches the request path. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `id` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | +| `path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | +| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | +| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | +| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | +| `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | +| `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | +| `flushInterval` | _[Duration](#duration)_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | +| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | +| `timeout` | _[Duration](#duration)_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | +| `disableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | + +### UpstreamConfig + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +UpstreamConfig is a collection of definitions for upstream servers. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | +| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | diff --git a/docs/versioned_docs/version-7.12.x/configuration/alpha_config.md.tmpl b/docs/versioned_docs/version-7.12.x/configuration/alpha_config.md.tmpl new file mode 100644 index 0000000000..8258201f2a --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/alpha_config.md.tmpl @@ -0,0 +1,139 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference diff --git a/docs/versioned_docs/version-7.12.x/configuration/integration.md b/docs/versioned_docs/version-7.12.x/configuration/integration.md new file mode 100644 index 0000000000..05d39281e5 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/integration.md @@ -0,0 +1,318 @@ +--- +id: integration +title: Integration +--- + +## Configuring for use with the Nginx `auth_request` directive + +**This option requires `--reverse-proxy` option to be set.** + +The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: + +```nginx +server { + listen 443 ssl; + server_name ...; + include ssl/ssl.conf; + + location /oauth2/ { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Auth-Request-Redirect $request_uri; + # or, if you are handling multiple domains: + # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; + } + location = /oauth2/auth { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; + # nginx auth_request includes headers but not body + proxy_set_header Content-Length ""; + proxy_pass_request_body off; + } + + location / { + auth_request /oauth2/auth; + error_page 401 =403 /oauth2/sign_in; + + # pass information via X-User and X-Email headers to backend, + # requires running with --set-xauthrequest flag + auth_request_set $user $upstream_http_x_auth_request_user; + auth_request_set $email $upstream_http_x_auth_request_email; + proxy_set_header X-User $user; + proxy_set_header X-Email $email; + + # if you enabled --pass-access-token, this will pass the token to the backend + auth_request_set $token $upstream_http_x_auth_request_access_token; + proxy_set_header X-Access-Token $token; + + # if you enabled --cookie-refresh, this is needed for it to work with auth_request + auth_request_set $auth_cookie $upstream_http_set_cookie; + add_header Set-Cookie $auth_cookie; + + # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb + # limit and so the OAuth2 Proxy splits these into multiple parts. + # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, + # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. + auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; + + # Extract the Cookie attributes from the first Set-Cookie header and append them + # to the second part ($upstream_cookie_* variables only contain the raw cookie content) + if ($auth_cookie ~* "(; .*)") { + set $auth_cookie_name_0 $auth_cookie; + set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; + } + + # Send both Set-Cookie headers now if there was a second part + if ($auth_cookie_name_upstream_1) { + add_header Set-Cookie $auth_cookie_name_0; + add_header Set-Cookie $auth_cookie_name_1; + } + + proxy_pass http://backend/; + # or "root /path/to/site;" or "fastcgi_pass ..." etc + } +} +``` + +When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`. +Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua. +Note that `nginxinc/kubernetes-ingress` does not include the Lua module. + +```yaml +nginx.ingress.kubernetes.io/auth-response-headers: Authorization +nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri +nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth +nginx.ingress.kubernetes.io/configuration-snippet: | + auth_request_set $name_upstream_1 $upstream_cookie_name_1; + + access_by_lua_block { + if ngx.var.name_upstream_1 ~= "" then + ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)") + end + } +``` +It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). + +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=". + +## Configuring for use with the Traefik (v2) `ForwardAuth` middleware + +**This option requires `--reverse-proxy` option to be set.** + +### ForwardAuth with 401 errors middleware + +The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: + +```yaml +http: + routers: + a-service: + rule: "Host(`a-service.example.com`)" + service: a-service-backend + middlewares: + - oauth-errors + - oauth-auth + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth: + rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + oauth-errors: + errors: + status: + - "401-403" + service: oauth-backend + query: "/oauth2/sign_in?rd={url}" +``` + +### ForwardAuth with static upstreams configuration + +Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint + +**Following options need to be set on `oauth2-proxy`:** +- `--upstream=static://202`: Configures a static response for authenticated sessions +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```yaml +http: + routers: + a-service-route-1: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" + service: a-service-backend + middlewares: + - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + a-service-route-2: + rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" + service: a-service-backend + middlewares: + - oauth-auth-wo-redirect # unauthenticated session will return a 401 + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + services-oauth2-route: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth2-proxy-route: + rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + b-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.3:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth-redirect: + forwardAuth: + address: https://oauth.example.com/ + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization + oauth-auth-wo-redirect: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization +``` + +## Configuring for use with the Caddy (v2) `forward_auth` directive + +The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. + +This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. + +**Following options need to be set on `oauth2-proxy`:** +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```nginx title="Caddyfile" +example.com { + # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. + # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. + handle /oauth2/* { + reverse_proxy oauth2-proxy.internal:4180 { + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. + header_up X-Real-IP {remote_host} + header_up X-Forwarded-Uri {uri} + } + } + + # Requests to other paths are first processed by oauth2-proxy for authentication. + handle { + forward_auth oauth2-proxy.internal:4180 { + uri /oauth2/auth + + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. + header_up X-Real-IP {remote_host} + + # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. + # Make sure to configure the --set-xauthrequest flag to enable this feature. + #copy_headers X-Auth-Request-User X-Auth-Request-Email + + # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. + @error status 401 + handle_response @error { + redir * /oauth2/sign_in?rd={scheme}://{host}{uri} + } + } + + # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. + reverse_proxy upstream.internal:3000 + } +} +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.12.x/configuration/overview.md b/docs/versioned_docs/version-7.12.x/configuration/overview.md new file mode 100644 index 0000000000..b159df09cc --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/overview.md @@ -0,0 +1,406 @@ +--- +id: overview +title: Overview +--- + +`oauth2-proxy` can be configured via [command line options](#command-line-options), [environment variables](#environment-variables) or [config file](#config-file) (in decreasing order of precedence, i.e. command line options will overwrite environment variables and environment variables will overwrite configuration file settings). + +## Generating a Cookie Secret + +To generate a strong cookie secret use one of the below commands: + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + + +```shell +python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())' +``` + + + + +```shell +dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64 | tr -d -- '\n' | tr -- '+/' '-_' ; echo +``` + + + + +```shell +openssl rand -base64 32 | tr -- '+/' '-_' +``` + + + + +```powershell +# Add System.Web assembly to session, just in case +Add-Type -AssemblyName System.Web +[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([System.Web.Security.Membership]::GeneratePassword(32,4))).Replace("+","-").Replace("/","_") +``` + + + + +```hcl +# Valid 32 Byte Base64 URL encoding set that will decode to 24 []byte AES-192 secret +resource "random_password" "cookie_secret" { + length = 32 + override_special = "-_" +} +``` + + + + +## Config File + +Every command line argument can be specified in a config file by replacing hyphens (-) with underscores (\_). If the argument can be specified multiple times, the config option should be plural (trailing s). + +An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/oauth2-proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `--config=/etc/oauth2-proxy.cfg` + +## Config Options + +### Command Line Options + +| Flag | Description | +| ----------- | -------------------- | +| `--config` | path to config file | +| `--version` | print version string | + + +### General Provider Options + +Provider specific options can be found on their respective subpages. + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| flag: `--acr-values`
toml: `acr_values` | string | optional, see [docs](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues) | `""` | +| flag: `--allowed-group`
toml: `allowed_groups` | string \| list | Restrict login to members of a group or list of groups. Furthermore, if you aren't setting the `scope` and use `allowed_groups` with the generic OIDC provider the scope `groups` gets added implicitly. | | +| flag: `--approval-prompt`
toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` | +| flag: `--backend-logout-url`
toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | | +| flag: `--client-id`
toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | | +| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret | | +| flag: `--client-secret`
toml: `client_secret` | string | the OAuth Client Secret | | +| flag: `--code-challenge-method`
toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | | +| flag: `--insecure-oidc-allow-unverified-email`
toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false | +| flag: `--insecure-oidc-skip-issuer-verification`
toml: `insecure_oidc_skip_issuer_verification` | bool | allow the OIDC issuer URL to differ from the expected (currently required for Azure multi-tenant compatibility) | false | +| flag: `--insecure-oidc-skip-nonce`
toml: `insecure_oidc_skip_nonce` | bool | skip verifying the OIDC ID Token's nonce claim | true | +| flag: `--jwt-key-file`
toml: `jwt_key_file` | string | path to the private key file in PEM format used to sign the JWT so that you can say something like `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem`: required by login.gov | | +| flag: `--jwt-key`
toml: `jwt_key` | string | private key in PEM format used to sign JWT, so that you can say something like `--jwt-key="${OAUTH2_PROXY_JWT_KEY}"`: required by login.gov | | +| flag: `--login-url`
toml: `login_url` | string | Authentication endpoint | | +| flag: `--auth-request-response-mode`
toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | | +| flag: `--oidc-audience-claim`
toml: `oidc_audience_claims` | string | which OIDC claim contains the audience | `"aud"` | +| flag: `--oidc-email-claim`
toml: `oidc_email_claim` | string | which OIDC claim contains the user's email | `"email"` | +| flag: `--oidc-extra-audience`
toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` | +| flag: `--oidc-groups-claim`
toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` | +| flag: `--oidc-issuer-url`
toml: `oidc_issuer_url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | | +| flag: `--oidc-jwks-url`
toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled and public key files are not provided | | +| flag: `--oidc-public-key-file`
toml: `oidc_public_key_files` | string | Path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times). Required if OIDC discovery is disabled na JWKS URL isn't provided | string \| list | +| flag: `--profile-url`
toml: `profile_url` | string | Profile access endpoint | | +| flag: `--prompt`
toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` | +| flag: `--provider-ca-file`
toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. | +| flag: `--provider-display-name`
toml: `provider_display_name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) | +| flag: `--provider`
toml: `provider` | string | OAuth provider | google | +| flag: `--pubjwk-url`
toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | | +| flag: `--redeem-url`
toml: `redeem_url` | string | Token redemption endpoint | | +| flag: `--scope`
toml:`scope` | string | OAuth scope specification. Every provider has a default list of scopes which will be used in case no scope is configured. | | +| flag: `--skip-claims-from-profile-url`
toml: `skip_claims_from_profile_url` | bool | skip request to Profile URL for resolving claims not present in id_token | false | +| flag: `--skip-oidc-discovery`
toml: `skip_oidc_discovery` | bool | bypass OIDC endpoint discovery. `--login-url`, `--redeem-url` and `--oidc-jwks-url` must be configured in this case | false | +| flag: `--use-system-trust-store`
toml: `use_system_trust_store` | bool | Determines if `provider-ca-file` files and the system trust store are used. If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | false | +| flag: `--validate-url`
toml: `validate_url` | string | Access token validation endpoint | | + +### Cookie Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | +| flag: `--cookie-csrf-expire`
toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m | +| flag: `--cookie-csrf-per-request`
toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false | +| flag: `--cookie-csrf-per-request-limit`
toml: `cookie_csrf_per_request_limit` | int | Sets a limit on the number of CSRF requests cookies that oauth2-proxy will create. The oldest cookie will be removed. Useful if users end up with 431 Request headers too large status codes. Only effective if --cookie-csrf-per-request is true | "infinite" | +| flag: `--cookie-domain`
toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | | +| flag: `--cookie-expire`
toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s | +| flag: `--cookie-httponly`
toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true | +| flag: `--cookie-name`
toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` | +| flag: `--cookie-path`
toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` | +| flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | +| flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | +| flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | +| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | For defining a separate cookie secret file to read the encryption key from | | +| flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | + +[^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) + +### Header Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--basic-auth-password`
toml: `basic_auth_password` | string | the password to set when passing the HTTP Basic Auth header | | +| flag: `--set-xauthrequest`
toml: `set_xauthrequest` | bool | set X-Auth-Request-User, X-Auth-Request-Groups, X-Auth-Request-Email and X-Auth-Request-Preferred-Username response headers (useful in Nginx auth_request mode). When used with `--pass-access-token`, X-Auth-Request-Access-Token is added to response headers. | false | +| flag: `--set-authorization-header`
toml: `set_authorization_header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false | +| flag: `--set-basic-auth`
toml: `set_basic_auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false | +| flag: `--skip-auth-strip-headers`
toml: `skip_auth_strip_headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy | true | +| flag: `--pass-access-token`
toml: `pass_access_token` | bool | pass OAuth access_token to upstream via X-Forwarded-Access-Token header. When used with `--set-xauthrequest` this adds the X-Auth-Request-Access-Token header to the response | false | +| flag: `--pass-authorization-header`
toml: `pass_authorization_header` | bool | pass OIDC IDToken to upstream via Authorization Bearer header | false | +| flag: `--pass-basic-auth`
toml: `pass_basic_auth` | bool | pass HTTP Basic Auth, X-Forwarded-User, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | +| flag: `--prefer-email-to-user`
toml: `prefer_email_to_user` | bool | Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, e.g. htaccess authentication. Used in conjunction with `--pass-basic-auth` and `--pass-user-headers` | false | +| flag: `--pass-user-headers`
toml: `pass_user_headers` | bool | pass X-Forwarded-User, X-Forwarded-Groups, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | + +### Logging Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------- | --------------------------------------------------- | +| flag: `--auth-logging-format`
toml: `auth_logging_format` | string | Template for authentication log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--auth-logging`
toml: `auth_logging` | bool | Log authentication attempts | true | +| flag: `--errors-to-info-log`
toml: `errors_to_info_log` | bool | redirects error-level logging to default log channel instead of stderr | false | +| flag: `--exclude-logging-path`
toml: `exclude_logging_paths` | string | comma separated list of paths to exclude from logging, e.g. `"/ping,/path2"` | `""` (no paths excluded) | +| flag: `--logging-compress`
toml: `logging_compress` | bool | Should rotated log files be compressed using gzip | false | +| flag: `--logging-filename`
toml: `logging_filename` | string | File to log requests to, empty for `stdout` | `""` (stdout) | +| flag: `--logging-local-time`
toml: `logging_local_time` | bool | Use local time in log files and backup filenames instead of UTC | true (local time) | +| flag: `--logging-max-age`
toml: `logging_max_age` | int | Maximum number of days to retain old log files | 7 | +| flag: `--logging-max-backups`
toml: `logging_max_backups` | int | Maximum number of old log files to retain; 0 to disable | 0 | +| flag: `--logging-max-size`
toml: `logging_max_size` | int | Maximum size in megabytes of the log file before rotation | 100 | +| flag: `--request-id-header`
toml: `request_id_header` | string | Request header to use as the request ID in logging | X-Request-Id | +| flag: `--request-logging-format`
toml: `request_logging_format` | string | Template for request log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--request-logging`
toml: `request_logging` | bool | Log requests | true | +| flag: `--silence-ping-logging`
toml: `silence_ping_logging` | bool | disable logging of requests to ping & ready endpoints | false | +| flag: `--standard-logging-format`
toml: `standard_logging_format` | string | Template for standard log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--standard-logging`
toml: `standard_logging` | bool | Log standard runtime information | true | + +### Page Template Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--banner`
toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | | +| flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | +| flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | +| flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | +| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | | +| flag: `--show-debug-on-error`
toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false | + +### Probe Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------- | ------ | ---------------------------------------------------------- | ----------------------------- | +| flag: `--ping-path`
toml: `ping_path` | string | the ping endpoint that can be used for basic health checks | `"/ping"` | +| flag: `--ping-user-agent`
toml: `ping_user_agent` | string | a User-Agent that can be used for basic health checks | `""` (don't check user agent) | +| flag: `--ready-path`
toml: `ready_path` | string | the ready endpoint that can be used for deep health checks | `"/ready"` | +| flag: `--gcp-healthchecks`
toml: `gcp_healthchecks` | bool | Enable GCP/GKE healthcheck endpoints (deprecated) | false | + +### Proxy Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--bearer-token-login-fallback`
toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | + +[^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. + +### Server Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | +| flag: `--http-address`
toml: `http_address` | string | `[http://]:` or `unix://` or `fd:` (case insensitive) to listen on for HTTP clients. Square brackets are required for ipv6 address, e.g. `http://[::1]:4180` | `"127.0.0.1:4180"` | +| flag: `--https-address`
toml: `https_address` | string | `[https://]:` to listen on for HTTPS clients. Square brackets are required for ipv6 address, e.g. `https://[::1]:443` | `":443"` | +| flag: `--metrics-address`
toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` | +| flag: `--metrics-secure-address`
toml: `metrics_secure_address` | string | the address prometheus metrics will be scraped from if using HTTPS | `""` | +| flag: `--metrics-tls-cert-file`
toml: `metrics_tls_cert_file` | string | path to certificate file for secure metrics server | `""` | +| flag: `--metrics-tls-key-file`
toml: `metrics_tls_key_file` | string | path to private key file for secure metrics server | `""` | +| flag: `--tls-cert-file`
toml: `tls_cert_file` | string | path to certificate file | | +| flag: `--tls-key-file`
toml: `tls_key_file` | string | path to private key file | | +| flag: `--tls-cipher-suite`
toml: `tls_cipher_suites` | string \| list | Restricts TLS cipher suites used by server to those listed (e.g. TLS_RSA_WITH_RC4_128_SHA) (may be given multiple times). If not specified, the default Go safe cipher list is used. List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | | +| flag: `--tls-min-version`
toml: `tls_min_version` | string | minimum TLS version that is acceptable, either `"TLS1.2"` or `"TLS1.3"` | `"TLS1.2"` | + +### Session Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--session-cookie-minimal`
toml: `session_cookie_minimal` | bool | strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only) | false | +| flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | +| flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | +| flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | +| flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | +| flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | +| flag: `--redis-sentinel-master-name`
toml: `redis_sentinel_master_name` | string | Redis sentinel master name. Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-sentinel-connection-urls`
toml: `redis_sentinel_connection_urls` | string \| list | List of Redis sentinel connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-use-cluster`
toml: `redis_use_cluster` | bool | Connect to redis cluster. Must set `--redis-cluster-connection-urls` to use this feature | false | +| flag: `--redis-use-sentinel`
toml: `redis_use_sentinel` | bool | Connect to redis via sentinels. Must set `--redis-sentinel-master-name` and `--redis-sentinel-connection-urls` to use this feature | false | +| flag: `--redis-connection-idle-timeout`
toml: `redis_connection_idle_timeout` | int | Redis connection idle timeout seconds. If Redis [timeout](https://redis.io/docs/reference/clients/#client-timeouts) option is set to non-zero, the `--redis-connection-idle-timeout` must be less than Redis timeout option. Example: if either redis.conf includes `timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` | 0 | + +### Upstream Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | +| flag: `--flush-interval`
toml: `flush_interval` | duration | period between flushing response buffers when streaming responses | `"1s"` | +| flag: `--pass-host-header`
toml: `pass_host_header` | bool | pass the request Host Header to upstream | true | +| flag: `--proxy-websockets`
toml: `proxy_websockets` | bool | enables WebSocket proxying | true | +| flag: `--ssl-upstream-insecure-skip-verify`
toml: `ssl_upstream_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false | +| flag: `--disable-keep-alives`
toml: `disable_keep_alives` | bool | disable HTTP keep-alive connections to the upstream server | false | +| flag: `--upstream-timeout`
toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s | +| flag: `--upstream`
toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://` for static response. Routing is based on the path | | + +## Upstreams Configuration + +`oauth2-proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers, unix socket or serve static files from the file system. + +To configure **HTTP and HTTPS upstreams**, provide such a URL in `--upstream=URL`. The scheme+host portion and the path portion are extracted to configure proxying behavior. When processing incoming requests, the path portion becomes a lookup key for selecting the destination server of the proxied request. + +* Upstream URLs *without a trailing slash,* like in `--upstream=http://service2.internal/foo`, will match an incoming request exactly to `/foo` in `https://this.o2p.example.com/foo`, and forward the request on to service2.internal, but not match a request to `https://this.o2p.example.com/foo/more` nor ...`.com/food`. +* Upstream URLs *with a trailing slash,* like in `--upstream=http://service1.internal/foo/`, will match any incoming request to any incoming requests's path *starting with* `/foo/`, like `/foo/` and `/foo/more` and `/foo/lots/more?etc`. + +If multiple `--upstream` URLs' paths match an incoming request, the one with the longest matching path (the most specific match) takes priority over shorter (less specific) ones. + +**Unix socket upstreams** are configured as `unix:///path/to/unix.sock`. + +**Static file paths** are configured as a file:// URL. `file:///var/www/static/` will serve the files from that directory at `http://[oauth2-proxy url]/var/www/static/`, which may not be what you want. You can provide the path to where the files should be available by adding a fragment to the configured URL. The value of the fragment will then be used to specify which path the files are available at, e.g. `file:///var/www/static/#/static/` will make `/var/www/static/` available at `http://[oauth2-proxy url]/static/`. + +Multiple upstreams can either be configured by supplying a comma separated list to the `--upstream` parameter, supplying the parameter multiple times or providing a list in the [config file](#config-file). When multiple upstreams are used routing to them will be based on the path they are set up with. + +## Environment variables + +Every command line argument can be specified as an environment variable by +prefixing it with `OAUTH2_PROXY_`, capitalising it, and replacing hyphens (`-`) +with underscores (`_`). If the argument can be specified multiple times, the +environment variable should be plural (trailing `S`). + +This is particularly useful for storing secrets outside a configuration file +or the command line. + +For example, the `--cookie-secret` flag becomes `OAUTH2_PROXY_COOKIE_SECRET`. +If a flag has the type `string | list` like the `--email-domain` flag it is +available as an environment variable in plural form e.g. `OAUTH2_PROXY_EMAIL_DOMAINS` + +Values for type `string | list` usually have a plural environment variable name +and need to be seperated by `,` e.g. +`OAUTH2_PROXY_SKIP_AUTH_ROUTES="GET=^/api/status,POST=^/api/saved_objects/_import"` + +Please check the type for each [config option](#config-options) first. + +## Logging Configuration + +By default, OAuth2 Proxy logs all output to stdout. Logging can be configured to output to a rotating log file using the `--logging-filename` command. + +If logging to a file you can also configure the maximum file size (`--logging-max-size`), age (`--logging-max-age`), max backup logs (`--logging-max-backups`), and if backup logs should be compressed (`--logging-compress`). + +There are three different types of logging: standard, authentication, and HTTP requests. These can each be enabled or disabled with `--standard-logging`, `--auth-logging`, and `--request-logging`. + +Each type of logging has its own configurable format and variables. By default, these formats are similar to the Apache Combined Log. + +Logging of requests to the `/ping` endpoint (or using `--ping-user-agent`) and the `/ready` endpoint can be disabled with `--silence-ping-logging` reducing log volume. + +## Auth Log Format + +Authentication logs are logs which are guaranteed to contain a username or email address of a user attempting to authenticate. These logs are output by default in the below format: + +``` + - - [2015/03/19 17:20:19] [] +``` + +The status block will contain one of the below strings: + +- `AuthSuccess` If a user has authenticated successfully by any method +- `AuthFailure` If the user failed to authenticate explicitly +- `AuthError` If there was an unexpected error during authentication + +If you require a different format than that, you can configure it with the `--auth-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}} +``` + +Available variables for auth logging: + +| Variable | Example | Description | +| ------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Message | Authenticated via OAuth2 | The details of the auth attempt. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | +| Status | AuthSuccess | The status of the auth request. See above for details. | + +## Request Log Format + +HTTP request logs will output by default in the below format: + +``` + - - [2015/03/19 17:20:19] GET "/path/" HTTP/1.1 "" +``` + +If you require a different format than that, you can configure it with the `--request-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}} +``` + +Available variables for request logging: + +| Variable | Example | Description | +| --------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestDuration | 0.001 | The time in seconds that a request took to process. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| RequestURI | "/oauth2/auth" | The URI path of the request. | +| ResponseSize | 12 | The size in bytes of the response. | +| StatusCode | 200 | The HTTP status code of the response. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| Upstream | - | The upstream data of the HTTP request. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | + +## Standard Log Format + +All other logging that is not covered by the above two types of logging will be output in this standard logging format. This includes configuration information at startup and errors that occur outside of a session. The default format is below: + +``` +[2015/03/19 17:20:19] [main.go:40] +``` + +If you require a different format than that, you can configure it with the `--standard-logging-format` flag. The default format is configured as follows: + +``` +[{{.Timestamp}}] [{{.File}}] {{.Message}} +``` + +Available variables for standard logging: + +| Variable | Example | Description | +| --------- | --------------------------------- | -------------------------------------------------- | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| File | main.go:40 | The file and line number of the logging statement. | +| Message | HTTP: listening on 127.0.0.1:4180 | The details of the log statement. | diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/adfs.md b/docs/versioned_docs/version-7.12.x/configuration/providers/adfs.md new file mode 100644 index 0000000000..ec8d72d2af --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/adfs.md @@ -0,0 +1,19 @@ +--- +id: adfs +title: ADFS +--- + +1. Open the ADFS administration console on your Windows Server and add a new Application Group +2. Provide a name for the integration, select Server Application from the Standalone applications section and click Next +3. Follow the wizard to get the client-id, client-secret and configure the application credentials +4. Configure the proxy with + +``` + --provider=adfs + --client-id= + --client-secret= +``` + +Note: When using the ADFS Auth provider with nginx and the cookie session store you may find the cookie is too large and +doesn't get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the +[redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/bitbucket.md b/docs/versioned_docs/version-7.12.x/configuration/providers/bitbucket.md new file mode 100644 index 0000000000..e31de7526c --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/bitbucket.md @@ -0,0 +1,25 @@ +--- +id: bitbucket +title: BitBucket +--- + +1. [Add a new OAuth consumer](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html) + * In "Callback URL" use `https:///oauth2/callback`, substituting `` with the actual + hostname that oauth2-proxy is running on. + * In Permissions section select: + * Account -> Email + * Team membership -> Read + * Repositories -> Read +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=bitbucket + --client-id= + --client-secret= +``` + +The default configuration allows everyone with Bitbucket account to authenticate. To restrict the access to the team +members use additional configuration option: `--bitbucket-team=`. To restrict the access to only these users +who have access to one selected repository use `--bitbucket-repository=`. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/cidaas.md b/docs/versioned_docs/version-7.12.x/configuration/providers/cidaas.md new file mode 100644 index 0000000000..7a9870181f --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/cidaas.md @@ -0,0 +1,37 @@ +--- +id: cidaas +title: Cidaas +--- + +[Cidaas](https://www.cidaas.com/) is an Identity as a Service (IDaaS) solution that provides authentication and authorization services. +It supports various protocols including OpenID Connect, OAuth 2.0, and SAML. + +However, Cidaas provides groups and their roles as hierarchical claims, which are not supported by oauth2-proxy yet. +The Cidaas provider transforms the hierarchical claims into a flat list of groups, which can be used by oauth2-proxy. + +Example of groups and roles in Cidaas: + +```json +{ + "groups": [ + { + "groupId": "group1", + "roles": ["role1", "role2"] + }, + { + "groupId": "group2", + "roles": ["role3"] + } + ] +} +``` + +This will be transformed into a flat list of groups: + +```json +{ + "groups": ["group1:role1", "group2:role2", "group2:role3"] +} +``` + +Apart from that the Cidaas provider inherits all the features of the [OpenID Connect provider](openid_connect.md). \ No newline at end of file diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/digitalocean.md b/docs/versioned_docs/version-7.12.x/configuration/providers/digitalocean.md new file mode 100644 index 0000000000..f6a1e89181 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/digitalocean.md @@ -0,0 +1,21 @@ +--- +id: digitalocean +title: DigitalOcean +--- + +1. [Create a new OAuth application](https://cloud.digitalocean.com/account/api/applications) + * You can fill in the name, homepage, and description however you wish. + * In the "Application callback URL" field, enter: `https://oauth-proxy/oauth2/callback`, substituting `oauth2-proxy` + with the actual hostname that oauth2-proxy is running on. The URL must match oauth2-proxy's configured redirect URL. +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=digitalocean + --client-id= + --client-secret= +``` + +Alternatively, set the equivalent options in the config file. The redirect URL defaults to +`https:///oauth2/callback`. If you need to change it, you can use the `--redirect-url` command-line option. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/facebook.md b/docs/versioned_docs/version-7.12.x/configuration/providers/facebook.md new file mode 100644 index 0000000000..352c95ce1e --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/facebook.md @@ -0,0 +1,7 @@ +--- +id: facebook +title: Facebook +--- + +1. Create a new FB App from https://developers.facebook.com/ +2. Under FB Login, set your Valid OAuth redirect URIs to `https://internal.yourcompany.com/oauth2/callback` diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/gitea.md b/docs/versioned_docs/version-7.12.x/configuration/providers/gitea.md new file mode 100644 index 0000000000..6c679dd0f4 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/gitea.md @@ -0,0 +1,24 @@ +--- +id: gitea +title: Gitea / Forgejo +--- + +:::note +This is not actually a fully serparate provider. For more details and options please refer to the [GitHub Provider Options](github.md) +::: + +1. Create a new application: `https://< your gitea host >/user/settings/applications` +2. Under `Redirect URI` enter the correct URL i.e. `https:///oauth2/callback` +3. Note the Client ID and Client Secret. +4. Pass the following options to the proxy: + +``` + --provider="github" + --redirect-url="https:///oauth2/callback" + --provider-display-name="Gitea" + --client-id="< client_id as generated by Gitea >" + --client-secret="< client_secret as generated by Gitea >" + --login-url="https://< your gitea host >/login/oauth/authorize" + --redeem-url="https://< your gitea host >/login/oauth/access_token" + --validate-url="https://< your gitea host >/api/v1/user/emails" +``` diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/github.md b/docs/versioned_docs/version-7.12.x/configuration/providers/github.md new file mode 100644 index 0000000000..cebca31411 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/github.md @@ -0,0 +1,81 @@ +--- +id: github +title: GitHub +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------- | ------- | +| `--github-org` | `github_org` | string | restrict logins to members of this organisation | | +| `--github-team` | `github_team` | string | restrict logins to members of any of these teams (slug) or (org:team), comma separated | | +| `--github-repo` | `github_repo` | string | restrict logins to collaborators of this repository formatted as `orgname/repo` | | +| `--github-token` | `github_token` | string | the token to use when verifying repository collaborators (must have push access to the repository) | | +| `--github-user` | `github_users` | string \| list | To allow users to login by username even if they do not belong to the specified org and team or collaborators | | + +## Usage + +1. Create a new project: https://github.com/settings/developers +2. Under `Authorization callback URL` enter the correct url ie `https://internal.yourcompany.com/oauth2/callback` + +The GitHub auth provider supports two additional ways to restrict authentication to either organization and optional +team level access, or to collaborators of a repository. Restricting by these options is normally accompanied with `--email-domain=*`. Additionally, all the organizations and teams a user belongs to are set as part of the `X-Forwarded-Groups` header. e.g. `org1:team1,org1:team2,org2:team1` + +NOTE: When `--github-user` is set, the specified users are allowed to log in even if they do not belong to the specified +org and team or collaborators. + +To restrict access to your organization: + +```shell + # restrict logins to members of this organisation + --github-org="your-org" +``` + +To restrict access to specific teams within an organization: + +```shell + --github-org="your-org" + # restrict logins to members of any of these teams (slug), comma separated + --github-team="team1,team2,team3" +``` + +To restrict to teams within different organizations, keep the organization flag empty and use `--github-team` like so: + +```shell + # keep empty + --github-org="" + # restrict logins to members to any of the following teams (format :, like octo:team1), comma separated + --github-team="org1:team1,org2:team1,org3:team42,octo:cat" +``` + +If you would rather restrict access to collaborators of a repository, those users must either have push access to a +public repository or any access to a private repository: + +```shell + # restrict logins to collaborators of this repository formatted as orgname/repo + --github-repo="" +``` + +If you'd like to allow access to users with **read only** access to a **public** repository you will need to provide a +[token](https://github.com/settings/tokens) for a user that has write access to the repository. The token must be +created with at least the `public_repo` scope: + +```shell + # the token to use when verifying repository collaborators + --github-token="" +``` + +To allow a user to log in with their username even if they do not belong to the specified org and team or collaborators: + +```shell + # allow logins by username, comma separated + --github-user="" +``` + +If you are using GitHub enterprise, make sure you set the following to the appropriate url: + +```shell + --login-url="http(s):///login/oauth/authorize" + --redeem-url="http(s):///login/oauth/access_token" + --validate-url="http(s):///api/v3" +``` diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.12.x/configuration/providers/gitlab.md new file mode 100644 index 0000000000..4cdbbbe1e0 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/gitlab.md @@ -0,0 +1,49 @@ +--- +id: gitlab +title: GitLab +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | +| `--gitlab-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 | | + +## Usage + +This auth provider has been tested against Gitlab version 12.X. Due to Gitlab API changes, it may not work for version +prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)). + +Whether you are using GitLab.com or self-hosting GitLab, follow +[these steps to add an application](https://docs.gitlab.com/integration/oauth_provider/). Make sure to enable at +least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. +https://myapp.com/oauth2/callback. + +If you need projects filtering, add the extra `read_api` scope to your application. + +The following config should be set to ensure that the oauth will work properly. To get a cookie secret follow +[these steps](../overview.md#generating-a-cookie-secret) + +``` + --provider="gitlab" + --redirect-url="https://myapp.com/oauth2/callback" // Should be the same as the redirect url for the application in gitlab + --client-id=GITLAB_CLIENT_ID + --client-secret=GITLAB_CLIENT_SECRET + --cookie-secret=COOKIE_SECRET +``` + +Restricting by group membership is possible with the following option: + +```shell + --gitlab-group="mygroup,myothergroup" # restrict logins to members of any of these groups (slug), separated by a comma +``` + +If you are using self-hosted GitLab, make sure you set the following to the appropriate URL: + +```shell + --oidc-issuer-url="" +``` + +If your self-hosted GitLab is on a subdirectory (e.g. domain.tld/gitlab), as opposed to its own subdomain +(e.g. gitlab.domain.tld), you may need to add a redirect from domain.tld/oauth pointing at e.g. domain.tld/gitlab/oauth. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/google.md b/docs/versioned_docs/version-7.12.x/configuration/providers/google.md new file mode 100644 index 0000000000..ac2a7dfaaf --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/google.md @@ -0,0 +1,75 @@ +--- +id: google +title: Google (default) +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------------------------------------- | -------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------ | -------------------------------------------------- | +| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | +| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). If not specified and service account or default credentials are configured, all user groups will be allowed. | | +| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | +| `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | +| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | + +## Usage + +For Google, the registration steps are: + +1. Create a new project: https://console.developers.google.com/project +2. Choose the new project from the top right project dropdown (only if another project is selected) +3. In the project Dashboard center pane, choose **"APIs & Services"** +4. In the left Nav pane, choose **"Credentials"** +5. In the center pane, choose **"OAuth consent screen"** tab. Fill in **"Product name shown to users"** and hit save. +6. In the center pane, choose **"Credentials"** tab. + - Open the **"New credentials"** drop down + - Choose **"OAuth client ID"** + - Choose **"Web application"** + - Application name is freeform, choose something appropriate + - Authorized JavaScript origins is your domain ex: `https://internal.yourcompany.com` + - Authorized redirect URIs is the location of oauth2/callback ex: `https://internal.yourcompany.com/oauth2/callback` + - Choose **"Create"** +7. Take note of the **Client ID** and **Client Secret** + +It's recommended to refresh sessions on a short interval (1h) with `cookie-refresh` setting which validates that the +account is still authorized. + +#### Restrict auth to specific Google groups on your domain. (optional) + +1. Create a [service account](https://developers.google.com/identity/protocols/oauth2/service-account) and configure it + to use [Application Default Credentials / Workload Identity / Workload Identity Federation (recommended)](#using-application-default-credentials-adc--workload-identity--workload-identity-federation-recommended) or, + alternatively download the JSON. +2. Make note of the Client ID for a future step. +3. Under "APIs & Auth", choose APIs. +4. Click on Admin SDK and then Enable API. +5. Follow the steps on [Set up domain-wide delegation for a service account](https://developers.google.com/workspace/guides/create-credentials#optional_set_up_domain-wide_delegation_for_a_service_account) + and give the client id from step 2 the following oauth scopes: + + ``` + https://www.googleapis.com/auth/admin.directory.group.member.readonly + ``` + +6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access. +7. Create or choose an existing administrative email address on the Gmail domain to assign to the `google-admin-email` + flag. This email will be impersonated by this client to make calls to the Admin SDK. See the note on the link from + step 5 for the reason why. +8. Create or choose an existing email group and set that email to the `google-group` flag. You can pass multiple instances + of this flag with different groups and the user will be checked against all the provided groups. + +(Only if using a JSON file (see step 1)) + +9. Lock down the permissions on the json file downloaded from step 1 so only oauth2-proxy is able to read the file and + set the path to the file in the `google-service-account-json` flag. +10. Restart oauth2-proxy. + +Note: The user is checked against the group members list on initial authentication and every time the token is +refreshed ( about once an hour ). + +##### Using Application Default Credentials (ADC) / Workload Identity / Workload Identity Federation (recommended) +oauth2-proxy can make use of [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials). +When deployed within GCP, this means that it can automatically use the service account attached to the resource. When deployed to GKE, ADC +can be leveraged through a feature called Workload Identity. Follow Google's [guide](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity) +to set up Workload Identity. + +When deployed outside of GCP, [Workload Identity Federation](https://cloud.google.com/docs/authentication/provide-credentials-adc#wlif) might be an option. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/index.md b/docs/versioned_docs/version-7.12.x/configuration/providers/index.md new file mode 100644 index 0000000000..713b5cb95e --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/index.md @@ -0,0 +1,44 @@ +--- +id: index +title: OAuth Provider Configuration +--- + +You will need to register an OAuth application with a Provider (Google, GitHub or another provider), and configure it +with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on. + +Valid providers are : + +- [ADFS](adfs.md) +- [Bitbucket](bitbucket.md) +- [Cidaas](cidaas.md) +- [DigitalOcean](digitalocean.md) +- [Facebook](facebook.md) +- [Gitea](gitea.md) +- [GitHub](github.md) +- [GitLab](gitlab.md) +- [Google](google.md) _default_ +- [Keycloak](keycloak.md) (Deprecated) +- [Keycloak OIDC](keycloak_oidc.md) +- [LinkedIn](linkedin.md) +- [login.gov](login_gov.md) +- [Microsoft Azure](ms_azure_ad.md) (Deprecated) +- [Microsoft Entra ID](ms_entra_id.md) +- [Nextcloud](nextcloud.md) +- [OpenID Connect](openid_connect.md) + +The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the +OpenID Connect provider. + +## Email Authentication + +To authorize a specific email-domain use `--email-domain=yourcompany.com`. To authorize individual email addresses use +`--authenticated-emails-file=/path/to/file` with one email per line. To authorize all email addresses use `--email-domain=*`. + +## Adding a new Provider + +Follow the examples in the [`providers` package](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/) to define a new +`Provider` instance. Add a new `case` to +[`providers.New()`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/providers.go) to allow `oauth2-proxy` to use the +new `Provider`. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/keycloak.md b/docs/versioned_docs/version-7.12.x/configuration/providers/keycloak.md new file mode 100644 index 0000000000..11a1abca1c --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/keycloak.md @@ -0,0 +1,36 @@ +--- +id: keycloak +title: Keycloak (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Keycloak, use [Keycloak OIDC Auth Provider](keycloak_oidc.md) if possible. +::: + +1. Create new client in your Keycloak realm with **Access Type** 'confidential' and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. + +Make sure you set the following to the appropriate url: + +``` + --provider=keycloak + --client-id= + --client-secret= + --login-url="http(s):///auth/realms//protocol/openid-connect/auth" + --redeem-url="http(s):///auth/realms//protocol/openid-connect/token" + --profile-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --validate-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --keycloak-group= + --keycloak-group= +``` + +For group based authorization, the optional `--keycloak-group` (legacy) or `--allowed-group` (global standard) +flags can be used to specify which groups to limit access to. + +If these are unset but a `groups` mapper is set up above in step (3), the provider will still +populate the `X-Forwarded-Groups` header to your upstream server with the `groups` data in the +Keycloak userinfo endpoint response. + +The group management in keycloak is using a tree. If you create a group named admin in keycloak +you should define the 'keycloak-group' value to /admin. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/keycloak_oidc.md b/docs/versioned_docs/version-7.12.x/configuration/providers/keycloak_oidc.md new file mode 100644 index 0000000000..b29096e35d --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/keycloak_oidc.md @@ -0,0 +1,151 @@ +--- +id: keycloak_oidc +title: Keycloak OIDC +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------ | ------- | +| `--allowed-role` | `allowed_roles` | string \| list | restrict logins to users with this role (may be given multiple times). Only works with the keycloak-oidc provider. | | + +## Usage + +``` + --provider=keycloak-oidc + --client-id= + --client-secret= + --redirect-url=https://internal.yourcompany.com/oauth2/callback + --oidc-issuer-url=https:///realms/ // For Keycloak versions <17: --oidc-issuer-url=https:///auth/realms/ + --email-domain= // Validate email domain for users, see option documentation + --allowed-role= // Optional, required realm role + --allowed-role=: // Optional, required client role + --allowed-group= // Optional, requires group client scope + --code-challenge-method=S256 // PKCE +``` + +:::note +Keycloak has updated its admin console and as of version 19.0.0, the new admin console is enabled by default. The +legacy admin console has been announced for removal with the release of version 21.0.0. +::: + +**Keycloak legacy admin console** + +1. Create new client in your Keycloak realm with **Access Type** 'confidential', **Client protocol** 'openid-connect' + and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. +4. Create a mapper with **Mapper Type** 'Audience' and **Included Client Audience** and **Included Custom Audience** set + to your client name. + +**Keycloak new admin console (default as of v19.0.0)** + +The following example shows how to create a simple OIDC client using the new Keycloak admin2 console. However, for best +practices, it is recommended to consult the Keycloak documentation. + +The OIDC client must be configured with an _audience mapper_ to include the client's name in the `aud` claim of the JWT token. +The `aud` claim specifies the intended recipient of the token, and OAuth2 Proxy expects a match against the values of +either `--client-id` or `--oidc-extra-audience`. + +_In Keycloak, claims are added to JWT tokens through the use of mappers at either the realm level using "client scopes" or +through "dedicated" client mappers._ + +**Creating the client** + +1. Create a new OIDC client in your Keycloak realm by navigating to: + **Clients** -> **Create client** + * **Client Type** 'OpenID Connect' + * **Client ID** ``, please complete the remaining fields as appropriate and click **Next**. + * **Client authentication** 'On' + * **Authentication flow** + * **Standard flow** 'selected' + * **Direct access grants** 'deselect' + * _Save the configuration._ + * **Settings / Access settings**: + * **Valid redirect URIs** `https://internal.yourcompany.com/oauth2/callback` + * _Save the configuration._ + * Under the **Credentials** tab you will now be able to locate ``. +2. Configure a dedicated *audience mapper* for your client by navigating to **Clients** -> **\** -> **Client scopes**. +* Access the dedicated mappers pane by clicking **\-dedicated**, located under *Assigned client scope*. + _(It should have a description of "Dedicated scope and mappers for this client")_ + * Click **Configure a new mapper** and select **Audience** + * **Name** 'aud-mapper-\' + * **Included Client Audience** select `` from the dropdown. + * _OAuth2 proxy can be set up to pass both the access and ID JWT tokens to your upstream services. + If you require additional audience entries, you can use the **Included Custom Audience** field in addition + to the "Included Client Audience" dropdown. Note that the "aud" claim of a JWT token should be limited and + only specify its intended recipients._ + * **Add to ID token** 'On' + * **Add to access token** 'On' - [#1916](https://github.com/oauth2-proxy/oauth2-proxy/pull/1916) + * _Save the configuration._ +* Any subsequent dedicated client mappers can be defined by clicking **Dedicated scopes** -> **Add mapper** -> + **By configuration** -> *Select mapper* + +You should now be able to create a test user in Keycloak and get access to the OAuth2 Proxy instance, make sure to set +an email address matching `` and select _Email verified_. + +**Authorization** + +_OAuth2 Proxy will perform authorization by requiring a valid user, this authorization can be extended to take into +account a user's membership in Keycloak `groups`, `realm roles`, and `client roles` using the keycloak-oidc provider options +`--allowed-role` or `--allowed-group`_ + +**Roles** + +_A standard Keycloak installation comes with the required mappers for **realm roles** and **client roles** through the +pre-defined client scope "roles". This ensures that any roles assigned to a user are included in the `JWT` tokens when +using an OIDC client that has the "Full scope allowed" feature activated, the feature is enabled by default._ + +_Creating a realm role_ +* Navigate to **Realm roles** -> **Create role** + * **Role name**, *``* -> **save** + +_Creating a client role_ +* Navigate to **Clients** -> `` -> **Roles** -> **Create role** + * **Role name**, *``* -> **save** + + +_Assign a role to a user_ + +**Users** -> _Username_ -> **Role mapping** -> **Assign role** -> _filter by roles or clients and select_ -> **Assign**. + +Keycloak "realm roles" can be authorized using the `--allowed-role=` option, while "client roles" can be +evaluated using `--allowed-role=:`. + +You may limit the _realm roles_ included in the JWT tokens for any given client by navigating to: +**Clients** -> `` -> **Client scopes** -> _\-dedicated_ -> **Scope** +Disabling **Full scope allowed** activates the **Assign role** option, allowing you to select which roles, if assigned +to a user, will be included in the user's JWT tokens. This can be useful when a user has many associated roles, and you +want to reduce the size and impact of the JWT token. + + +**Groups** + +You may also do authorization on group memberships by using the OAuth2 Proxy option `--allowed-group`. +We will only do a brief description of creating the required _client scope_ **groups** and refer you to read the Keycloak +documentation. + +To summarize, the steps required to authorize Keycloak group membership with OAuth2 Proxy are as follows: + +* Create a new Client Scope with the name **groups** in Keycloak. + * Include a mapper of type **Group Membership**. + * Set the "Token Claim Name" to **groups** or customize by matching it to the `--oidc-groups-claim` option of OAuth2 Proxy. + * If the "Full group path" option is selected, you need to include a "/" separator in the group names defined in the + `--allowed-group` option of OAuth2 Proxy. Example: "/groupname" or "/groupname/child_group". + +After creating the _Client Scope_ named _groups_ you will need to attach it to your client. +**Clients** -> `` -> **Client scopes** -> **Add client scope** -> Select **groups** and choose Optional +and you should now have a client that maps group memberships into the JWT tokens so that Oauth2 Proxy may evaluate them. + +Create a group by navigating to **Groups** -> **Create group** and _add_ your test user as a member. + +The OAuth2 Proxy option `--allowed-group=/groupname` will now allow you to filter on group membership + +Keycloak also has the option of attaching roles to groups, please refer to the Keycloak documentation for more information. + +**Tip** + +To check if roles or groups are added to JWT tokens, you can preview a users token in the Keycloak console by following +these steps: **Clients** -> `` -> **Client scopes** -> **Evaluate**. +Select a _realm user_ and optional _scope parameters_ such as groups, and generate the JSON representation of an access +or id token to examine its contents. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/linkedin.md b/docs/versioned_docs/version-7.12.x/configuration/providers/linkedin.md new file mode 100644 index 0000000000..7d26ec4334 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/linkedin.md @@ -0,0 +1,13 @@ +--- +id: linkedin +title: LinkedIn +--- + +For LinkedIn, the registration steps are: + +1. Create a new project: https://www.linkedin.com/secure/developer +2. In the OAuth User Agreement section: + - In default scope, select r_basicprofile and r_emailaddress. + - In "OAuth 2.0 Redirect URLs", enter `https://internal.yourcompany.com/oauth2/callback` +3. Fill in the remaining required fields and Save. +4. Take note of the **Consumer Key / API Key** and **Consumer Secret / Secret Key** diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/login_gov.md b/docs/versioned_docs/version-7.12.x/configuration/providers/login_gov.md new file mode 100644 index 0000000000..badbe48e69 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/login_gov.md @@ -0,0 +1,79 @@ +--- +id: login_gov +title: Login.gov +--- + +login.gov is an OIDC provider for the US Government. +If you are a US Government agency, you can contact the login.gov team through the contact information +that you can find on https://login.gov/developers/ and work with them to understand how to get login.gov +accounts for integration/test and production access. + +A developer guide is available here: https://developers.login.gov/, though this proxy handles everything +but the data you need to create to register your application in the login.gov dashboard. + +As a demo, we will assume that you are running your application that you want to secure locally on +http://localhost:3000/, that you will be starting your proxy up on http://localhost:4180/, and that +you have an agency integration account for testing. + +First, register your application in the dashboard. The important bits are: +* Identity protocol: make this `Openid connect` +* Issuer: do what they say for OpenID Connect. We will refer to this string as `${LOGINGOV_ISSUER}`. +* Public key: This is a self-signed certificate in .pem format generated from a 2048-bit RSA private key. + A quick way to do this is + `openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -nodes -subj '/C=US/ST=Washington/L=DC/O=GSA/OU=18F/CN=localhost'`. + The contents of the `key.pem` shall be referred to as `${OAUTH2_PROXY_JWT_KEY}`. +* Return to App URL: Make this be `http://localhost:4180/` +* Redirect URIs: Make this be `http://localhost:4180/oauth2/callback`. +* Attribute Bundle: Make sure that email is selected. + +Now start the proxy up with the following options: +``` +./oauth2-proxy -provider login.gov \ + -client-id=${LOGINGOV_ISSUER} \ + -redirect-url=http://localhost:4180/oauth2/callback \ + -oidc-issuer-url=https://idp.int.identitysandbox.gov/ \ + -cookie-secure=false \ + -email-domain=gsa.gov \ + -upstream=http://localhost:3000/ \ + -cookie-secret=somerandomstring12341234567890AB \ + -cookie-domain=localhost \ + -skip-provider-button=true \ + -pubjwk-url=https://idp.int.identitysandbox.gov/api/openid_connect/certs \ + -profile-url=https://idp.int.identitysandbox.gov/api/openid_connect/userinfo \ + -jwt-key="${OAUTH2_PROXY_JWT_KEY}" +``` +You can also set all these options with environment variables, for use in cloud/docker environments. +One tricky thing that you may encounter is that some cloud environments will pass in environment +variables in a docker env-file, which does not allow multiline variables like a PEM file. +If you encounter this, then you can create a `jwt_signing_key.pem` file in the top level +directory of the repo which contains the key in PEM format and then do your docker build. +The docker build process will copy that file into your image which you can then access by +setting the `OAUTH2_PROXY_JWT_KEY_FILE=/etc/ssl/private/jwt_signing_key.pem` +environment variable, or by setting `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem` on the commandline. + +Once it is running, you should be able to go to `http://localhost:4180/` in your browser, +get authenticated by the login.gov integration server, and then get proxied on to your +application running on `http://localhost:3000/`. In a real deployment, you would secure +your application with a firewall or something so that it was only accessible from the +proxy, and you would use real hostnames everywhere. + +#### Skip OIDC discovery + +Some providers do not support OIDC discovery via their issuer URL, so oauth2-proxy cannot simply grab the authorization, +token and jwks URI endpoints from the provider's metadata. + +In this case, you can set the `--skip-oidc-discovery` option, and supply those required endpoints manually: + +``` + -provider oidc + -client-id oauth2-proxy + -client-secret proxy + -redirect-url http://127.0.0.1:4180/oauth2/callback + -oidc-issuer-url http://127.0.0.1:5556 + -skip-oidc-discovery + -login-url http://127.0.0.1:5556/authorize + -redeem-url http://127.0.0.1:5556/token + -oidc-jwks-url http://127.0.0.1:5556/keys + -cookie-secure=false + -email-domain example.com +``` diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/ms_azure_ad.md b/docs/versioned_docs/version-7.12.x/configuration/providers/ms_azure_ad.md new file mode 100644 index 0000000000..4feefc6800 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/ms_azure_ad.md @@ -0,0 +1,59 @@ +--- +id: azure +title: Azure (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Azure, use [Microsoft Entra ID](ms_entra_id.md) if possible. +::: + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | ------ | ---------------------------------------------------------------- | ---------- | +| `--azure-tenant` | `azure_tenant` | string | go to a tenant-specific or common (tenant-independent) endpoint. | `"common"` | +| `--resource` | `resource` | string | The resource that is protected (Azure AD only) | | + +## Usage + +1. Add an application: go to [https://portal.azure.com](https://portal.azure.com), choose **Azure Active Directory**, select + **App registrations** and then click on **New registration**. +2. Pick a name, check the supported account type(single-tenant, multi-tenant, etc). In the **Redirect URI** section create a new + **Web** platform entry for each app that you want to protect by the oauth2 proxy(e.g. + https://internal.yourcompanycom/oauth2/callback). Click **Register**. +3. Next we need to add group read permissions for the app registration, on the **API Permissions** page of the app, click on + **Add a permission**, select **Microsoft Graph**, then select **Application permissions**, then click on **Group** and select + **Group.Read.All**. Hit **Add permissions** and then on **Grant admin consent** (you might need an admin to do this). +
**IMPORTANT**: Even if this permission is listed with **"Admin consent required=No"** the consent might actually + be required, due to AAD policies you won't be able to see. If you get a **"Need admin approval"** during login, + most likely this is what you're missing! +4. Next, if you are planning to use v2.0 Azure Auth endpoint, go to the **Manifest** page and set `"accessTokenAcceptedVersion": 2` + in the App registration manifest file. +5. On the **Certificates & secrets** page of the app, add a new client secret and note down the value after hitting **Add**. +6. Configure the proxy with: +- for V1 Azure Auth endpoint (Azure Active Directory Endpoints - https://login.microsoftonline.com/common/oauth2/authorize) + +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://sts.windows.net/{tenant-id}/ +``` + +- for V2 Azure Auth endpoint (Microsoft Identity Platform Endpoints - https://login.microsoftonline.com/common/oauth2/v2.0/authorize) +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://login.microsoftonline.com/{tenant-id}/v2.0 +``` + +***Notes***: +- When using v2.0 Azure Auth endpoint (`https://login.microsoftonline.com/{tenant-id}/v2.0`) as `--oidc_issuer_url`, in conjunction + with `--resource` flag, be sure to append `/.default` at the end of the resource name. See + https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope for more details. +- When using the Azure Auth provider with nginx and the cookie session store you may find the cookie is too large and doesn't + get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the + [redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.12.x/configuration/providers/ms_entra_id.md new file mode 100644 index 0000000000..c5d9594edd --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/ms_entra_id.md @@ -0,0 +1,197 @@ +--- +id: ms_entra_id +title: Microsoft Entra ID +--- + +Provider for Microsoft Entra ID. Fully compliant with OIDC, with support for group overage and multi-tenant apps. + +## Config Options + +The provider is OIDC-compliant, so all the OIDC parameters are honored. Additional provider-specific configuration parameters are: + +| Flag | Toml Field | Type | Description | Default | +| --------------------------- | -------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--entra-id-allowed-tenant` | `entra_id_allowed_tenants` | string \| list | List of allowed tenants. In case of multi-tenant apps, incoming tokens are issued by different issuers and OIDC issuer verification needs to be disabled. When not specified, all tenants are allowed. Redundant for single-tenant apps (regular ID token validation matches the issuer). | | +| `--entra-id-federated-token-auth` | `entra_id_federated_token_auth` | boolean | Enable oAuth2 client authentication with federated token projected by Entra Workload Identity plugin, instead of client secret. | false | + +## Configure App registration +To begin, create an App registration, set a redirect URI, and generate a secret. All account types are supported, including single-tenant, multi-tenant, multi-tenant with Microsoft accounts, and Microsoft accounts only. + +
+ See Azure Portal example +
+ +
+
+ +
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" # Others are also supported + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + // We don't specify any required API permissions - we allow user consent only + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Configure groups +If you want to make use of groups, you can configure *groups claim* to be present in ID Tokens issued by the App registration. +
+ See Azure Portal example +
+
+ +
+
+
+
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" + + group_membership_claims = [ + "SecurityGroup" + ] + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Scopes and claims +For single-tenant and multi-tenant apps without groups, the only required scope is `openid` (See: [Scopes and permissions](https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#the-openid-scope)). + +To make use of groups - for example use `allowed_groups` setting or authorize based on groups inside your service - you need to enable *groups claims* in the App Registration. When enabled, list of groups is present in the issued ID token. No additional scopes are required besides `openid`. This works up to 200 groups. + +When user has more than 200 group memberships, OAuth2-Proxy attempts to retrieve the complete list from Microsoft Graph API's [`transitiveMemberOf`](https://learn.microsoft.com/en-us/graph/api/user-list-transitivememberof). Endpoint requires `User.Read` scope (delegated permission). This permission can be by default consented by user during first login. Set scope to `openid User.Read` to request user consent. Without proper scope, user with 200+ groups will authenticate with 0 groups. See: [group overages](https://learn.microsoft.com/en-us/security/zero-trust/develop/configure-tokens-group-claims-app-roles#group-overages). + +Alternatively to user consent, both `openid` and `User.Read` permissions can be consented by admistrator. Then, user is not asked for consent on the first login, and group overage works with `openid` scope only. Admin consent can also be required for some tenants. It can be granted with [azuread_service_principal_delegated_permission_grant](https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/service_principal_delegated_permission_grant) terraform resource. + +For personal microsoft accounts, required scope is `openid profile email`. + +See: [Overview of permissions and consent in the Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview). + +### Multi-tenant apps +To authenticate apps from multiple tenants (including personal Microsoft accounts), set the common OIDC issuer url and disable verification: +```toml +oidc_issuer_url=https://login.microsoftonline.com/common/v2.0 +insecure_oidc_skip_issuer_verification=true +``` +`insecure_oidc_skip_issuer_verification` setting is required to disable following checks: +* Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). + +To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. + +### Workload Identity +Provider supports authentication with federated token, without need of using client secret. Following conditions have to be met: + +* Cluster has public OIDC provider URL. For major cloud providers, it can be enabled with a single flag, for example for [Azure Kubernetes Service deployed with Terraform](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster), it's `oidc_issuer_enabled`. +* Workload Identity admission webhook is deployed on the cluster. For AKS, it can be enabled with a flag (`workload_identity_enabled` in Terraform resource), for clusters outside of Azure, it can be installed from [helm chart](https://github.com/Azure/azure-workload-identity). +* Appropriate federated credential is added to application registration. +
+ See federated credential terraform example +``` + resource "azuread_application_federated_identity_credential" "fedcred" { + application_id = azuread_application.application.id # ID of your application + display_name = "federation-cred" + description = "Workload identity for oauth2-proxy" + audiences = ["api://AzureADTokenExchange"] # Fixed value + issuer = "https://cluster-oidc-issuer-url..." + subject = "system:serviceaccount:oauth2-proxy-namespace-name:oauth2-proxy-sa-name" # set proper NS and SA name + } +``` +
+ +* Kubernetes service account associated with oauth2-proxy deployment, is annotated with `azure.workload.identity/client-id: ` +* oauth2-proxy pod is labeled with `azure.workload.identity/use: "true"` +* oauth2-proxy is configured with `entra_id_federated_token_auth` set to `true`. + +`client_secret` setting can be omitted when using federated token authentication. + +See: [Azure Workload Identity documentation](https://azure.github.io/azure-workload-identity/docs/). + +### Example configurations +Single-tenant app without groups (*groups claim* not enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +``` + +Single-tenant app with up to 200 groups (*groups claim* enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +allowed_groups=["ac51800c-2679-4ecb-8130-636380a3b491"] +``` + +Single-tenant app with more than 200 groups: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +``` + +Single-tenant app with more than 200 groups and workload identity enabled: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +entra_id_federated_token_auth=true +``` + +Multi-tenant app with Microsoft personal accounts & one Entra tenant allowed, with group overage considered: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com/common/v2.0" +client_id="" +client_secret="" +insecure_oidc_skip_issuer_verification=true +scope="openid profile email User.Read" +entra_id_allowed_tenants=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant +email_domains="*" +``` diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/nextcloud.md b/docs/versioned_docs/version-7.12.x/configuration/providers/nextcloud.md new file mode 100644 index 0000000000..85ebff0398 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/nextcloud.md @@ -0,0 +1,28 @@ +--- +id: nextcloud +title: NextCloud +--- + +The Nextcloud provider allows you to authenticate against users in your +Nextcloud instance. + +When you are using the Nextcloud provider, you must specify the urls via +configuration, environment variable, or command line argument. Depending +on whether your Nextcloud instance is using pretty urls your urls may be of the +form `/index.php/apps/oauth2/*` or `/apps/oauth2/*`. + +Refer to the [OAuth2 +documentation](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/oauth2.html) +to set up the client id and client secret. Your "Redirection URI" will be +`https://internalapp.yourcompany.com/oauth2/callback`. + +``` + -provider nextcloud + -client-id + -client-secret + -login-url="/index.php/apps/oauth2/authorize" + -redeem-url="/index.php/apps/oauth2/api/v1/token" + -validate-url="/ocs/v2.php/cloud/user?format=json" +``` + +Note: in *all* cases the validate-url will *not* have the `index.php`. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/openid_connect.md b/docs/versioned_docs/version-7.12.x/configuration/providers/openid_connect.md new file mode 100644 index 0000000000..de17005808 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/openid_connect.md @@ -0,0 +1,146 @@ +--- +id: openid_connect +title: OpenID Connect +--- + +OpenID Connect is a spec for OAUTH 2.0 + identity that is implemented by many major providers and several open source projects. + +This provider was originally built against CoreOS Dex, and we will use it as an example. +The OpenID Connect Provider (OIDC) can also be used to connect to other Identity Providers such as Okta, an example can be found below. + +#### Dex + +To configure the OIDC provider for Dex, perform the following steps: + +1. Download Dex: + + ``` + go get github.com/dexidp/dex + ``` + + See the [getting started guide](https://dexidp.io/docs/getting-started/) for more details. + +2. Setup oauth2-proxy with the correct provider and using the default ports and callbacks. Add a configuration block to + the `staticClients` section of `examples/config-dev.yaml`: + + ``` + - id: oauth2-proxy + redirectURIs: + - 'http://127.0.0.1:4180/oauth2/callback' + name: 'oauth2-proxy' + secret: proxy + ``` + +3. Launch Dex: from `$GOPATH/github.com/dexidp/dex`, run: + + ``` + bin/dex serve examples/config-dev.yaml + ``` + +4. In a second terminal, run the oauth2-proxy with the following args: + + ```shell + --provider oidc + --provider-display-name "My OIDC Provider" + --client-id oauth2-proxy + --client-secret proxy + --redirect-url http://127.0.0.1:4180/oauth2/callback + --oidc-issuer-url http://127.0.0.1:5556/dex + --cookie-secure=false + --cookie-secret=secret + --email-domain kilgore.trout + ``` + + To serve the current working directory as a website under the `/static` endpoint, add: + + ```shell + --upstream file://$PWD/#/static/ + ``` + +5. Test the setup by visiting http://127.0.0.1:4180 or http://127.0.0.1:4180/static . + +See also [our local testing environment](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/local-environment) for a self-contained example using Docker and etcd as storage for Dex. + +#### Okta + +To configure the OIDC provider for Okta, perform the following steps: + +1. Log in to Okta using an administrative account. It is suggested you try this in preview first, `example.oktapreview.com` +2. (OPTIONAL) If you want to configure authorization scopes and claims to be passed on to multiple applications, + you may wish to configure an authorization server for each application. Otherwise, the provided `default` will work. + * Navigate to **Security** then select **API** + * Click **Add Authorization Server**, if this option is not available you may require an additional license for a custom + authorization server. + * Fill out the **Name** with something to describe the application you are protecting. e.g. 'Example App'. + * For **Audience**, pick the URL of the application you wish to protect: https://example.corp.com + * Fill out a **Description** + * Add any **Access Policies** you wish to configure to limit application access. + * The default settings will work for other options. + [See Okta documentation for more information on Authorization Servers](https://developer.okta.com/docs/guides/customize-authz-server/overview/) +3. Navigate to **Applications** then select **Add Application**. + * Select **Web** for the **Platform** setting. + * Select **OpenID Connect** and click **Create** + * Pick an **Application Name** such as `Example App`. + * Set the **Login redirect URI** to `https://example.corp.com`. + * Under **General** set the **Allowed grant types** to `Authorization Code` and `Refresh Token`. + * Leave the rest as default, taking note of the `Client ID` and `Client Secret`. + * Under **Assignments** select the users or groups you wish to access your application. +4. Create a configuration file like the following: + + ``` + provider = "oidc" + redirect_url = "https://example.corp.com/oauth2/callback" + oidc_issuer_url = "https://corp.okta.com/oauth2/abCd1234" + upstreams = [ + "https://example.corp.com" + ] + email_domains = [ + "corp.com" + ] + client_id = "XXXXX" + client_secret = "YYYYY" + pass_access_token = true + cookie_secret = "ZZZZZ" + skip_provider_button = true + ``` + +The `oidc_issuer_url` is based on URL from your **Authorization Server**'s **Issuer** field in step 2, or simply +https://corp.okta.com. The `client_id` and `client_secret` are configured in the application settings. +Generate a unique `cookie_secret` to encrypt the cookie. + +Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/example.cfg` + +#### Okta - localhost + +1. Signup for developer account: https://developer.okta.com/signup/ +2. Create New `Web` Application: https://$\{your-okta-domain\}/dev/console/apps/new +3. Example Application Settings for localhost: + * **Name:** My Web App + * **Base URIs:** http://localhost:4180/ + * **Login redirect URIs:** http://localhost:4180/oauth2/callback + * **Logout redirect URIs:** http://localhost:4180/ + * **Group assignments:** `Everyone` + * **Grant type allowed:** `Authorization Code` and `Refresh Token` +4. Make note of the `Client ID` and `Client secret`, they are needed in a future step +5. Make note of the **default** Authorization Server Issuer URI from: https://$\{your-okta-domain\}/admin/oauth2/as +6. Example config file `/etc/localhost.cfg` + ```shell + provider = "oidc" + redirect_url = "http://localhost:4180/oauth2/callback" + oidc_issuer_url = "https://$\{your-okta-domain\}/oauth2/default" + upstreams = [ + "http://0.0.0.0:8080" + ] + email_domains = [ + "*" + ] + client_id = "XXX" + client_secret = "YYY" + pass_access_token = true + cookie_secret = "ZZZ" + cookie_secure = false + skip_provider_button = true + # Note: use the following for testing within a container + # http_address = "0.0.0.0:4180" + ``` +7. Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/localhost.cfg` diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/sourcehut.md b/docs/versioned_docs/version-7.12.x/configuration/providers/sourcehut.md new file mode 100644 index 0000000000..88d14622bd --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/sourcehut.md @@ -0,0 +1,25 @@ +--- +id: sourcehut +title: SourceHut +--- + +1. Create a new OAuth client: https://meta.sr.ht/oauth2 +2. Under `Redirection URI` enter the correct URL, i.e. + `https://internal.yourcompany.com/oauth2/callback` + +To use the provider, start with `--provider=sourcehut`. + +If you are hosting your own SourceHut instance, make sure you set the following +to the appropriate URLs: + +```shell + --login-url="https:///oauth2/authorize" + --redeem-url="https:///oauth2/access-token" + --profile-url="https:///query" + --validate-url="https:///profile" +``` + +The default configuration allows everyone with an account to authenticate. +Restricting access is currently only supported by +[email](#email-authentication). + diff --git a/docs/versioned_docs/version-7.12.x/configuration/sessions.md b/docs/versioned_docs/version-7.12.x/configuration/sessions.md new file mode 100644 index 0000000000..e20378170a --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/sessions.md @@ -0,0 +1,99 @@ +--- +id: session_storage +title: Session Storage +--- + +Sessions allow a user's authentication to be tracked between multiple HTTP +requests to a service. + +The OAuth2 Proxy uses a Cookie to track user sessions and will store the session +data in one of the available session storage backends. + +At present the available backends are (as passed to `--session-store-type`): +- [cookie](#cookie-storage) (default) +- [redis](#redis-storage) + +### Cookie Storage + +The Cookie storage backend is the default backend implementation and has +been used in the OAuth2 Proxy historically. + +With the Cookie storage backend, all session information is stored in client +side cookies and transferred with each and every request. + +The following should be known when using this implementation: +- Since all state is stored client side, this storage backend means that the OAuth2 Proxy is completely stateless +- Cookies are signed server side to prevent modification client-side +- It is mandatory to set a `cookie-secret` which will ensure data is encrypted within the cookie data. +- Since multiple requests can be made concurrently to the OAuth2 Proxy, this session implementation +cannot lock sessions and while updating and refreshing sessions, there can be conflicts which force +users to re-authenticate + + +### Redis Storage + +The Redis Storage backend stores encrypted sessions in redis. Instead of sending all the information +back the client for storage, as in the [Cookie storage](#cookie-storage), a ticket is sent back +to the user as the cookie value instead. + +A ticket is composed as the following: + +`{CookieName}-{ticketID}.{secret}` + +Where: + +- The `CookieName` is the OAuth2 cookie name (_oauth2_proxy by default) +- The `ticketID` is a 128-bit random number, hex-encoded +- The `secret` is a 128-bit random number, base64url encoded (no padding). The secret is unique for every session. +- The pair of `{CookieName}-{ticketID}` comprises a ticket handle, and thus, the redis key +to which the session is stored. The encoded session is encrypted with the secret and stored +in redis via the `SETEX` command. + +Encrypting every session uniquely protects the refresh/access/id tokens stored in the session from +disclosure. Additionally, the browser only has to send a short Cookie with every request and not the whole JWT, +which can get quite big. + +Two settings are used to configure the OAuth2 Proxy cookie lifetime: + + --cookie-refresh duration refresh the cookie after this duration; 0 to disable + --cookie-expire duration expire timeframe for cookie 168h0m0s + +The "cookie-expire" value should be equal to the lifetime of the Refresh-Token that is issued by the OAuth2 authorization server. +If it expires earlier and is deleted by the browser, OAuth2 Proxy cannot find the stored Refresh-Tokens in Redis and thus cannot start +the refresh flow to get a new Access-Token. If it is longer, it might be that the old Refresh-Token will be found in Redis but has already +expired. + +The "cookie-refresh" value controls when OAuth2 Proxy tries to refresh an Access-Token. If it is set to "0", the +Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2-Proxy will +refresh the Access-Token after this many seconds whether it is still valid or not. According to the official OAuth2.0 specification +Access-Tokens are not required to follow a specific format. Therefore OAuth2-Proxy cannot check for any expiry date without an +introspection endpoint. If an Access-Token expires and you have not set a corresponding "cookie-refresh" value, you will likely +encounter expiry issues. + +Caveat: It can happen that the Access-Token is valid for e.g. "1m" and a request happens after exactly "59s". +It would pass OAuth2 Proxy and be forwarded to the backend but is just expired when the backend tries to validate +it. This is especially relevant if the backend uses the JWT to make requests to other backends. +For this reason, it's advised to set the cookie-refresh a couple of seconds less than the Access-Token lifespan. + +Recommended settings: + +* cookie_refresh := Access-Token lifespan - 1m +* cookie_expire := Refresh-Token lifespan (i.e. Keycloak client_session_idle) + +#### Usage + +When using the redis store, specify `--session-store-type=redis` as well as the Redis connection URL, via +`--redis-connection-url=redis://host[:port][/db-number]`. + +You may also configure the store for Redis Sentinel. In this case, you will want to use the +`--redis-use-sentinel=true` flag, as well as configure the flags `--redis-sentinel-master-name` +and `--redis-sentinel-connection-urls` appropriately. + +Redis Cluster is available to be the backend store as well. To leverage it, you will need to set the +`--redis-use-cluster=true` flag, and configure the flags `--redis-cluster-connection-urls` appropriately. + +Note that flags `--redis-use-sentinel=true` and `--redis-use-cluster=true` are mutually exclusive. + +Note, if Redis timeout option is set to non-zero, the `--redis-connection-idle-timeout` +must be less than [Redis timeout option](https://redis.io/docs/reference/clients/#client-timeouts). For example: if either redis.conf includes +`timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` diff --git a/docs/versioned_docs/version-7.12.x/configuration/systemd_socket.md b/docs/versioned_docs/version-7.12.x/configuration/systemd_socket.md new file mode 100644 index 0000000000..642e6f3f7b --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/systemd_socket.md @@ -0,0 +1,43 @@ +--- +id: systemd_socket +title: Systemd Socket Activation +--- + +Pass an existing listener created by systemd.socket to oauth2-proxy. + +To do this create a socket: + +oauth2-proxy.socket +``` +[Socket] +ListenStream=%t/oauth2.sock +SocketGroup=www-data +SocketMode=0660 +``` + +Now it's possible to call this socket from e.g. nginx: +``` +server { + location /oauth2/ { + proxy_pass http://unix:/run/oauth2-proxy/oauth2.sock; +} +``` + +The oauth2-proxy should have `--http-address=fd:3` as a parameter. +Here fd is case insensitive and means file descriptor. The number 3 refers to the first non-stdin/stdout/stderr file descriptor, +systemd-socket-activate (which is what systemd.socket uses), listens to what it is told and passes +the listener it created onto the process, starting with file descriptor 3. + +``` +./oauth2-proxy \ + --http-address="fd:3" \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... +``` + +Currently TLS is not supported (but it's doable). diff --git a/docs/versioned_docs/version-7.12.x/configuration/tls.md b/docs/versioned_docs/version-7.12.x/configuration/tls.md new file mode 100644 index 0000000000..68344b22d5 --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/configuration/tls.md @@ -0,0 +1,85 @@ +--- +id: tls +title: TLS Configuration +--- + +There are two recommended configurations: +- [At OAuth2 Proxy](#terminate-tls-at-oauth2-proxy) +- [At Reverse Proxy](#terminate-tls-at-reverse-proxy-eg-nginx) + +### Terminate TLS at OAuth2 Proxy + +1. Configure SSL Termination with OAuth2 Proxy by providing a `--tls-cert-file=/path/to/cert.pem` and `--tls-key-file=/path/to/cert.key`. + + The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --tls-cert-file=/path/to/cert.pem \ + --tls-key-file=/path/to/cert.key \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... + ``` + +2. With this configuration approach the customization of the TLS settings is limited. + + The minimal acceptable TLS version can be set with `--tls-min-version=TLS1.3`. + The defaults set `TLS1.2` as the minimal version. + Regardless of the minimum version configured, `TLS1.3` is currently always used as the maximal version. + + TLS server side cipher suites can be specified with `--tls-cipher-suite=TLS_RSA_WITH_RC4_128_SHA`. + If not specified, the defaults from [`crypto/tls`](https://pkg.go.dev/crypto/tls#CipherSuites) of the currently used `go` version for building `oauth2-proxy` will be used. + A complete list of valid TLS cipher suite names can be found in [`crypto/tls`](https://pkg.go.dev/crypto/tls#pkg-constants). + +### Terminate TLS at Reverse Proxy, e.g. Nginx + +1. Configure SSL Termination with [Nginx](http://nginx.org/) (example config below), Amazon ELB, Google Cloud Platform Load Balancing, or ... + + Because `oauth2-proxy` listens on `127.0.0.1:4180` by default, to listen on all interfaces (needed when using an + external load balancer like Amazon ELB or Google Platform Load Balancing) use `--http-address="0.0.0.0:4180"` or + `--http-address="http://:4180"`. + + Nginx will listen on port `443` and handle SSL connections while proxying to `oauth2-proxy` on port `4180`. + `oauth2-proxy` will then authenticate requests for an upstream application. The external endpoint for this example + would be `https://internal.yourcompany.com/`. + + An example Nginx config follows. Note the use of `Strict-Transport-Security` header to pin requests to SSL + via [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security): + + ``` + server { + listen 443 default ssl; + server_name internal.yourcompany.com; + ssl_certificate /path/to/cert.pem; + ssl_certificate_key /path/to/cert.key; + add_header Strict-Transport-Security max-age=2592000; + + location / { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_connect_timeout 1; + proxy_send_timeout 30; + proxy_read_timeout 30; + } + } + ``` + +2. The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --reverse-proxy=true \ + --client-id=... \ + --client-secret=... + ``` diff --git a/docs/versioned_docs/version-7.12.x/features/endpoints.md b/docs/versioned_docs/version-7.12.x/features/endpoints.md new file mode 100644 index 0000000000..3ec1e2aa8a --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/features/endpoints.md @@ -0,0 +1,47 @@ +--- +id: endpoints +title: Endpoints +--- + +OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable. + +- /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info +- /ping - returns a 200 OK response, which is intended for use with health checks +- /ready - returns a 200 OK response if all the underlying connections (e.g., Redis store) are connected +- /metrics - Metrics endpoint for Prometheus to scrape, serve on the address specified by `--metrics-address`, disabled by default +- /oauth2/sign_in - the login page, which also doubles as a sign-out page (it clears cookies) +- /oauth2/sign_out - this URL is used to clear the session cookie +- /oauth2/start - a URL that will redirect to start the OAuth cycle +- /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url. +- /oauth2/userinfo - the URL is used to return user's email from the session in JSON format. +- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integration#configuring-for-use-with-the-nginx-auth_request-directive) +- /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages + +### Sign out + +To sign the user out, redirect them to `/oauth2/sign_out`. This endpoint only removes oauth2-proxy's own cookies, i.e. the user is still logged in with the authentication provider and may automatically re-login when accessing the application again. You will also need to redirect the user to the authentication provider's sign-out page afterward using the `rd` query parameter, i.e. redirect the user to something like (notice the url-encoding!): + +``` +/oauth2/sign_out?rd=https%3A%2F%2Fmy-oidc-provider.example.com%2Fsign_out_page +``` + +Alternatively, include the redirect URL in the `X-Auth-Request-Redirect` header: + +``` +GET /oauth2/sign_out HTTP/1.1 +X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page +... +``` + +(The "sign_out_page" should be the [`end_session_endpoint`](https://openid.net/specs/openid-connect-session-1_0.html#rfc.section.2.1) from [the metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) if your OIDC provider supports Session Management and Discovery.) + +BEWARE that the domain you want to redirect to (`my-oidc-provider.example.com` in the example) must be added to the [`--whitelist-domain`](../configuration/overview) configuration option otherwise the redirect will be ignored. Make sure to include the actual domain and port (if needed) and not the URL (e.g "localhost:8081" instead of "http://localhost:8081"). + +### Auth + +This endpoint returns 202 Accepted response or a 401 Unauthorized response. + +It can be configured using the following query parameters: +- `allowed_groups`: comma separated list of allowed groups +- `allowed_email_domains`: comma separated list of allowed email domains +- `allowed_emails`: comma separated list of allowed emails diff --git a/docs/versioned_docs/version-7.12.x/installation.md b/docs/versioned_docs/version-7.12.x/installation.md new file mode 100644 index 0000000000..b6fc9d011a --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/installation.md @@ -0,0 +1,32 @@ +--- +id: installation +title: Installation +--- + +1. Choose how to deploy: + + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.11.0`) + + b. Using Go to install the latest release + ```bash + $ go install github.com/oauth2-proxy/oauth2-proxy/v7@latest + ``` + This will install the binary into `$GOPATH/bin`. Make sure you include `$GOPATH` in your `$PATH`. Otherwise your system won't find binaries installed via `go install` + + c. Using a [Prebuilt Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy) (AMD64, PPC64LE, S390x, ARMv6, ARMv7, and ARM64 available) + + d. Using a [Pre-Release Nightly Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy-nightly) (AMD64, PPC64LE, ARMv6, ARMv7, and ARM64 available) + + e. Using the official [Kubernetes manifest](https://github.com/oauth2-proxy/manifests) (Helm) + + Prebuilt binaries can be validated by extracting the file and verifying it against the `sha256sum.txt` checksum file provided for each release starting with version `v3.0.0`. + + ``` + $ sha256sum -c sha256sum.txt + oauth2-proxy-x.y.z.linux-amd64: OK + ``` + +2. [Select a Provider and Register an OAuth Application with a Provider](configuration/providers/index.md) +3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration/overview.md) +4. [Configure SSL or Deploy behind an SSL endpoint](configuration/tls.md) (example provided for Nginx) +5. [Configure OAuth2 Proxy using systemd.socket](configuration/systemd_socket.md) (example provided for Nginx/Systemd) diff --git a/docs/versioned_docs/version-7.12.x/welcome.md b/docs/versioned_docs/version-7.12.x/welcome.md new file mode 100644 index 0000000000..7bceadd80e --- /dev/null +++ b/docs/versioned_docs/version-7.12.x/welcome.md @@ -0,0 +1,23 @@ +--- +id: welcome +title: Welcome +hide_table_of_contents: true +slug: / +--- + +![OAuth2 Proxy](/img/logos/OAuth2_Proxy_horizontal.svg) + +A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others) +to validate accounts by email, domain or group. + +:::note +This repository was forked from [bitly/OAuth2_Proxy](https://github.com/bitly/oauth2_proxy) on 27/11/2018. +Versions v3.0.0 and up are from this fork and will have diverged from any changes in the original fork. +A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/CHANGELOG.md). +::: + +![Sign In Page](/img/sign-in-page.png) + +## Architecture + +![OAuth2 Proxy Architecture](/img/simplified-architecture.svg) diff --git a/docs/versioned_sidebars/version-7.12.x-sidebars.json b/docs/versioned_sidebars/version-7.12.x-sidebars.json new file mode 100644 index 0000000000..0dbf04bd44 --- /dev/null +++ b/docs/versioned_sidebars/version-7.12.x-sidebars.json @@ -0,0 +1,83 @@ +{ + "docs": [ + { + "type": "doc", + "id": "welcome" + }, + { + "type": "doc", + "id": "installation" + }, + { + "type": "doc", + "id": "behaviour" + }, + { + "type": "category", + "label": "Configuration", + "link": { + "type": "doc", + "id": "configuration/overview" + }, + "collapsed": false, + "items": [ + "configuration/overview", + "configuration/integration", + { + "type": "category", + "label": "OAuth Provider Configuration", + "link": { + "type": "doc", + "id": "configuration/providers/index" + }, + "items": [ + "configuration/providers/adfs", + "configuration/providers/azure", + "configuration/providers/bitbucket", + "configuration/providers/digitalocean", + "configuration/providers/facebook", + "configuration/providers/gitea", + "configuration/providers/github", + "configuration/providers/gitlab", + "configuration/providers/google", + "configuration/providers/keycloak", + "configuration/providers/keycloak_oidc", + "configuration/providers/linkedin", + "configuration/providers/login_gov", + "configuration/providers/ms_entra_id", + "configuration/providers/nextcloud", + "configuration/providers/openid_connect" + ] + }, + "configuration/session_storage", + "configuration/tls", + "configuration/alpha-config" + ] + }, + { + "type": "category", + "label": "Features", + "link": { + "type": "doc", + "id": "features/endpoints" + }, + "collapsed": false, + "items": [ + "features/endpoints" + ] + }, + { + "type": "category", + "label": "Community", + "link": { + "type": "doc", + "id": "community/security" + }, + "collapsed": false, + "items": [ + "community/contribution", + "community/security" + ] + } + ] +} diff --git a/docs/versions.json b/docs/versions.json index b4f8a9f55d..ada187c69e 100644 --- a/docs/versions.json +++ b/docs/versions.json @@ -1,4 +1,5 @@ [ + "7.12.x", "7.11.x", "7.10.x", "7.9.x", From b4b69a6cb370e863d45c17f90a9567b0ff474b67 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 19 Aug 2025 05:58:41 +0000 Subject: [PATCH 039/125] update to release version v7.12.0 --- CHANGELOG.md | 10 ++++++++++ .../local-environment/docker-compose-alpha-config.yaml | 2 +- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-keycloak.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/installation.md | 2 +- docs/versioned_docs/version-7.12.x/installation.md | 2 +- 9 files changed, 18 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index faecde024d..7717e65919 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Release Highlights +## Important Notes + +## Breaking Changes + +## Changes since v7.12.0 + +# V7.12.0 + +## Release Highlights + - 🕵️‍♀️ Vulnerabilities have been addressed - [CVE-2025-47907](https://pkg.go.dev/vuln/GO-2025-3849) diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index 55b4649ede..a43dc45771 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml volumes: - "./oauth2-proxy-alpha-config.cfg:/oauth2-proxy.cfg" diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 92c1dedf19..14228880e5 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index 1796b65cd9..faa1b47b4f 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 91374fbb76..668e61ffc9 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,7 +22,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 8636340008..b56ff12e34 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index aaae15515e..6490ca8eba 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.11.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/installation.md b/docs/docs/installation.md index b6fc9d011a..bba3f4c39f 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.11.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.12.0`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.12.x/installation.md b/docs/versioned_docs/version-7.12.x/installation.md index b6fc9d011a..bba3f4c39f 100644 --- a/docs/versioned_docs/version-7.12.x/installation.md +++ b/docs/versioned_docs/version-7.12.x/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.11.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.12.0`) b. Using Go to install the latest release ```bash From 7294eebce1d626f1a47a1b4567b987f78365ad23 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Tue, 19 Aug 2025 08:40:59 +0200 Subject: [PATCH 040/125] add changelog entry for v7.12.0 Signed-off-by: Jan Larwig --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7717e65919..f2c9b4410f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,9 @@ - 🕵️‍♀️ Vulnerabilities have been addressed - [CVE-2025-47907](https://pkg.go.dev/vuln/GO-2025-3849) +- 🦸 Support for Cidaas IDP +- 🐛 Squashed some bugs + ## Important Notes From 8afb047e01906a20d73f7578ef5d54b592e2a4ef Mon Sep 17 00:00:00 2001 From: Conrad Hoffmann <1226676+bitfehler@users.noreply.github.com> Date: Wed, 20 Aug 2025 12:02:32 +0200 Subject: [PATCH 041/125] doc: SourceHut documentation fixes (#3170) * fix: SourceHut documentation - Add it to sidebar and provider index - Fix broken link This fixes an oversight in #2359, where I had not fully understood how the documentation works. Signed-off-by: Conrad Hoffmann * fix: doc build instructions in docs/README.md --------- Signed-off-by: Conrad Hoffmann --- docs/README.md | 2 +- docs/docs/configuration/providers/index.md | 1 + docs/docs/configuration/providers/sourcehut.md | 2 +- docs/sidebars.js | 1 + .../version-7.11.x/configuration/providers/index.md | 1 + .../version-7.11.x/configuration/providers/sourcehut.md | 2 +- .../version-7.12.x/configuration/providers/index.md | 1 + .../version-7.12.x/configuration/providers/sourcehut.md | 2 +- docs/versioned_sidebars/version-7.11.x-sidebars.json | 3 ++- docs/versioned_sidebars/version-7.12.x-sidebars.json | 3 ++- 10 files changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/README.md b/docs/README.md index 349f3456e3..5aa1c060f6 100644 --- a/docs/README.md +++ b/docs/README.md @@ -19,7 +19,7 @@ This command starts a local development server and open up a browser window. Mos ## Build ```console -npm build +npm run build ``` This command generates static content into the `build` directory and can be served using any static contents hosting service. diff --git a/docs/docs/configuration/providers/index.md b/docs/docs/configuration/providers/index.md index 713b5cb95e..3d3938ff65 100644 --- a/docs/docs/configuration/providers/index.md +++ b/docs/docs/configuration/providers/index.md @@ -25,6 +25,7 @@ Valid providers are : - [Microsoft Entra ID](ms_entra_id.md) - [Nextcloud](nextcloud.md) - [OpenID Connect](openid_connect.md) +- [SourceHut](sourcehut.md) The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). diff --git a/docs/docs/configuration/providers/sourcehut.md b/docs/docs/configuration/providers/sourcehut.md index 88d14622bd..2c196bda4e 100644 --- a/docs/docs/configuration/providers/sourcehut.md +++ b/docs/docs/configuration/providers/sourcehut.md @@ -21,5 +21,5 @@ to the appropriate URLs: The default configuration allows everyone with an account to authenticate. Restricting access is currently only supported by -[email](#email-authentication). +[email](index.md#email-authentication). diff --git a/docs/sidebars.js b/docs/sidebars.js index 3240e7dfc1..0a1bf0b458 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -47,6 +47,7 @@ const sidebars = { "configuration/providers/ms_entra_id", "configuration/providers/nextcloud", "configuration/providers/openid_connect", + "configuration/providers/sourcehut" ], }, 'configuration/session_storage', diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/index.md b/docs/versioned_docs/version-7.11.x/configuration/providers/index.md index b947c09b7e..248e43803f 100644 --- a/docs/versioned_docs/version-7.11.x/configuration/providers/index.md +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/index.md @@ -24,6 +24,7 @@ Valid providers are : - [Microsoft Entra ID](ms_entra_id.md) - [Nextcloud](nextcloud.md) - [OpenID Connect](openid_connect.md) +- [SourceHut](sourcehut.md) The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/sourcehut.md b/docs/versioned_docs/version-7.11.x/configuration/providers/sourcehut.md index 88d14622bd..2c196bda4e 100644 --- a/docs/versioned_docs/version-7.11.x/configuration/providers/sourcehut.md +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/sourcehut.md @@ -21,5 +21,5 @@ to the appropriate URLs: The default configuration allows everyone with an account to authenticate. Restricting access is currently only supported by -[email](#email-authentication). +[email](index.md#email-authentication). diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/index.md b/docs/versioned_docs/version-7.12.x/configuration/providers/index.md index 713b5cb95e..3d3938ff65 100644 --- a/docs/versioned_docs/version-7.12.x/configuration/providers/index.md +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/index.md @@ -25,6 +25,7 @@ Valid providers are : - [Microsoft Entra ID](ms_entra_id.md) - [Nextcloud](nextcloud.md) - [OpenID Connect](openid_connect.md) +- [SourceHut](sourcehut.md) The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/sourcehut.md b/docs/versioned_docs/version-7.12.x/configuration/providers/sourcehut.md index 88d14622bd..2c196bda4e 100644 --- a/docs/versioned_docs/version-7.12.x/configuration/providers/sourcehut.md +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/sourcehut.md @@ -21,5 +21,5 @@ to the appropriate URLs: The default configuration allows everyone with an account to authenticate. Restricting access is currently only supported by -[email](#email-authentication). +[email](index.md#email-authentication). diff --git a/docs/versioned_sidebars/version-7.11.x-sidebars.json b/docs/versioned_sidebars/version-7.11.x-sidebars.json index 0dbf04bd44..3f5eb854ba 100644 --- a/docs/versioned_sidebars/version-7.11.x-sidebars.json +++ b/docs/versioned_sidebars/version-7.11.x-sidebars.json @@ -46,7 +46,8 @@ "configuration/providers/login_gov", "configuration/providers/ms_entra_id", "configuration/providers/nextcloud", - "configuration/providers/openid_connect" + "configuration/providers/openid_connect", + "configuration/providers/sourcehut" ] }, "configuration/session_storage", diff --git a/docs/versioned_sidebars/version-7.12.x-sidebars.json b/docs/versioned_sidebars/version-7.12.x-sidebars.json index 0dbf04bd44..3f5eb854ba 100644 --- a/docs/versioned_sidebars/version-7.12.x-sidebars.json +++ b/docs/versioned_sidebars/version-7.12.x-sidebars.json @@ -46,7 +46,8 @@ "configuration/providers/login_gov", "configuration/providers/ms_entra_id", "configuration/providers/nextcloud", - "configuration/providers/openid_connect" + "configuration/providers/openid_connect", + "configuration/providers/sourcehut" ] }, "configuration/session_storage", From f1c08a3cd7e0d643dd0808416d1d189879baa8d1 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 25 Sep 2025 20:09:52 +0200 Subject: [PATCH 042/125] chore(deps): update actions/upload-pages-artifact action to v4 (#3194) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 81ab689a0c..6ae15ac6f2 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -49,7 +49,7 @@ jobs: npm run build - name: Upload artifact - uses: actions/upload-pages-artifact@v3 + uses: actions/upload-pages-artifact@v4 with: path: ./docs/build From 66cdb9d9398caa44f2596d8e4dda13f1e3c9eff1 Mon Sep 17 00:00:00 2001 From: David Symonds Date: Fri, 26 Sep 2025 04:11:57 +1000 Subject: [PATCH 043/125] doc: update contribution guide to avoid a specific mention of the version of Go being used. (#3157) --- docs/docs/community/contribution.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/docs/community/contribution.md b/docs/docs/community/contribution.md index 92255eda17..a8e4734988 100644 --- a/docs/docs/community/contribution.md +++ b/docs/docs/community/contribution.md @@ -15,7 +15,9 @@ We suggest using [Visual Studio Code](https://code.visualstudio.com/docs/languag # Go version -This project is currently still using go 1.22. You can follow the installation guide for go [here.](https://go.dev/doc/install) And you can find go version 1.22 in the archived section [here.](https://go.dev/dl/) +See the `go.mod` file in the root of this repository for the version of Go used by this project. +You can follow [the installation guide for Go](https://go.dev/doc/install), +and you can find this specific Go version on [the Go downloads page](https://go.dev/dl/). # Preparing your fork Clone your fork, create a feature branch and update the depedencies to get started. From 9168731c7afa26698c7ee84a230b351e2163dee4 Mon Sep 17 00:00:00 2001 From: Richard Ahlquist Date: Sun, 28 Sep 2025 14:48:59 +0200 Subject: [PATCH 044/125] fix(deps): revert actions/upload-pages-artifact action to v3 (#3211) Signed-off-by: Richard Ahlquist --- .github/workflows/docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 6ae15ac6f2..81ab689a0c 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -49,7 +49,7 @@ jobs: npm run build - name: Upload artifact - uses: actions/upload-pages-artifact@v4 + uses: actions/upload-pages-artifact@v3 with: path: ./docs/build From a3349add545bce2c25e35c39194add36d3eaec17 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 07:40:08 +0100 Subject: [PATCH 045/125] chore(deps): update alpine docker tag to v3.22.2 (#3241) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 091ca726e8..20ed88c921 100644 --- a/Makefile +++ b/Makefile @@ -67,7 +67,7 @@ DOCKER_BUILDX_PUSH := $(DOCKER_BUILDX) --push DOCKER_BUILDX_PUSH_X_PLATFORM := $(DOCKER_BUILDX_PUSH) --platform ${DOCKER_BUILD_PLATFORM} DOCKER_BUILD_PLATFORM_ALPINE ?= linux/amd64,linux/arm64,linux/ppc64le,linux/arm/v6,linux/arm/v7,linux/s390x -DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.22.1 +DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.22.2 DOCKER_BUILDX_ARGS_ALPINE ?= --build-arg RUNTIME_IMAGE=${DOCKER_BUILD_RUNTIME_IMAGE_ALPINE} ${DOCKER_BUILDX_COMMON_ARGS} DOCKER_BUILDX_X_PLATFORM_ALPINE := docker buildx build ${DOCKER_BUILDX_ARGS_ALPINE} --platform ${DOCKER_BUILD_PLATFORM_ALPINE} DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE := $(DOCKER_BUILDX_X_PLATFORM_ALPINE) --push From bccc988366d6d8a1ebd1fc6cd9c40969cc4f91e3 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 07:41:34 +0100 Subject: [PATCH 046/125] chore(deps): update actions/setup-node action to v6 (#3242) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/create-release.yml | 2 +- .github/workflows/docs.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/create-release.yml b/.github/workflows/create-release.yml index 9ab0d79fd9..ea8fcb02b3 100644 --- a/.github/workflows/create-release.yml +++ b/.github/workflows/create-release.yml @@ -54,7 +54,7 @@ jobs: git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com" - name: Setup node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 with: node-version-file: docs/package.json diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 81ab689a0c..6f8f7ad6db 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -20,7 +20,7 @@ jobs: id: pages uses: actions/configure-pages@v5 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@v6 with: # renovate: datasource=node-version depName=node node-version: 22 @@ -37,7 +37,7 @@ jobs: steps: - uses: actions/checkout@v5 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@v6 with: # renovate: datasource=node-version depName=node node-version: 22 From 65ef2ca3c946c1ddf64f473db99bb28def648bda Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 07:42:13 +0100 Subject: [PATCH 047/125] chore(deps): update actions/stale action to v10 (#3193) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/stale.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 2406f69593..d14e99350e 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/stale@v9 + - uses: actions/stale@v10 with: repo-token: ${{ secrets.GITHUB_TOKEN }} days-before-stale: 180 From 5539e590025c4e66ace6e764675600ade1ebf9fa Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 07:43:04 +0100 Subject: [PATCH 048/125] chore(deps): update actions/setup-go action to v6 (#3191) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 2 +- .github/workflows/publish-release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b8bcd58080..01826f970f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,7 @@ jobs: uses: actions/checkout@v5 - name: Set up Go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: go-version-file: go.mod id: go diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index f45debabd2..637a6780ea 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -43,7 +43,7 @@ jobs: id: tag - name: Set up go - uses: actions/setup-go@v5 + uses: actions/setup-go@v6 with: go-version-file: go.mod From e693f4070a42f3f8f133eadfb8367ea842fbfc8c Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 07:43:22 +0100 Subject: [PATCH 049/125] chore(deps): update actions/labeler action to v6 (#3190) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/labeler.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index b3e8543821..6b2762f02d 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -9,7 +9,7 @@ jobs: pull-requests: write runs-on: ubuntu-latest steps: - - uses: actions/labeler@v5 + - uses: actions/labeler@v6 with: sync-labels: true dot: true From dea0d0cf44452cd3666790ddc85579c1d4c02d83 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 07:53:12 +0100 Subject: [PATCH 050/125] chore(deps): update helmv3 (#3189) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/kubernetes/Chart.lock | 8 ++++---- contrib/local-environment/kubernetes/Chart.yaml | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/contrib/local-environment/kubernetes/Chart.lock b/contrib/local-environment/kubernetes/Chart.lock index e6774fb24b..527eab3be1 100644 --- a/contrib/local-environment/kubernetes/Chart.lock +++ b/contrib/local-environment/kubernetes/Chart.lock @@ -1,15 +1,15 @@ dependencies: - name: dex repository: https://charts.dexidp.io - version: 0.23.0 + version: 0.24.0 - name: oauth2-proxy repository: https://oauth2-proxy.github.io/manifests - version: 7.14.1 + version: 7.18.0 - name: httpbin repository: https://conservis.github.io/helm-charts version: 1.1.0 - name: hello-world repository: https://conservis.github.io/helm-charts version: 1.1.0 -digest: sha256:9b18e072db6863053c2967d023929ab4b9c03b6bd84f6529d90fe7a9ec5e315f -generated: "2025-07-20T08:56:43.559585022Z" +digest: sha256:fee913531bfb67e5555e995d8fb040c330e6eb4b5a8c777ceb9841135ea9bb84 +generated: "2025-10-28T06:46:35.38300324Z" diff --git a/contrib/local-environment/kubernetes/Chart.yaml b/contrib/local-environment/kubernetes/Chart.yaml index 3d224378a0..83c09b477a 100644 --- a/contrib/local-environment/kubernetes/Chart.yaml +++ b/contrib/local-environment/kubernetes/Chart.yaml @@ -3,10 +3,10 @@ description: K8S example based on https://kind.sigs.k8s.io name: kubernetes dependencies: - name: dex - version: 0.23.0 + version: 0.24.0 repository: https://charts.dexidp.io - name: oauth2-proxy - version: &chartVersion 7.14.1 + version: &chartVersion 7.18.0 repository: https://oauth2-proxy.github.io/manifests # https://github.com/postmanlabs/httpbin/issues/549 is still in progress, for now using a non-official chart - name: httpbin From a50bbcd6f6fe2e6c0516678fd536848e650ac2f1 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 07:53:29 +0100 Subject: [PATCH 051/125] chore(deps): update docker-compose (#3188) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 4 ++-- contrib/local-environment/docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 14228880e5..f506c4acdb 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -39,7 +39,7 @@ services: httpbin: {} gitea: - image: gitea/gitea:1.24.5 + image: gitea/gitea:1.24.7 container_name: gitea environment: - USER_UID=1000 diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 668e61ffc9..60343012f8 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -55,7 +55,7 @@ services: httpbin: {} dex: container_name: dex - image: ghcr.io/dexidp/dex:v2.43.1 + image: ghcr.io/dexidp/dex:v2.44.0 command: dex serve /dex.yaml hostname: dex volumes: @@ -78,7 +78,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.4 + image: gcr.io/etcd-development/etcd:v3.6.5 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index b56ff12e34..8bff6b034d 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -34,7 +34,7 @@ services: # Reverse proxy gateway: container_name: traefik - image: traefik:v2.11.28 + image: traefik:v2.11.29 volumes: - "./traefik:/etc/traefik" ports: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 6490ca8eba..ae9e3bf13b 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -29,7 +29,7 @@ services: - httpbin dex: container_name: dex - image: ghcr.io/dexidp/dex:v2.43.1 + image: ghcr.io/dexidp/dex:v2.44.0 command: dex serve /dex.yaml hostname: dex volumes: @@ -52,7 +52,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.4 + image: gcr.io/etcd-development/etcd:v3.6.5 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 From 4295f0c1f94a4bb6b50b046ef35b1eb9797cbc77 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 08:00:27 +0100 Subject: [PATCH 052/125] chore(deps): update dependency golangci/golangci-lint to v2.5.0 (#3212) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 2 +- .github/workflows/publish-release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 01826f970f..4764c81302 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,7 +25,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.4.0 + GOLANGCI_LINT_VERSION: v2.5.0 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 637a6780ea..fe27cabeee 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -50,7 +50,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.4.0 + GOLANGCI_LINT_VERSION: v2.5.0 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter From c0a087d7f2bcaf2142f259fd834b4b8af66a4a5b Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 08:03:40 +0100 Subject: [PATCH 053/125] chore(deps): update actions/upload-artifact action to v5 (#3243) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/publish-release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index fe27cabeee..ccefd1c939 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -64,7 +64,7 @@ jobs: # Upload artifacts in case of workflow failure - name: Upload Artifacts - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: oauth2-proxy-artifacts path: | From 51e80f24ef25252d65476cf33e31242e43919af9 Mon Sep 17 00:00:00 2001 From: stagswtf <142280349+stagswtf@users.noreply.github.com> Date: Tue, 28 Oct 2025 00:37:25 -0700 Subject: [PATCH 054/125] fix: use GetSecret() in ticket.go makeCookie to respect cookie-secret-file (#3228) * fix: use GetSecret() in ticket.go makeCookie The makeCookie method in ticket.go was using t.options.Secret directly, which meant cookie-secret-file was not being respected. Updated to use GetSecret() which handles both cookie-secret and cookie-secret-file properly. Also added test coverage for cookie-secret-file functionality. Fixes #3224 Signed-off-by: stagswtf <142280349+stagswtf@users.noreply.github.com> * docs: update CHANGELOG.md for cookie-secret-file fix Signed-off-by: stagswtf <142280349+stagswtf@users.noreply.github.com> * correct PR link and undo file formatting Signed-off-by: stagswtf <142280349+stagswtf@users.noreply.github.com> * fix: error wrapping Signed-off-by: Jan Larwig --------- Signed-off-by: stagswtf <142280349+stagswtf@users.noreply.github.com> Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 4 ++- pkg/sessions/persistence/ticket.go | 11 +++++-- pkg/sessions/tests/session_store_tests.go | 37 +++++++++++++++++++++++ 3 files changed, 48 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f2c9b4410f..5aefaafa1a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ ## Changes since v7.12.0 +- [#3228](https://github.com/oauth2-proxy/oauth2-proxy/pull/3228) fix: use GetSecret() in ticket.go makeCookie to respect cookie-secret-file (@stagswtf) + # V7.12.0 ## Release Highlights @@ -119,7 +121,7 @@ For detailed information, migration guidance, and security implications, see the - 🕵️‍♀️ Vulnerabilities have been addressed - [CVE-2025-22871](https://github.com/advisories/GHSA-g9pc-8g42-g6vq) - 🐛 Squashed some bugs - + ## Important Notes ## Breaking Changes diff --git a/pkg/sessions/persistence/ticket.go b/pkg/sessions/persistence/ticket.go index 7855db4556..56d6bd9b21 100644 --- a/pkg/sessions/persistence/ticket.go +++ b/pkg/sessions/persistence/ticket.go @@ -233,12 +233,17 @@ func (t *ticket) clearCookie(rw http.ResponseWriter, req *http.Request) { // makeCookie makes a cookie, signing the value if present func (t *ticket) makeCookie(req *http.Request, value string, expires time.Duration, now time.Time) (*http.Cookie, error) { if value != "" { - var err error - value, err = encryption.SignedValue(t.options.Secret, t.options.Name, []byte(value), now) + secret, err := t.options.GetSecret() if err != nil { - return nil, err + return nil, fmt.Errorf("retrieving secret failed: %w", err) + } + + value, err = encryption.SignedValue(secret, t.options.Name, []byte(value), now) + if err != nil { + return nil, fmt.Errorf("signing cookie value failed: %w", err) } } + return cookies.MakeCookieFromOptions( req, t.options.Name, diff --git a/pkg/sessions/tests/session_store_tests.go b/pkg/sessions/tests/session_store_tests.go index a4818ef290..05b67d8df2 100644 --- a/pkg/sessions/tests/session_store_tests.go +++ b/pkg/sessions/tests/session_store_tests.go @@ -4,6 +4,7 @@ import ( "crypto/rand" "net/http" "net/http/httptest" + "os" "strconv" "strings" "time" @@ -133,6 +134,42 @@ func RunSessionStoreTests(newSS NewSessionStoreFunc, persistentFastForward Persi PersistentSessionStoreInterfaceTests(&input) } }) + + Context("with cookie secret file", func() { + var tmpfile *os.File + var err error + BeforeEach(func() { + tmpfile, err = os.CreateTemp("", "cookie-secret-test") + secretBytes := make([]byte, 32) + tmpfile.Write(secretBytes) + tmpfile.Close() + + input.cookieOpts = &options.Cookie{ + Name: "_oauth2_proxy_file", + Path: "/", + Expire: time.Duration(168) * time.Hour, + Refresh: time.Duration(1) * time.Hour, + Secure: true, + HTTPOnly: true, + SameSite: "", + Secret: "", + SecretFile: tmpfile.Name(), + } + ss, err = newSS(opts, input.cookieOpts) + Expect(err).ToNot(HaveOccurred()) + }) + + AfterEach(func() { + if tmpfile != nil { + os.Remove(tmpfile.Name()) + } + }) + + SessionStoreInterfaceTests(&input) + if persistentFastForward != nil { + PersistentSessionStoreInterfaceTests(&input) + } + }) }) } From ea1dc3f606fa5a5817bc168ecb64c67f792ca25e Mon Sep 17 00:00:00 2001 From: Vincent Privat <146961743+vprivat-ads@users.noreply.github.com> Date: Tue, 28 Oct 2025 08:40:51 +0100 Subject: [PATCH 055/125] Fix typo: diffrerent -> different (#3222) Signed-off-by: Vincent Privat --- docs/docs/configuration/providers/ms_entra_id.md | 2 +- .../version-7.10.x/configuration/providers/ms_entra_id.md | 2 +- .../version-7.11.x/configuration/providers/ms_entra_id.md | 2 +- .../version-7.12.x/configuration/providers/ms_entra_id.md | 2 +- .../version-7.8.x/configuration/providers/ms_entra_id.md | 2 +- .../version-7.9.x/configuration/providers/ms_entra_id.md | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/docs/configuration/providers/ms_entra_id.md b/docs/docs/configuration/providers/ms_entra_id.md index c5d9594edd..95fb99bc60 100644 --- a/docs/docs/configuration/providers/ms_entra_id.md +++ b/docs/docs/configuration/providers/ms_entra_id.md @@ -112,7 +112,7 @@ insecure_oidc_skip_issuer_verification=true ``` `insecure_oidc_skip_issuer_verification` setting is required to disable following checks: * Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). -* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. diff --git a/docs/versioned_docs/version-7.10.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.10.x/configuration/providers/ms_entra_id.md index c5d9594edd..95fb99bc60 100644 --- a/docs/versioned_docs/version-7.10.x/configuration/providers/ms_entra_id.md +++ b/docs/versioned_docs/version-7.10.x/configuration/providers/ms_entra_id.md @@ -112,7 +112,7 @@ insecure_oidc_skip_issuer_verification=true ``` `insecure_oidc_skip_issuer_verification` setting is required to disable following checks: * Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). -* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. diff --git a/docs/versioned_docs/version-7.11.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.11.x/configuration/providers/ms_entra_id.md index c5d9594edd..95fb99bc60 100644 --- a/docs/versioned_docs/version-7.11.x/configuration/providers/ms_entra_id.md +++ b/docs/versioned_docs/version-7.11.x/configuration/providers/ms_entra_id.md @@ -112,7 +112,7 @@ insecure_oidc_skip_issuer_verification=true ``` `insecure_oidc_skip_issuer_verification` setting is required to disable following checks: * Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). -* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. diff --git a/docs/versioned_docs/version-7.12.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.12.x/configuration/providers/ms_entra_id.md index c5d9594edd..95fb99bc60 100644 --- a/docs/versioned_docs/version-7.12.x/configuration/providers/ms_entra_id.md +++ b/docs/versioned_docs/version-7.12.x/configuration/providers/ms_entra_id.md @@ -112,7 +112,7 @@ insecure_oidc_skip_issuer_verification=true ``` `insecure_oidc_skip_issuer_verification` setting is required to disable following checks: * Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). -* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. diff --git a/docs/versioned_docs/version-7.8.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.8.x/configuration/providers/ms_entra_id.md index c5d9594edd..95fb99bc60 100644 --- a/docs/versioned_docs/version-7.8.x/configuration/providers/ms_entra_id.md +++ b/docs/versioned_docs/version-7.8.x/configuration/providers/ms_entra_id.md @@ -112,7 +112,7 @@ insecure_oidc_skip_issuer_verification=true ``` `insecure_oidc_skip_issuer_verification` setting is required to disable following checks: * Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). -* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. diff --git a/docs/versioned_docs/version-7.9.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.9.x/configuration/providers/ms_entra_id.md index c5d9594edd..95fb99bc60 100644 --- a/docs/versioned_docs/version-7.9.x/configuration/providers/ms_entra_id.md +++ b/docs/versioned_docs/version-7.9.x/configuration/providers/ms_entra_id.md @@ -112,7 +112,7 @@ insecure_oidc_skip_issuer_verification=true ``` `insecure_oidc_skip_issuer_verification` setting is required to disable following checks: * Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). -* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by diffrerent tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. From 31b275f5805ee1d6c62906a81274c21587e70a40 Mon Sep 17 00:00:00 2001 From: Schmitt Paul <100230730+paulsc54@users.noreply.github.com> Date: Tue, 28 Oct 2025 08:48:23 +0100 Subject: [PATCH 056/125] docs: clarify ingress-nginx integration and remove Lua block example (#3202) * docs: clarify ingress-nginx integration and remove Lua block example for oauth2-proxy This PR revises the integration guide for oauth2-proxy with ingress-nginx in Kubernetes: Recommends the minimal configuration: just auth-url and auth-signin annotations. Removes the Lua block example, as it did not work in practice despite following nginx documentation and extensive testing. Clearly states that the official ingress-nginx external auth example is the recommended approach for most users. Notes that advanced Lua/cookie handling is only needed for rare, advanced scenarios. Signed-off-by: Jan Larwig * doc: update 3 latest docs versions Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- docs/docs/configuration/integration.md | 20 ++++++------------- .../configuration/integration.md | 20 ++++++------------- .../configuration/integration.md | 20 ++++++------------- .../configuration/integration.md | 20 ++++++------------- 4 files changed, 24 insertions(+), 56 deletions(-) diff --git a/docs/docs/configuration/integration.md b/docs/docs/configuration/integration.md index 05d39281e5..c57cfa6b36 100644 --- a/docs/docs/configuration/integration.md +++ b/docs/docs/configuration/integration.md @@ -77,23 +77,15 @@ server { } ``` -When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`. -Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua. -Note that `nginxinc/kubernetes-ingress` does not include the Lua module. +When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: ```yaml -nginx.ingress.kubernetes.io/auth-response-headers: Authorization -nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri -nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth -nginx.ingress.kubernetes.io/configuration-snippet: | - auth_request_set $name_upstream_1 $upstream_cookie_name_1; - - access_by_lua_block { - if ngx.var.name_upstream_1 ~= "" then - ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)") - end - } +nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" +nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" ``` + +This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. + It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). 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=". diff --git a/docs/versioned_docs/version-7.10.x/configuration/integration.md b/docs/versioned_docs/version-7.10.x/configuration/integration.md index 05d39281e5..c57cfa6b36 100644 --- a/docs/versioned_docs/version-7.10.x/configuration/integration.md +++ b/docs/versioned_docs/version-7.10.x/configuration/integration.md @@ -77,23 +77,15 @@ server { } ``` -When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`. -Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua. -Note that `nginxinc/kubernetes-ingress` does not include the Lua module. +When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: ```yaml -nginx.ingress.kubernetes.io/auth-response-headers: Authorization -nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri -nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth -nginx.ingress.kubernetes.io/configuration-snippet: | - auth_request_set $name_upstream_1 $upstream_cookie_name_1; - - access_by_lua_block { - if ngx.var.name_upstream_1 ~= "" then - ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)") - end - } +nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" +nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" ``` + +This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. + It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). 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=". diff --git a/docs/versioned_docs/version-7.11.x/configuration/integration.md b/docs/versioned_docs/version-7.11.x/configuration/integration.md index 05d39281e5..c57cfa6b36 100644 --- a/docs/versioned_docs/version-7.11.x/configuration/integration.md +++ b/docs/versioned_docs/version-7.11.x/configuration/integration.md @@ -77,23 +77,15 @@ server { } ``` -When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`. -Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua. -Note that `nginxinc/kubernetes-ingress` does not include the Lua module. +When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: ```yaml -nginx.ingress.kubernetes.io/auth-response-headers: Authorization -nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri -nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth -nginx.ingress.kubernetes.io/configuration-snippet: | - auth_request_set $name_upstream_1 $upstream_cookie_name_1; - - access_by_lua_block { - if ngx.var.name_upstream_1 ~= "" then - ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)") - end - } +nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" +nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" ``` + +This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. + It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). 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=". diff --git a/docs/versioned_docs/version-7.12.x/configuration/integration.md b/docs/versioned_docs/version-7.12.x/configuration/integration.md index 05d39281e5..c57cfa6b36 100644 --- a/docs/versioned_docs/version-7.12.x/configuration/integration.md +++ b/docs/versioned_docs/version-7.12.x/configuration/integration.md @@ -77,23 +77,15 @@ server { } ``` -When you use ingress-nginx in Kubernetes, you MUST use `kubernetes/ingress-nginx` (which includes the Lua module) and the following configuration snippet for your `Ingress`. -Variables set with `auth_request_set` are not `set`-able in plain nginx config when the location is processed via `proxy_pass` and then may only be processed by Lua. -Note that `nginxinc/kubernetes-ingress` does not include the Lua module. +When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: ```yaml -nginx.ingress.kubernetes.io/auth-response-headers: Authorization -nginx.ingress.kubernetes.io/auth-signin: https://$host/oauth2/start?rd=$escaped_request_uri -nginx.ingress.kubernetes.io/auth-url: https://$host/oauth2/auth -nginx.ingress.kubernetes.io/configuration-snippet: | - auth_request_set $name_upstream_1 $upstream_cookie_name_1; - - access_by_lua_block { - if ngx.var.name_upstream_1 ~= "" then - ngx.header["Set-Cookie"] = "name_1=" .. ngx.var.name_upstream_1 .. ngx.var.auth_cookie:match("(; .*)") - end - } +nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" +nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" ``` + +This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. + It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). 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=". From f950dc99426014f3973b2c9193ee5eecf515e39b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olivier=20Mengu=C3=A9?= Date: Tue, 28 Oct 2025 09:13:35 +0100 Subject: [PATCH 057/125] feat(makefile): simplify validate-go-version (#3147) Since Go 1.21 the go toolchain validates strictly the "go" version directive in go.mod, and downloads and uses the requested toolchain if necessary. See https://go.dev/doc/toolchain So we can just run "go list" to tell the Go toolchain to validate our build environment according to go.mod. To extract the "go" directive version from go.mod (used to select the Docker build image) we also use "go list". --- Makefile | 23 +++++++---------------- 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/Makefile b/Makefile index 20ed88c921..0647110037 100644 --- a/Makefile +++ b/Makefile @@ -36,13 +36,12 @@ REPOSITORY ?= oauth2-proxy DATE := $(shell date +"%Y%m%d") .NOTPARALLEL: -GO_MAJOR_VERSION = $(shell $(GO) version | cut -c 14- | cut -d' ' -f1 | cut -d'.' -f1) -GO_MINOR_VERSION = $(shell $(GO) version | cut -c 14- | cut -d' ' -f1 | cut -d'.' -f2) +# The go version in go.mod used for the Docker build toolchain, without the patch +GO_MOD_VERSION_MINOR := $(shell $(GO) list -f '{{printf "%.4s" .Module.GoVersion}}' ) -GO_MOD_VERSION = $(shell sed -En 's/^go ([[:digit:]]\.[[:digit:]]+)\.[[:digit:]]+/\1/p' go.mod) -MINIMUM_SUPPORTED_GO_MAJOR_VERSION = $(shell echo ${GO_MOD_VERSION} | cut -d' ' -f1 | cut -d'.' -f1) -MINIMUM_SUPPORTED_GO_MINOR_VERSION = $(shell echo ${GO_MOD_VERSION} | cut -d' ' -f1 | cut -d'.' -f2) -GO_VERSION_VALIDATION_ERR_MSG = Golang version is not supported, please update to at least $(MINIMUM_SUPPORTED_GO_MAJOR_VERSION).$(MINIMUM_SUPPORTED_GO_MINOR_VERSION) +# From go1.21 go will transparently download the toolchain declared in go.mod. https://go.dev/doc/toolchain +# We don't need to keep this message updated: the important info is in go.mod. +GO_VERSION_VALIDATION_ERR_MSG = Golang version is not supported, please update to at least go1.21 ifeq ($(COVER),true) TESTCOVER ?= -coverprofile c.out @@ -56,7 +55,7 @@ build: validate-go-version clean $(BINARY) ## Build and create oauth2-proxy bina $(BINARY): CGO_ENABLED=0 $(GO) build -a -installsuffix cgo -ldflags="-X github.com/oauth2-proxy/oauth2-proxy/v7/pkg/version.VERSION=${VERSION}" -o $@ github.com/oauth2-proxy/oauth2-proxy/v7 -DOCKER_BUILDX_COMMON_ARGS ?= --build-arg BUILD_IMAGE=docker.io/library/golang:${GO_MOD_VERSION}-bookworm --build-arg VERSION=${VERSION} +DOCKER_BUILDX_COMMON_ARGS ?= --build-arg BUILD_IMAGE=docker.io/library/golang:$(GO_MOD_VERSION_MINOR)-bookworm --build-arg VERSION=$(VERSION) DOCKER_BUILD_PLATFORM ?= linux/amd64,linux/arm64,linux/ppc64le,linux/arm/v7,linux/s390x DOCKER_BUILD_RUNTIME_IMAGE ?= gcr.io/distroless/static:nonroot @@ -158,15 +157,7 @@ lint: validate-go-version ## Lint all files using golangci-lint .PHONY: validate-go-version validate-go-version: ## Validate Go environment requirements - @if [ $(GO_MAJOR_VERSION) -gt $(MINIMUM_SUPPORTED_GO_MAJOR_VERSION) ]; then \ - exit 0 ;\ - elif [ $(GO_MAJOR_VERSION) -lt $(MINIMUM_SUPPORTED_GO_MAJOR_VERSION) ]; then \ - echo '$(GO_VERSION_VALIDATION_ERR_MSG)';\ - exit 1; \ - elif [ $(GO_MINOR_VERSION) -lt $(MINIMUM_SUPPORTED_GO_MINOR_VERSION) ] ; then \ - echo '$(GO_VERSION_VALIDATION_ERR_MSG)';\ - exit 1; \ - fi + @$(GO) list . >/dev/null || { echo '$(GO_VERSION_VALIDATION_ERR_MSG)'; exit 1; } # local-env can be used to interact with the local development environment # eg: From 8f687e4d0cb416232397b1076f387a23c9622183 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Tue, 28 Oct 2025 09:54:10 +0100 Subject: [PATCH 058/125] chore(deps): upgrade to latest go1.25.3 (#3244) Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + go.mod | 2 +- go.sum | 34 ++-------------------------------- 3 files changed, 4 insertions(+), 33 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5aefaafa1a..c52eedef40 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ## Changes since v7.12.0 - [#3228](https://github.com/oauth2-proxy/oauth2-proxy/pull/3228) fix: use GetSecret() in ticket.go makeCookie to respect cookie-secret-file (@stagswtf) +- [#3244](https://github.com/oauth2-proxy/oauth2-proxy/pull/3244) chore(deps): upgrade to latest go1.25.3 (@tuunit) # V7.12.0 diff --git a/go.mod b/go.mod index 24f316e406..3aeeda0a7f 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/oauth2-proxy/oauth2-proxy/v7 -go 1.24.6 +go 1.25.3 require ( cloud.google.com/go/compute/metadata v0.7.0 diff --git a/go.sum b/go.sum index caa8e2a0b0..2e8db1ef32 100644 --- a/go.sum +++ b/go.sum @@ -61,12 +61,8 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= -github.com/go-viper/mapstructure/v2 v2.3.0 h1:27XbWsHIqhbdR5TIC911OfYvgSaW93HM+dX7970Q7jk= -github.com/go-viper/mapstructure/v2 v2.3.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= -github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8= -github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang-jwt/jwt/v5 v5.2.3 h1:kkGXqQOBSDDWRhWNXTFpqGSCMyh/PLnqUvMGJPDJDs0= github.com/golang-jwt/jwt/v5 v5.2.3/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= @@ -85,8 +81,6 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU9uHLo7OnF5tL52HFAgMmyrf4= github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= -github.com/googleapis/gax-go/v2 v2.14.2 h1:eBLnkZ9635krYIPD+ag1USrOAI0Nr0QYF3+/3GqO0k0= -github.com/googleapis/gax-go/v2 v2.14.2/go.mod h1:ON64QhlJkhVtSqp4v1uaK92VyZ2gmvDQsweuyLV+8+w= github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81vgd/bo= github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= @@ -142,8 +136,6 @@ github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA= github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo= github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE= github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= -github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= -github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.7 h1:vN6T9TfwStFPFM5XzjsvmzZkLuaLX+HS+0SeFLRgU6M= github.com/spf13/pflag v1.0.7/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4= @@ -186,8 +178,6 @@ go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN8 golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= -golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM= -golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U= golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM= golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= @@ -197,8 +187,6 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw= -golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA= golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs= golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8= golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= @@ -206,8 +194,6 @@ golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKl golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8= -golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw= golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -219,8 +205,6 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= -golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA= golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= @@ -234,8 +218,6 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M= -golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA= golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4= golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU= golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= @@ -244,25 +226,15 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo= -golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg= golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0= golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.240.0 h1:PxG3AA2UIqT1ofIzWV2COM3j3JagKTKSwy7L6RHNXNU= -google.golang.org/api v0.240.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= -google.golang.org/api v0.241.0 h1:QKwqWQlkc6O895LchPEDUSYr22Xp3NCxpQRiWTB6avE= -google.golang.org/api v0.241.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= google.golang.org/api v0.242.0 h1:7Lnb1nfnpvbkCiZek6IXKdJ0MFuAZNAJKQfA1ws62xg= google.golang.org/api v0.242.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= -google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2 h1:1tXaIXCracvtsRxSBsYDiSBN0cuJvM7QYW+MrpIRY78= -google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2/go.mod h1:49MsLSx0oWMOZqcpB3uL8ZOkAh1+TndpJ8ONoCBWiZk= google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= -google.golang.org/genproto/googleapis/api v0.0.0-20250505200425-f936aa4a68b2 h1:vPV0tzlsK6EzEDHNNH5sa7Hs9bd7iXR7B1tSiPepkV0= -google.golang.org/genproto/googleapis/api v0.0.0-20250505200425-f936aa4a68b2/go.mod h1:pKLAc5OolXC3ViWGI62vvC0n10CpwAtRcTNCFwTKBEw= +google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 h1:oWVWY3NzT7KJppx2UKhKmzPq4SRe0LdCijVRwvGeikY= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 h1:fc6jSaCT0vBduLYZHYrBBNY4dsWuvgyff9noRNDdBeE= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= +google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822/go.mod h1:h3c4v36UTKzUiuaOKQ6gr3S+0hovBtUrXzTG/i3+XEc= google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7 h1:pFyd6EwwL2TqFf8emdthzeX+gZE1ElRq3iM8pui4KBY= google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= google.golang.org/grpc v1.73.0 h1:VIWSmpI2MegBtTuFt5/JWy2oXxtjJ/e89Z70ImfD2ok= @@ -280,7 +252,5 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/apimachinery v0.33.2 h1:IHFVhqg59mb8PJWTLi8m1mAoepkUNYmptHsV+Z1m5jY= -k8s.io/apimachinery v0.33.2/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= k8s.io/apimachinery v0.33.3 h1:4ZSrmNa0c/ZpZJhAgRdcsFcZOw1PQU1bALVQ0B3I5LA= k8s.io/apimachinery v0.33.3/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= From 110d51d1d742b5cde9cb629d6912f47e5d9ab878 Mon Sep 17 00:00:00 2001 From: David Symonds Date: Tue, 28 Oct 2025 20:05:02 +1100 Subject: [PATCH 059/125] test: replace mock pkg/clock with narrowly targeted stub clocks. (#3238) The package under pkg/clock is github.com/benbjohnson/clock, which is archived. It's also way more complex than is what is actually needed here, so we can entirely remove the dependency and remove the helper package. Fixes #2840. Signed-off-by: David Symonds --- CHANGELOG.md | 1 + go.mod | 1 - go.sum | 2 - pkg/apis/sessions/session_state.go | 18 +- pkg/apis/sessions/session_state_test.go | 6 +- pkg/clock/clock.go | 157 ---------- pkg/clock/clock_suite_test.go | 17 -- pkg/clock/clock_test.go | 380 ------------------------ pkg/cookies/csrf.go | 16 +- pkg/cookies/csrf_per_request_test.go | 10 +- pkg/cookies/csrf_test.go | 6 +- pkg/middleware/stored_session_test.go | 25 +- providers/provider_default_test.go | 5 +- 13 files changed, 50 insertions(+), 594 deletions(-) delete mode 100644 pkg/clock/clock.go delete mode 100644 pkg/clock/clock_suite_test.go delete mode 100644 pkg/clock/clock_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index c52eedef40..e014aee3cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - [#3228](https://github.com/oauth2-proxy/oauth2-proxy/pull/3228) fix: use GetSecret() in ticket.go makeCookie to respect cookie-secret-file (@stagswtf) - [#3244](https://github.com/oauth2-proxy/oauth2-proxy/pull/3244) chore(deps): upgrade to latest go1.25.3 (@tuunit) +- [#3238](https://github.com/oauth2-proxy/oauth2-proxy/pull/3238) chore: Replace pkg/clock with narrowly targeted stub clocks (@dsymonds) # V7.12.0 diff --git a/go.mod b/go.mod index 3aeeda0a7f..0e14464cd6 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,6 @@ require ( github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb github.com/a8m/envsubst v1.4.3 github.com/alicebob/miniredis/v2 v2.35.0 - github.com/benbjohnson/clock v1.3.5 github.com/bitly/go-simplejson v0.5.1 github.com/bsm/redislock v0.9.4 github.com/coreos/go-oidc/v3 v3.14.1 diff --git a/go.sum b/go.sum index 2e8db1ef32..8bc3166049 100644 --- a/go.sum +++ b/go.sum @@ -14,8 +14,6 @@ github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGn github.com/alicebob/miniredis/v2 v2.11.1/go.mod h1:UA48pmi7aSazcGAvcdKcBB49z521IC9VjTTRz2nIaJE= github.com/alicebob/miniredis/v2 v2.35.0 h1:QwLphYqCEAo1eu1TqPRN2jgVMPBweeQcR21jeqDCONI= github.com/alicebob/miniredis/v2 v2.35.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM= -github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o= -github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bitly/go-simplejson v0.5.1 h1:xgwPbetQScXt1gh9BmoJ6j9JMr3TElvuIyjR8pgdoow= diff --git a/pkg/apis/sessions/session_state.go b/pkg/apis/sessions/session_state.go index b5e4fc8348..5b063c3f06 100644 --- a/pkg/apis/sessions/session_state.go +++ b/pkg/apis/sessions/session_state.go @@ -7,7 +7,6 @@ import ( "io" "time" - "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/clock" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption" "github.com/pierrec/lz4/v4" "github.com/vmihailenco/msgpack/v5" @@ -30,8 +29,15 @@ type SessionState struct { PreferredUsername string `msgpack:"pu,omitempty"` // Internal helpers, not serialized - Clock clock.Clock `msgpack:"-"` - Lock Lock `msgpack:"-"` + Clock func() time.Time `msgpack:"-"` // override for time.Now, for testing + Lock Lock `msgpack:"-"` +} + +func (s *SessionState) now() time.Time { + if s.Clock != nil { + return s.Clock() + } + return time.Now() } func (s *SessionState) ObtainLock(ctx context.Context, expiration time.Duration) error { @@ -64,7 +70,7 @@ func (s *SessionState) PeekLock(ctx context.Context) (bool, error) { // CreatedAtNow sets a SessionState's CreatedAt to now func (s *SessionState) CreatedAtNow() { - now := s.Clock.Now() + now := s.now() s.CreatedAt = &now } @@ -85,7 +91,7 @@ func (s *SessionState) ExpiresIn(d time.Duration) { // IsExpired checks whether the session has expired func (s *SessionState) IsExpired() bool { - if s.ExpiresOn != nil && !s.ExpiresOn.IsZero() && s.ExpiresOn.Before(s.Clock.Now()) { + if s.ExpiresOn != nil && !s.ExpiresOn.IsZero() && s.ExpiresOn.Before(s.now()) { return true } return false @@ -94,7 +100,7 @@ func (s *SessionState) IsExpired() bool { // Age returns the age of a session func (s *SessionState) Age() time.Duration { if s.CreatedAt != nil && !s.CreatedAt.IsZero() { - return s.Clock.Now().Truncate(time.Second).Sub(*s.CreatedAt) + return s.now().Truncate(time.Second).Sub(*s.CreatedAt) } return 0 } diff --git a/pkg/apis/sessions/session_state_test.go b/pkg/apis/sessions/session_state_test.go index e12c277636..442fcea8bd 100644 --- a/pkg/apis/sessions/session_state_test.go +++ b/pkg/apis/sessions/session_state_test.go @@ -22,7 +22,7 @@ func TestCreatedAtNow(t *testing.T) { ss := &SessionState{} now := time.Unix(1234567890, 0) - ss.Clock.Set(now) + ss.Clock = func() time.Time { return now } ss.CreatedAtNow() g.Expect(*ss.CreatedAt).To(Equal(now)) @@ -33,9 +33,9 @@ func TestExpiresIn(t *testing.T) { ss := &SessionState{} now := time.Unix(1234567890, 0) - ss.Clock.Set(now) + ss.Clock = func() time.Time { return now } - ttl := time.Duration(743) * time.Second + ttl := 743 * time.Second ss.ExpiresIn(ttl) g.Expect(*ss.ExpiresOn).To(Equal(ss.CreatedAt.Add(ttl))) diff --git a/pkg/clock/clock.go b/pkg/clock/clock.go deleted file mode 100644 index 887bf0aa40..0000000000 --- a/pkg/clock/clock.go +++ /dev/null @@ -1,157 +0,0 @@ -package clock - -import ( - "errors" - "sync" - "time" - - clockapi "github.com/benbjohnson/clock" -) - -var ( - globalClock = clockapi.New() - mu sync.Mutex -) - -// Set the global clock to a clockapi.Mock with the given time.Time -func Set(t time.Time) { - mu.Lock() - defer mu.Unlock() - mock, ok := globalClock.(*clockapi.Mock) - if !ok { - mock = clockapi.NewMock() - } - mock.Set(t) - globalClock = mock -} - -// Add moves the mocked global clock forward the given duration. It will error -// if the global clock is not mocked. -func Add(d time.Duration) error { - mu.Lock() - defer mu.Unlock() - mock, ok := globalClock.(*clockapi.Mock) - if !ok { - return errors.New("time not mocked") - } - mock.Add(d) - return nil -} - -// Reset sets the global clock to a pure time implementation. Returns any -// existing Mock if set in case lingering time operations are attached to it. -func Reset() *clockapi.Mock { - mu.Lock() - defer mu.Unlock() - existing := globalClock - globalClock = clockapi.New() - - mock, ok := existing.(*clockapi.Mock) - if !ok { - return nil - } - return mock -} - -// Clock is a non-package level wrapper around time that supports stubbing. -// It will use its localized stubs (allowing for parallelized unit tests -// where package level stubbing would cause issues). It falls back to any -// package level time stubs for non-parallel, cross-package integration -// testing scenarios. -// -// If nothing is stubbed, it defaults to default time behavior in the time -// package. -type Clock struct { - mock *clockapi.Mock -} - -// Set sets the Clock to a clock.Mock at the given time.Time -func (c *Clock) Set(t time.Time) { - if c.mock == nil { - c.mock = clockapi.NewMock() - } - c.mock.Set(t) -} - -// Add moves clock forward time.Duration if it is mocked. It will error -// if the clock is not mocked. -func (c *Clock) Add(d time.Duration) error { - if c.mock == nil { - return errors.New("clock not mocked") - } - c.mock.Add(d) - return nil -} - -// Reset removes local clock.Mock. Returns any existing Mock if set in case -// lingering time operations are attached to it. -func (c *Clock) Reset() *clockapi.Mock { - existing := c.mock - c.mock = nil - return existing -} - -func (c *Clock) After(d time.Duration) <-chan time.Time { - m := c.mock - if m == nil { - return globalClock.After(d) - } - return m.After(d) -} - -func (c *Clock) AfterFunc(d time.Duration, f func()) *clockapi.Timer { - m := c.mock - if m == nil { - return globalClock.AfterFunc(d, f) - } - return m.AfterFunc(d, f) -} - -func (c *Clock) Now() time.Time { - m := c.mock - if m == nil { - return globalClock.Now() - } - return m.Now() -} - -func (c *Clock) Since(t time.Time) time.Duration { - m := c.mock - if m == nil { - return globalClock.Since(t) - } - return m.Since(t) -} - -func (c *Clock) Sleep(d time.Duration) { - m := c.mock - if m == nil { - globalClock.Sleep(d) - return - } - m.Sleep(d) -} - -func (c *Clock) Tick(d time.Duration) <-chan time.Time { - m := c.mock - if m == nil { - return globalClock.Tick(d) - } - return m.Tick(d) -} - -func (c *Clock) Ticker(d time.Duration) *clockapi.Ticker { - m := c.mock - if m == nil { - return globalClock.Ticker(d) - } - return m.Ticker(d) -} - -func (c *Clock) Timer(d time.Duration) *clockapi.Timer { - m := c.mock - if m == nil { - return globalClock.Timer(d) - } - return m.Timer(d) -} diff --git a/pkg/clock/clock_suite_test.go b/pkg/clock/clock_suite_test.go deleted file mode 100644 index 99d39f2419..0000000000 --- a/pkg/clock/clock_suite_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package clock_test - -import ( - "testing" - - "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" -) - -func TestClockSuite(t *testing.T) { - logger.SetOutput(GinkgoWriter) - logger.SetErrOutput(GinkgoWriter) - - RegisterFailHandler(Fail) - RunSpecs(t, "Clock") -} diff --git a/pkg/clock/clock_test.go b/pkg/clock/clock_test.go deleted file mode 100644 index e1b6d4407a..0000000000 --- a/pkg/clock/clock_test.go +++ /dev/null @@ -1,380 +0,0 @@ -package clock_test - -import ( - "sync" - "sync/atomic" - "time" - - "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/clock" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" -) - -const ( - testGlobalEpoch = 1000000000 - testLocalEpoch = 1234567890 -) - -var _ = Describe("Clock suite", func() { - var testClock = clock.Clock{} - - AfterEach(func() { - clock.Reset() - testClock.Reset() - }) - - Context("Global time not overridden", func() { - It("errors when trying to Add", func() { - err := clock.Add(123 * time.Hour) - Expect(err).To(HaveOccurred()) - }) - - Context("Clock not mocked via Set", func() { - const ( - outsideTolerance = int32(0) - withinTolerance = int32(1) - ) - - It("uses time.After for After", func() { - var tolerance int32 - go func() { - time.Sleep(10 * time.Millisecond) - atomic.StoreInt32(&tolerance, withinTolerance) - }() - go func() { - time.Sleep(30 * time.Millisecond) - atomic.StoreInt32(&tolerance, outsideTolerance) - }() - - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - - <-testClock.After(20 * time.Millisecond) - Expect(atomic.LoadInt32(&tolerance)).To(Equal(withinTolerance)) - - <-testClock.After(20 * time.Millisecond) - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - }) - - It("uses time.AfterFunc for AfterFunc", func() { - var tolerance int32 - go func() { - time.Sleep(10 * time.Millisecond) - atomic.StoreInt32(&tolerance, withinTolerance) - }() - go func() { - time.Sleep(30 * time.Millisecond) - atomic.StoreInt32(&tolerance, outsideTolerance) - }() - - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - - var wg sync.WaitGroup - wg.Add(1) - testClock.AfterFunc(20*time.Millisecond, func() { - wg.Done() - }) - wg.Wait() - Expect(atomic.LoadInt32(&tolerance)).To(Equal(withinTolerance)) - - wg.Add(1) - testClock.AfterFunc(20*time.Millisecond, func() { - wg.Done() - }) - wg.Wait() - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - }) - - It("uses time.Now for Now", func() { - a := time.Now() - b := testClock.Now() - Expect(b.Sub(a).Round(10 * time.Millisecond)).To(Equal(0 * time.Millisecond)) - }) - - It("uses time.Since for Since", func() { - past := time.Now().Add(-60 * time.Second) - Expect(time.Since(past).Round(10 * time.Millisecond)). - To(Equal(60 * time.Second)) - }) - - It("uses time.Sleep for Sleep", func() { - var tolerance int32 - go func() { - time.Sleep(10 * time.Millisecond) - atomic.StoreInt32(&tolerance, withinTolerance) - }() - go func() { - time.Sleep(30 * time.Millisecond) - atomic.StoreInt32(&tolerance, outsideTolerance) - }() - - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - - testClock.Sleep(20 * time.Millisecond) - Expect(atomic.LoadInt32(&tolerance)).To(Equal(withinTolerance)) - - testClock.Sleep(20 * time.Millisecond) - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - }) - - It("uses time.Tick for Tick", func() { - var tolerance int32 - go func() { - time.Sleep(10 * time.Millisecond) - atomic.StoreInt32(&tolerance, withinTolerance) - }() - go func() { - time.Sleep(50 * time.Millisecond) - atomic.StoreInt32(&tolerance, outsideTolerance) - }() - - ch := testClock.Tick(20 * time.Millisecond) - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - <-ch - Expect(atomic.LoadInt32(&tolerance)).To(Equal(withinTolerance)) - <-ch - Expect(atomic.LoadInt32(&tolerance)).To(Equal(withinTolerance)) - <-ch - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - }) - - It("uses time.Ticker for Ticker", func() { - var tolerance int32 - go func() { - time.Sleep(10 * time.Millisecond) - atomic.StoreInt32(&tolerance, withinTolerance) - }() - go func() { - time.Sleep(50 * time.Millisecond) - atomic.StoreInt32(&tolerance, outsideTolerance) - }() - - ticker := testClock.Ticker(20 * time.Millisecond) - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - <-ticker.C - Expect(atomic.LoadInt32(&tolerance)).To(Equal(withinTolerance)) - <-ticker.C - Expect(atomic.LoadInt32(&tolerance)).To(Equal(withinTolerance)) - <-ticker.C - Expect(atomic.LoadInt32(&tolerance)).To(Equal(outsideTolerance)) - }) - - It("errors if Add is used", func() { - err := testClock.Add(100 * time.Second) - Expect(err).To(HaveOccurred()) - }) - }) - - Context("Clock mocked via Set", func() { - var now = time.Unix(testLocalEpoch, 0) - - BeforeEach(func() { - testClock.Set(now) - }) - - It("mocks After", func() { - var after int32 - ready := make(chan struct{}) - ch := testClock.After(10 * time.Second) - go func(ch <-chan time.Time) { - close(ready) - <-ch - atomic.StoreInt32(&after, 1) - }(ch) - <-ready - - err := testClock.Add(9 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(0))) - - err = testClock.Add(1 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(1))) - }) - - It("mocks AfterFunc", func() { - var after int32 - testClock.AfterFunc(10*time.Second, func() { - atomic.StoreInt32(&after, 1) - }) - - err := testClock.Add(9 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(0))) - - err = testClock.Add(1 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(1))) - }) - - It("mocks AfterFunc with a stopped timer", func() { - var after int32 - timer := testClock.AfterFunc(10*time.Second, func() { - atomic.StoreInt32(&after, 1) - }) - timer.Stop() - - err := testClock.Add(11 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(0))) - }) - - It("mocks Now", func() { - Expect(testClock.Now()).To(Equal(now)) - err := testClock.Add(123 * time.Hour) - Expect(err).ToNot(HaveOccurred()) - Expect(testClock.Now()).To(Equal(now.Add(123 * time.Hour))) - }) - - It("mocks Since", func() { - Expect(testClock.Since(time.Unix(testLocalEpoch-100, 0))). - To(Equal(100 * time.Second)) - }) - - It("mocks Sleep", func() { - var after int32 - ready := make(chan struct{}) - go func() { - close(ready) - testClock.Sleep(10 * time.Second) - atomic.StoreInt32(&after, 1) - }() - <-ready - - err := testClock.Add(9 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(0))) - - err = testClock.Add(1 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(1))) - }) - - It("mocks Tick", func() { - var ticks int32 - ready := make(chan struct{}) - go func() { - close(ready) - tick := testClock.Tick(10 * time.Second) - for ticks < 5 { - <-tick - atomic.AddInt32(&ticks, 1) - } - }() - <-ready - - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(0))) - - err := testClock.Add(9 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(0))) - - err = testClock.Add(1 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(1))) - - err = testClock.Add(30 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(4))) - - err = testClock.Add(10 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(5))) - }) - - It("mocks Ticker", func() { - var ticks int32 - ready := make(chan struct{}) - go func() { - ticker := testClock.Ticker(10 * time.Second) - close(ready) - for ticks < 5 { - <-ticker.C - atomic.AddInt32(&ticks, 1) - } - }() - <-ready - - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(0))) - - err := testClock.Add(9 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(0))) - - err = testClock.Add(1 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(1))) - - err = testClock.Add(30 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(4))) - - err = testClock.Add(10 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&ticks)).To(Equal(int32(5))) - }) - - It("mocks Timer", func() { - var after int32 - ready := make(chan struct{}) - go func() { - timer := testClock.Timer(10 * time.Second) - close(ready) - <-timer.C - atomic.AddInt32(&after, 1) - }() - <-ready - - err := testClock.Add(9 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(0))) - - err = testClock.Add(1 * time.Second) - Expect(err).ToNot(HaveOccurred()) - Expect(atomic.LoadInt32(&after)).To(Equal(int32(1))) - }) - }) - }) - - Context("Global time overridden", func() { - var ( - globalNow = time.Unix(testGlobalEpoch, 0) - localNow = time.Unix(testLocalEpoch, 0) - ) - - BeforeEach(func() { - clock.Set(globalNow) - }) - - Context("Clock not mocked via Set", func() { - It("uses globally mocked Now", func() { - Expect(testClock.Now()).To(Equal(globalNow)) - err := clock.Add(123 * time.Hour) - Expect(err).ToNot(HaveOccurred()) - Expect(testClock.Now()).To(Equal(globalNow.Add(123 * time.Hour))) - }) - - It("errors when Add is called on the local Clock", func() { - err := testClock.Add(100 * time.Hour) - Expect(err).To(HaveOccurred()) - }) - }) - - Context("Clock is mocked via Set", func() { - BeforeEach(func() { - testClock.Set(localNow) - }) - - It("uses the local mock and ignores the global", func() { - Expect(testClock.Now()).To(Equal(localNow)) - - err := clock.Add(456 * time.Hour) - Expect(err).ToNot(HaveOccurred()) - - err = testClock.Add(123 * time.Hour) - Expect(err).ToNot(HaveOccurred()) - - Expect(testClock.Now()).To(Equal(localNow.Add(123 * time.Hour))) - }) - }) - }) -}) diff --git a/pkg/cookies/csrf.go b/pkg/cookies/csrf.go index 3b8efaf306..939578a276 100644 --- a/pkg/cookies/csrf.go +++ b/pkg/cookies/csrf.go @@ -10,7 +10,6 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" - "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/clock" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption" "github.com/vmihailenco/msgpack/v5" ) @@ -47,7 +46,7 @@ type csrf struct { CodeVerifier string `msgpack:"cv,omitempty"` cookieOpts *options.Cookie - time clock.Clock + clock func() time.Time } // csrtStateTrim will indicate the length of the state trimmed for the name of the csrf cookie @@ -70,6 +69,7 @@ func NewCSRF(opts *options.Cookie, codeVerifier string) (CSRF, error) { CodeVerifier: codeVerifier, cookieOpts: opts, + clock: time.Now, }, nil } @@ -187,7 +187,7 @@ func ClearExtraCsrfCookies(opts *options.Cookie, rw http.ResponseWriter, req *ht // delete the X oldest cookies slices.SortStableFunc(decodedCookies, func(a, b *csrf) int { - return a.time.Now().Compare(b.time.Now()) + return a.clock().Compare(b.clock()) }) for i := 0; i < len(decodedCookies)-opts.CSRFPerRequestLimit; i++ { @@ -223,7 +223,7 @@ func (c *csrf) encodeCookie() (string, error) { if err != nil { return "", fmt.Errorf("error getting cookie secret: %v", err) } - return encryption.SignedValue(secret, c.cookieName(), encrypted, c.time.Now()) + return encryption.SignedValue(secret, c.cookieName(), encrypted, c.clock()) } // decodeCSRFCookie validates the signature then decrypts and decodes a CSRF @@ -249,10 +249,10 @@ func decodeCSRFCookie(cookie *http.Cookie, opts *options.Cookie) (*csrf, error) // unmarshalCSRF unmarshals decrypted data into a CSRF struct func unmarshalCSRF(decrypted []byte, opts *options.Cookie, csrfTime time.Time) (*csrf, error) { - clock := clock.Clock{} - clock.Set(csrfTime) - - csrf := &csrf{cookieOpts: opts, time: clock} + csrf := &csrf{ + cookieOpts: opts, + clock: func() time.Time { return csrfTime }, + } if err := msgpack.Unmarshal(decrypted, csrf); err != nil { return nil, fmt.Errorf("error unmarshalling data to CSRF: %v", err) } diff --git a/pkg/cookies/csrf_per_request_test.go b/pkg/cookies/csrf_per_request_test.go index 9b7d4e592d..6a17013bfa 100644 --- a/pkg/cookies/csrf_per_request_test.go +++ b/pkg/cookies/csrf_per_request_test.go @@ -128,7 +128,7 @@ var _ = Describe("CSRF Cookie with non-fixed name Tests", func() { testNow := time.Unix(nowEpoch, 0) BeforeEach(func() { - privateCSRF.time.Set(testNow) + privateCSRF.clock = func() time.Time { return testNow } req = &http.Request{ Method: http.MethodGet, @@ -144,7 +144,7 @@ var _ = Describe("CSRF Cookie with non-fixed name Tests", func() { }) AfterEach(func() { - privateCSRF.time.Reset() + privateCSRF.clock = time.Now }) Context("SetCookie", func() { @@ -200,17 +200,17 @@ var _ = Describe("CSRF Cookie with non-fixed name Tests", func() { publicCSRF1, err := NewCSRF(cookieOpts, "verifier") Expect(err).ToNot(HaveOccurred()) privateCSRF1 := publicCSRF1.(*csrf) - privateCSRF1.time.Set(testNow) + privateCSRF1.clock = func() time.Time { return testNow } publicCSRF2, err := NewCSRF(cookieOpts, "verifier") Expect(err).ToNot(HaveOccurred()) privateCSRF2 := publicCSRF2.(*csrf) - privateCSRF2.time.Set(testNow.Add(time.Minute)) + privateCSRF2.clock = func() time.Time { return testNow.Add(time.Minute) } publicCSRF3, err := NewCSRF(cookieOpts, "verifier") Expect(err).ToNot(HaveOccurred()) privateCSRF3 := publicCSRF3.(*csrf) - privateCSRF3.time.Set(testNow.Add(time.Minute * 2)) + privateCSRF3.clock = func() time.Time { return testNow.Add(time.Minute * 2) } cookies := []string{} for _, csrf := range []*csrf{privateCSRF1, privateCSRF2, privateCSRF3} { diff --git a/pkg/cookies/csrf_test.go b/pkg/cookies/csrf_test.go index 37527bd079..085b91df1f 100644 --- a/pkg/cookies/csrf_test.go +++ b/pkg/cookies/csrf_test.go @@ -130,7 +130,7 @@ var _ = Describe("CSRF Cookie Tests", func() { testNow := time.Unix(nowEpoch, 0) BeforeEach(func() { - privateCSRF.time.Set(testNow) + privateCSRF.clock = func() time.Time { return testNow } req = &http.Request{ Method: http.MethodGet, @@ -146,7 +146,7 @@ var _ = Describe("CSRF Cookie Tests", func() { }) AfterEach(func() { - privateCSRF.time.Reset() + privateCSRF.clock = time.Now }) Context("SetCookie", func() { @@ -173,7 +173,7 @@ var _ = Describe("CSRF Cookie Tests", func() { Context("LoadCSRFCookie", func() { BeforeEach(func() { // we need to reset the time to ensure the cookie is valid - privateCSRF.time.Reset() + privateCSRF.clock = time.Now }) It("should return error when no cookie is set", func() { diff --git a/pkg/middleware/stored_session_test.go b/pkg/middleware/stored_session_test.go index 904c2028fa..d8e78f2fce 100644 --- a/pkg/middleware/stored_session_test.go +++ b/pkg/middleware/stored_session_test.go @@ -11,7 +11,6 @@ import ( middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" sessionsapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" - "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/clock" "github.com/oauth2-proxy/oauth2-proxy/v7/providers" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -95,6 +94,7 @@ var _ = Describe("Stored Session Suite", func() { now := time.Now() createdPast := now.Add(-5 * time.Minute) createdFuture := now.Add(5 * time.Minute) + clock := func() time.Time { return now } var defaultRefreshFunc = func(_ context.Context, ss *sessionsapi.SessionState) (bool, error) { switch ss.RefreshToken { @@ -120,6 +120,7 @@ var _ = Describe("Stored Session Suite", func() { RefreshToken: noRefresh, CreatedAt: &createdPast, ExpiresOn: &createdFuture, + Clock: clock, }, nil case "_oauth2_proxy=InvalidNoRefreshSession": return &sessionsapi.SessionState{ @@ -127,24 +128,28 @@ var _ = Describe("Stored Session Suite", func() { RefreshToken: noRefresh, CreatedAt: &createdPast, ExpiresOn: &createdFuture, + Clock: clock, }, nil case "_oauth2_proxy=ExpiredNoRefreshSession": return &sessionsapi.SessionState{ RefreshToken: noRefresh, CreatedAt: &createdPast, ExpiresOn: &createdPast, + Clock: clock, }, nil case "_oauth2_proxy=RefreshSession": return &sessionsapi.SessionState{ RefreshToken: refresh, CreatedAt: &createdPast, ExpiresOn: &createdFuture, + Clock: clock, }, nil case "_oauth2_proxy=RefreshError": return &sessionsapi.SessionState{ RefreshToken: "RefreshError", CreatedAt: &createdPast, ExpiresOn: &createdFuture, + Clock: clock, }, nil case "_oauth2_proxy=NonExistent": return nil, fmt.Errorf("invalid cookie") @@ -154,14 +159,6 @@ var _ = Describe("Stored Session Suite", func() { }, } - BeforeEach(func() { - clock.Set(now) - }) - - AfterEach(func() { - clock.Reset() - }) - type storedSessionLoaderTableInput struct { requestHeaders http.Header existingSession *sessionsapi.SessionState @@ -200,7 +197,15 @@ var _ = Describe("Stored Session Suite", func() { })) handler.ServeHTTP(rw, req) - Expect(gotSession).To(Equal(in.expectedSession)) + // Compare, ignoring testing Clock. + if in.expectedSession == nil { + Expect(gotSession).To(BeNil()) + return + } + Expect(gotSession).ToNot(BeNil()) + got := *gotSession + got.Clock = nil + Expect(&got).To(Equal(in.expectedSession)) }, Entry("with no cookie", storedSessionLoaderTableInput{ requestHeaders: http.Header{}, diff --git a/providers/provider_default_test.go b/providers/provider_default_test.go index f678d13d60..0fbe7abde8 100644 --- a/providers/provider_default_test.go +++ b/providers/provider_default_test.go @@ -17,8 +17,9 @@ func TestRefresh(t *testing.T) { now := time.Unix(1234567890, 10) expires := time.Unix(1234567890, 0) - ss := &sessions.SessionState{} - ss.Clock.Set(now) + ss := &sessions.SessionState{ + Clock: func() time.Time { return now }, + } ss.SetExpiresOn(expires) refreshed, err := p.RefreshSession(context.Background(), ss) From 87827435ce895a8d7c6dfa03a879dd3399d36cce Mon Sep 17 00:00:00 2001 From: Drew Foehn Date: Fri, 7 Nov 2025 13:44:32 -0500 Subject: [PATCH 060/125] feat: added organizationId/employee id as preferred username (#3237) Signed-off-by: Drew Foehn Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + docs/docs/configuration/alpha_config.md | 2 + docs/docs/configuration/providers/google.md | 23 ++++-- pkg/apis/options/legacy_options.go | 6 ++ pkg/apis/options/providers.go | 4 + providers/google.go | 83 +++++++++++++++++++-- providers/google_test.go | 80 ++++++++++++++++++++ 7 files changed, 185 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e014aee3cb..dbb0974cbb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - [#3228](https://github.com/oauth2-proxy/oauth2-proxy/pull/3228) fix: use GetSecret() in ticket.go makeCookie to respect cookie-secret-file (@stagswtf) - [#3244](https://github.com/oauth2-proxy/oauth2-proxy/pull/3244) chore(deps): upgrade to latest go1.25.3 (@tuunit) - [#3238](https://github.com/oauth2-proxy/oauth2-proxy/pull/3238) chore: Replace pkg/clock with narrowly targeted stub clocks (@dsymonds) +- [#3237](https://github.com/oauth2-proxy/oauth2-proxy/pull/3237) - feat: add option to use organization id for preferred username in Google Provider (@pixeldrew) # V7.12.0 diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index 28645ceba1..54ccb01ee4 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -252,6 +252,8 @@ Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". | `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | | `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | | `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | +| `useOrganizationID` | _bool_ | UseOrganizationId indicates whether to use the organization ID as the UserName claim | +| `adminAPIUserScope` | _string_ | admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly | ### Header diff --git a/docs/docs/configuration/providers/google.md b/docs/docs/configuration/providers/google.md index ac2a7dfaaf..0de5bb74a5 100644 --- a/docs/docs/configuration/providers/google.md +++ b/docs/docs/configuration/providers/google.md @@ -5,13 +5,15 @@ title: Google (default) ## Config Options -| Flag | Toml Field | Type | Description | Default | -| ---------------------------------------------- | -------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------ | -------------------------------------------------- | -| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | -| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). If not specified and service account or default credentials are configured, all user groups will be allowed. | | -| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | -| `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | -| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | +| Flag | Toml Field | Type | Description | Default | +|-------------------------------------------------|----------------------------------------------| ------ |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------| +| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | +| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). If not specified and service account or default credentials are configured, all user groups will be allowed. | | +| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | +| `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | +| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | +| `--google-use-organization-id` | `google_use_organization_id` | bool | use organization id as preferred username | false | +| `--google-admin-api-user-scope` | `google_admin_api_user_scope` | string | the OAuth scope to use when querying the Google Admin SDK for organization id, can be 'readonly', 'user' or 'cloud'
| `readonly` | ## Usage @@ -73,3 +75,10 @@ can be leveraged through a feature called Workload Identity. Follow Google's [gu to set up Workload Identity. When deployed outside of GCP, [Workload Identity Federation](https://cloud.google.com/docs/authentication/provide-credentials-adc#wlif) might be an option. + +##### Using Organization ID as Preferred Username (optional) +By default, the google provider uses the google id as username. If you would like to use an organization id instead, you can set the `google-use-organization-id` flag to true. +This requires that the service account used to query the Google Admin SDK has one of the following scopes granted in step 5 above: +- `https://www.googleapis.com/auth/admin.directory.user.readonly`, +- `https://www.googleapis.com/auth/admin.directory.user` +- `https://www.googleapis.com/auth/cloud-platform` diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index 1297522520..e22278fa82 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -510,6 +510,8 @@ type LegacyProvider struct { GoogleServiceAccountJSON string `flag:"google-service-account-json" cfg:"google_service_account_json"` GoogleUseApplicationDefaultCredentials bool `flag:"google-use-application-default-credentials" cfg:"google_use_application_default_credentials"` GoogleTargetPrincipal string `flag:"google-target-principal" cfg:"google_target_principal"` + GoogleUseOrganizationID bool `flag:"google-use-organization-id" cfg:"google_use_organization_id"` + GoogleAdminAPIUserScope string `flag:"google-admin-api-user-scope" cfg:"google_admin_api_user_scope"` // These options allow for other providers besides Google, with // potential overrides. @@ -623,6 +625,8 @@ func legacyGoogleFlagSet() *pflag.FlagSet { flagSet.String("google-service-account-json", "", "the path to the service account json credentials") flagSet.String("google-use-application-default-credentials", "", "use application default credentials instead of service account json (i.e. GKE Workload Identity)") flagSet.String("google-target-principal", "", "the target principal to impersonate when using ADC") + flagSet.String("google-use-organization-id", "", "use organization id as preferred username") + flagSet.String("google-admin-api-user-scope", "", "authorization scope required to call users.get, can be one of ") return flagSet } @@ -770,6 +774,8 @@ func (l *LegacyProvider) convert() (Providers, error) { ServiceAccountJSON: l.GoogleServiceAccountJSON, UseApplicationDefaultCredentials: l.GoogleUseApplicationDefaultCredentials, TargetPrincipal: l.GoogleTargetPrincipal, + UseOrganizationID: l.GoogleUseOrganizationID, + AdminAPIUserScope: l.GoogleAdminAPIUserScope, } case "entra-id": provider.MicrosoftEntraIDConfig = MicrosoftEntraIDOptions{ diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 0f25457585..3a5094dacf 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -230,6 +230,10 @@ type GoogleOptions struct { UseApplicationDefaultCredentials bool `json:"useApplicationDefaultCredentials,omitempty"` // TargetPrincipal is the Google Service Account used for Application Default Credentials TargetPrincipal string `json:"targetPrincipal,omitempty"` + // UseOrganizationId indicates whether to use the organization ID as the UserName claim + UseOrganizationID bool `json:"useOrganizationID,omitempty"` + // admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly + AdminAPIUserScope string `json:"adminAPIUserScope,omitempty"` } type OIDCOptions struct { diff --git a/providers/google.go b/providers/google.go index 097e35670d..a6a9d283f1 100644 --- a/providers/google.go +++ b/providers/google.go @@ -40,6 +40,8 @@ type GoogleProvider struct { // Refresh. `Authorize` uses the results of this saved in `session.Groups` // Since it is called on every request. groupValidator func(*sessions.SessionState) bool + + setPreferredUsername func(s *sessions.SessionState) error } var _ Provider = (*GoogleProvider)(nil) @@ -100,17 +102,59 @@ func NewGoogleProvider(p *ProviderData, opts options.GoogleOptions) (*GoogleProv groupValidator: func(*sessions.SessionState) bool { return true }, - } - if opts.ServiceAccountJSON != "" || opts.UseApplicationDefaultCredentials { - provider.configureGroups(opts) + setPreferredUsername: func(_ *sessions.SessionState) error { + return nil + }, } + if opts.UseOrganizationID || opts.ServiceAccountJSON != "" || opts.UseApplicationDefaultCredentials { + + // reuse admin service to avoid multiple calls for token + var adminService *admin.Service + + if opts.UseOrganizationID { + // add user scopes to admin api + userScope := getAdminAPIUserScope(opts.AdminAPIUserScope) + for index, scope := range possibleScopesList { + possibleScopesList[index] = scope + " " + userScope + } + + adminService = getAdminService(opts) + + provider.setPreferredUsername = func(s *sessions.SessionState) error { + userName, err := getUserInfo(adminService, s.Email) + if err != nil { + return err + } + s.PreferredUsername = userName + return nil + } + } + + if opts.ServiceAccountJSON != "" || opts.UseApplicationDefaultCredentials { + if adminService == nil { + adminService = getAdminService(opts) + } + provider.configureGroups(opts, adminService) + } + + } return provider, nil } -func (p *GoogleProvider) configureGroups(opts options.GoogleOptions) { - adminService := getAdminService(opts) +// by default can be readonly user scope +func getAdminAPIUserScope(scope string) string { + switch scope { + case "cloud": + return admin.CloudPlatformScope + case "user": + return admin.AdminDirectoryUserScope + } + return admin.AdminDirectoryUserReadonlyScope +} + +func (p *GoogleProvider) configureGroups(opts options.GoogleOptions, adminService *admin.Service) { // Backwards compatibility with `--google-group` option if len(opts.Groups) > 0 { p.setAllowedGroups(opts.Groups) @@ -204,6 +248,7 @@ func (p *GoogleProvider) Redeem(ctx context.Context, redirectURL, code, codeVeri // EnrichSession checks the listed Google Groups configured and adds any // that the user is a member of to session.Groups. +// if preferred username is configured to be organization ID, it sets that as well. func (p *GoogleProvider) EnrichSession(_ context.Context, s *sessions.SessionState) error { // TODO (@NickMeves) - Move to pure EnrichSession logic and stop // reusing legacy `groupValidator`. @@ -212,7 +257,7 @@ func (p *GoogleProvider) EnrichSession(_ context.Context, s *sessions.SessionSta // populating logic. p.groupValidator(s) - return nil + return p.setPreferredUsername(s) } // SetGroupRestriction configures the GoogleProvider to restrict access to the @@ -262,7 +307,7 @@ func getOauth2TokenSource(ctx context.Context, opts options.GoogleOptions, scope if opts.UseApplicationDefaultCredentials { ts, err := impersonate.CredentialsTokenSource(ctx, impersonate.CredentialsConfig{ TargetPrincipal: getTargetPrincipal(ctx, opts), - Scopes: []string{scope}, + Scopes: strings.Split(scope, " "), Subject: opts.AdminEmail, }) if err != nil { @@ -364,6 +409,30 @@ func getTargetPrincipal(ctx context.Context, opts options.GoogleOptions) (target return targetPrincipal } +func getUserInfo(service *admin.Service, email string) (string, error) { + req := service.Users.Get(email) + user, err := req.Do() + if err != nil { + return "", fmt.Errorf("failed to get user details for %s: %v", email, err) + } + + ext, _ := user.ExternalIds.([]interface{}) + for _, v := range ext { + m, _ := v.(map[string]interface{}) + if m == nil { + continue + } + if t, _ := m["type"].(string); t != "organization" { + continue + } + if val, _ := m["value"].(string); val != "" { + return val, nil + } + } + + return "", fmt.Errorf("failed to get organization id for %s", email) +} + // getUserGroups retrieves all groups that a user is a member of using the Google Admin Directory API func getUserGroups(service *admin.Service, email string) ([]string, error) { var allGroups []string diff --git a/providers/google_test.go b/providers/google_test.go index dc061203fc..f168e31cb6 100644 --- a/providers/google_test.go +++ b/providers/google_test.go @@ -325,3 +325,83 @@ func TestGoogleProvider_getUserGroups(t *testing.T) { assert.NoError(t, err) assert.Equal(t, []string{"group1@example.com", "group2@example.com"}, groups) } + +func TestGoogleProvider_getUserInfo(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/admin/directory/v1/users/test@example.com" { + response := `{ + "kind": "admin#directory#user", + "id": "", + "etag": "\"\"", + "primaryEmail": "test@example.com", + "name": { + "givenName": "Test", + "familyName": "User", + "fullName": "Test User" + }, + "isAdmin": false, + "isDelegatedAdmin": false, + "lastLoginTime": "", + "creationTime": "", + "agreedToTerms": true, + "suspended": false, + "archived": false, + "changePasswordAtNextLogin": false, + "ipWhitelisted": false, + "emails": [ + { + "address": "test@example.com", + "primary": true + } + ], + "externalIds": [ + { + "value": "test.user", + "type": "organization" + } + ], + "organizations": [ + ], + "phones": [ + ], + "languages": [ + { + "languageCode": "en", + "preference": "preferred" + } + ], + "aliases": [ + "test.user@example.com" + ], + "nonEditableAliases": [ + "test.user@example.com" + ], + "gender": { + "type": "male" + }, + "customerId": "", + "orgUnitPath": "/", + "isMailboxSetup": true, + "isEnrolledIn2Sv": true, + "isEnforcedIn2Sv": false, + "includeInGlobalAddressList": true, + "thumbnailPhotoUrl": "", + "thumbnailPhotoEtag": "\"\"", + "recoveryEmail": "test.user@gmail.com", + "recoveryPhone": "+55555555555" + }` + fmt.Fprintln(w, response) + } else { + http.NotFound(w, r) + } + })) + defer ts.Close() + + client := &http.Client{} + adminService, err := admin.NewService(context.Background(), option.WithHTTPClient(client), option.WithEndpoint(ts.URL)) + assert.NoError(t, err) + + info, err := getUserInfo(adminService, "test@example.com") + assert.NoError(t, err) + assert.Equal(t, "test.user", info) +} From 5993067505cac4c8e80192787ccd1f4cba05d994 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 8 Nov 2025 12:42:45 +0100 Subject: [PATCH 061/125] Merge commit from fork Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + pkg/middleware/headers.go | 37 ++++++++++++++++++++++++++++++---- pkg/middleware/headers_test.go | 21 +++++++++++++++++++ 3 files changed, 55 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dbb0974cbb..20a8f67f86 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - [#3244](https://github.com/oauth2-proxy/oauth2-proxy/pull/3244) chore(deps): upgrade to latest go1.25.3 (@tuunit) - [#3238](https://github.com/oauth2-proxy/oauth2-proxy/pull/3238) chore: Replace pkg/clock with narrowly targeted stub clocks (@dsymonds) - [#3237](https://github.com/oauth2-proxy/oauth2-proxy/pull/3237) - feat: add option to use organization id for preferred username in Google Provider (@pixeldrew) +- [GHSA-vjrc-mh2v-45x6](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-vjrc-mh2v-45x6) fix: request header smuggling by stripping all normalized header variants (@tuunit) # V7.12.0 diff --git a/pkg/middleware/headers.go b/pkg/middleware/headers.go index 8d2f8e3ebf..f833848f7f 100644 --- a/pkg/middleware/headers.go +++ b/pkg/middleware/headers.go @@ -25,10 +25,10 @@ func NewRequestHeaderInjector(headers []options.Header) (alice.Constructor, erro } func newStripHeaders(headers []options.Header) alice.Constructor { - headersToStrip := []string{} + headersToStrip := []options.Header{} for _, header := range headers { if !header.PreserveRequestValue { - headersToStrip = append(headersToStrip, header.Name) + headersToStrip = append(headersToStrip, header) } } @@ -50,10 +50,10 @@ func flattenHeaders(headers http.Header) { } } -func stripHeaders(headers []string, next http.Handler) http.Handler { +func stripHeaders(headers []options.Header, next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { for _, header := range headers { - req.Header.Del(header) + stripNormalizedHeader(req, header) } next.ServeHTTP(rw, req) }) @@ -113,3 +113,32 @@ func injectResponseHeaders(injector header.Injector, next http.Handler) http.Han next.ServeHTTP(rw, req) }) } + +// normalizeHeaderName normalizes the header name by lowercasing it +// and replacing underscores with hyphens. +func normalizeHeaderName(headerName string) string { + headerName = strings.ToLower(headerName) + headerName = strings.ReplaceAll(headerName, "_", "-") + return headerName +} + +// stripNormalizedHeader removes any headers from the request that match +// the normalized version of the provided header's name. +func stripNormalizedHeader(req *http.Request, header options.Header) { + normalizedName := normalizeHeaderName(header.Name) + + toBeDeleted := []string{} + for h := range req.Header { + if normalizeHeaderName(h) == normalizedName { + // necessary to avoid modifying the map while iterating + toBeDeleted = append(toBeDeleted, h) + } + } + + for _, h := range toBeDeleted { + // necessary because req.Header.Del accesses the map via + // the header's canonicalized name. We need to delete by + // the original name. + delete(req.Header, h) + } +} diff --git a/pkg/middleware/headers_test.go b/pkg/middleware/headers_test.go index 06440eea5f..1493795529 100644 --- a/pkg/middleware/headers_test.go +++ b/pkg/middleware/headers_test.go @@ -205,6 +205,27 @@ var _ = Describe("Headers Suite", func() { expectedHeaders: nil, expectedErr: "error building request header injector: error building request injector: error building injector for header \"X-Auth-Request-Authorization\": error loading basicAuthPassword: secret source is invalid: exactly one entry required, specify either value, fromEnv or fromFile", }), + Entry("strips normalized variants before injecting (no preservation)", headersTableInput{ + headers: []options.Header{ + { + Name: "X-Auth-Request-User", + Values: []options.HeaderValue{ + { + ClaimSource: &options.ClaimSource{Claim: "user"}, + }, + }, + }, + }, + initialHeaders: http.Header{ + "X-Auth-Request-User": []string{"old"}, + "X-Auth_Request_User": []string{"evil"}, + }, + session: &sessionsapi.SessionState{User: "user-123"}, + expectedHeaders: http.Header{ + "X-Auth-Request-User": []string{"user-123"}, + }, + expectedErr: "", + }), ) DescribeTable("the response header injector", From f3f30fa976fb4bb97d6345ba4735cb6d86e24f95 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 8 Nov 2025 12:52:31 +0100 Subject: [PATCH 062/125] Merge commit from fork Signed-off-by: Jan Larwig --- docs/docs/configuration/alpha_config.md | 1 + pkg/apis/options/header.go | 10 ++++++++++ pkg/middleware/headers.go | 5 +++++ pkg/middleware/headers_test.go | 25 ++++++++++++++++++++++++- 4 files changed, 40 insertions(+), 1 deletion(-) diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index 54ccb01ee4..9e6c2873ea 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -266,6 +266,7 @@ response header. | ----- | ---- | ----------- | | `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | | `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `InsecureSkipHeaderNormalization` | _bool_ | InsecureSkipHeaderNormalization disables normalizing the header name
According to RFC 7230 Section 3.2 there aren't any rules about
capitalization of header names, but the standard practice is to use
Title-Case (e.g. X-Forwarded-For). By default, header names will be
normalized to Title-Case and any incoming headers that match will be
treated as the same header. Additionally underscores (_) in header names
will be converted to dashes (-) when normalizing.
Defaults to false (header names will be normalized). | | `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | ### HeaderValue diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index 90e6445cb6..4299fd35da 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -13,6 +13,16 @@ type Header struct { // Defaults to false (headers that match this header will be stripped). PreserveRequestValue bool `json:"preserveRequestValue,omitempty"` + // InsecureSkipHeaderNormalization disables normalizing the header name + // According to RFC 7230 Section 3.2 there aren't any rules about + // capitalization of header names, but the standard practice is to use + // Title-Case (e.g. X-Forwarded-For). By default, header names will be + // normalized to Title-Case and any incoming headers that match will be + // treated as the same header. Additionally underscores (_) in header names + // will be converted to dashes (-) when normalizing. + // Defaults to false (header names will be normalized). + InsecureSkipHeaderNormalization bool `json:"InsecureSkipHeaderNormalization,omitempty"` + // Values contains the desired values for this header Values []HeaderValue `json:"values,omitempty"` } diff --git a/pkg/middleware/headers.go b/pkg/middleware/headers.go index f833848f7f..623d50e9f0 100644 --- a/pkg/middleware/headers.go +++ b/pkg/middleware/headers.go @@ -53,6 +53,11 @@ func flattenHeaders(headers http.Header) { func stripHeaders(headers []options.Header, next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { for _, header := range headers { + if header.InsecureSkipHeaderNormalization { + req.Header.Del(header.Name) + continue + } + stripNormalizedHeader(req, header) } next.ServeHTTP(rw, req) diff --git a/pkg/middleware/headers_test.go b/pkg/middleware/headers_test.go index 1493795529..6a60ec0162 100644 --- a/pkg/middleware/headers_test.go +++ b/pkg/middleware/headers_test.go @@ -205,7 +205,7 @@ var _ = Describe("Headers Suite", func() { expectedHeaders: nil, expectedErr: "error building request header injector: error building request injector: error building injector for header \"X-Auth-Request-Authorization\": error loading basicAuthPassword: secret source is invalid: exactly one entry required, specify either value, fromEnv or fromFile", }), - Entry("strips normalized variants before injecting (no preservation)", headersTableInput{ + Entry("strips normalized variants before injecting", headersTableInput{ headers: []options.Header{ { Name: "X-Auth-Request-User", @@ -226,6 +226,29 @@ var _ = Describe("Headers Suite", func() { }, expectedErr: "", }), + Entry("doesn't strip normalized variants before injecting", headersTableInput{ + headers: []options.Header{ + { + Name: "X-Auth-Request-User", + InsecureSkipHeaderNormalization: true, + Values: []options.HeaderValue{ + { + ClaimSource: &options.ClaimSource{Claim: "user"}, + }, + }, + }, + }, + initialHeaders: http.Header{ + "X-Auth-Request-User": []string{"old"}, + "X-Auth_Request_User": []string{"evil"}, + }, + session: &sessionsapi.SessionState{User: "user-123"}, + expectedHeaders: http.Header{ + "X-Auth-Request-User": []string{"user-123"}, + "X-Auth_Request_User": []string{"evil"}, + }, + expectedErr: "", + }), ) DescribeTable("the response header injector", From 22053dcadeb530d70f4a58fa1908cca489b4b39a Mon Sep 17 00:00:00 2001 From: Michi Gysel Date: Sat, 8 Nov 2025 13:49:48 +0100 Subject: [PATCH 063/125] fix: validation of refreshed sessions using the access_token in the OIDC provider (#1933) Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + pkg/apis/sessions/session_state.go | 5 +++-- providers/oidc.go | 27 +++++++++++++++++++++------ 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20a8f67f86..cb4904c5e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ - [#3238](https://github.com/oauth2-proxy/oauth2-proxy/pull/3238) chore: Replace pkg/clock with narrowly targeted stub clocks (@dsymonds) - [#3237](https://github.com/oauth2-proxy/oauth2-proxy/pull/3237) - feat: add option to use organization id for preferred username in Google Provider (@pixeldrew) - [GHSA-vjrc-mh2v-45x6](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-vjrc-mh2v-45x6) fix: request header smuggling by stripping all normalized header variants (@tuunit) +- [#1933](https://github.com/oauth2-proxy/oauth2-proxy/pull/1933) fix: validation of refreshed sessions using the access_token in the OIDC provider (@gysel / @tuunit) # V7.12.0 diff --git a/pkg/apis/sessions/session_state.go b/pkg/apis/sessions/session_state.go index 5b063c3f06..a1f807aba9 100644 --- a/pkg/apis/sessions/session_state.go +++ b/pkg/apis/sessions/session_state.go @@ -29,8 +29,9 @@ type SessionState struct { PreferredUsername string `msgpack:"pu,omitempty"` // Internal helpers, not serialized - Clock func() time.Time `msgpack:"-"` // override for time.Now, for testing - Lock Lock `msgpack:"-"` + Clock func() time.Time `msgpack:"-"` // override for time.Now, for testing + Lock Lock `msgpack:"-"` + Refreshed bool `msgpack:"-"` // indicates whether the session was refreshed } func (s *SessionState) now() time.Time { diff --git a/providers/oidc.go b/providers/oidc.go index 15598aba58..eeac407322 100644 --- a/providers/oidc.go +++ b/providers/oidc.go @@ -110,11 +110,24 @@ func (p *OIDCProvider) EnrichSession(_ context.Context, s *sessions.SessionState return nil } -// ValidateSession checks that the session's IDToken is still valid +// ValidateSession checks that the session's id_token or access_token (when a ValidateURL is configured) is still valid func (p *OIDCProvider) ValidateSession(ctx context.Context, s *sessions.SessionState) bool { ctx = oidc.ClientContext(ctx, requests.DefaultHTTPClient) - _, err := p.Verifier.Verify(ctx, s.IDToken) - if err != nil { + + // https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse + // The ID Token is optional in the Refresh Token Response + // TODO: @tuunit remove dependency on refreshed flag and only rely on presence of access_token + // in accordance with the spec. For now, keep existing behavior. + if s.Refreshed { + if !validateToken(ctx, p, s.AccessToken, makeOIDCHeader(s.AccessToken)) { + logger.Errorf("access_token validation failed") + return false + } + + return true + } + + if _, err := p.Verifier.Verify(ctx, s.IDToken); err != nil { logger.Errorf("id_token verification failed: %v", err) return false } @@ -122,8 +135,8 @@ func (p *OIDCProvider) ValidateSession(ctx context.Context, s *sessions.SessionS if p.SkipNonce { return true } - err = p.checkNonce(s) - if err != nil { + + if err := p.checkNonce(s); err != nil { logger.Errorf("nonce verification failed: %v", err) return false } @@ -147,7 +160,8 @@ func (p *OIDCProvider) RefreshSession(ctx context.Context, s *sessions.SessionSt } // redeemRefreshToken uses a RefreshToken with the RedeemURL to refresh the -// Access Token and (probably) the ID Token. +// Access Token and (optionally) the ID Token. +// https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse func (p *OIDCProvider) redeemRefreshToken(ctx context.Context, s *sessions.SessionState) error { clientSecret, err := p.GetClientSecret() if err != nil { @@ -250,6 +264,7 @@ func (p *OIDCProvider) createSession(ctx context.Context, token *oauth2.Token, r ss.CreatedAtNow() ss.SetExpiresOn(token.Expiry) + ss.Refreshed = refresh return ss, nil } From fcc2db040e2da5781919f21577f721911a384419 Mon Sep 17 00:00:00 2001 From: Jacob Alberty Date: Sat, 8 Nov 2025 06:58:34 -0600 Subject: [PATCH 064/125] feat: add allowed_* constraint option to proxy endpoint query string (#2841) * Add check for constraints to the proxy endpoint * Add tests for allowed_groups query string * Add this feature to the changelog * Apply suggestions from code review Co-authored-by: Jan Larwig * Use explicit key names in TestProxyAllowedGroups * Document the query parameters on proxy endpoint * Comment was copied from the AuthOnly handler but on closer inspection is not relevant here replacing comment with one more relevant --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + docs/docs/features/endpoints.md | 12 ++++++ oauthproxy.go | 7 ++++ oauthproxy_test.go | 73 ++++++++++++++++++++++++++++++--- 4 files changed, 88 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb4904c5e2..7594b407a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ - [#3237](https://github.com/oauth2-proxy/oauth2-proxy/pull/3237) - feat: add option to use organization id for preferred username in Google Provider (@pixeldrew) - [GHSA-vjrc-mh2v-45x6](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-vjrc-mh2v-45x6) fix: request header smuggling by stripping all normalized header variants (@tuunit) - [#1933](https://github.com/oauth2-proxy/oauth2-proxy/pull/1933) fix: validation of refreshed sessions using the access_token in the OIDC provider (@gysel / @tuunit) +- [#2841](https://github.com/oauth2-proxy/oauth2-proxy/pull/2841) feat: add allowed_* constraint option to proxy endpoint query string (@jacobalberty) # V7.12.0 diff --git a/docs/docs/features/endpoints.md b/docs/docs/features/endpoints.md index 3ec1e2aa8a..db00ba1e0b 100644 --- a/docs/docs/features/endpoints.md +++ b/docs/docs/features/endpoints.md @@ -5,6 +5,7 @@ title: Endpoints OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable. +- / - the proxy endpoint provides authentication and returns the appropriate 40x error if not authenticated or authorized then passes the request upstream. - /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info - /ping - returns a 200 OK response, which is intended for use with health checks - /ready - returns a 200 OK response if all the underlying connections (e.g., Redis store) are connected @@ -45,3 +46,14 @@ It can be configured using the following query parameters: - `allowed_groups`: comma separated list of allowed groups - `allowed_email_domains`: comma separated list of allowed email domains - `allowed_emails`: comma separated list of allowed emails + +### Proxy (/) + +This endpoint returns the upstream response if authenticated. +If unauthenticated it returns a 401 Unauthorized. If the authenticatd user +is not in one of the allowed groups, or emails then it returns a 403 forbidden + +It can be configured using the following query parameters: +- `allowed_groups`: comma separated list of allowed groups +- `allowed_email_domains`: comma separated list of allowed email domains +- `allowed_emails`: comma separated list of allowed emails diff --git a/oauthproxy.go b/oauthproxy.go index 7526d6417a..c6db18a766 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -1012,6 +1012,13 @@ func (p *OAuthProxy) Proxy(rw http.ResponseWriter, req *http.Request) { session, err := p.getAuthenticatedSession(rw, req) switch err { case nil: + // Check against our authorization constraints and return forbidden + // if this request fails to satisfy them. + if !authOnlyAuthorize(req, session) { + http.Error(rw, http.StatusText(http.StatusForbidden), http.StatusForbidden) + return + } + // we are authenticated p.addHeadersForProxying(rw, session) p.headersChain.Then(p.upstreamProxy).ServeHTTP(rw, req) diff --git a/oauthproxy_test.go b/oauthproxy_test.go index 488b8cead2..e05396cd3c 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -2938,12 +2938,75 @@ func TestProxyAllowedGroups(t *testing.T) { name string allowedGroups []string groups []string + querystring string expectUnauthorized bool }{ - {"NoAllowedGroups", []string{}, []string{}, false}, - {"NoAllowedGroupsUserHasGroups", []string{}, []string{"a", "b"}, false}, - {"UserInAllowedGroup", []string{"a"}, []string{"a", "b"}, false}, - {"UserNotInAllowedGroup", []string{"a"}, []string{"c"}, true}, + { + name: "NoAllowedGroups", + allowedGroups: []string{}, + groups: []string{}, + querystring: "", + expectUnauthorized: false}, + { + name: "NoAllowedGroupsUserHasGroups", + allowedGroups: []string{}, + groups: []string{"a", "b"}, + querystring: "", + expectUnauthorized: false}, + { + name: "UserInAllowedGroup", + allowedGroups: []string{"a"}, + groups: []string{"a", "b"}, + querystring: "", + expectUnauthorized: false}, + { + name: "UserNotInAllowedGroup", + allowedGroups: []string{"a"}, + groups: []string{"c"}, + querystring: "", + expectUnauthorized: true}, + { + name: "UserInQuerystringGroup", + allowedGroups: []string{"a", "b"}, + groups: []string{"a", "c"}, + querystring: "?allowed_groups=a", + expectUnauthorized: false}, + { + name: "UserInMultiParamQuerystringGroup", + allowedGroups: []string{"a", "b"}, + groups: []string{"b"}, + querystring: "?allowed_groups=a&allowed_groups=b,d", + expectUnauthorized: false}, + { + name: "UserInOnlyQuerystringGroup", + allowedGroups: []string{}, + groups: []string{"a", "c"}, + querystring: "?allowed_groups=a,b", + expectUnauthorized: false}, + { + name: "UserInDelimitedQuerystringGroup", + allowedGroups: []string{"a", "b", "c"}, + groups: []string{"c"}, + querystring: "?allowed_groups=a,c", + expectUnauthorized: false}, + { + name: "UserNotInQuerystringGroup", + allowedGroups: []string{}, + groups: []string{"c"}, + querystring: "?allowed_groups=a,b", + expectUnauthorized: true}, + { + name: "UserInConfigGroupNotInQuerystringGroup", + allowedGroups: []string{"a", "b", "c"}, + groups: []string{"c"}, + querystring: "?allowed_groups=a,b", + expectUnauthorized: true}, + { + name: "UserInQuerystringGroupNotInConfigGroup", + allowedGroups: []string{"a", "b"}, + groups: []string{"c"}, + querystring: "?allowed_groups=b,c", + expectUnauthorized: true}, } for _, tt := range tests { @@ -2979,7 +3042,7 @@ func TestProxyAllowedGroups(t *testing.T) { t.Fatal(err) } - test.req, _ = http.NewRequest("GET", "/", nil) + test.req, _ = http.NewRequest("GET", fmt.Sprintf("/%s", tt.querystring), nil) test.req.Header.Add("accept", applicationJSON) err = test.SaveSession(session) From 082b49aaeb656fea23ad9accdc5a4be9218bb0d4 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 8 Nov 2025 14:29:37 +0100 Subject: [PATCH 065/125] release: v7.13.0 (#3251) * add new docs version 7.13.x * update to release version v7.13.0 * doc: add release notes v7.13.0 Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Jan Larwig --- CHANGELOG.md | 23 + .../docker-compose-alpha-config.yaml | 2 +- .../docker-compose-gitea.yaml | 2 +- .../docker-compose-keycloak.yaml | 2 +- .../docker-compose-nginx.yaml | 2 +- .../docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/installation.md | 2 +- .../version-7.13.x/behaviour.md | 11 + .../version-7.13.x/community/contribution.md | 91 +++ .../version-7.13.x/community/security.md | 49 ++ .../configuration/alpha_config.md | 568 ++++++++++++++++++ .../configuration/alpha_config.md.tmpl | 139 +++++ .../configuration/integration.md | 310 ++++++++++ .../version-7.13.x/configuration/overview.md | 406 +++++++++++++ .../configuration/providers/adfs.md | 19 + .../configuration/providers/bitbucket.md | 25 + .../configuration/providers/cidaas.md | 37 ++ .../configuration/providers/digitalocean.md | 21 + .../configuration/providers/facebook.md | 7 + .../configuration/providers/gitea.md | 24 + .../configuration/providers/github.md | 81 +++ .../configuration/providers/gitlab.md | 49 ++ .../configuration/providers/google.md | 84 +++ .../configuration/providers/index.md | 45 ++ .../configuration/providers/keycloak.md | 36 ++ .../configuration/providers/keycloak_oidc.md | 151 +++++ .../configuration/providers/linkedin.md | 13 + .../configuration/providers/login_gov.md | 79 +++ .../configuration/providers/ms_azure_ad.md | 59 ++ .../configuration/providers/ms_entra_id.md | 197 ++++++ .../configuration/providers/nextcloud.md | 28 + .../configuration/providers/openid_connect.md | 146 +++++ .../configuration/providers/sourcehut.md | 25 + .../version-7.13.x/configuration/sessions.md | 99 +++ .../configuration/systemd_socket.md | 43 ++ .../version-7.13.x/configuration/tls.md | 85 +++ .../version-7.13.x/features/endpoints.md | 47 ++ .../version-7.13.x/installation.md | 32 + docs/versioned_docs/version-7.13.x/welcome.md | 23 + .../version-7.13.x-sidebars.json | 84 +++ docs/versions.json | 1 + 42 files changed, 3144 insertions(+), 7 deletions(-) create mode 100644 docs/versioned_docs/version-7.13.x/behaviour.md create mode 100644 docs/versioned_docs/version-7.13.x/community/contribution.md create mode 100644 docs/versioned_docs/version-7.13.x/community/security.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/alpha_config.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/alpha_config.md.tmpl create mode 100644 docs/versioned_docs/version-7.13.x/configuration/integration.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/overview.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/adfs.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/bitbucket.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/cidaas.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/digitalocean.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/facebook.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/gitea.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/github.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/gitlab.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/google.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/index.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/keycloak.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/keycloak_oidc.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/linkedin.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/login_gov.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/ms_azure_ad.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/ms_entra_id.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/nextcloud.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/openid_connect.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/sourcehut.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/sessions.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/systemd_socket.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/tls.md create mode 100644 docs/versioned_docs/version-7.13.x/features/endpoints.md create mode 100644 docs/versioned_docs/version-7.13.x/installation.md create mode 100644 docs/versioned_docs/version-7.13.x/welcome.md create mode 100644 docs/versioned_sidebars/version-7.13.x-sidebars.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 7594b407a9..13ef6807dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,29 @@ ## Breaking Changes +## Changes since v7.13.0 + +# V7.13.0 + +## Release Highlights + +- 🕵️‍♀️ Vulnerabilities have been addressd + - [CVE-2025-47912](https://nvd.nist.gov/vuln/detail/CVE-2025-47912) + - [CVE-2025-58183](https://nvd.nist.gov/vuln/detail/CVE-2025-58183) + - [CVE-2025-58186](https://nvd.nist.gov/vuln/detail/CVE-2025-58186) + - [CVE-2025-64484](https://nvd.nist.gov/vuln/detail/CVE-2025-64484) +- 🐛 Squashed some bugs + +## Important Notes + +By default all specified headers will now be normalized, meaning that both capitalization and the use of underscores (_) versus dashes (-) will be ignored when matching headers to be stripped. For example, both `X-Forwarded-For` and `X_Forwarded-for` will now be treated as equivalent and stripped away. + +Please read our security advisory for CVE-2025-64484: [GHSA-vjrc-mh2v-45x6](https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-vjrc-mh2v-45x6) + +Furthermore, we now use the access_token for validating refreshed sessions in OIDC providers instead of the id_token. This is to align with the [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) which states that id_tokens are not guaranteed to be issued when using refresh tokens. In future releases we might remove the id_token validation for sessions completely. + +## Breaking Changes + ## Changes since v7.12.0 - [#3228](https://github.com/oauth2-proxy/oauth2-proxy/pull/3228) fix: use GetSecret() in ticket.go makeCookie to respect cookie-secret-file (@stagswtf) diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index a43dc45771..57d330407c 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml volumes: - "./oauth2-proxy-alpha-config.cfg:/oauth2-proxy.cfg" diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index f506c4acdb..5df6d471d6 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index faa1b47b4f..3aa138973f 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 60343012f8..201bfe8d20 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,7 +22,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 8bff6b034d..1ad4805c40 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index ae9e3bf13b..f1e7a23d53 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.12.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/installation.md b/docs/docs/installation.md index bba3f4c39f..20a6561471 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.12.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.13.0`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.13.x/behaviour.md b/docs/versioned_docs/version-7.13.x/behaviour.md new file mode 100644 index 0000000000..e063d4f966 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/behaviour.md @@ -0,0 +1,11 @@ +--- +id: behaviour +title: Behaviour +--- + +1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). +2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) +3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set +4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) + +Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). diff --git a/docs/versioned_docs/version-7.13.x/community/contribution.md b/docs/versioned_docs/version-7.13.x/community/contribution.md new file mode 100644 index 0000000000..a8e4734988 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/community/contribution.md @@ -0,0 +1,91 @@ +--- +id: contribution +title: Contribution Guide +--- + +We track bugs and issues using Github. + +If you find a bug, please open an Issue. When opening an Issue or Pull Request please follow the preconfigured template and take special note of the checkboxes. + +If you want to fix a bug, add a new feature or extend existing functionality, please create a fork, create a feature branch and open a PR back to this repo. +Please mention open bug issue number(s) within your PR if applicable. + +We suggest using [Visual Studio Code](https://code.visualstudio.com/docs/languages/go) with the official [Go for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=golang.go) extension. + + +# Go version + +See the `go.mod` file in the root of this repository for the version of Go used by this project. +You can follow [the installation guide for Go](https://go.dev/doc/install), +and you can find this specific Go version on [the Go downloads page](https://go.dev/dl/). + +# Preparing your fork +Clone your fork, create a feature branch and update the depedencies to get started. +```bash +git clone git@github.com:/oauth2-proxy +cd oauth2-proxy +git branch feature/ +git push --set-upstream origin feature/ +go mod download +``` + + +# Testing / Debugging +For starting oauth2-proxy locally open the debugging tab and create the `launch.json` and select `Go: Launch Package`. + +![Debugging Tab](/img/debug-tab.png) +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch OAuth2-Proxy with Dex", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and dex as an idetity provider + "contrib/local-environment/oauth2-proxy.cfg" + ] + }, + { + "name": "Launch OAuth2-Proxy with Keycloak", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and keycloak as an idetity provider + "contrib/local-environment/oauth2-proxy-keycloak.cfg" + ] + } + ] +} +``` + +Before you can start your local version of oauth2-proxy, you will have to use the provided docker compose files to start a local upstream service and identity provider. We suggest using [httpbin](https://hub.docker.com/r/kennethreitz/httpbin) as your upstream for testing as it allows for request and response introspection of all things HTTP. + +Inside the `contrib/local-environment` directory you can use the `Makefile` for +starting different example setups: + +- Dex as your IdP: `make up` or `make down` +- Dex as your IdP using the alpha-config: `make alpha-config-up` +- Keycloak as your IdP: `make keycloak-up` +- Dex as your IdP & nginx reverse proxy: `make nginx-up` +- and many more... + +Check out the `Makefile` to see what is available. + +The username and password for all setups is usually `admin@example.com` and `password`. + +The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me + +- OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 +- Upstream: http://httpbin.localtest.me:8080 +- Dex: http://dex.localtest.me:5556 + diff --git a/docs/versioned_docs/version-7.13.x/community/security.md b/docs/versioned_docs/version-7.13.x/community/security.md new file mode 100644 index 0000000000..c24b57d9e5 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/community/security.md @@ -0,0 +1,49 @@ +--- +id: security +title: Security +--- + +:::note +OAuth2 Proxy is a community project. +Maintainers do not work on this project full time, and as such, +while we endeavour to respond to disclosures as quickly as possible, +this may take longer than in projects with corporate sponsorship. +::: + +## Security Disclosures + +:::important +If you believe you have found a vulnerability within OAuth2 Proxy or any of its +dependencies, please do NOT open an issue or PR on GitHub, please do NOT post +any details publicly. +::: + +Security disclosures MUST be done in private. +If you have found an issue that you would like to bring to the attention of the +maintenance team for OAuth2 Proxy, please compose an email and send it to the +list of maintainers in our [MAINTAINERS](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS) file. + +Please include as much detail as possible. +Ideally, your disclosure should include: +- A reproducible case that can be used to demonstrate the exploit +- How you discovered this vulnerability +- A potential fix for the issue (if you have thought of one) +- Versions affected (if not present in master) +- Your GitHub ID + +### How will we respond to disclosures? + +We use [GitHub Security Advisories](https://docs.github.com/en/github/managing-security-vulnerabilities/about-github-security-advisories) +to privately discuss fixes for disclosed vulnerabilities. +If you include a GitHub ID with your disclosure we will add you as a collaborator +for the advisory so that you can join the discussion and validate any fixes +we may propose. + +For minor issues and previously disclosed vulnerabilities (typically for +dependencies), we may use regular PRs for fixes and forego the security advisory. + +Once a fix has been agreed upon, we will merge the fix and create a new release. +If we have multiple security issues in flight simultaneously, we may delay +merging fixes until all patches are ready. +We may also backport the fix to previous releases, +but this will be at the discretion of the maintainers. diff --git a/docs/versioned_docs/version-7.13.x/configuration/alpha_config.md b/docs/versioned_docs/version-7.13.x/configuration/alpha_config.md new file mode 100644 index 0000000000..9e6c2873ea --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/alpha_config.md @@ -0,0 +1,568 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference + + + +### ADFSOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `skipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | + +### AlphaOptions + +AlphaOptions contains alpha structured configuration options. +Usage of these options allows users to access alpha features that are not +available as part of the primary configuration structure for OAuth2 Proxy. + +:::warning +The options within this structure are considered alpha. +They may change between releases without notice. +::: + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | +| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | + +### AzureOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | +| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | + +### BitbucketOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repository` | _string_ | Repository sets restrict logins to user with access to this repository | + +### ClaimSource + +(**Appears on:** [HeaderValue](#headervalue)) + +ClaimSource allows loading a header value from a claim within the session + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### Duration +#### (`string` alias) + +(**Appears on:** [Upstream](#upstream)) + +Duration is as string representation of a period of time. +A duration string is a is a possibly signed sequence of decimal numbers, +each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". +Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + +### GitHubOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `org` | _string_ | Org sets restrict logins to members of this organisation | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository | +| `token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | +| `users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | + +### GitLabOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Group sets restrict logins to members of this group | +| `projects` | _[]string_ | Projects restricts logins to members of these projects | + +### GoogleOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Groups sets restrict logins to members of this Google group | +| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | +| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | +| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | +| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | +| `useOrganizationID` | _bool_ | UseOrganizationId indicates whether to use the organization ID as the UserName claim | +| `adminAPIUserScope` | _string_ | admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly | + +### Header + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Header represents an individual header that will be added to a request or +response header. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | +| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `InsecureSkipHeaderNormalization` | _bool_ | InsecureSkipHeaderNormalization disables normalizing the header name
According to RFC 7230 Section 3.2 there aren't any rules about
capitalization of header names, but the standard practice is to use
Title-Case (e.g. X-Forwarded-For). By default, header names will be
normalized to Title-Case and any incoming headers that match will be
treated as the same header. Additionally underscores (_) in header names
will be converted to dashes (-) when normalizing.
Defaults to false (header names will be normalized). | +| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | + +### HeaderValue + +(**Appears on:** [Header](#header)) + +HeaderValue represents a single header value and the sources that can +make up the header value + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### KeycloakOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `groups` | _[]string_ | Group enables to restrict login to members of indicated group | +| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | + +### LoginGovOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | +| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | +| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | + +### LoginURLParameter + +(**Appears on:** [Provider](#provider)) + +LoginURLParameter is the configuration for a single query parameter that +can be passed through from the `/oauth2/start` endpoint to the IdP login +URL. The "default" option specifies the default value or values (if any) +that will be passed to the IdP for this parameter, and "allow" is a list +of options for ways in which this parameter can be set or overridden via +the query string to `/oauth2/start`. +If _only_ a default is specified and no "allow" then the parameter is +effectively fixed - the default value will always be used and anything +passed to the start URL will be ignored. If _only_ "allow" is specified +but no default then the parameter will only be passed on to the IdP if +the caller provides it, and no value will be sent otherwise. + +Examples: + +# A parameter whose value is fixed + +``` +name: organization +default: +- myorg +``` + +A parameter that is not passed by default, but may be set to one of a +fixed set of values + +``` +name: prompt +allow: +- value: login +- value: consent +- value: select_account +``` + +A parameter that is passed by default but may be overridden by one of +a fixed set of values + +``` +name: prompt +default: ["login"] +allow: +- value: consent +- value: select_account +``` + +A parameter that may be overridden, but only by values that match a +regular expression. For example to restrict `login_hint` to email +addresses in your organization's domain: + +``` +name: login_hint +allow: +- pattern: '^[^@]*@example\.com$' +# this allows at most one "@" sign, and requires "example.com" domain. +``` + +Note that the YAML rules around exactly which characters are allowed +and/or require escaping in different types of string literals are +convoluted. For regular expressions the single quoted form is simplest +as backslash is not considered to be an escape character. Alternatively +use the "chomped block" format `|-`: + +``` + - pattern: |- + ^[^@]*@example\.com$ + +``` + +The hyphen is important, a `|` block would have a trailing newline +character. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name specifies the name of the query parameter. | +| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | +| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | + +### MicrosoftEntraIDOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | +| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | + +### OIDCOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | +| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | +| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | +| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | +| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | +| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | +| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | +| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | +| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | +| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | +| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | +| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | + +### Provider + +(**Appears on:** [Providers](#providers)) + +Provider holds all configuration for a single provider + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | +| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | +| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | +| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | +| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | +| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | +| `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. | +| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | +| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | +| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | +| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | +| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | +| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | +| `id` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | +| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | +| `name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | +| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | +| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | +| `loginURL` | _string_ | LoginURL is the authentication endpoint | +| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | +| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | +| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint | +| `profileURL` | _string_ | ProfileURL is the profile access endpoint | +| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | +| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | +| `validateURL` | _string_ | ValidateURL is the access token validation endpoint | +| `scope` | _string_ | Scope is the OAuth scope specification | +| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | +| `code_challenge_method` | _string_ | The code challenge method | +| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | + +### ProviderType +#### (`string` alias) + +(**Appears on:** [Provider](#provider)) + +ProviderType is used to enumerate the different provider type options +Valid options are: adfs, azure, bitbucket, digitalocean facebook, github, +gitlab, google, keycloak, keycloak-oidc, linkedin, login.gov, nextcloud +and oidc. + +### Providers + +#### ([[]Provider](#provider) alias) + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +The provider can be selected using the `provider` configuration value, or +set in the [`providers` array using +AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). +However, [**the feature to implement multiple providers is not +complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +### SecretSource + +(**Appears on:** [ClaimSource](#claimsource), [HeaderValue](#headervalue), [TLS](#tls)) + +SecretSource references an individual secret value. +Only one source within the struct should be defined at any time. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | + +### Server + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Server represents the configuration for an HTTP(S) server + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `BindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Leave blank or set to "-" to disable. | +| `SecureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Leave blank or set to "-" to disable. | +| `TLS` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the
secure traffic and further configuration for the TLS server. | + +### TLS + +(**Appears on:** [Server](#server)) + +TLS contains the information for loading a TLS certificate and key +as well as an optional minimal TLS version that is acceptable. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `Key` | _[SecretSource](#secretsource)_ | Key is the TLS key data to use.
Typically this will come from a file. | +| `Cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.
Typically this will come from a file. | +| `MinVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.
E.g. Set to "TLS1.3" to select TLS version 1.3 | +| `CipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.
E.g.:
- TLS_RSA_WITH_RC4_128_SHA
- TLS_RSA_WITH_AES_256_GCM_SHA384
If not specified, the default Go safe cipher list is used.
List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | + +### URLParameterRule + +(**Appears on:** [LoginURLParameter](#loginurlparameter)) + +URLParameterRule represents a rule by which query parameters +passed to the `/oauth2/start` endpoint are checked to determine whether +they are valid overrides for the given parameter passed to the IdP's +login URL. Either Value or Pattern should be supplied, not both. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _string_ | A Value rule matches just this specific value | +| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | + +### Upstream + +(**Appears on:** [UpstreamConfig](#upstreamconfig)) + +Upstream represents the configuration for an upstream server. +Requests will be proxied to this upstream if the path matches the request path. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `id` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | +| `path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | +| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | +| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | +| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | +| `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | +| `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | +| `flushInterval` | _[Duration](#duration)_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | +| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | +| `timeout` | _[Duration](#duration)_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | +| `disableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | + +### UpstreamConfig + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +UpstreamConfig is a collection of definitions for upstream servers. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | +| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | diff --git a/docs/versioned_docs/version-7.13.x/configuration/alpha_config.md.tmpl b/docs/versioned_docs/version-7.13.x/configuration/alpha_config.md.tmpl new file mode 100644 index 0000000000..8258201f2a --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/alpha_config.md.tmpl @@ -0,0 +1,139 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference diff --git a/docs/versioned_docs/version-7.13.x/configuration/integration.md b/docs/versioned_docs/version-7.13.x/configuration/integration.md new file mode 100644 index 0000000000..c57cfa6b36 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/integration.md @@ -0,0 +1,310 @@ +--- +id: integration +title: Integration +--- + +## Configuring for use with the Nginx `auth_request` directive + +**This option requires `--reverse-proxy` option to be set.** + +The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: + +```nginx +server { + listen 443 ssl; + server_name ...; + include ssl/ssl.conf; + + location /oauth2/ { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Auth-Request-Redirect $request_uri; + # or, if you are handling multiple domains: + # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; + } + location = /oauth2/auth { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; + # nginx auth_request includes headers but not body + proxy_set_header Content-Length ""; + proxy_pass_request_body off; + } + + location / { + auth_request /oauth2/auth; + error_page 401 =403 /oauth2/sign_in; + + # pass information via X-User and X-Email headers to backend, + # requires running with --set-xauthrequest flag + auth_request_set $user $upstream_http_x_auth_request_user; + auth_request_set $email $upstream_http_x_auth_request_email; + proxy_set_header X-User $user; + proxy_set_header X-Email $email; + + # if you enabled --pass-access-token, this will pass the token to the backend + auth_request_set $token $upstream_http_x_auth_request_access_token; + proxy_set_header X-Access-Token $token; + + # if you enabled --cookie-refresh, this is needed for it to work with auth_request + auth_request_set $auth_cookie $upstream_http_set_cookie; + add_header Set-Cookie $auth_cookie; + + # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb + # limit and so the OAuth2 Proxy splits these into multiple parts. + # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, + # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. + auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; + + # Extract the Cookie attributes from the first Set-Cookie header and append them + # to the second part ($upstream_cookie_* variables only contain the raw cookie content) + if ($auth_cookie ~* "(; .*)") { + set $auth_cookie_name_0 $auth_cookie; + set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; + } + + # Send both Set-Cookie headers now if there was a second part + if ($auth_cookie_name_upstream_1) { + add_header Set-Cookie $auth_cookie_name_0; + add_header Set-Cookie $auth_cookie_name_1; + } + + proxy_pass http://backend/; + # or "root /path/to/site;" or "fastcgi_pass ..." etc + } +} +``` + +When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: + +```yaml +nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" +nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" +``` + +This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. + +It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). + +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=". + +## Configuring for use with the Traefik (v2) `ForwardAuth` middleware + +**This option requires `--reverse-proxy` option to be set.** + +### ForwardAuth with 401 errors middleware + +The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: + +```yaml +http: + routers: + a-service: + rule: "Host(`a-service.example.com`)" + service: a-service-backend + middlewares: + - oauth-errors + - oauth-auth + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth: + rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + oauth-errors: + errors: + status: + - "401-403" + service: oauth-backend + query: "/oauth2/sign_in?rd={url}" +``` + +### ForwardAuth with static upstreams configuration + +Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint + +**Following options need to be set on `oauth2-proxy`:** +- `--upstream=static://202`: Configures a static response for authenticated sessions +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```yaml +http: + routers: + a-service-route-1: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" + service: a-service-backend + middlewares: + - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + a-service-route-2: + rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" + service: a-service-backend + middlewares: + - oauth-auth-wo-redirect # unauthenticated session will return a 401 + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + services-oauth2-route: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth2-proxy-route: + rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + b-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.3:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth-redirect: + forwardAuth: + address: https://oauth.example.com/ + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization + oauth-auth-wo-redirect: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization +``` + +## Configuring for use with the Caddy (v2) `forward_auth` directive + +The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. + +This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. + +**Following options need to be set on `oauth2-proxy`:** +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```nginx title="Caddyfile" +example.com { + # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. + # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. + handle /oauth2/* { + reverse_proxy oauth2-proxy.internal:4180 { + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. + header_up X-Real-IP {remote_host} + header_up X-Forwarded-Uri {uri} + } + } + + # Requests to other paths are first processed by oauth2-proxy for authentication. + handle { + forward_auth oauth2-proxy.internal:4180 { + uri /oauth2/auth + + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. + header_up X-Real-IP {remote_host} + + # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. + # Make sure to configure the --set-xauthrequest flag to enable this feature. + #copy_headers X-Auth-Request-User X-Auth-Request-Email + + # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. + @error status 401 + handle_response @error { + redir * /oauth2/sign_in?rd={scheme}://{host}{uri} + } + } + + # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. + reverse_proxy upstream.internal:3000 + } +} +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.13.x/configuration/overview.md b/docs/versioned_docs/version-7.13.x/configuration/overview.md new file mode 100644 index 0000000000..b159df09cc --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/overview.md @@ -0,0 +1,406 @@ +--- +id: overview +title: Overview +--- + +`oauth2-proxy` can be configured via [command line options](#command-line-options), [environment variables](#environment-variables) or [config file](#config-file) (in decreasing order of precedence, i.e. command line options will overwrite environment variables and environment variables will overwrite configuration file settings). + +## Generating a Cookie Secret + +To generate a strong cookie secret use one of the below commands: + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + + +```shell +python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())' +``` + + + + +```shell +dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64 | tr -d -- '\n' | tr -- '+/' '-_' ; echo +``` + + + + +```shell +openssl rand -base64 32 | tr -- '+/' '-_' +``` + + + + +```powershell +# Add System.Web assembly to session, just in case +Add-Type -AssemblyName System.Web +[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([System.Web.Security.Membership]::GeneratePassword(32,4))).Replace("+","-").Replace("/","_") +``` + + + + +```hcl +# Valid 32 Byte Base64 URL encoding set that will decode to 24 []byte AES-192 secret +resource "random_password" "cookie_secret" { + length = 32 + override_special = "-_" +} +``` + + + + +## Config File + +Every command line argument can be specified in a config file by replacing hyphens (-) with underscores (\_). If the argument can be specified multiple times, the config option should be plural (trailing s). + +An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/oauth2-proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `--config=/etc/oauth2-proxy.cfg` + +## Config Options + +### Command Line Options + +| Flag | Description | +| ----------- | -------------------- | +| `--config` | path to config file | +| `--version` | print version string | + + +### General Provider Options + +Provider specific options can be found on their respective subpages. + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| flag: `--acr-values`
toml: `acr_values` | string | optional, see [docs](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues) | `""` | +| flag: `--allowed-group`
toml: `allowed_groups` | string \| list | Restrict login to members of a group or list of groups. Furthermore, if you aren't setting the `scope` and use `allowed_groups` with the generic OIDC provider the scope `groups` gets added implicitly. | | +| flag: `--approval-prompt`
toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` | +| flag: `--backend-logout-url`
toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | | +| flag: `--client-id`
toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | | +| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret | | +| flag: `--client-secret`
toml: `client_secret` | string | the OAuth Client Secret | | +| flag: `--code-challenge-method`
toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | | +| flag: `--insecure-oidc-allow-unverified-email`
toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false | +| flag: `--insecure-oidc-skip-issuer-verification`
toml: `insecure_oidc_skip_issuer_verification` | bool | allow the OIDC issuer URL to differ from the expected (currently required for Azure multi-tenant compatibility) | false | +| flag: `--insecure-oidc-skip-nonce`
toml: `insecure_oidc_skip_nonce` | bool | skip verifying the OIDC ID Token's nonce claim | true | +| flag: `--jwt-key-file`
toml: `jwt_key_file` | string | path to the private key file in PEM format used to sign the JWT so that you can say something like `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem`: required by login.gov | | +| flag: `--jwt-key`
toml: `jwt_key` | string | private key in PEM format used to sign JWT, so that you can say something like `--jwt-key="${OAUTH2_PROXY_JWT_KEY}"`: required by login.gov | | +| flag: `--login-url`
toml: `login_url` | string | Authentication endpoint | | +| flag: `--auth-request-response-mode`
toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | | +| flag: `--oidc-audience-claim`
toml: `oidc_audience_claims` | string | which OIDC claim contains the audience | `"aud"` | +| flag: `--oidc-email-claim`
toml: `oidc_email_claim` | string | which OIDC claim contains the user's email | `"email"` | +| flag: `--oidc-extra-audience`
toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` | +| flag: `--oidc-groups-claim`
toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` | +| flag: `--oidc-issuer-url`
toml: `oidc_issuer_url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | | +| flag: `--oidc-jwks-url`
toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled and public key files are not provided | | +| flag: `--oidc-public-key-file`
toml: `oidc_public_key_files` | string | Path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times). Required if OIDC discovery is disabled na JWKS URL isn't provided | string \| list | +| flag: `--profile-url`
toml: `profile_url` | string | Profile access endpoint | | +| flag: `--prompt`
toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` | +| flag: `--provider-ca-file`
toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. | +| flag: `--provider-display-name`
toml: `provider_display_name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) | +| flag: `--provider`
toml: `provider` | string | OAuth provider | google | +| flag: `--pubjwk-url`
toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | | +| flag: `--redeem-url`
toml: `redeem_url` | string | Token redemption endpoint | | +| flag: `--scope`
toml:`scope` | string | OAuth scope specification. Every provider has a default list of scopes which will be used in case no scope is configured. | | +| flag: `--skip-claims-from-profile-url`
toml: `skip_claims_from_profile_url` | bool | skip request to Profile URL for resolving claims not present in id_token | false | +| flag: `--skip-oidc-discovery`
toml: `skip_oidc_discovery` | bool | bypass OIDC endpoint discovery. `--login-url`, `--redeem-url` and `--oidc-jwks-url` must be configured in this case | false | +| flag: `--use-system-trust-store`
toml: `use_system_trust_store` | bool | Determines if `provider-ca-file` files and the system trust store are used. If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | false | +| flag: `--validate-url`
toml: `validate_url` | string | Access token validation endpoint | | + +### Cookie Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | +| flag: `--cookie-csrf-expire`
toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m | +| flag: `--cookie-csrf-per-request`
toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false | +| flag: `--cookie-csrf-per-request-limit`
toml: `cookie_csrf_per_request_limit` | int | Sets a limit on the number of CSRF requests cookies that oauth2-proxy will create. The oldest cookie will be removed. Useful if users end up with 431 Request headers too large status codes. Only effective if --cookie-csrf-per-request is true | "infinite" | +| flag: `--cookie-domain`
toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | | +| flag: `--cookie-expire`
toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s | +| flag: `--cookie-httponly`
toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true | +| flag: `--cookie-name`
toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` | +| flag: `--cookie-path`
toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` | +| flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | +| flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | +| flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | +| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | For defining a separate cookie secret file to read the encryption key from | | +| flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | + +[^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) + +### Header Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--basic-auth-password`
toml: `basic_auth_password` | string | the password to set when passing the HTTP Basic Auth header | | +| flag: `--set-xauthrequest`
toml: `set_xauthrequest` | bool | set X-Auth-Request-User, X-Auth-Request-Groups, X-Auth-Request-Email and X-Auth-Request-Preferred-Username response headers (useful in Nginx auth_request mode). When used with `--pass-access-token`, X-Auth-Request-Access-Token is added to response headers. | false | +| flag: `--set-authorization-header`
toml: `set_authorization_header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false | +| flag: `--set-basic-auth`
toml: `set_basic_auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false | +| flag: `--skip-auth-strip-headers`
toml: `skip_auth_strip_headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy | true | +| flag: `--pass-access-token`
toml: `pass_access_token` | bool | pass OAuth access_token to upstream via X-Forwarded-Access-Token header. When used with `--set-xauthrequest` this adds the X-Auth-Request-Access-Token header to the response | false | +| flag: `--pass-authorization-header`
toml: `pass_authorization_header` | bool | pass OIDC IDToken to upstream via Authorization Bearer header | false | +| flag: `--pass-basic-auth`
toml: `pass_basic_auth` | bool | pass HTTP Basic Auth, X-Forwarded-User, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | +| flag: `--prefer-email-to-user`
toml: `prefer_email_to_user` | bool | Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, e.g. htaccess authentication. Used in conjunction with `--pass-basic-auth` and `--pass-user-headers` | false | +| flag: `--pass-user-headers`
toml: `pass_user_headers` | bool | pass X-Forwarded-User, X-Forwarded-Groups, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | + +### Logging Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------- | --------------------------------------------------- | +| flag: `--auth-logging-format`
toml: `auth_logging_format` | string | Template for authentication log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--auth-logging`
toml: `auth_logging` | bool | Log authentication attempts | true | +| flag: `--errors-to-info-log`
toml: `errors_to_info_log` | bool | redirects error-level logging to default log channel instead of stderr | false | +| flag: `--exclude-logging-path`
toml: `exclude_logging_paths` | string | comma separated list of paths to exclude from logging, e.g. `"/ping,/path2"` | `""` (no paths excluded) | +| flag: `--logging-compress`
toml: `logging_compress` | bool | Should rotated log files be compressed using gzip | false | +| flag: `--logging-filename`
toml: `logging_filename` | string | File to log requests to, empty for `stdout` | `""` (stdout) | +| flag: `--logging-local-time`
toml: `logging_local_time` | bool | Use local time in log files and backup filenames instead of UTC | true (local time) | +| flag: `--logging-max-age`
toml: `logging_max_age` | int | Maximum number of days to retain old log files | 7 | +| flag: `--logging-max-backups`
toml: `logging_max_backups` | int | Maximum number of old log files to retain; 0 to disable | 0 | +| flag: `--logging-max-size`
toml: `logging_max_size` | int | Maximum size in megabytes of the log file before rotation | 100 | +| flag: `--request-id-header`
toml: `request_id_header` | string | Request header to use as the request ID in logging | X-Request-Id | +| flag: `--request-logging-format`
toml: `request_logging_format` | string | Template for request log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--request-logging`
toml: `request_logging` | bool | Log requests | true | +| flag: `--silence-ping-logging`
toml: `silence_ping_logging` | bool | disable logging of requests to ping & ready endpoints | false | +| flag: `--standard-logging-format`
toml: `standard_logging_format` | string | Template for standard log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--standard-logging`
toml: `standard_logging` | bool | Log standard runtime information | true | + +### Page Template Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--banner`
toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | | +| flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | +| flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | +| flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | +| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | | +| flag: `--show-debug-on-error`
toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false | + +### Probe Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------- | ------ | ---------------------------------------------------------- | ----------------------------- | +| flag: `--ping-path`
toml: `ping_path` | string | the ping endpoint that can be used for basic health checks | `"/ping"` | +| flag: `--ping-user-agent`
toml: `ping_user_agent` | string | a User-Agent that can be used for basic health checks | `""` (don't check user agent) | +| flag: `--ready-path`
toml: `ready_path` | string | the ready endpoint that can be used for deep health checks | `"/ready"` | +| flag: `--gcp-healthchecks`
toml: `gcp_healthchecks` | bool | Enable GCP/GKE healthcheck endpoints (deprecated) | false | + +### Proxy Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--bearer-token-login-fallback`
toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | + +[^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. + +### Server Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | +| flag: `--http-address`
toml: `http_address` | string | `[http://]:` or `unix://` or `fd:` (case insensitive) to listen on for HTTP clients. Square brackets are required for ipv6 address, e.g. `http://[::1]:4180` | `"127.0.0.1:4180"` | +| flag: `--https-address`
toml: `https_address` | string | `[https://]:` to listen on for HTTPS clients. Square brackets are required for ipv6 address, e.g. `https://[::1]:443` | `":443"` | +| flag: `--metrics-address`
toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` | +| flag: `--metrics-secure-address`
toml: `metrics_secure_address` | string | the address prometheus metrics will be scraped from if using HTTPS | `""` | +| flag: `--metrics-tls-cert-file`
toml: `metrics_tls_cert_file` | string | path to certificate file for secure metrics server | `""` | +| flag: `--metrics-tls-key-file`
toml: `metrics_tls_key_file` | string | path to private key file for secure metrics server | `""` | +| flag: `--tls-cert-file`
toml: `tls_cert_file` | string | path to certificate file | | +| flag: `--tls-key-file`
toml: `tls_key_file` | string | path to private key file | | +| flag: `--tls-cipher-suite`
toml: `tls_cipher_suites` | string \| list | Restricts TLS cipher suites used by server to those listed (e.g. TLS_RSA_WITH_RC4_128_SHA) (may be given multiple times). If not specified, the default Go safe cipher list is used. List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | | +| flag: `--tls-min-version`
toml: `tls_min_version` | string | minimum TLS version that is acceptable, either `"TLS1.2"` or `"TLS1.3"` | `"TLS1.2"` | + +### Session Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--session-cookie-minimal`
toml: `session_cookie_minimal` | bool | strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only) | false | +| flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | +| flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | +| flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | +| flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | +| flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | +| flag: `--redis-sentinel-master-name`
toml: `redis_sentinel_master_name` | string | Redis sentinel master name. Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-sentinel-connection-urls`
toml: `redis_sentinel_connection_urls` | string \| list | List of Redis sentinel connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-use-cluster`
toml: `redis_use_cluster` | bool | Connect to redis cluster. Must set `--redis-cluster-connection-urls` to use this feature | false | +| flag: `--redis-use-sentinel`
toml: `redis_use_sentinel` | bool | Connect to redis via sentinels. Must set `--redis-sentinel-master-name` and `--redis-sentinel-connection-urls` to use this feature | false | +| flag: `--redis-connection-idle-timeout`
toml: `redis_connection_idle_timeout` | int | Redis connection idle timeout seconds. If Redis [timeout](https://redis.io/docs/reference/clients/#client-timeouts) option is set to non-zero, the `--redis-connection-idle-timeout` must be less than Redis timeout option. Example: if either redis.conf includes `timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` | 0 | + +### Upstream Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | +| flag: `--flush-interval`
toml: `flush_interval` | duration | period between flushing response buffers when streaming responses | `"1s"` | +| flag: `--pass-host-header`
toml: `pass_host_header` | bool | pass the request Host Header to upstream | true | +| flag: `--proxy-websockets`
toml: `proxy_websockets` | bool | enables WebSocket proxying | true | +| flag: `--ssl-upstream-insecure-skip-verify`
toml: `ssl_upstream_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false | +| flag: `--disable-keep-alives`
toml: `disable_keep_alives` | bool | disable HTTP keep-alive connections to the upstream server | false | +| flag: `--upstream-timeout`
toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s | +| flag: `--upstream`
toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://` for static response. Routing is based on the path | | + +## Upstreams Configuration + +`oauth2-proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers, unix socket or serve static files from the file system. + +To configure **HTTP and HTTPS upstreams**, provide such a URL in `--upstream=URL`. The scheme+host portion and the path portion are extracted to configure proxying behavior. When processing incoming requests, the path portion becomes a lookup key for selecting the destination server of the proxied request. + +* Upstream URLs *without a trailing slash,* like in `--upstream=http://service2.internal/foo`, will match an incoming request exactly to `/foo` in `https://this.o2p.example.com/foo`, and forward the request on to service2.internal, but not match a request to `https://this.o2p.example.com/foo/more` nor ...`.com/food`. +* Upstream URLs *with a trailing slash,* like in `--upstream=http://service1.internal/foo/`, will match any incoming request to any incoming requests's path *starting with* `/foo/`, like `/foo/` and `/foo/more` and `/foo/lots/more?etc`. + +If multiple `--upstream` URLs' paths match an incoming request, the one with the longest matching path (the most specific match) takes priority over shorter (less specific) ones. + +**Unix socket upstreams** are configured as `unix:///path/to/unix.sock`. + +**Static file paths** are configured as a file:// URL. `file:///var/www/static/` will serve the files from that directory at `http://[oauth2-proxy url]/var/www/static/`, which may not be what you want. You can provide the path to where the files should be available by adding a fragment to the configured URL. The value of the fragment will then be used to specify which path the files are available at, e.g. `file:///var/www/static/#/static/` will make `/var/www/static/` available at `http://[oauth2-proxy url]/static/`. + +Multiple upstreams can either be configured by supplying a comma separated list to the `--upstream` parameter, supplying the parameter multiple times or providing a list in the [config file](#config-file). When multiple upstreams are used routing to them will be based on the path they are set up with. + +## Environment variables + +Every command line argument can be specified as an environment variable by +prefixing it with `OAUTH2_PROXY_`, capitalising it, and replacing hyphens (`-`) +with underscores (`_`). If the argument can be specified multiple times, the +environment variable should be plural (trailing `S`). + +This is particularly useful for storing secrets outside a configuration file +or the command line. + +For example, the `--cookie-secret` flag becomes `OAUTH2_PROXY_COOKIE_SECRET`. +If a flag has the type `string | list` like the `--email-domain` flag it is +available as an environment variable in plural form e.g. `OAUTH2_PROXY_EMAIL_DOMAINS` + +Values for type `string | list` usually have a plural environment variable name +and need to be seperated by `,` e.g. +`OAUTH2_PROXY_SKIP_AUTH_ROUTES="GET=^/api/status,POST=^/api/saved_objects/_import"` + +Please check the type for each [config option](#config-options) first. + +## Logging Configuration + +By default, OAuth2 Proxy logs all output to stdout. Logging can be configured to output to a rotating log file using the `--logging-filename` command. + +If logging to a file you can also configure the maximum file size (`--logging-max-size`), age (`--logging-max-age`), max backup logs (`--logging-max-backups`), and if backup logs should be compressed (`--logging-compress`). + +There are three different types of logging: standard, authentication, and HTTP requests. These can each be enabled or disabled with `--standard-logging`, `--auth-logging`, and `--request-logging`. + +Each type of logging has its own configurable format and variables. By default, these formats are similar to the Apache Combined Log. + +Logging of requests to the `/ping` endpoint (or using `--ping-user-agent`) and the `/ready` endpoint can be disabled with `--silence-ping-logging` reducing log volume. + +## Auth Log Format + +Authentication logs are logs which are guaranteed to contain a username or email address of a user attempting to authenticate. These logs are output by default in the below format: + +``` + - - [2015/03/19 17:20:19] [] +``` + +The status block will contain one of the below strings: + +- `AuthSuccess` If a user has authenticated successfully by any method +- `AuthFailure` If the user failed to authenticate explicitly +- `AuthError` If there was an unexpected error during authentication + +If you require a different format than that, you can configure it with the `--auth-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}} +``` + +Available variables for auth logging: + +| Variable | Example | Description | +| ------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Message | Authenticated via OAuth2 | The details of the auth attempt. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | +| Status | AuthSuccess | The status of the auth request. See above for details. | + +## Request Log Format + +HTTP request logs will output by default in the below format: + +``` + - - [2015/03/19 17:20:19] GET "/path/" HTTP/1.1 "" +``` + +If you require a different format than that, you can configure it with the `--request-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}} +``` + +Available variables for request logging: + +| Variable | Example | Description | +| --------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestDuration | 0.001 | The time in seconds that a request took to process. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| RequestURI | "/oauth2/auth" | The URI path of the request. | +| ResponseSize | 12 | The size in bytes of the response. | +| StatusCode | 200 | The HTTP status code of the response. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| Upstream | - | The upstream data of the HTTP request. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | + +## Standard Log Format + +All other logging that is not covered by the above two types of logging will be output in this standard logging format. This includes configuration information at startup and errors that occur outside of a session. The default format is below: + +``` +[2015/03/19 17:20:19] [main.go:40] +``` + +If you require a different format than that, you can configure it with the `--standard-logging-format` flag. The default format is configured as follows: + +``` +[{{.Timestamp}}] [{{.File}}] {{.Message}} +``` + +Available variables for standard logging: + +| Variable | Example | Description | +| --------- | --------------------------------- | -------------------------------------------------- | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| File | main.go:40 | The file and line number of the logging statement. | +| Message | HTTP: listening on 127.0.0.1:4180 | The details of the log statement. | diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/adfs.md b/docs/versioned_docs/version-7.13.x/configuration/providers/adfs.md new file mode 100644 index 0000000000..ec8d72d2af --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/adfs.md @@ -0,0 +1,19 @@ +--- +id: adfs +title: ADFS +--- + +1. Open the ADFS administration console on your Windows Server and add a new Application Group +2. Provide a name for the integration, select Server Application from the Standalone applications section and click Next +3. Follow the wizard to get the client-id, client-secret and configure the application credentials +4. Configure the proxy with + +``` + --provider=adfs + --client-id= + --client-secret= +``` + +Note: When using the ADFS Auth provider with nginx and the cookie session store you may find the cookie is too large and +doesn't get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the +[redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/bitbucket.md b/docs/versioned_docs/version-7.13.x/configuration/providers/bitbucket.md new file mode 100644 index 0000000000..e31de7526c --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/bitbucket.md @@ -0,0 +1,25 @@ +--- +id: bitbucket +title: BitBucket +--- + +1. [Add a new OAuth consumer](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html) + * In "Callback URL" use `https:///oauth2/callback`, substituting `` with the actual + hostname that oauth2-proxy is running on. + * In Permissions section select: + * Account -> Email + * Team membership -> Read + * Repositories -> Read +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=bitbucket + --client-id= + --client-secret= +``` + +The default configuration allows everyone with Bitbucket account to authenticate. To restrict the access to the team +members use additional configuration option: `--bitbucket-team=`. To restrict the access to only these users +who have access to one selected repository use `--bitbucket-repository=`. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/cidaas.md b/docs/versioned_docs/version-7.13.x/configuration/providers/cidaas.md new file mode 100644 index 0000000000..7a9870181f --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/cidaas.md @@ -0,0 +1,37 @@ +--- +id: cidaas +title: Cidaas +--- + +[Cidaas](https://www.cidaas.com/) is an Identity as a Service (IDaaS) solution that provides authentication and authorization services. +It supports various protocols including OpenID Connect, OAuth 2.0, and SAML. + +However, Cidaas provides groups and their roles as hierarchical claims, which are not supported by oauth2-proxy yet. +The Cidaas provider transforms the hierarchical claims into a flat list of groups, which can be used by oauth2-proxy. + +Example of groups and roles in Cidaas: + +```json +{ + "groups": [ + { + "groupId": "group1", + "roles": ["role1", "role2"] + }, + { + "groupId": "group2", + "roles": ["role3"] + } + ] +} +``` + +This will be transformed into a flat list of groups: + +```json +{ + "groups": ["group1:role1", "group2:role2", "group2:role3"] +} +``` + +Apart from that the Cidaas provider inherits all the features of the [OpenID Connect provider](openid_connect.md). \ No newline at end of file diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/digitalocean.md b/docs/versioned_docs/version-7.13.x/configuration/providers/digitalocean.md new file mode 100644 index 0000000000..f6a1e89181 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/digitalocean.md @@ -0,0 +1,21 @@ +--- +id: digitalocean +title: DigitalOcean +--- + +1. [Create a new OAuth application](https://cloud.digitalocean.com/account/api/applications) + * You can fill in the name, homepage, and description however you wish. + * In the "Application callback URL" field, enter: `https://oauth-proxy/oauth2/callback`, substituting `oauth2-proxy` + with the actual hostname that oauth2-proxy is running on. The URL must match oauth2-proxy's configured redirect URL. +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=digitalocean + --client-id= + --client-secret= +``` + +Alternatively, set the equivalent options in the config file. The redirect URL defaults to +`https:///oauth2/callback`. If you need to change it, you can use the `--redirect-url` command-line option. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/facebook.md b/docs/versioned_docs/version-7.13.x/configuration/providers/facebook.md new file mode 100644 index 0000000000..352c95ce1e --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/facebook.md @@ -0,0 +1,7 @@ +--- +id: facebook +title: Facebook +--- + +1. Create a new FB App from https://developers.facebook.com/ +2. Under FB Login, set your Valid OAuth redirect URIs to `https://internal.yourcompany.com/oauth2/callback` diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/gitea.md b/docs/versioned_docs/version-7.13.x/configuration/providers/gitea.md new file mode 100644 index 0000000000..6c679dd0f4 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/gitea.md @@ -0,0 +1,24 @@ +--- +id: gitea +title: Gitea / Forgejo +--- + +:::note +This is not actually a fully serparate provider. For more details and options please refer to the [GitHub Provider Options](github.md) +::: + +1. Create a new application: `https://< your gitea host >/user/settings/applications` +2. Under `Redirect URI` enter the correct URL i.e. `https:///oauth2/callback` +3. Note the Client ID and Client Secret. +4. Pass the following options to the proxy: + +``` + --provider="github" + --redirect-url="https:///oauth2/callback" + --provider-display-name="Gitea" + --client-id="< client_id as generated by Gitea >" + --client-secret="< client_secret as generated by Gitea >" + --login-url="https://< your gitea host >/login/oauth/authorize" + --redeem-url="https://< your gitea host >/login/oauth/access_token" + --validate-url="https://< your gitea host >/api/v1/user/emails" +``` diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/github.md b/docs/versioned_docs/version-7.13.x/configuration/providers/github.md new file mode 100644 index 0000000000..cebca31411 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/github.md @@ -0,0 +1,81 @@ +--- +id: github +title: GitHub +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------- | ------- | +| `--github-org` | `github_org` | string | restrict logins to members of this organisation | | +| `--github-team` | `github_team` | string | restrict logins to members of any of these teams (slug) or (org:team), comma separated | | +| `--github-repo` | `github_repo` | string | restrict logins to collaborators of this repository formatted as `orgname/repo` | | +| `--github-token` | `github_token` | string | the token to use when verifying repository collaborators (must have push access to the repository) | | +| `--github-user` | `github_users` | string \| list | To allow users to login by username even if they do not belong to the specified org and team or collaborators | | + +## Usage + +1. Create a new project: https://github.com/settings/developers +2. Under `Authorization callback URL` enter the correct url ie `https://internal.yourcompany.com/oauth2/callback` + +The GitHub auth provider supports two additional ways to restrict authentication to either organization and optional +team level access, or to collaborators of a repository. Restricting by these options is normally accompanied with `--email-domain=*`. Additionally, all the organizations and teams a user belongs to are set as part of the `X-Forwarded-Groups` header. e.g. `org1:team1,org1:team2,org2:team1` + +NOTE: When `--github-user` is set, the specified users are allowed to log in even if they do not belong to the specified +org and team or collaborators. + +To restrict access to your organization: + +```shell + # restrict logins to members of this organisation + --github-org="your-org" +``` + +To restrict access to specific teams within an organization: + +```shell + --github-org="your-org" + # restrict logins to members of any of these teams (slug), comma separated + --github-team="team1,team2,team3" +``` + +To restrict to teams within different organizations, keep the organization flag empty and use `--github-team` like so: + +```shell + # keep empty + --github-org="" + # restrict logins to members to any of the following teams (format :, like octo:team1), comma separated + --github-team="org1:team1,org2:team1,org3:team42,octo:cat" +``` + +If you would rather restrict access to collaborators of a repository, those users must either have push access to a +public repository or any access to a private repository: + +```shell + # restrict logins to collaborators of this repository formatted as orgname/repo + --github-repo="" +``` + +If you'd like to allow access to users with **read only** access to a **public** repository you will need to provide a +[token](https://github.com/settings/tokens) for a user that has write access to the repository. The token must be +created with at least the `public_repo` scope: + +```shell + # the token to use when verifying repository collaborators + --github-token="" +``` + +To allow a user to log in with their username even if they do not belong to the specified org and team or collaborators: + +```shell + # allow logins by username, comma separated + --github-user="" +``` + +If you are using GitHub enterprise, make sure you set the following to the appropriate url: + +```shell + --login-url="http(s):///login/oauth/authorize" + --redeem-url="http(s):///login/oauth/access_token" + --validate-url="http(s):///api/v3" +``` diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.13.x/configuration/providers/gitlab.md new file mode 100644 index 0000000000..4cdbbbe1e0 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/gitlab.md @@ -0,0 +1,49 @@ +--- +id: gitlab +title: GitLab +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | +| `--gitlab-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 | | + +## Usage + +This auth provider has been tested against Gitlab version 12.X. Due to Gitlab API changes, it may not work for version +prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)). + +Whether you are using GitLab.com or self-hosting GitLab, follow +[these steps to add an application](https://docs.gitlab.com/integration/oauth_provider/). Make sure to enable at +least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. +https://myapp.com/oauth2/callback. + +If you need projects filtering, add the extra `read_api` scope to your application. + +The following config should be set to ensure that the oauth will work properly. To get a cookie secret follow +[these steps](../overview.md#generating-a-cookie-secret) + +``` + --provider="gitlab" + --redirect-url="https://myapp.com/oauth2/callback" // Should be the same as the redirect url for the application in gitlab + --client-id=GITLAB_CLIENT_ID + --client-secret=GITLAB_CLIENT_SECRET + --cookie-secret=COOKIE_SECRET +``` + +Restricting by group membership is possible with the following option: + +```shell + --gitlab-group="mygroup,myothergroup" # restrict logins to members of any of these groups (slug), separated by a comma +``` + +If you are using self-hosted GitLab, make sure you set the following to the appropriate URL: + +```shell + --oidc-issuer-url="" +``` + +If your self-hosted GitLab is on a subdirectory (e.g. domain.tld/gitlab), as opposed to its own subdomain +(e.g. gitlab.domain.tld), you may need to add a redirect from domain.tld/oauth pointing at e.g. domain.tld/gitlab/oauth. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/google.md b/docs/versioned_docs/version-7.13.x/configuration/providers/google.md new file mode 100644 index 0000000000..0de5bb74a5 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/google.md @@ -0,0 +1,84 @@ +--- +id: google +title: Google (default) +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +|-------------------------------------------------|----------------------------------------------| ------ |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------| +| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | +| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). If not specified and service account or default credentials are configured, all user groups will be allowed. | | +| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | +| `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | +| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | +| `--google-use-organization-id` | `google_use_organization_id` | bool | use organization id as preferred username | false | +| `--google-admin-api-user-scope` | `google_admin_api_user_scope` | string | the OAuth scope to use when querying the Google Admin SDK for organization id, can be 'readonly', 'user' or 'cloud'
| `readonly` | + +## Usage + +For Google, the registration steps are: + +1. Create a new project: https://console.developers.google.com/project +2. Choose the new project from the top right project dropdown (only if another project is selected) +3. In the project Dashboard center pane, choose **"APIs & Services"** +4. In the left Nav pane, choose **"Credentials"** +5. In the center pane, choose **"OAuth consent screen"** tab. Fill in **"Product name shown to users"** and hit save. +6. In the center pane, choose **"Credentials"** tab. + - Open the **"New credentials"** drop down + - Choose **"OAuth client ID"** + - Choose **"Web application"** + - Application name is freeform, choose something appropriate + - Authorized JavaScript origins is your domain ex: `https://internal.yourcompany.com` + - Authorized redirect URIs is the location of oauth2/callback ex: `https://internal.yourcompany.com/oauth2/callback` + - Choose **"Create"** +7. Take note of the **Client ID** and **Client Secret** + +It's recommended to refresh sessions on a short interval (1h) with `cookie-refresh` setting which validates that the +account is still authorized. + +#### Restrict auth to specific Google groups on your domain. (optional) + +1. Create a [service account](https://developers.google.com/identity/protocols/oauth2/service-account) and configure it + to use [Application Default Credentials / Workload Identity / Workload Identity Federation (recommended)](#using-application-default-credentials-adc--workload-identity--workload-identity-federation-recommended) or, + alternatively download the JSON. +2. Make note of the Client ID for a future step. +3. Under "APIs & Auth", choose APIs. +4. Click on Admin SDK and then Enable API. +5. Follow the steps on [Set up domain-wide delegation for a service account](https://developers.google.com/workspace/guides/create-credentials#optional_set_up_domain-wide_delegation_for_a_service_account) + and give the client id from step 2 the following oauth scopes: + + ``` + https://www.googleapis.com/auth/admin.directory.group.member.readonly + ``` + +6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access. +7. Create or choose an existing administrative email address on the Gmail domain to assign to the `google-admin-email` + flag. This email will be impersonated by this client to make calls to the Admin SDK. See the note on the link from + step 5 for the reason why. +8. Create or choose an existing email group and set that email to the `google-group` flag. You can pass multiple instances + of this flag with different groups and the user will be checked against all the provided groups. + +(Only if using a JSON file (see step 1)) + +9. Lock down the permissions on the json file downloaded from step 1 so only oauth2-proxy is able to read the file and + set the path to the file in the `google-service-account-json` flag. +10. Restart oauth2-proxy. + +Note: The user is checked against the group members list on initial authentication and every time the token is +refreshed ( about once an hour ). + +##### Using Application Default Credentials (ADC) / Workload Identity / Workload Identity Federation (recommended) +oauth2-proxy can make use of [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials). +When deployed within GCP, this means that it can automatically use the service account attached to the resource. When deployed to GKE, ADC +can be leveraged through a feature called Workload Identity. Follow Google's [guide](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity) +to set up Workload Identity. + +When deployed outside of GCP, [Workload Identity Federation](https://cloud.google.com/docs/authentication/provide-credentials-adc#wlif) might be an option. + +##### Using Organization ID as Preferred Username (optional) +By default, the google provider uses the google id as username. If you would like to use an organization id instead, you can set the `google-use-organization-id` flag to true. +This requires that the service account used to query the Google Admin SDK has one of the following scopes granted in step 5 above: +- `https://www.googleapis.com/auth/admin.directory.user.readonly`, +- `https://www.googleapis.com/auth/admin.directory.user` +- `https://www.googleapis.com/auth/cloud-platform` diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/index.md b/docs/versioned_docs/version-7.13.x/configuration/providers/index.md new file mode 100644 index 0000000000..3d3938ff65 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/index.md @@ -0,0 +1,45 @@ +--- +id: index +title: OAuth Provider Configuration +--- + +You will need to register an OAuth application with a Provider (Google, GitHub or another provider), and configure it +with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on. + +Valid providers are : + +- [ADFS](adfs.md) +- [Bitbucket](bitbucket.md) +- [Cidaas](cidaas.md) +- [DigitalOcean](digitalocean.md) +- [Facebook](facebook.md) +- [Gitea](gitea.md) +- [GitHub](github.md) +- [GitLab](gitlab.md) +- [Google](google.md) _default_ +- [Keycloak](keycloak.md) (Deprecated) +- [Keycloak OIDC](keycloak_oidc.md) +- [LinkedIn](linkedin.md) +- [login.gov](login_gov.md) +- [Microsoft Azure](ms_azure_ad.md) (Deprecated) +- [Microsoft Entra ID](ms_entra_id.md) +- [Nextcloud](nextcloud.md) +- [OpenID Connect](openid_connect.md) +- [SourceHut](sourcehut.md) + +The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the +OpenID Connect provider. + +## Email Authentication + +To authorize a specific email-domain use `--email-domain=yourcompany.com`. To authorize individual email addresses use +`--authenticated-emails-file=/path/to/file` with one email per line. To authorize all email addresses use `--email-domain=*`. + +## Adding a new Provider + +Follow the examples in the [`providers` package](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/) to define a new +`Provider` instance. Add a new `case` to +[`providers.New()`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/providers.go) to allow `oauth2-proxy` to use the +new `Provider`. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/keycloak.md b/docs/versioned_docs/version-7.13.x/configuration/providers/keycloak.md new file mode 100644 index 0000000000..11a1abca1c --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/keycloak.md @@ -0,0 +1,36 @@ +--- +id: keycloak +title: Keycloak (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Keycloak, use [Keycloak OIDC Auth Provider](keycloak_oidc.md) if possible. +::: + +1. Create new client in your Keycloak realm with **Access Type** 'confidential' and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. + +Make sure you set the following to the appropriate url: + +``` + --provider=keycloak + --client-id= + --client-secret= + --login-url="http(s):///auth/realms//protocol/openid-connect/auth" + --redeem-url="http(s):///auth/realms//protocol/openid-connect/token" + --profile-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --validate-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --keycloak-group= + --keycloak-group= +``` + +For group based authorization, the optional `--keycloak-group` (legacy) or `--allowed-group` (global standard) +flags can be used to specify which groups to limit access to. + +If these are unset but a `groups` mapper is set up above in step (3), the provider will still +populate the `X-Forwarded-Groups` header to your upstream server with the `groups` data in the +Keycloak userinfo endpoint response. + +The group management in keycloak is using a tree. If you create a group named admin in keycloak +you should define the 'keycloak-group' value to /admin. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/keycloak_oidc.md b/docs/versioned_docs/version-7.13.x/configuration/providers/keycloak_oidc.md new file mode 100644 index 0000000000..b29096e35d --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/keycloak_oidc.md @@ -0,0 +1,151 @@ +--- +id: keycloak_oidc +title: Keycloak OIDC +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------ | ------- | +| `--allowed-role` | `allowed_roles` | string \| list | restrict logins to users with this role (may be given multiple times). Only works with the keycloak-oidc provider. | | + +## Usage + +``` + --provider=keycloak-oidc + --client-id= + --client-secret= + --redirect-url=https://internal.yourcompany.com/oauth2/callback + --oidc-issuer-url=https:///realms/ // For Keycloak versions <17: --oidc-issuer-url=https:///auth/realms/ + --email-domain= // Validate email domain for users, see option documentation + --allowed-role= // Optional, required realm role + --allowed-role=: // Optional, required client role + --allowed-group= // Optional, requires group client scope + --code-challenge-method=S256 // PKCE +``` + +:::note +Keycloak has updated its admin console and as of version 19.0.0, the new admin console is enabled by default. The +legacy admin console has been announced for removal with the release of version 21.0.0. +::: + +**Keycloak legacy admin console** + +1. Create new client in your Keycloak realm with **Access Type** 'confidential', **Client protocol** 'openid-connect' + and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. +4. Create a mapper with **Mapper Type** 'Audience' and **Included Client Audience** and **Included Custom Audience** set + to your client name. + +**Keycloak new admin console (default as of v19.0.0)** + +The following example shows how to create a simple OIDC client using the new Keycloak admin2 console. However, for best +practices, it is recommended to consult the Keycloak documentation. + +The OIDC client must be configured with an _audience mapper_ to include the client's name in the `aud` claim of the JWT token. +The `aud` claim specifies the intended recipient of the token, and OAuth2 Proxy expects a match against the values of +either `--client-id` or `--oidc-extra-audience`. + +_In Keycloak, claims are added to JWT tokens through the use of mappers at either the realm level using "client scopes" or +through "dedicated" client mappers._ + +**Creating the client** + +1. Create a new OIDC client in your Keycloak realm by navigating to: + **Clients** -> **Create client** + * **Client Type** 'OpenID Connect' + * **Client ID** ``, please complete the remaining fields as appropriate and click **Next**. + * **Client authentication** 'On' + * **Authentication flow** + * **Standard flow** 'selected' + * **Direct access grants** 'deselect' + * _Save the configuration._ + * **Settings / Access settings**: + * **Valid redirect URIs** `https://internal.yourcompany.com/oauth2/callback` + * _Save the configuration._ + * Under the **Credentials** tab you will now be able to locate ``. +2. Configure a dedicated *audience mapper* for your client by navigating to **Clients** -> **\** -> **Client scopes**. +* Access the dedicated mappers pane by clicking **\-dedicated**, located under *Assigned client scope*. + _(It should have a description of "Dedicated scope and mappers for this client")_ + * Click **Configure a new mapper** and select **Audience** + * **Name** 'aud-mapper-\' + * **Included Client Audience** select `` from the dropdown. + * _OAuth2 proxy can be set up to pass both the access and ID JWT tokens to your upstream services. + If you require additional audience entries, you can use the **Included Custom Audience** field in addition + to the "Included Client Audience" dropdown. Note that the "aud" claim of a JWT token should be limited and + only specify its intended recipients._ + * **Add to ID token** 'On' + * **Add to access token** 'On' - [#1916](https://github.com/oauth2-proxy/oauth2-proxy/pull/1916) + * _Save the configuration._ +* Any subsequent dedicated client mappers can be defined by clicking **Dedicated scopes** -> **Add mapper** -> + **By configuration** -> *Select mapper* + +You should now be able to create a test user in Keycloak and get access to the OAuth2 Proxy instance, make sure to set +an email address matching `` and select _Email verified_. + +**Authorization** + +_OAuth2 Proxy will perform authorization by requiring a valid user, this authorization can be extended to take into +account a user's membership in Keycloak `groups`, `realm roles`, and `client roles` using the keycloak-oidc provider options +`--allowed-role` or `--allowed-group`_ + +**Roles** + +_A standard Keycloak installation comes with the required mappers for **realm roles** and **client roles** through the +pre-defined client scope "roles". This ensures that any roles assigned to a user are included in the `JWT` tokens when +using an OIDC client that has the "Full scope allowed" feature activated, the feature is enabled by default._ + +_Creating a realm role_ +* Navigate to **Realm roles** -> **Create role** + * **Role name**, *``* -> **save** + +_Creating a client role_ +* Navigate to **Clients** -> `` -> **Roles** -> **Create role** + * **Role name**, *``* -> **save** + + +_Assign a role to a user_ + +**Users** -> _Username_ -> **Role mapping** -> **Assign role** -> _filter by roles or clients and select_ -> **Assign**. + +Keycloak "realm roles" can be authorized using the `--allowed-role=` option, while "client roles" can be +evaluated using `--allowed-role=:`. + +You may limit the _realm roles_ included in the JWT tokens for any given client by navigating to: +**Clients** -> `` -> **Client scopes** -> _\-dedicated_ -> **Scope** +Disabling **Full scope allowed** activates the **Assign role** option, allowing you to select which roles, if assigned +to a user, will be included in the user's JWT tokens. This can be useful when a user has many associated roles, and you +want to reduce the size and impact of the JWT token. + + +**Groups** + +You may also do authorization on group memberships by using the OAuth2 Proxy option `--allowed-group`. +We will only do a brief description of creating the required _client scope_ **groups** and refer you to read the Keycloak +documentation. + +To summarize, the steps required to authorize Keycloak group membership with OAuth2 Proxy are as follows: + +* Create a new Client Scope with the name **groups** in Keycloak. + * Include a mapper of type **Group Membership**. + * Set the "Token Claim Name" to **groups** or customize by matching it to the `--oidc-groups-claim` option of OAuth2 Proxy. + * If the "Full group path" option is selected, you need to include a "/" separator in the group names defined in the + `--allowed-group` option of OAuth2 Proxy. Example: "/groupname" or "/groupname/child_group". + +After creating the _Client Scope_ named _groups_ you will need to attach it to your client. +**Clients** -> `` -> **Client scopes** -> **Add client scope** -> Select **groups** and choose Optional +and you should now have a client that maps group memberships into the JWT tokens so that Oauth2 Proxy may evaluate them. + +Create a group by navigating to **Groups** -> **Create group** and _add_ your test user as a member. + +The OAuth2 Proxy option `--allowed-group=/groupname` will now allow you to filter on group membership + +Keycloak also has the option of attaching roles to groups, please refer to the Keycloak documentation for more information. + +**Tip** + +To check if roles or groups are added to JWT tokens, you can preview a users token in the Keycloak console by following +these steps: **Clients** -> `` -> **Client scopes** -> **Evaluate**. +Select a _realm user_ and optional _scope parameters_ such as groups, and generate the JSON representation of an access +or id token to examine its contents. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/linkedin.md b/docs/versioned_docs/version-7.13.x/configuration/providers/linkedin.md new file mode 100644 index 0000000000..7d26ec4334 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/linkedin.md @@ -0,0 +1,13 @@ +--- +id: linkedin +title: LinkedIn +--- + +For LinkedIn, the registration steps are: + +1. Create a new project: https://www.linkedin.com/secure/developer +2. In the OAuth User Agreement section: + - In default scope, select r_basicprofile and r_emailaddress. + - In "OAuth 2.0 Redirect URLs", enter `https://internal.yourcompany.com/oauth2/callback` +3. Fill in the remaining required fields and Save. +4. Take note of the **Consumer Key / API Key** and **Consumer Secret / Secret Key** diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/login_gov.md b/docs/versioned_docs/version-7.13.x/configuration/providers/login_gov.md new file mode 100644 index 0000000000..badbe48e69 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/login_gov.md @@ -0,0 +1,79 @@ +--- +id: login_gov +title: Login.gov +--- + +login.gov is an OIDC provider for the US Government. +If you are a US Government agency, you can contact the login.gov team through the contact information +that you can find on https://login.gov/developers/ and work with them to understand how to get login.gov +accounts for integration/test and production access. + +A developer guide is available here: https://developers.login.gov/, though this proxy handles everything +but the data you need to create to register your application in the login.gov dashboard. + +As a demo, we will assume that you are running your application that you want to secure locally on +http://localhost:3000/, that you will be starting your proxy up on http://localhost:4180/, and that +you have an agency integration account for testing. + +First, register your application in the dashboard. The important bits are: +* Identity protocol: make this `Openid connect` +* Issuer: do what they say for OpenID Connect. We will refer to this string as `${LOGINGOV_ISSUER}`. +* Public key: This is a self-signed certificate in .pem format generated from a 2048-bit RSA private key. + A quick way to do this is + `openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -nodes -subj '/C=US/ST=Washington/L=DC/O=GSA/OU=18F/CN=localhost'`. + The contents of the `key.pem` shall be referred to as `${OAUTH2_PROXY_JWT_KEY}`. +* Return to App URL: Make this be `http://localhost:4180/` +* Redirect URIs: Make this be `http://localhost:4180/oauth2/callback`. +* Attribute Bundle: Make sure that email is selected. + +Now start the proxy up with the following options: +``` +./oauth2-proxy -provider login.gov \ + -client-id=${LOGINGOV_ISSUER} \ + -redirect-url=http://localhost:4180/oauth2/callback \ + -oidc-issuer-url=https://idp.int.identitysandbox.gov/ \ + -cookie-secure=false \ + -email-domain=gsa.gov \ + -upstream=http://localhost:3000/ \ + -cookie-secret=somerandomstring12341234567890AB \ + -cookie-domain=localhost \ + -skip-provider-button=true \ + -pubjwk-url=https://idp.int.identitysandbox.gov/api/openid_connect/certs \ + -profile-url=https://idp.int.identitysandbox.gov/api/openid_connect/userinfo \ + -jwt-key="${OAUTH2_PROXY_JWT_KEY}" +``` +You can also set all these options with environment variables, for use in cloud/docker environments. +One tricky thing that you may encounter is that some cloud environments will pass in environment +variables in a docker env-file, which does not allow multiline variables like a PEM file. +If you encounter this, then you can create a `jwt_signing_key.pem` file in the top level +directory of the repo which contains the key in PEM format and then do your docker build. +The docker build process will copy that file into your image which you can then access by +setting the `OAUTH2_PROXY_JWT_KEY_FILE=/etc/ssl/private/jwt_signing_key.pem` +environment variable, or by setting `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem` on the commandline. + +Once it is running, you should be able to go to `http://localhost:4180/` in your browser, +get authenticated by the login.gov integration server, and then get proxied on to your +application running on `http://localhost:3000/`. In a real deployment, you would secure +your application with a firewall or something so that it was only accessible from the +proxy, and you would use real hostnames everywhere. + +#### Skip OIDC discovery + +Some providers do not support OIDC discovery via their issuer URL, so oauth2-proxy cannot simply grab the authorization, +token and jwks URI endpoints from the provider's metadata. + +In this case, you can set the `--skip-oidc-discovery` option, and supply those required endpoints manually: + +``` + -provider oidc + -client-id oauth2-proxy + -client-secret proxy + -redirect-url http://127.0.0.1:4180/oauth2/callback + -oidc-issuer-url http://127.0.0.1:5556 + -skip-oidc-discovery + -login-url http://127.0.0.1:5556/authorize + -redeem-url http://127.0.0.1:5556/token + -oidc-jwks-url http://127.0.0.1:5556/keys + -cookie-secure=false + -email-domain example.com +``` diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/ms_azure_ad.md b/docs/versioned_docs/version-7.13.x/configuration/providers/ms_azure_ad.md new file mode 100644 index 0000000000..4feefc6800 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/ms_azure_ad.md @@ -0,0 +1,59 @@ +--- +id: azure +title: Azure (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Azure, use [Microsoft Entra ID](ms_entra_id.md) if possible. +::: + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | ------ | ---------------------------------------------------------------- | ---------- | +| `--azure-tenant` | `azure_tenant` | string | go to a tenant-specific or common (tenant-independent) endpoint. | `"common"` | +| `--resource` | `resource` | string | The resource that is protected (Azure AD only) | | + +## Usage + +1. Add an application: go to [https://portal.azure.com](https://portal.azure.com), choose **Azure Active Directory**, select + **App registrations** and then click on **New registration**. +2. Pick a name, check the supported account type(single-tenant, multi-tenant, etc). In the **Redirect URI** section create a new + **Web** platform entry for each app that you want to protect by the oauth2 proxy(e.g. + https://internal.yourcompanycom/oauth2/callback). Click **Register**. +3. Next we need to add group read permissions for the app registration, on the **API Permissions** page of the app, click on + **Add a permission**, select **Microsoft Graph**, then select **Application permissions**, then click on **Group** and select + **Group.Read.All**. Hit **Add permissions** and then on **Grant admin consent** (you might need an admin to do this). +
**IMPORTANT**: Even if this permission is listed with **"Admin consent required=No"** the consent might actually + be required, due to AAD policies you won't be able to see. If you get a **"Need admin approval"** during login, + most likely this is what you're missing! +4. Next, if you are planning to use v2.0 Azure Auth endpoint, go to the **Manifest** page and set `"accessTokenAcceptedVersion": 2` + in the App registration manifest file. +5. On the **Certificates & secrets** page of the app, add a new client secret and note down the value after hitting **Add**. +6. Configure the proxy with: +- for V1 Azure Auth endpoint (Azure Active Directory Endpoints - https://login.microsoftonline.com/common/oauth2/authorize) + +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://sts.windows.net/{tenant-id}/ +``` + +- for V2 Azure Auth endpoint (Microsoft Identity Platform Endpoints - https://login.microsoftonline.com/common/oauth2/v2.0/authorize) +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://login.microsoftonline.com/{tenant-id}/v2.0 +``` + +***Notes***: +- When using v2.0 Azure Auth endpoint (`https://login.microsoftonline.com/{tenant-id}/v2.0`) as `--oidc_issuer_url`, in conjunction + with `--resource` flag, be sure to append `/.default` at the end of the resource name. See + https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope for more details. +- When using the Azure Auth provider with nginx and the cookie session store you may find the cookie is too large and doesn't + get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the + [redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.13.x/configuration/providers/ms_entra_id.md new file mode 100644 index 0000000000..95fb99bc60 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/ms_entra_id.md @@ -0,0 +1,197 @@ +--- +id: ms_entra_id +title: Microsoft Entra ID +--- + +Provider for Microsoft Entra ID. Fully compliant with OIDC, with support for group overage and multi-tenant apps. + +## Config Options + +The provider is OIDC-compliant, so all the OIDC parameters are honored. Additional provider-specific configuration parameters are: + +| Flag | Toml Field | Type | Description | Default | +| --------------------------- | -------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--entra-id-allowed-tenant` | `entra_id_allowed_tenants` | string \| list | List of allowed tenants. In case of multi-tenant apps, incoming tokens are issued by different issuers and OIDC issuer verification needs to be disabled. When not specified, all tenants are allowed. Redundant for single-tenant apps (regular ID token validation matches the issuer). | | +| `--entra-id-federated-token-auth` | `entra_id_federated_token_auth` | boolean | Enable oAuth2 client authentication with federated token projected by Entra Workload Identity plugin, instead of client secret. | false | + +## Configure App registration +To begin, create an App registration, set a redirect URI, and generate a secret. All account types are supported, including single-tenant, multi-tenant, multi-tenant with Microsoft accounts, and Microsoft accounts only. + +
+ See Azure Portal example +
+ +
+
+ +
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" # Others are also supported + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + // We don't specify any required API permissions - we allow user consent only + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Configure groups +If you want to make use of groups, you can configure *groups claim* to be present in ID Tokens issued by the App registration. +
+ See Azure Portal example +
+
+ +
+
+
+
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" + + group_membership_claims = [ + "SecurityGroup" + ] + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Scopes and claims +For single-tenant and multi-tenant apps without groups, the only required scope is `openid` (See: [Scopes and permissions](https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#the-openid-scope)). + +To make use of groups - for example use `allowed_groups` setting or authorize based on groups inside your service - you need to enable *groups claims* in the App Registration. When enabled, list of groups is present in the issued ID token. No additional scopes are required besides `openid`. This works up to 200 groups. + +When user has more than 200 group memberships, OAuth2-Proxy attempts to retrieve the complete list from Microsoft Graph API's [`transitiveMemberOf`](https://learn.microsoft.com/en-us/graph/api/user-list-transitivememberof). Endpoint requires `User.Read` scope (delegated permission). This permission can be by default consented by user during first login. Set scope to `openid User.Read` to request user consent. Without proper scope, user with 200+ groups will authenticate with 0 groups. See: [group overages](https://learn.microsoft.com/en-us/security/zero-trust/develop/configure-tokens-group-claims-app-roles#group-overages). + +Alternatively to user consent, both `openid` and `User.Read` permissions can be consented by admistrator. Then, user is not asked for consent on the first login, and group overage works with `openid` scope only. Admin consent can also be required for some tenants. It can be granted with [azuread_service_principal_delegated_permission_grant](https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/service_principal_delegated_permission_grant) terraform resource. + +For personal microsoft accounts, required scope is `openid profile email`. + +See: [Overview of permissions and consent in the Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview). + +### Multi-tenant apps +To authenticate apps from multiple tenants (including personal Microsoft accounts), set the common OIDC issuer url and disable verification: +```toml +oidc_issuer_url=https://login.microsoftonline.com/common/v2.0 +insecure_oidc_skip_issuer_verification=true +``` +`insecure_oidc_skip_issuer_verification` setting is required to disable following checks: +* Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). + +To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. + +### Workload Identity +Provider supports authentication with federated token, without need of using client secret. Following conditions have to be met: + +* Cluster has public OIDC provider URL. For major cloud providers, it can be enabled with a single flag, for example for [Azure Kubernetes Service deployed with Terraform](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster), it's `oidc_issuer_enabled`. +* Workload Identity admission webhook is deployed on the cluster. For AKS, it can be enabled with a flag (`workload_identity_enabled` in Terraform resource), for clusters outside of Azure, it can be installed from [helm chart](https://github.com/Azure/azure-workload-identity). +* Appropriate federated credential is added to application registration. +
+ See federated credential terraform example +``` + resource "azuread_application_federated_identity_credential" "fedcred" { + application_id = azuread_application.application.id # ID of your application + display_name = "federation-cred" + description = "Workload identity for oauth2-proxy" + audiences = ["api://AzureADTokenExchange"] # Fixed value + issuer = "https://cluster-oidc-issuer-url..." + subject = "system:serviceaccount:oauth2-proxy-namespace-name:oauth2-proxy-sa-name" # set proper NS and SA name + } +``` +
+ +* Kubernetes service account associated with oauth2-proxy deployment, is annotated with `azure.workload.identity/client-id: ` +* oauth2-proxy pod is labeled with `azure.workload.identity/use: "true"` +* oauth2-proxy is configured with `entra_id_federated_token_auth` set to `true`. + +`client_secret` setting can be omitted when using federated token authentication. + +See: [Azure Workload Identity documentation](https://azure.github.io/azure-workload-identity/docs/). + +### Example configurations +Single-tenant app without groups (*groups claim* not enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +``` + +Single-tenant app with up to 200 groups (*groups claim* enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +allowed_groups=["ac51800c-2679-4ecb-8130-636380a3b491"] +``` + +Single-tenant app with more than 200 groups: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +``` + +Single-tenant app with more than 200 groups and workload identity enabled: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +entra_id_federated_token_auth=true +``` + +Multi-tenant app with Microsoft personal accounts & one Entra tenant allowed, with group overage considered: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com/common/v2.0" +client_id="" +client_secret="" +insecure_oidc_skip_issuer_verification=true +scope="openid profile email User.Read" +entra_id_allowed_tenants=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant +email_domains="*" +``` diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/nextcloud.md b/docs/versioned_docs/version-7.13.x/configuration/providers/nextcloud.md new file mode 100644 index 0000000000..85ebff0398 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/nextcloud.md @@ -0,0 +1,28 @@ +--- +id: nextcloud +title: NextCloud +--- + +The Nextcloud provider allows you to authenticate against users in your +Nextcloud instance. + +When you are using the Nextcloud provider, you must specify the urls via +configuration, environment variable, or command line argument. Depending +on whether your Nextcloud instance is using pretty urls your urls may be of the +form `/index.php/apps/oauth2/*` or `/apps/oauth2/*`. + +Refer to the [OAuth2 +documentation](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/oauth2.html) +to set up the client id and client secret. Your "Redirection URI" will be +`https://internalapp.yourcompany.com/oauth2/callback`. + +``` + -provider nextcloud + -client-id + -client-secret + -login-url="/index.php/apps/oauth2/authorize" + -redeem-url="/index.php/apps/oauth2/api/v1/token" + -validate-url="/ocs/v2.php/cloud/user?format=json" +``` + +Note: in *all* cases the validate-url will *not* have the `index.php`. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/openid_connect.md b/docs/versioned_docs/version-7.13.x/configuration/providers/openid_connect.md new file mode 100644 index 0000000000..de17005808 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/openid_connect.md @@ -0,0 +1,146 @@ +--- +id: openid_connect +title: OpenID Connect +--- + +OpenID Connect is a spec for OAUTH 2.0 + identity that is implemented by many major providers and several open source projects. + +This provider was originally built against CoreOS Dex, and we will use it as an example. +The OpenID Connect Provider (OIDC) can also be used to connect to other Identity Providers such as Okta, an example can be found below. + +#### Dex + +To configure the OIDC provider for Dex, perform the following steps: + +1. Download Dex: + + ``` + go get github.com/dexidp/dex + ``` + + See the [getting started guide](https://dexidp.io/docs/getting-started/) for more details. + +2. Setup oauth2-proxy with the correct provider and using the default ports and callbacks. Add a configuration block to + the `staticClients` section of `examples/config-dev.yaml`: + + ``` + - id: oauth2-proxy + redirectURIs: + - 'http://127.0.0.1:4180/oauth2/callback' + name: 'oauth2-proxy' + secret: proxy + ``` + +3. Launch Dex: from `$GOPATH/github.com/dexidp/dex`, run: + + ``` + bin/dex serve examples/config-dev.yaml + ``` + +4. In a second terminal, run the oauth2-proxy with the following args: + + ```shell + --provider oidc + --provider-display-name "My OIDC Provider" + --client-id oauth2-proxy + --client-secret proxy + --redirect-url http://127.0.0.1:4180/oauth2/callback + --oidc-issuer-url http://127.0.0.1:5556/dex + --cookie-secure=false + --cookie-secret=secret + --email-domain kilgore.trout + ``` + + To serve the current working directory as a website under the `/static` endpoint, add: + + ```shell + --upstream file://$PWD/#/static/ + ``` + +5. Test the setup by visiting http://127.0.0.1:4180 or http://127.0.0.1:4180/static . + +See also [our local testing environment](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/local-environment) for a self-contained example using Docker and etcd as storage for Dex. + +#### Okta + +To configure the OIDC provider for Okta, perform the following steps: + +1. Log in to Okta using an administrative account. It is suggested you try this in preview first, `example.oktapreview.com` +2. (OPTIONAL) If you want to configure authorization scopes and claims to be passed on to multiple applications, + you may wish to configure an authorization server for each application. Otherwise, the provided `default` will work. + * Navigate to **Security** then select **API** + * Click **Add Authorization Server**, if this option is not available you may require an additional license for a custom + authorization server. + * Fill out the **Name** with something to describe the application you are protecting. e.g. 'Example App'. + * For **Audience**, pick the URL of the application you wish to protect: https://example.corp.com + * Fill out a **Description** + * Add any **Access Policies** you wish to configure to limit application access. + * The default settings will work for other options. + [See Okta documentation for more information on Authorization Servers](https://developer.okta.com/docs/guides/customize-authz-server/overview/) +3. Navigate to **Applications** then select **Add Application**. + * Select **Web** for the **Platform** setting. + * Select **OpenID Connect** and click **Create** + * Pick an **Application Name** such as `Example App`. + * Set the **Login redirect URI** to `https://example.corp.com`. + * Under **General** set the **Allowed grant types** to `Authorization Code` and `Refresh Token`. + * Leave the rest as default, taking note of the `Client ID` and `Client Secret`. + * Under **Assignments** select the users or groups you wish to access your application. +4. Create a configuration file like the following: + + ``` + provider = "oidc" + redirect_url = "https://example.corp.com/oauth2/callback" + oidc_issuer_url = "https://corp.okta.com/oauth2/abCd1234" + upstreams = [ + "https://example.corp.com" + ] + email_domains = [ + "corp.com" + ] + client_id = "XXXXX" + client_secret = "YYYYY" + pass_access_token = true + cookie_secret = "ZZZZZ" + skip_provider_button = true + ``` + +The `oidc_issuer_url` is based on URL from your **Authorization Server**'s **Issuer** field in step 2, or simply +https://corp.okta.com. The `client_id` and `client_secret` are configured in the application settings. +Generate a unique `cookie_secret` to encrypt the cookie. + +Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/example.cfg` + +#### Okta - localhost + +1. Signup for developer account: https://developer.okta.com/signup/ +2. Create New `Web` Application: https://$\{your-okta-domain\}/dev/console/apps/new +3. Example Application Settings for localhost: + * **Name:** My Web App + * **Base URIs:** http://localhost:4180/ + * **Login redirect URIs:** http://localhost:4180/oauth2/callback + * **Logout redirect URIs:** http://localhost:4180/ + * **Group assignments:** `Everyone` + * **Grant type allowed:** `Authorization Code` and `Refresh Token` +4. Make note of the `Client ID` and `Client secret`, they are needed in a future step +5. Make note of the **default** Authorization Server Issuer URI from: https://$\{your-okta-domain\}/admin/oauth2/as +6. Example config file `/etc/localhost.cfg` + ```shell + provider = "oidc" + redirect_url = "http://localhost:4180/oauth2/callback" + oidc_issuer_url = "https://$\{your-okta-domain\}/oauth2/default" + upstreams = [ + "http://0.0.0.0:8080" + ] + email_domains = [ + "*" + ] + client_id = "XXX" + client_secret = "YYY" + pass_access_token = true + cookie_secret = "ZZZ" + cookie_secure = false + skip_provider_button = true + # Note: use the following for testing within a container + # http_address = "0.0.0.0:4180" + ``` +7. Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/localhost.cfg` diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/sourcehut.md b/docs/versioned_docs/version-7.13.x/configuration/providers/sourcehut.md new file mode 100644 index 0000000000..2c196bda4e --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/sourcehut.md @@ -0,0 +1,25 @@ +--- +id: sourcehut +title: SourceHut +--- + +1. Create a new OAuth client: https://meta.sr.ht/oauth2 +2. Under `Redirection URI` enter the correct URL, i.e. + `https://internal.yourcompany.com/oauth2/callback` + +To use the provider, start with `--provider=sourcehut`. + +If you are hosting your own SourceHut instance, make sure you set the following +to the appropriate URLs: + +```shell + --login-url="https:///oauth2/authorize" + --redeem-url="https:///oauth2/access-token" + --profile-url="https:///query" + --validate-url="https:///profile" +``` + +The default configuration allows everyone with an account to authenticate. +Restricting access is currently only supported by +[email](index.md#email-authentication). + diff --git a/docs/versioned_docs/version-7.13.x/configuration/sessions.md b/docs/versioned_docs/version-7.13.x/configuration/sessions.md new file mode 100644 index 0000000000..e20378170a --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/sessions.md @@ -0,0 +1,99 @@ +--- +id: session_storage +title: Session Storage +--- + +Sessions allow a user's authentication to be tracked between multiple HTTP +requests to a service. + +The OAuth2 Proxy uses a Cookie to track user sessions and will store the session +data in one of the available session storage backends. + +At present the available backends are (as passed to `--session-store-type`): +- [cookie](#cookie-storage) (default) +- [redis](#redis-storage) + +### Cookie Storage + +The Cookie storage backend is the default backend implementation and has +been used in the OAuth2 Proxy historically. + +With the Cookie storage backend, all session information is stored in client +side cookies and transferred with each and every request. + +The following should be known when using this implementation: +- Since all state is stored client side, this storage backend means that the OAuth2 Proxy is completely stateless +- Cookies are signed server side to prevent modification client-side +- It is mandatory to set a `cookie-secret` which will ensure data is encrypted within the cookie data. +- Since multiple requests can be made concurrently to the OAuth2 Proxy, this session implementation +cannot lock sessions and while updating and refreshing sessions, there can be conflicts which force +users to re-authenticate + + +### Redis Storage + +The Redis Storage backend stores encrypted sessions in redis. Instead of sending all the information +back the client for storage, as in the [Cookie storage](#cookie-storage), a ticket is sent back +to the user as the cookie value instead. + +A ticket is composed as the following: + +`{CookieName}-{ticketID}.{secret}` + +Where: + +- The `CookieName` is the OAuth2 cookie name (_oauth2_proxy by default) +- The `ticketID` is a 128-bit random number, hex-encoded +- The `secret` is a 128-bit random number, base64url encoded (no padding). The secret is unique for every session. +- The pair of `{CookieName}-{ticketID}` comprises a ticket handle, and thus, the redis key +to which the session is stored. The encoded session is encrypted with the secret and stored +in redis via the `SETEX` command. + +Encrypting every session uniquely protects the refresh/access/id tokens stored in the session from +disclosure. Additionally, the browser only has to send a short Cookie with every request and not the whole JWT, +which can get quite big. + +Two settings are used to configure the OAuth2 Proxy cookie lifetime: + + --cookie-refresh duration refresh the cookie after this duration; 0 to disable + --cookie-expire duration expire timeframe for cookie 168h0m0s + +The "cookie-expire" value should be equal to the lifetime of the Refresh-Token that is issued by the OAuth2 authorization server. +If it expires earlier and is deleted by the browser, OAuth2 Proxy cannot find the stored Refresh-Tokens in Redis and thus cannot start +the refresh flow to get a new Access-Token. If it is longer, it might be that the old Refresh-Token will be found in Redis but has already +expired. + +The "cookie-refresh" value controls when OAuth2 Proxy tries to refresh an Access-Token. If it is set to "0", the +Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2-Proxy will +refresh the Access-Token after this many seconds whether it is still valid or not. According to the official OAuth2.0 specification +Access-Tokens are not required to follow a specific format. Therefore OAuth2-Proxy cannot check for any expiry date without an +introspection endpoint. If an Access-Token expires and you have not set a corresponding "cookie-refresh" value, you will likely +encounter expiry issues. + +Caveat: It can happen that the Access-Token is valid for e.g. "1m" and a request happens after exactly "59s". +It would pass OAuth2 Proxy and be forwarded to the backend but is just expired when the backend tries to validate +it. This is especially relevant if the backend uses the JWT to make requests to other backends. +For this reason, it's advised to set the cookie-refresh a couple of seconds less than the Access-Token lifespan. + +Recommended settings: + +* cookie_refresh := Access-Token lifespan - 1m +* cookie_expire := Refresh-Token lifespan (i.e. Keycloak client_session_idle) + +#### Usage + +When using the redis store, specify `--session-store-type=redis` as well as the Redis connection URL, via +`--redis-connection-url=redis://host[:port][/db-number]`. + +You may also configure the store for Redis Sentinel. In this case, you will want to use the +`--redis-use-sentinel=true` flag, as well as configure the flags `--redis-sentinel-master-name` +and `--redis-sentinel-connection-urls` appropriately. + +Redis Cluster is available to be the backend store as well. To leverage it, you will need to set the +`--redis-use-cluster=true` flag, and configure the flags `--redis-cluster-connection-urls` appropriately. + +Note that flags `--redis-use-sentinel=true` and `--redis-use-cluster=true` are mutually exclusive. + +Note, if Redis timeout option is set to non-zero, the `--redis-connection-idle-timeout` +must be less than [Redis timeout option](https://redis.io/docs/reference/clients/#client-timeouts). For example: if either redis.conf includes +`timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` diff --git a/docs/versioned_docs/version-7.13.x/configuration/systemd_socket.md b/docs/versioned_docs/version-7.13.x/configuration/systemd_socket.md new file mode 100644 index 0000000000..642e6f3f7b --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/systemd_socket.md @@ -0,0 +1,43 @@ +--- +id: systemd_socket +title: Systemd Socket Activation +--- + +Pass an existing listener created by systemd.socket to oauth2-proxy. + +To do this create a socket: + +oauth2-proxy.socket +``` +[Socket] +ListenStream=%t/oauth2.sock +SocketGroup=www-data +SocketMode=0660 +``` + +Now it's possible to call this socket from e.g. nginx: +``` +server { + location /oauth2/ { + proxy_pass http://unix:/run/oauth2-proxy/oauth2.sock; +} +``` + +The oauth2-proxy should have `--http-address=fd:3` as a parameter. +Here fd is case insensitive and means file descriptor. The number 3 refers to the first non-stdin/stdout/stderr file descriptor, +systemd-socket-activate (which is what systemd.socket uses), listens to what it is told and passes +the listener it created onto the process, starting with file descriptor 3. + +``` +./oauth2-proxy \ + --http-address="fd:3" \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... +``` + +Currently TLS is not supported (but it's doable). diff --git a/docs/versioned_docs/version-7.13.x/configuration/tls.md b/docs/versioned_docs/version-7.13.x/configuration/tls.md new file mode 100644 index 0000000000..68344b22d5 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/tls.md @@ -0,0 +1,85 @@ +--- +id: tls +title: TLS Configuration +--- + +There are two recommended configurations: +- [At OAuth2 Proxy](#terminate-tls-at-oauth2-proxy) +- [At Reverse Proxy](#terminate-tls-at-reverse-proxy-eg-nginx) + +### Terminate TLS at OAuth2 Proxy + +1. Configure SSL Termination with OAuth2 Proxy by providing a `--tls-cert-file=/path/to/cert.pem` and `--tls-key-file=/path/to/cert.key`. + + The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --tls-cert-file=/path/to/cert.pem \ + --tls-key-file=/path/to/cert.key \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... + ``` + +2. With this configuration approach the customization of the TLS settings is limited. + + The minimal acceptable TLS version can be set with `--tls-min-version=TLS1.3`. + The defaults set `TLS1.2` as the minimal version. + Regardless of the minimum version configured, `TLS1.3` is currently always used as the maximal version. + + TLS server side cipher suites can be specified with `--tls-cipher-suite=TLS_RSA_WITH_RC4_128_SHA`. + If not specified, the defaults from [`crypto/tls`](https://pkg.go.dev/crypto/tls#CipherSuites) of the currently used `go` version for building `oauth2-proxy` will be used. + A complete list of valid TLS cipher suite names can be found in [`crypto/tls`](https://pkg.go.dev/crypto/tls#pkg-constants). + +### Terminate TLS at Reverse Proxy, e.g. Nginx + +1. Configure SSL Termination with [Nginx](http://nginx.org/) (example config below), Amazon ELB, Google Cloud Platform Load Balancing, or ... + + Because `oauth2-proxy` listens on `127.0.0.1:4180` by default, to listen on all interfaces (needed when using an + external load balancer like Amazon ELB or Google Platform Load Balancing) use `--http-address="0.0.0.0:4180"` or + `--http-address="http://:4180"`. + + Nginx will listen on port `443` and handle SSL connections while proxying to `oauth2-proxy` on port `4180`. + `oauth2-proxy` will then authenticate requests for an upstream application. The external endpoint for this example + would be `https://internal.yourcompany.com/`. + + An example Nginx config follows. Note the use of `Strict-Transport-Security` header to pin requests to SSL + via [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security): + + ``` + server { + listen 443 default ssl; + server_name internal.yourcompany.com; + ssl_certificate /path/to/cert.pem; + ssl_certificate_key /path/to/cert.key; + add_header Strict-Transport-Security max-age=2592000; + + location / { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_connect_timeout 1; + proxy_send_timeout 30; + proxy_read_timeout 30; + } + } + ``` + +2. The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --reverse-proxy=true \ + --client-id=... \ + --client-secret=... + ``` diff --git a/docs/versioned_docs/version-7.13.x/features/endpoints.md b/docs/versioned_docs/version-7.13.x/features/endpoints.md new file mode 100644 index 0000000000..3ec1e2aa8a --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/features/endpoints.md @@ -0,0 +1,47 @@ +--- +id: endpoints +title: Endpoints +--- + +OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable. + +- /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info +- /ping - returns a 200 OK response, which is intended for use with health checks +- /ready - returns a 200 OK response if all the underlying connections (e.g., Redis store) are connected +- /metrics - Metrics endpoint for Prometheus to scrape, serve on the address specified by `--metrics-address`, disabled by default +- /oauth2/sign_in - the login page, which also doubles as a sign-out page (it clears cookies) +- /oauth2/sign_out - this URL is used to clear the session cookie +- /oauth2/start - a URL that will redirect to start the OAuth cycle +- /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url. +- /oauth2/userinfo - the URL is used to return user's email from the session in JSON format. +- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integration#configuring-for-use-with-the-nginx-auth_request-directive) +- /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages + +### Sign out + +To sign the user out, redirect them to `/oauth2/sign_out`. This endpoint only removes oauth2-proxy's own cookies, i.e. the user is still logged in with the authentication provider and may automatically re-login when accessing the application again. You will also need to redirect the user to the authentication provider's sign-out page afterward using the `rd` query parameter, i.e. redirect the user to something like (notice the url-encoding!): + +``` +/oauth2/sign_out?rd=https%3A%2F%2Fmy-oidc-provider.example.com%2Fsign_out_page +``` + +Alternatively, include the redirect URL in the `X-Auth-Request-Redirect` header: + +``` +GET /oauth2/sign_out HTTP/1.1 +X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page +... +``` + +(The "sign_out_page" should be the [`end_session_endpoint`](https://openid.net/specs/openid-connect-session-1_0.html#rfc.section.2.1) from [the metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) if your OIDC provider supports Session Management and Discovery.) + +BEWARE that the domain you want to redirect to (`my-oidc-provider.example.com` in the example) must be added to the [`--whitelist-domain`](../configuration/overview) configuration option otherwise the redirect will be ignored. Make sure to include the actual domain and port (if needed) and not the URL (e.g "localhost:8081" instead of "http://localhost:8081"). + +### Auth + +This endpoint returns 202 Accepted response or a 401 Unauthorized response. + +It can be configured using the following query parameters: +- `allowed_groups`: comma separated list of allowed groups +- `allowed_email_domains`: comma separated list of allowed email domains +- `allowed_emails`: comma separated list of allowed emails diff --git a/docs/versioned_docs/version-7.13.x/installation.md b/docs/versioned_docs/version-7.13.x/installation.md new file mode 100644 index 0000000000..20a6561471 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/installation.md @@ -0,0 +1,32 @@ +--- +id: installation +title: Installation +--- + +1. Choose how to deploy: + + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.13.0`) + + b. Using Go to install the latest release + ```bash + $ go install github.com/oauth2-proxy/oauth2-proxy/v7@latest + ``` + This will install the binary into `$GOPATH/bin`. Make sure you include `$GOPATH` in your `$PATH`. Otherwise your system won't find binaries installed via `go install` + + c. Using a [Prebuilt Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy) (AMD64, PPC64LE, S390x, ARMv6, ARMv7, and ARM64 available) + + d. Using a [Pre-Release Nightly Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy-nightly) (AMD64, PPC64LE, ARMv6, ARMv7, and ARM64 available) + + e. Using the official [Kubernetes manifest](https://github.com/oauth2-proxy/manifests) (Helm) + + Prebuilt binaries can be validated by extracting the file and verifying it against the `sha256sum.txt` checksum file provided for each release starting with version `v3.0.0`. + + ``` + $ sha256sum -c sha256sum.txt + oauth2-proxy-x.y.z.linux-amd64: OK + ``` + +2. [Select a Provider and Register an OAuth Application with a Provider](configuration/providers/index.md) +3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration/overview.md) +4. [Configure SSL or Deploy behind an SSL endpoint](configuration/tls.md) (example provided for Nginx) +5. [Configure OAuth2 Proxy using systemd.socket](configuration/systemd_socket.md) (example provided for Nginx/Systemd) diff --git a/docs/versioned_docs/version-7.13.x/welcome.md b/docs/versioned_docs/version-7.13.x/welcome.md new file mode 100644 index 0000000000..7bceadd80e --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/welcome.md @@ -0,0 +1,23 @@ +--- +id: welcome +title: Welcome +hide_table_of_contents: true +slug: / +--- + +![OAuth2 Proxy](/img/logos/OAuth2_Proxy_horizontal.svg) + +A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others) +to validate accounts by email, domain or group. + +:::note +This repository was forked from [bitly/OAuth2_Proxy](https://github.com/bitly/oauth2_proxy) on 27/11/2018. +Versions v3.0.0 and up are from this fork and will have diverged from any changes in the original fork. +A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/CHANGELOG.md). +::: + +![Sign In Page](/img/sign-in-page.png) + +## Architecture + +![OAuth2 Proxy Architecture](/img/simplified-architecture.svg) diff --git a/docs/versioned_sidebars/version-7.13.x-sidebars.json b/docs/versioned_sidebars/version-7.13.x-sidebars.json new file mode 100644 index 0000000000..3f5eb854ba --- /dev/null +++ b/docs/versioned_sidebars/version-7.13.x-sidebars.json @@ -0,0 +1,84 @@ +{ + "docs": [ + { + "type": "doc", + "id": "welcome" + }, + { + "type": "doc", + "id": "installation" + }, + { + "type": "doc", + "id": "behaviour" + }, + { + "type": "category", + "label": "Configuration", + "link": { + "type": "doc", + "id": "configuration/overview" + }, + "collapsed": false, + "items": [ + "configuration/overview", + "configuration/integration", + { + "type": "category", + "label": "OAuth Provider Configuration", + "link": { + "type": "doc", + "id": "configuration/providers/index" + }, + "items": [ + "configuration/providers/adfs", + "configuration/providers/azure", + "configuration/providers/bitbucket", + "configuration/providers/digitalocean", + "configuration/providers/facebook", + "configuration/providers/gitea", + "configuration/providers/github", + "configuration/providers/gitlab", + "configuration/providers/google", + "configuration/providers/keycloak", + "configuration/providers/keycloak_oidc", + "configuration/providers/linkedin", + "configuration/providers/login_gov", + "configuration/providers/ms_entra_id", + "configuration/providers/nextcloud", + "configuration/providers/openid_connect", + "configuration/providers/sourcehut" + ] + }, + "configuration/session_storage", + "configuration/tls", + "configuration/alpha-config" + ] + }, + { + "type": "category", + "label": "Features", + "link": { + "type": "doc", + "id": "features/endpoints" + }, + "collapsed": false, + "items": [ + "features/endpoints" + ] + }, + { + "type": "category", + "label": "Community", + "link": { + "type": "doc", + "id": "community/security" + }, + "collapsed": false, + "items": [ + "community/contribution", + "community/security" + ] + } + ] +} diff --git a/docs/versions.json b/docs/versions.json index ada187c69e..0d7ef6967f 100644 --- a/docs/versions.json +++ b/docs/versions.json @@ -1,4 +1,5 @@ [ + "7.13.x", "7.12.x", "7.11.x", "7.10.x", From fcf4e7947b86cda798c64bb9bb03ffeb3be90e3e Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sun, 9 Nov 2025 20:14:54 +0100 Subject: [PATCH 066/125] fix: hmacauth dependency licensing issue (#3253) * fix: upstream licensing issue by adopting hmacauth library and changing asserting library for its test cases Signed-off-by: Jan Larwig * fix: golang code quality and linting issues for hmacauth Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig --- go.mod | 4 +- go.sum | 4 +- oauthproxy_test.go | 2 +- pkg/authentication/hmacauth/LICENSE.md | 5 + pkg/authentication/hmacauth/hmacauth.go | 237 +++++++++++++++ pkg/authentication/hmacauth/hmacauth_test.go | 302 +++++++++++++++++++ pkg/upstream/http.go | 4 +- pkg/validation/options.go | 2 +- 8 files changed, 551 insertions(+), 9 deletions(-) create mode 100644 pkg/authentication/hmacauth/LICENSE.md create mode 100644 pkg/authentication/hmacauth/hmacauth.go create mode 100644 pkg/authentication/hmacauth/hmacauth_test.go diff --git a/go.mod b/go.mod index 0e14464cd6..69ffc5fb57 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,6 @@ require ( github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 github.com/justinas/alice v1.2.0 - github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 github.com/onsi/ginkgo/v2 v2.23.4 github.com/onsi/gomega v1.37.0 @@ -30,7 +29,7 @@ require ( github.com/spf13/cast v1.9.2 github.com/spf13/pflag v1.0.7 github.com/spf13/viper v1.20.1 - github.com/stretchr/testify v1.10.0 + github.com/stretchr/testify v1.11.1 github.com/vmihailenco/msgpack/v5 v5.4.1 golang.org/x/crypto v0.40.0 golang.org/x/net v0.42.0 @@ -45,7 +44,6 @@ require ( cloud.google.com/go/auth v0.16.2 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect github.com/beorn7/perks v1.0.1 // indirect - github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect diff --git a/go.sum b/go.sum index 8bc3166049..863da770ca 100644 --- a/go.sum +++ b/go.sum @@ -18,8 +18,6 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bitly/go-simplejson v0.5.1 h1:xgwPbetQScXt1gh9BmoJ6j9JMr3TElvuIyjR8pgdoow= github.com/bitly/go-simplejson v0.5.1/go.mod h1:YOPVLzCfwK14b4Sff3oP1AmGhI9T9Vsg84etUnlyp+Q= -github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY= -github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4= github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= @@ -142,6 +140,8 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8= diff --git a/oauthproxy_test.go b/oauthproxy_test.go index e05396cd3c..44569a3583 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -15,9 +15,9 @@ import ( "time" "github.com/coreos/go-oidc/v3/oidc" - "github.com/mbland/hmacauth" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/hmacauth" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/cookies" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" internaloidc "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/providers/oidc" diff --git a/pkg/authentication/hmacauth/LICENSE.md b/pkg/authentication/hmacauth/LICENSE.md new file mode 100644 index 0000000000..4bc7272f98 --- /dev/null +++ b/pkg/authentication/hmacauth/LICENSE.md @@ -0,0 +1,5 @@ +Copyright (c) 2017 Mike Bland mbland@acm.org + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/pkg/authentication/hmacauth/hmacauth.go b/pkg/authentication/hmacauth/hmacauth.go new file mode 100644 index 0000000000..77d2b9e257 --- /dev/null +++ b/pkg/authentication/hmacauth/hmacauth.go @@ -0,0 +1,237 @@ +package hmacauth + +import ( + "bytes" + "crypto" + "crypto/hmac" + "encoding/base64" + "errors" + "fmt" + "io" + "net/http" + "strings" +) + +// HmacAuth signs outbound requests and authenticates inbound requests. +type HmacAuth interface { + // Produces the string that will be prefixed to the request body and + // used to generate the signature. + StringToSign(req *http.Request) string + + // Adds a signature header to the request. + SignRequest(req *http.Request) + + // Generates a signature for the request. + RequestSignature(req *http.Request) string + + // Retrieves the signature included in the request header. + SignatureFromHeader(req *http.Request) string + + // Authenticates the request, returning the result code, the signature + // from the header, and the locally-computed signature. + AuthenticateRequest(request *http.Request) ( + result AuthenticationResult, + headerSignature, computedSignature string) +} + +var supportedAlgorithms = map[string]crypto.Hash{ + "md4": crypto.MD4, + "md5": crypto.MD5, + "sha1": crypto.SHA1, + "sha224": crypto.SHA224, + "sha256": crypto.SHA256, + "sha384": crypto.SHA384, + "sha512": crypto.SHA512, + "ripemd160": crypto.RIPEMD160, +} + +var algorithmName map[crypto.Hash]string + +func init() { + algorithmName = make(map[crypto.Hash]string) + for name, algorithm := range supportedAlgorithms { + algorithmName[algorithm] = name + // Make sure the algorithm is linked into the binary, per + // https://golang.org/pkg/crypto/#Hash.Available + // + // Note that both sides of the client/server connection must + // have an algorithm available in order to successfully + // authenticate using that algorithm + if !algorithm.Available() { + delete(supportedAlgorithms, name) + } + } +} + +// DigestNameToCryptoHash returns the crypto.Hash value corresponding to the +// algorithm name, or an error if the algorithm is not supported. +func DigestNameToCryptoHash(name string) (result crypto.Hash, err error) { + var supported bool + if result, supported = supportedAlgorithms[name]; !supported { + err = errors.New("hmacauth: hash algorithm not supported: " + + name) + } + return +} + +// CryptoHashToDigestName returns the algorithm name corresponding to the +// crypto.Hash ID, or an error if the algorithm is not supported. +func CryptoHashToDigestName(id crypto.Hash) (result string, err error) { + var supported bool + if result, supported = algorithmName[id]; !supported { + err = fmt.Errorf("hmacauth: unsupported crypto.Hash #%d", id) + } + return +} + +type hmacAuth struct { + hash crypto.Hash + key []byte + header string + headers []string +} + +// NewHmacAuth returns an HmacAuth object that can be used to sign or +// authenticate HTTP requests based on the supplied parameters. +func NewHmacAuth(hash crypto.Hash, key []byte, header string, + headers []string) HmacAuth { + if !hash.Available() { + var name string + var supported bool + if name, supported = algorithmName[hash]; !supported { + name = fmt.Sprintf("#%d", hash) + } + panic("hmacauth: hash algorithm " + name + " is unavailable") + } + canonicalHeaders := make([]string, len(headers)) + for i, h := range headers { + canonicalHeaders[i] = http.CanonicalHeaderKey(h) + } + return &hmacAuth{hash, key, header, canonicalHeaders} +} + +func (auth *hmacAuth) StringToSign(req *http.Request) string { + var buffer bytes.Buffer + _, _ = buffer.WriteString(req.Method) + _, _ = buffer.WriteString("\n") + + for _, header := range auth.headers { + values := req.Header[header] + lastIndex := len(values) - 1 + for i, value := range values { + _, _ = buffer.WriteString(value) + if i != lastIndex { + _, _ = buffer.WriteString(",") + } + } + _, _ = buffer.WriteString("\n") + } + _, _ = buffer.WriteString(req.URL.Path) + if req.URL.RawQuery != "" { + _, _ = buffer.WriteString("?") + _, _ = buffer.WriteString(req.URL.RawQuery) + } + if req.URL.Fragment != "" { + _, _ = buffer.WriteString("#") + _, _ = buffer.WriteString(req.URL.Fragment) + } + _, _ = buffer.WriteString("\n") + return buffer.String() +} + +func (auth *hmacAuth) SignRequest(req *http.Request) { + req.Header.Set(auth.header, auth.RequestSignature(req)) +} + +func (auth *hmacAuth) RequestSignature(req *http.Request) string { + return requestSignature(auth, req, auth.hash) +} + +func requestSignature(auth *hmacAuth, req *http.Request, + hashAlgorithm crypto.Hash) string { + h := hmac.New(hashAlgorithm.New, auth.key) + _, _ = h.Write([]byte(auth.StringToSign(req))) + + if req.Body != nil { + reqBody, _ := io.ReadAll(req.Body) + req.Body = io.NopCloser(bytes.NewBuffer(reqBody)) + _, _ = h.Write(reqBody) + } + + var sig []byte + sig = h.Sum(sig) + return algorithmName[hashAlgorithm] + " " + + base64.StdEncoding.EncodeToString(sig) +} + +func (auth *hmacAuth) SignatureFromHeader(req *http.Request) string { + return req.Header.Get(auth.header) +} + +// AuthenticationResult is a code used to identify the outcome of +// HmacAuth.AuthenticateRequest(). +type AuthenticationResult int + +const ( + // ResultNoSignature - the incoming result did not have a signature + // header. + ResultNoSignature AuthenticationResult = iota + + // ResultInvalidFormat - the signature header was not parseable. + ResultInvalidFormat + + // ResultUnsupportedAlgorithm - the signature header specified an + // unsupported algorithm. + ResultUnsupportedAlgorithm + + // ResultMatch - the signature from the request header matched the + // locally-computed signature. + ResultMatch + + // ResultMismatch - the signature from the request header did not match + // the locally-computed signature. + ResultMismatch +) + +var validationResultStrings = []string{ + "", + "ResultNoSignature", + "ResultInvalidFormat", + "ResultUnsupportedAlgorithm", + "ResultMatch", + "ResultMismatch", +} + +func (result AuthenticationResult) String() string { + return validationResultStrings[result] +} + +func (auth *hmacAuth) AuthenticateRequest(request *http.Request) ( + result AuthenticationResult, headerSignature, + computedSignature string) { + headerSignature = auth.SignatureFromHeader(request) + if headerSignature == "" { + result = ResultNoSignature + return + } + + components := strings.Split(headerSignature, " ") + if len(components) != 2 { + result = ResultInvalidFormat + return + } + + algorithm, err := DigestNameToCryptoHash(components[0]) + if err != nil { + result = ResultUnsupportedAlgorithm + return + } + + computedSignature = requestSignature(auth, request, algorithm) + if hmac.Equal([]byte(headerSignature), []byte(computedSignature)) { + result = ResultMatch + } else { + result = ResultMismatch + } + return +} diff --git a/pkg/authentication/hmacauth/hmacauth_test.go b/pkg/authentication/hmacauth/hmacauth_test.go new file mode 100644 index 0000000000..84f257d9c2 --- /dev/null +++ b/pkg/authentication/hmacauth/hmacauth_test.go @@ -0,0 +1,302 @@ +package hmacauth + +import ( + "bufio" + "crypto" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +// These correspond to the headers used in bitly/oauth2_proxy#147. +var HEADERS = []string{ + "Content-Length", + "Content-Md5", + "Content-Type", + "Date", + "Authorization", + "X-Forwarded-User", + "X-Forwarded-Email", + "X-Forwarded-Access-Token", + "Cookie", + "Gap-Auth", +} + +func TestSupportedHashAlgorithm(t *testing.T) { + algorithm, err := DigestNameToCryptoHash("sha1") + assert.Equal(t, err, nil) + assert.Equal(t, algorithm, crypto.SHA1) + assert.Equal(t, algorithm.Available(), true) +} + +func TestUnsupportedHashAlgorithm(t *testing.T) { + algorithm, err := DigestNameToCryptoHash("unsupported") + assert.NotEqual(t, err, nil) + assert.Equal(t, err.Error(), + "hmacauth: hash algorithm not supported: unsupported") + assert.Equal(t, algorithm, crypto.Hash(0)) + assert.Equal(t, algorithm.Available(), false) +} + +func TestResultUnsupportedAlgorithmWillCauseNewHmacAuthToPanic(t *testing.T) { + defer func() { + err := recover() + assert.Equal(t, err, + "hmacauth: hash algorithm #0 is unavailable") + }() + NewHmacAuth(crypto.Hash(0), nil, "", nil) +} + +func newTestRequest(request ...string) (req *http.Request) { + reqBuf := bufio.NewReader( + strings.NewReader(strings.Join(request, "\n"))) + if req, err := http.ReadRequest(reqBuf); err != nil { + panic(err) + } else { + return req + } +} + +func testHmacAuth() HmacAuth { + return NewHmacAuth( + crypto.SHA1, []byte("foobar"), "GAP-Signature", HEADERS) +} + +func TestRequestSignaturePost(t *testing.T) { + body := `{ "hello": "world!" }` + req := newTestRequest( + "POST /foo/bar HTTP/1.1", + "Content-Length: "+strconv.Itoa(len(body)), + "Content-MD5: deadbeef", + "Content-Type: application/json", + "Date: 2015-09-28", + "Authorization: trust me", + "X-Forwarded-User: mbland", + "X-Forwarded-Email: mbland@acm.org", + "X-Forwarded-Access-Token: feedbead", + "Cookie: foo; bar; baz=quux", + "Gap-Auth: mbland", + "", + body, + ) + + h := testHmacAuth() + assert.Equal(t, h.StringToSign(req), strings.Join([]string{ + "POST", + strconv.Itoa(len(body)), + "deadbeef", + "application/json", + "2015-09-28", + "trust me", + "mbland", + "mbland@acm.org", + "feedbead", + "foo; bar; baz=quux", + "mbland", + "/foo/bar", + }, "\n")+"\n") + assert.Equal(t, h.RequestSignature(req), + "sha1 K4IrVDtMCRwwW8Oms0VyZWMjXHI=") + + if requestBody, err := io.ReadAll(req.Body); err != nil { + panic(err) + } else { + assert.Equal(t, string(requestBody), body) + } +} + +func newGetRequest() *http.Request { + return newTestRequest( + "GET /foo/bar HTTP/1.1", + "Date: 2015-09-29", + "Cookie: foo; bar; baz=quux", + "Gap-Auth: mbland", + "", + "", + ) +} + +func TestRequestSignatureGetWithFullUrl(t *testing.T) { + req := newTestRequest( + "GET http://localhost/foo/bar?baz=quux%2Fxyzzy#plugh HTTP/1.1", + "Date: 2015-09-29", + "Cookie: foo; bar; baz=quux", + "Gap-Auth: mbland", + "", + "", + ) + + h := testHmacAuth() + assert.Equal(t, h.StringToSign(req), strings.Join([]string{ + "GET", + "", + "", + "", + "2015-09-29", + "", + "", + "", + "", + "foo; bar; baz=quux", + "mbland", + "/foo/bar?baz=quux%2Fxyzzy#plugh", + }, "\n")+"\n") + assert.Equal(t, h.RequestSignature(req), + "sha1 ih5Jce9nsltry63rR4ImNz2hdnk=") +} + +func TestRequestSignatureGetWithMultipleHeadersWithTheSameName(t *testing.T) { + // Just using "Cookie:" out of convenience. + req := newTestRequest( + "GET /foo/bar HTTP/1.1", + "Date: 2015-09-29", + "Cookie: foo", + "Cookie: bar", + "Cookie: baz=quux", + "Gap-Auth: mbland", + "", + "", + ) + + h := testHmacAuth() + assert.Equal(t, h.StringToSign(req), strings.Join([]string{ + "GET", + "", + "", + "", + "2015-09-29", + "", + "", + "", + "", + "foo,bar,baz=quux", + "mbland", + "/foo/bar", + }, "\n")+"\n") + assert.Equal(t, h.RequestSignature(req), + "sha1 JlRkes1X+qq3Bgc/GcRyLos+4aI=") +} + +func TestAuthenticateRequestResultNoSignature(t *testing.T) { + h := testHmacAuth() + req := newGetRequest() + result, header, computed := h.AuthenticateRequest(req) + assert.Equal(t, result, ResultNoSignature) + assert.Equal(t, header, "") + assert.Equal(t, computed, "") +} + +func TestAuthenticateRequestResultInvalidFormat(t *testing.T) { + h := testHmacAuth() + req := newGetRequest() + badValue := "should be algorithm and digest value" + req.Header.Set("GAP-Signature", badValue) + result, header, computed := h.AuthenticateRequest(req) + assert.Equal(t, result, ResultInvalidFormat) + assert.Equal(t, header, badValue) + assert.Equal(t, computed, "") +} + +func TestAuthenticateRequestResultUnsupportedAlgorithm(t *testing.T) { + h := testHmacAuth() + req := newGetRequest() + validSignature := h.RequestSignature(req) + components := strings.Split(validSignature, " ") + signatureWithResultUnsupportedAlgorithm := "unsupported " + + components[1] + req.Header.Set("GAP-Signature", signatureWithResultUnsupportedAlgorithm) + result, header, computed := h.AuthenticateRequest(req) + assert.Equal(t, result, ResultUnsupportedAlgorithm) + assert.Equal(t, header, signatureWithResultUnsupportedAlgorithm) + assert.Equal(t, computed, "") +} + +func TestAuthenticateRequestResultMatch(t *testing.T) { + h := testHmacAuth() + req := newGetRequest() + expected := h.RequestSignature(req) + h.SignRequest(req) + result, header, computed := h.AuthenticateRequest(req) + assert.Equal(t, result, ResultMatch) + assert.Equal(t, header, expected) + assert.Equal(t, computed, expected) +} + +func TestAuthenticateRequestMismatch(t *testing.T) { + foobarAuth := testHmacAuth() + barbazAuth := NewHmacAuth( + crypto.SHA1, []byte("barbaz"), "GAP-Signature", HEADERS) + req := newGetRequest() + foobarAuth.SignRequest(req) + result, header, computed := barbazAuth.AuthenticateRequest(req) + assert.Equal(t, result, ResultMismatch) + assert.Equal(t, header, foobarAuth.RequestSignature(req)) + assert.Equal(t, computed, barbazAuth.RequestSignature(req)) +} + +type SignatureAuthenticator struct { + auth HmacAuth +} + +func (v *SignatureAuthenticator) Authenticate( + w http.ResponseWriter, r *http.Request) { + result, headerSig, computedSig := v.auth.AuthenticateRequest(r) + switch result { + case ResultNoSignature: + w.Write([]byte("no signature received")) + case ResultMatch: + w.Write([]byte("signatures match")) + case ResultMismatch: + w.Write([]byte("signatures do not match:" + + "\n received: " + headerSig + + "\n computed: " + computedSig)) + default: + panic("Unknown result value: " + result.String()) + } +} + +// fakeNetConn simulates an http.Request.Body buffer that will be consumed +// when it is read by the hmacauth.HmacAuth if not handled properly. See: +// +// https://github.com/18F/hmacauth/pull/4 +type fakeNetConn struct { + reqBody string +} + +func (fnc *fakeNetConn) Read(p []byte) (n int, err error) { + if bodyLen := len(fnc.reqBody); bodyLen != 0 { + copy(p, fnc.reqBody) + fnc.reqBody = "" + return bodyLen, io.EOF + } + return 0, io.EOF +} + +func TestSendAuthenticatedPostRequestToServer(t *testing.T) { + key := "foobar" + payload := `{ "hello": "world!" }` + + auth := NewHmacAuth(crypto.SHA1, []byte(key), "X-Test-Signature", nil) + authenticator := &SignatureAuthenticator{auth: auth} + upstream := httptest.NewServer( + http.HandlerFunc(authenticator.Authenticate)) + + req, err := http.NewRequest("POST", upstream.URL+"/foo/bar", + io.NopCloser(&fakeNetConn{reqBody: payload})) + if err != nil { + panic(err) + } + auth.SignRequest(req) + if response, err := http.DefaultClient.Do(req); err != nil { + panic(err) + } else { + assert.Equal(t, response.StatusCode, http.StatusOK) + responseBody, _ := io.ReadAll(response.Body) + assert.Equal(t, "signatures match", string(responseBody)) + } +} diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index 7a0e6e847e..c1541265ee 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -8,9 +8,9 @@ import ( "net/url" "strings" - "github.com/mbland/hmacauth" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/hmacauth" ) const ( @@ -86,7 +86,7 @@ func (h *httpUpstreamProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) // A scope should always be injected before this handler is called. scope.Upstream = h.upstream - // TODO (@NickMeves) - Deprecate GAP-Signature & remove GAP-Auth + // TODO (@tuunit) - Deprecate GAP-Signature & remove GAP-Auth if h.auth != nil { req.Header.Set("GAP-Auth", rw.Header().Get("GAP-Auth")) h.auth.SignRequest(req) diff --git a/pkg/validation/options.go b/pkg/validation/options.go index c720f47e51..0f648d6cc9 100644 --- a/pkg/validation/options.go +++ b/pkg/validation/options.go @@ -8,8 +8,8 @@ import ( "net/url" "strings" - "github.com/mbland/hmacauth" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/hmacauth" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" internaloidc "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/providers/oidc" From 0107d6da5bd166070ec10eba37dd7ced01fb58cb Mon Sep 17 00:00:00 2001 From: fossabot Date: Sun, 9 Nov 2025 14:20:20 -0500 Subject: [PATCH 067/125] Add license scan report and status (#3248) * Add license scan report and status Signed-off-by: fossabot * doc: fix fossa badge position Signed-off-by: Jan Larwig --------- Signed-off-by: fossabot Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index dfcdc7aaba..72e976fbc5 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE) [![Maintainability](https://api.codeclimate.com/v1/badges/a58ff79407212e2beacb/maintainability)](https://codeclimate.com/github/oauth2-proxy/oauth2-proxy/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/a58ff79407212e2beacb/test_coverage)](https://codeclimate.com/github/oauth2-proxy/oauth2-proxy/test_coverage) +[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Foauth2-proxy%2Foauth2-proxy.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Foauth2-proxy%2Foauth2-proxy?ref=badge_shield) ![OAuth2 Proxy](docs/static/img/logos/OAuth2_Proxy_horizontal.svg) @@ -84,3 +85,6 @@ See [open redirect vulnerability](https://github.com/oauth2-proxy/oauth2-proxy/s ## License OAuth2-Proxy is distributed under [The MIT License](LICENSE). + + +[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Foauth2-proxy%2Foauth2-proxy.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Foauth2-proxy%2Foauth2-proxy?ref=badge_large) From 6a4255c21a43ea16a3ae84f50273d030d690307b Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 11 Nov 2025 20:33:50 +0100 Subject: [PATCH 068/125] chore(deps): update docker-compose (#3255) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-traefik.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 5df6d471d6..f6defb5a6e 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -39,7 +39,7 @@ services: httpbin: {} gitea: - image: gitea/gitea:1.24.7 + image: gitea/gitea:1.25.1 container_name: gitea environment: - USER_UID=1000 diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 1ad4805c40..1e6f66204e 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -34,7 +34,7 @@ services: # Reverse proxy gateway: container_name: traefik - image: traefik:v2.11.29 + image: traefik:v2.11.30 volumes: - "./traefik:/etc/traefik" ports: From e4becfdf1fee464624f6db0620c51a0f1094a3ae Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 11 Nov 2025 20:34:16 +0100 Subject: [PATCH 069/125] chore(deps): update dependency node to v24 (#3256) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/docs.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 6f8f7ad6db..5f4bbe4f7a 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -23,7 +23,7 @@ jobs: - uses: actions/setup-node@v6 with: # renovate: datasource=node-version depName=node - node-version: 22 + node-version: 24 - name: Test Build working-directory: ./docs @@ -40,7 +40,7 @@ jobs: - uses: actions/setup-node@v6 with: # renovate: datasource=node-version depName=node - node-version: 22 + node-version: 24 - name: Build docusaurus working-directory: ./docs From 7cf69b27fa93923db4c3bc6104d21235f8d77712 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Sampedro?= <5142014+rsrdesarrollo@users.noreply.github.com> Date: Tue, 11 Nov 2025 21:08:08 +0100 Subject: [PATCH 070/125] fix: NewRemoteKeySet is not using DefaultHTTPClient (#3197) * fix: NewRemoteKeySet is not using DefaultHTTPClient Signed-off-by: Jan Larwig * doc: add changelog entry Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 2 ++ pkg/providers/oidc/provider_verifier.go | 3 +++ 2 files changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13ef6807dd..2aa2ef46b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ ## Changes since v7.13.0 +- [#3197](https://github.com/oauth2-proxy/oauth2-proxy/pull/3197) fix: NewRemoteKeySet is not using DefaultHTTPClient (@rsrdesarrollo / @tuunit) + # V7.13.0 ## Release Highlights diff --git a/pkg/providers/oidc/provider_verifier.go b/pkg/providers/oidc/provider_verifier.go index b6b9a97040..eac80a8c10 100644 --- a/pkg/providers/oidc/provider_verifier.go +++ b/pkg/providers/oidc/provider_verifier.go @@ -10,6 +10,7 @@ import ( "os" "github.com/coreos/go-oidc/v3/oidc" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" k8serrors "k8s.io/apimachinery/pkg/util/errors" ) @@ -127,6 +128,8 @@ func NewProviderVerifier(ctx context.Context, opts ProviderVerifierOptions) (Pro type verifierBuilder func(*oidc.Config) *oidc.IDTokenVerifier func getVerifierBuilder(ctx context.Context, opts ProviderVerifierOptions) (verifierBuilder, DiscoveryProvider, error) { + ctx = oidc.ClientContext(ctx, requests.DefaultHTTPClient) + if opts.SkipDiscovery { var keySet oidc.KeySet var err error From 7c20001045b63a3cc506ce6dbc50bff252efac02 Mon Sep 17 00:00:00 2001 From: tuunit Date: Sat, 4 May 2024 16:41:54 +0200 Subject: [PATCH 071/125] introduce mapstructure decoder for yaml parsing remove color output in tests for better readability in github actions bugfix: remove google as default provider for alpha options fix conversion flow for toml to yaml revert ginkgo color deactivation revert claim- and secret source back to pointers regenerate alpha config Signed-off-by: Jan Larwig --- .golangci.yml | 2 +- docs/docs/configuration/alpha_config.md | 18 +--- main.go | 33 ++++--- main_test.go | 39 +++++---- oauthproxy_test.go | 6 +- pkg/apis/options/alpha_options.go | 25 ++++-- pkg/apis/options/common.go | 63 -------------- pkg/apis/options/duration.go | 43 +++++++++ pkg/apis/options/header.go | 4 +- pkg/apis/options/legacy_options.go | 6 +- pkg/apis/options/legacy_options_test.go | 12 +-- pkg/apis/options/load.go | 111 +++++++++++++++--------- pkg/apis/options/load_test.go | 24 ++--- pkg/apis/options/providers.go | 6 +- pkg/apis/options/secret_source.go | 14 +++ pkg/apis/options/upstreams.go | 4 +- pkg/apis/options/util/util.go | 2 +- pkg/apis/options/util/util_test.go | 2 +- pkg/header/injector_test.go | 16 ++-- pkg/http/http_suite_test.go | 12 +-- pkg/http/server_test.go | 8 +- pkg/middleware/headers_test.go | 8 +- pkg/upstream/http.go | 4 +- pkg/upstream/http_test.go | 24 ++--- pkg/validation/common_test.go | 4 +- pkg/validation/header.go | 2 - pkg/validation/header_test.go | 4 +- pkg/validation/upstreams.go | 2 +- pkg/validation/upstreams_test.go | 2 +- 29 files changed, 268 insertions(+), 232 deletions(-) delete mode 100644 pkg/apis/options/common.go create mode 100644 pkg/apis/options/duration.go create mode 100644 pkg/apis/options/secret_source.go diff --git a/.golangci.yml b/.golangci.yml index edab12d06e..62e1df8eda 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -37,7 +37,7 @@ linters: - linters: - revive path: _test\.go - text: 'dot-imports:' + text: "dot-imports:" # # If we have tests in shared test folders, these can be less strictly linted - linters: - bodyclose diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index 9e6c2873ea..67b3fe1b3c 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -204,16 +204,6 @@ ClaimSource allows loading a header value from a claim within the session | `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | | `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | -### Duration -#### (`string` alias) - -(**Appears on:** [Upstream](#upstream)) - -Duration is as string representation of a period of time. -A duration string is a is a possibly signed sequence of decimal numbers, -each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". -Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". - ### GitHubOptions (**Appears on:** [Provider](#provider)) @@ -278,7 +268,7 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `value` | _string_ | Value expects a base64 encoded string value. | | `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | | `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | | `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | @@ -490,7 +480,7 @@ Only one source within the struct should be defined at any time. | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `value` | _string_ | Value expects a base64 encoded string value. | | `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | | `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | @@ -550,10 +540,10 @@ Requests will be proxied to this upstream if the path matches the request path. | `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | | `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | | `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | -| `flushInterval` | _[Duration](#duration)_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `flushInterval` | _duration_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | | `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | | `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | -| `timeout` | _[Duration](#duration)_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | +| `timeout` | _duration_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | | `disableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | ### UpstreamConfig diff --git a/main.go b/main.go index cf7e964cb6..d9fc406be0 100644 --- a/main.go +++ b/main.go @@ -67,12 +67,17 @@ func main() { // loadConfiguration will load in the user's configuration. // It will either load the alpha configuration (if alphaConfig is given) // or the legacy configuration. -func loadConfiguration(config, alphaConfig string, extraFlags *pflag.FlagSet, args []string) (*options.Options, error) { - if alphaConfig != "" { +func loadConfiguration(config, yamlConfig string, extraFlags *pflag.FlagSet, args []string) (*options.Options, error) { + opts, err := loadLegacyOptions(config, extraFlags, args) + if err != nil { + return nil, err + } + + if yamlConfig != "" { logger.Printf("WARNING: You are using alpha configuration. The structure in this configuration file may change without notice. You MUST remove conflicting options from your existing configuration.") - return loadAlphaOptions(config, alphaConfig, extraFlags, args) + return loadYamlOptions(yamlConfig, config, extraFlags, args) } - return loadLegacyOptions(config, extraFlags, args) + return opts, err } // loadLegacyOptions loads the old toml options using the legacy flagset @@ -97,17 +102,17 @@ func loadLegacyOptions(config string, extraFlags *pflag.FlagSet, args []string) return opts, nil } -// loadAlphaOptions loads the old style config excluding options converted to +// loadYamlOptions loads the old style config excluding options converted to // the new alpha format, then merges the alpha options, loaded from YAML, // into the core configuration. -func loadAlphaOptions(config, alphaConfig string, extraFlags *pflag.FlagSet, args []string) (*options.Options, error) { +func loadYamlOptions(yamlConfig, config string, extraFlags *pflag.FlagSet, args []string) (*options.Options, error) { opts, err := loadOptions(config, extraFlags, args) if err != nil { return nil, fmt.Errorf("failed to load core options: %v", err) } - alphaOpts := &options.AlphaOptions{} - if err := options.LoadYAML(alphaConfig, alphaOpts); err != nil { + alphaOpts := options.NewAlphaOptions(opts) + if err := options.LoadYAML(yamlConfig, alphaOpts); err != nil { return nil, fmt.Errorf("failed to load alpha options: %v", err) } @@ -137,10 +142,16 @@ func loadOptions(config string, extraFlags *pflag.FlagSet, args []string) (*opti // printConvertedConfig extracts alpha options from the loaded configuration // and renders these to stdout in YAML format. func printConvertedConfig(opts *options.Options) error { - alphaConfig := &options.AlphaOptions{} - alphaConfig.ExtractFrom(opts) + alphaConfig := options.NewAlphaOptions(opts) + + // Generic interface for loading arbitrary yaml structure + var buffer map[string]interface{} + + if err := options.Decode(alphaConfig, &buffer); err != nil { + return fmt.Errorf("unable to decode alpha config into interface: %w", err) + } - data, err := yaml.Marshal(alphaConfig) + data, err := yaml.Marshal(buffer) if err != nil { return fmt.Errorf("unable to marshal config: %v", err) } diff --git a/main_test.go b/main_test.go index 8e40fe7faf..a6ea83c28a 100644 --- a/main_test.go +++ b/main_test.go @@ -43,29 +43,35 @@ upstreamConfig: injectRequestHeaders: - name: Authorization values: - - claim: user - prefix: "Basic " - basicAuthPassword: - value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk + - claimSource: + claim: user + prefix: "Basic " + basicAuthPassword: + value: super-secret-password - name: X-Forwarded-Groups values: - - claim: groups + - claimSource: + claim: groups - name: X-Forwarded-User values: - - claim: user + - claimSource: + claim: user - name: X-Forwarded-Email values: - - claim: email + - claimSource: + claim: email - name: X-Forwarded-Preferred-Username values: - - claim: preferred_username + - claimSource: + claim: preferred_username injectResponseHeaders: - name: Authorization values: - - claim: user - prefix: "Basic " - basicAuthPassword: - value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk + - claimSource: + claim: user + prefix: "Basic " + basicAuthPassword: + value: super-secret-password server: bindAddress: "127.0.0.1:4180" providers: @@ -100,9 +106,8 @@ redirect_url="http://localhost:4180/oauth2/callback" return &b } - durationPtr := func(d time.Duration) *options.Duration { - du := options.Duration(d) - return &du + durationPtr := func(d time.Duration) *time.Duration { + return &d } testExpectedOptions := func() *options.Options { @@ -136,7 +141,7 @@ redirect_url="http://localhost:4180/oauth2/callback" Claim: "user", Prefix: "Basic ", BasicAuthPassword: &options.SecretSource{ - Value: []byte("super-secret-password"), + Value: "super-secret-password", }, }, }, @@ -226,7 +231,7 @@ redirect_url="http://localhost:4180/oauth2/callback" opts, err := loadConfiguration(configFileName, alphaConfigFileName, extraFlags, in.args) if in.expectedErr != nil { - Expect(err).To(MatchError(in.expectedErr.Error())) + Expect(err).To(MatchError(ContainSubstring(in.expectedErr.Error()))) } else { Expect(err).ToNot(HaveOccurred()) } diff --git a/oauthproxy_test.go b/oauthproxy_test.go index 44569a3583..d5fac782c9 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -215,7 +215,7 @@ func TestBasicAuthPassword(t *testing.T) { ClaimSource: &options.ClaimSource{ Claim: "email", BasicAuthPassword: &options.SecretSource{ - Value: []byte(basicAuthPassword), + Value: basicAuthPassword, }, }, }, @@ -1282,7 +1282,7 @@ func TestAuthOnlyEndpointSetBasicAuthTrueRequestHeaders(t *testing.T) { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: []byte("This is a secure password"), + Value: "This is a secure password", }, }, }, @@ -2044,7 +2044,7 @@ func baseTestOptions() *options.Options { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: []byte(base64.StdEncoding.EncodeToString([]byte("This is a secure password"))), + Value: base64.StdEncoding.EncodeToString([]byte("This is a secure password")), }, }, }, diff --git a/pkg/apis/options/alpha_options.go b/pkg/apis/options/alpha_options.go index a438518c62..278db40110 100644 --- a/pkg/apis/options/alpha_options.go +++ b/pkg/apis/options/alpha_options.go @@ -47,15 +47,11 @@ type AlphaOptions struct { Providers Providers `json:"providers,omitempty"` } -// MergeInto replaces alpha options in the Options struct with the values -// from the AlphaOptions -func (a *AlphaOptions) MergeInto(opts *Options) { - opts.UpstreamServers = a.UpstreamConfig - opts.InjectRequestHeaders = a.InjectRequestHeaders - opts.InjectResponseHeaders = a.InjectResponseHeaders - opts.Server = a.Server - opts.MetricsServer = a.MetricsServer - opts.Providers = a.Providers +// Initialize alpha options with default values and settings of the core options +func NewAlphaOptions(opts *Options) *AlphaOptions { + aOpts := &AlphaOptions{} + aOpts.ExtractFrom(opts) + return aOpts } // ExtractFrom populates the fields in the AlphaOptions with the values from @@ -68,3 +64,14 @@ func (a *AlphaOptions) ExtractFrom(opts *Options) { a.MetricsServer = opts.MetricsServer a.Providers = opts.Providers } + +// MergeInto replaces alpha options in the Options struct with the values +// from the AlphaOptions +func (a *AlphaOptions) MergeInto(opts *Options) { + opts.UpstreamServers = a.UpstreamConfig + opts.InjectRequestHeaders = a.InjectRequestHeaders + opts.InjectResponseHeaders = a.InjectResponseHeaders + opts.Server = a.Server + opts.MetricsServer = a.MetricsServer + opts.Providers = a.Providers +} diff --git a/pkg/apis/options/common.go b/pkg/apis/options/common.go deleted file mode 100644 index 88d24d82ba..0000000000 --- a/pkg/apis/options/common.go +++ /dev/null @@ -1,63 +0,0 @@ -package options - -import ( - "fmt" - "strconv" - "time" -) - -// SecretSource references an individual secret value. -// Only one source within the struct should be defined at any time. -type SecretSource struct { - // Value expects a base64 encoded string value. - Value []byte `json:"value,omitempty"` - - // FromEnv expects the name of an environment variable. - FromEnv string `json:"fromEnv,omitempty"` - - // FromFile expects a path to a file containing the secret value. - FromFile string `json:"fromFile,omitempty"` -} - -// Duration is an alias for time.Duration so that we can ensure the marshalling -// and unmarshalling of string durations is done as users expect. -// Intentional blank line below to keep this first part of the comment out of -// any generated references. - -// Duration is as string representation of a period of time. -// A duration string is a is a possibly signed sequence of decimal numbers, -// each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". -// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". -// +reference-gen:alias-name=string -type Duration time.Duration - -// UnmarshalJSON parses the duration string and sets the value of duration -// to the value of the duration string. -func (d *Duration) UnmarshalJSON(data []byte) error { - input := string(data) - if unquoted, err := strconv.Unquote(input); err == nil { - input = unquoted - } - - du, err := time.ParseDuration(input) - if err != nil { - return err - } - *d = Duration(du) - return nil -} - -// MarshalJSON ensures that when the string is marshalled to JSON as a human -// readable string. -func (d *Duration) MarshalJSON() ([]byte, error) { - dStr := fmt.Sprintf("%q", d.Duration().String()) - return []byte(dStr), nil -} - -// Duration returns the time.Duration version of this Duration -func (d *Duration) Duration() time.Duration { - if d == nil { - return time.Duration(0) - } - return time.Duration(*d) -} diff --git a/pkg/apis/options/duration.go b/pkg/apis/options/duration.go new file mode 100644 index 0000000000..da13d96ecd --- /dev/null +++ b/pkg/apis/options/duration.go @@ -0,0 +1,43 @@ +package options + +import ( + "reflect" + "time" + + "github.com/mitchellh/mapstructure" +) + +// Duration is an alias for time.Duration so that we can ensure the marshalling +// and unmarshalling of string durations is done as users expect. +// Intentional blank line below to keep this first part of the comment out of +// any generated references. + +// Duration is as string representation of a period of time. +// A duration string is a is a possibly signed sequence of decimal numbers, +// each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". +// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + +// Conversion from string or floating point to golang duration type +// This way floating points will be converted to seconds and strings +// of type 3s or 5m will be parsed with time.ParseDuration +func toDurationHookFunc() mapstructure.DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}) (interface{}, error) { + if t != reflect.TypeOf(time.Duration(0)) { + return data, nil + } + + switch f.Kind() { + case reflect.String: + return time.ParseDuration(data.(string)) + case reflect.Float64: + return time.Duration(data.(float64) * float64(time.Second)), nil + case reflect.Int64: + return time.Duration(data.(int64)), nil + default: + return data, nil + } + } +} diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index 4299fd35da..164f9fee63 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -31,10 +31,10 @@ type Header struct { // make up the header value type HeaderValue struct { // Allow users to load the value from a secret source - *SecretSource `json:",omitempty"` + *SecretSource `json:"secretSource,omitempty"` // Allow users to load the value from a session claim - *ClaimSource `json:",omitempty"` + *ClaimSource `json:"claimSource,omitempty"` } // ClaimSource allows loading a header value from a claim within the session diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index e22278fa82..45e4b11369 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -136,8 +136,8 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { u.Path = "/" } - flushInterval := Duration(l.FlushInterval) - timeout := Duration(l.Timeout) + flushInterval := l.FlushInterval + timeout := l.Timeout upstream := Upstream{ ID: u.Path, Path: u.Path, @@ -294,7 +294,7 @@ func getBasicAuthHeader(preferEmailToUser bool, basicAuthPassword string) Header Claim: claim, Prefix: "Basic ", BasicAuthPassword: &SecretSource{ - Value: []byte(basicAuthPassword), + Value: basicAuthPassword, }, }, }, diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index 9481cf9526..c5f0e4da64 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -15,8 +15,8 @@ var _ = Describe("Legacy Options", func() { legacyOpts := NewLegacyOptions() // Set upstreams and related options to test their conversion - flushInterval := Duration(5 * time.Second) - timeout := Duration(5 * time.Second) + flushInterval := 5 * time.Second + timeout := 5 * time.Second legacyOpts.LegacyUpstreams.FlushInterval = time.Duration(flushInterval) legacyOpts.LegacyUpstreams.Timeout = time.Duration(timeout) legacyOpts.LegacyUpstreams.PassHostHeader = true @@ -147,8 +147,8 @@ var _ = Describe("Legacy Options", func() { skipVerify := true passHostHeader := false proxyWebSockets := true - flushInterval := Duration(5 * time.Second) - timeout := Duration(5 * time.Second) + flushInterval := 5 * time.Second + timeout := 5 * time.Second disableKeepAlives := true // Test cases and expected outcomes @@ -369,7 +369,7 @@ var _ = Describe("Legacy Options", func() { Claim: "user", Prefix: "Basic ", BasicAuthPassword: &SecretSource{ - Value: []byte(basicAuthSecret), + Value: basicAuthSecret, }, }, }, @@ -409,7 +409,7 @@ var _ = Describe("Legacy Options", func() { Claim: "email", Prefix: "Basic ", BasicAuthPassword: &SecretSource{ - Value: []byte(basicAuthSecret), + Value: basicAuthSecret, }, }, }, diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index c302e8e775..22e775a80d 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -55,6 +55,76 @@ func Load(configFileName string, flagSet *pflag.FlagSet, into interface{}) error return nil } +// LoadYAML will load a YAML based configuration file into the options interface provided. +func LoadYAML(configFileName string, opts interface{}) error { + buffer, err := loadAndSubstituteEnvs(configFileName) + if err != nil { + return err + } + + // Generic interface for loading arbitrary yaml structure + var intermediate map[string]interface{} + + if err := yaml.Unmarshal(buffer, &intermediate); err != nil { + return fmt.Errorf("error unmarshalling config: %w", err) + } + + return Decode(intermediate, opts) +} + +func Decode(input interface{}, result interface{}) error { + // Using mapstructure to decode arbitrary yaml structure into options and + // merge with existing values instead of overwriting everything. This is especially + // important as we have a lot of default values for boolean which are supposed to be + // true by default. Normally by just parsing through yaml all booleans that aren't + // referenced in the config file would be parsed as false and we cannot identify after + // the fact if they have been explicitly set to false or have not been referenced. + decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ + DecodeHook: mapstructure.ComposeDecodeHookFunc(toDurationHookFunc()), + Metadata: nil, // Don't track any metadata + Result: result, // Decode the result into the prefilled options + TagName: "json", // Parse all fields that use the yaml tag + ZeroFields: false, // Don't clean the default values from the result map (options) + ErrorUnused: true, // Throw an error if keys have been used that aren't mapped to any struct fields + IgnoreUntaggedFields: true, // Ignore fields in structures that aren't tagged with yaml + }) + + if err != nil { + return fmt.Errorf("error creating decoder for config: %w", err) + } + + if err := decoder.Decode(input); err != nil { + return fmt.Errorf("error decoding config: %w", err) + } + + return nil +} + +// loadAndSubstituteEnvs reads the yaml config into a generic byte buffer and +// substitute env references +func loadAndSubstituteEnvs(configFileName string) ([]byte, error) { + if configFileName == "" { + return nil, errors.New("no configuration file provided") + } + + unparsedBuffer, err := os.ReadFile(configFileName) + if err != nil { + return nil, fmt.Errorf("unable to load config file: %w", err) + } + + modifiedBuffer, err := normalizeSubstitution(unparsedBuffer) + if err != nil { + return nil, fmt.Errorf("error normalizing substitution string : %w", err) + } + + buffer, err := envsubst.Bytes(modifiedBuffer) + if err != nil { + return nil, fmt.Errorf("error in substituting env variables : %w", err) + } + + return buffer, nil +} + // registerFlags uses `cfg` and `flag` tags to associate flags in the flagSet // to the fields in the options interface provided. // Each exported field in the options must have a `cfg` tag otherwise an error will occur. @@ -140,47 +210,6 @@ func isUnexported(name string) bool { return first == strings.ToLower(first) } -// LoadYAML will load a YAML based configuration file into the options interface provided. -func LoadYAML(configFileName string, into interface{}) error { - buffer, err := loadAndParseYaml(configFileName) - if err != nil { - return err - } - - // UnmarshalStrict will return an error if the config includes options that are - // not mapped to fields of the into struct - if err := yaml.UnmarshalStrict(buffer, into, yaml.DisallowUnknownFields); err != nil { - return fmt.Errorf("error unmarshalling config: %w", err) - } - - return nil -} - -// loadAndParseYaml reads the config from the filesystem and -// execute the environment variable substitution -func loadAndParseYaml(configFileName string) ([]byte, error) { - if configFileName == "" { - return nil, errors.New("no configuration file provided") - } - - unparsedBuffer, err := os.ReadFile(configFileName) - if err != nil { - return nil, fmt.Errorf("unable to load config file: %w", err) - } - - modifiedBuffer, err := normalizeSubstitution(unparsedBuffer) - if err != nil { - return nil, fmt.Errorf("error normalizing substitution string : %w", err) - } - - buffer, err := envsubst.Bytes(modifiedBuffer) - if err != nil { - return nil, fmt.Errorf("error in substituting env variables : %w", err) - } - - return buffer, nil -} - // normalizeSubstitution normalizes dollar signs ($) with numerals like // $1 or $2 properly by correctly escaping them func normalizeSubstitution(unparsedBuffer []byte) ([]byte, error) { diff --git a/pkg/apis/options/load_test.go b/pkg/apis/options/load_test.go index 06123c37f0..6f327a22c1 100644 --- a/pkg/apis/options/load_test.go +++ b/pkg/apis/options/load_test.go @@ -355,15 +355,15 @@ var _ = Describe("Load", func() { var _ = Describe("LoadYAML", func() { Context("with a testOptions structure", func() { type TestOptionSubStruct struct { - StringSliceOption []string `yaml:"stringSliceOption,omitempty"` + StringSliceOption []string `json:"stringSliceOption,omitempty"` } type TestOptions struct { - StringOption string `yaml:"stringOption,omitempty"` - Sub TestOptionSubStruct `yaml:"sub,omitempty"` + StringOption string `json:"stringOption,omitempty"` + Sub TestOptionSubStruct `json:"sub,omitempty"` // Check that embedded fields can be unmarshalled - TestOptionSubStruct `yaml:",inline,squash"` + TestOptionSubStruct `json:",inline,squash"` } var testOptionsConfigBytesFull = []byte(` @@ -416,7 +416,7 @@ sub: err := LoadYAML(configFileName, input) if in.expectedErr != nil { - Expect(err).To(MatchError(in.expectedErr.Error())) + Expect(err).To(MatchError(ContainSubstring(in.expectedErr.Error()))) } else { Expect(err).ToNot(HaveOccurred()) } @@ -459,13 +459,13 @@ sub: StringSliceOption: []string{"a", "b", "c"}, }, }, - expectedErr: errors.New("error unmarshalling config: error unmarshaling JSON: while decoding JSON: json: unknown field \"foo\""), + expectedErr: errors.New("has invalid keys: foo"), }), Entry("with an incorrect type for a string field", loadYAMLTableInput{ configFile: []byte(`stringOption: ["a", "b"]`), input: &TestOptions{}, expectedOutput: &TestOptions{}, - expectedErr: errors.New("error unmarshalling config: error unmarshaling JSON: while decoding JSON: json: cannot unmarshal array into Go struct field TestOptions.StringOption of type string"), + expectedErr: errors.New("'stringOption' expected type 'string', got unconvertible type"), }), Entry("with an incorrect type for an array field", loadYAMLTableInput{ configFile: []byte(`stringSliceOption: "a"`), @@ -526,11 +526,13 @@ upstreamConfig: injectRequestHeaders: - name: X-Forwarded-User values: - - claim: user + - claimSource: + claim: user injectResponseHeaders: - name: X-Secret values: - - value: c2VjcmV0 + - secretSource: + value: secret `) By("Creating a config file") @@ -548,7 +550,7 @@ injectResponseHeaders: into := &AlphaOptions{} Expect(LoadYAML(configFileName, into)).To(Succeed()) - flushInterval := Duration(500 * time.Millisecond) + flushInterval := 500 * time.Millisecond Expect(into).To(Equal(&AlphaOptions{ UpstreamConfig: UpstreamConfig{ @@ -579,7 +581,7 @@ injectResponseHeaders: Values: []HeaderValue{ { SecretSource: &SecretSource{ - Value: []byte("secret"), + Value: "secret", }, }, }, diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 3a5094dacf..c876f46b59 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -242,16 +242,16 @@ type OIDCOptions struct { IssuerURL string `json:"issuerURL,omitempty"` // InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified // default set to 'false' - InsecureAllowUnverifiedEmail bool `json:"insecureAllowUnverifiedEmail,omitempty"` + InsecureAllowUnverifiedEmail bool `json:"insecureAllowUnverifiedEmail"` // InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL // default set to 'false' - InsecureSkipIssuerVerification bool `json:"insecureSkipIssuerVerification,omitempty"` + InsecureSkipIssuerVerification bool `json:"insecureSkipIssuerVerification"` // InsecureSkipNonce skips verifying the ID Token's nonce claim that must match // the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked // after the initial OAuth redeem & subsequent token refreshes. // default set to 'true' // Warning: In a future release, this will change to 'false' by default for enhanced security. - InsecureSkipNonce bool `json:"insecureSkipNonce,omitempty"` + InsecureSkipNonce bool `json:"insecureSkipNonce"` // SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints // default set to 'false' SkipDiscovery bool `json:"skipDiscovery,omitempty"` diff --git a/pkg/apis/options/secret_source.go b/pkg/apis/options/secret_source.go new file mode 100644 index 0000000000..2be4d890dc --- /dev/null +++ b/pkg/apis/options/secret_source.go @@ -0,0 +1,14 @@ +package options + +// SecretSource references an individual secret value. +// Only one source within the struct should be defined at any time. +type SecretSource struct { + // Value expects a base64 encoded string value. + Value string `json:"value,omitempty"` + + // FromEnv expects the name of an environment variable. + FromEnv string `json:"fromEnv,omitempty"` + + // FromFile expects a path to a file containing the secret value. + FromFile string `json:"fromFile,omitempty"` +} diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index b3c7195f97..1002ae0744 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -79,7 +79,7 @@ type Upstream struct { // FlushInterval is the period between flushing the response buffer when // streaming response from the upstream. // Defaults to 1 second. - FlushInterval *Duration `json:"flushInterval,omitempty"` + FlushInterval *time.Duration `json:"flushInterval,omitempty"` // PassHostHeader determines whether the request host header should be proxied // to the upstream server. @@ -92,7 +92,7 @@ type Upstream struct { // Timeout is the maximum duration the server will wait for a response from the upstream server. // Defaults to 30 seconds. - Timeout *Duration `json:"timeout,omitempty"` + Timeout *time.Duration `json:"timeout,omitempty"` // DisableKeepAlives disables HTTP keep-alive connections to the upstream server. // Defaults to false. diff --git a/pkg/apis/options/util/util.go b/pkg/apis/options/util/util.go index 03f0a13469..794a6e91fd 100644 --- a/pkg/apis/options/util/util.go +++ b/pkg/apis/options/util/util.go @@ -11,7 +11,7 @@ import ( func GetSecretValue(source *options.SecretSource) ([]byte, error) { switch { case len(source.Value) > 0 && source.FromEnv == "" && source.FromFile == "": - return source.Value, nil + return []byte(source.Value), nil case len(source.Value) == 0 && source.FromEnv != "" && source.FromFile == "": return []byte(os.Getenv(source.FromEnv)), nil case len(source.Value) == 0 && source.FromEnv == "" && source.FromFile != "": diff --git a/pkg/apis/options/util/util_test.go b/pkg/apis/options/util/util_test.go index e84db1ec0b..5c4bfa6d96 100644 --- a/pkg/apis/options/util/util_test.go +++ b/pkg/apis/options/util/util_test.go @@ -31,7 +31,7 @@ var _ = Describe("GetSecretValue", func() { It("returns the correct value from the string value", func() { value, err := GetSecretValue(&options.SecretSource{ - Value: []byte("secret-value-1"), + Value: "secret-value-1", }) Expect(err).ToNot(HaveOccurred()) Expect(string(value)).To(Equal("secret-value-1")) diff --git a/pkg/header/injector_test.go b/pkg/header/injector_test.go index 25c276dcf7..bb37261dc7 100644 --- a/pkg/header/injector_test.go +++ b/pkg/header/injector_test.go @@ -55,7 +55,7 @@ var _ = Describe("Injector Suite", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: []byte("super-secret"), + Value: "super-secret", }, }, }, @@ -199,7 +199,7 @@ var _ = Describe("Injector Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: []byte("basic-password"), + Value: "basic-password", }, }, }, @@ -227,7 +227,7 @@ var _ = Describe("Injector Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))), + Value: base64.StdEncoding.EncodeToString([]byte("basic-password")), }, }, }, @@ -322,7 +322,7 @@ var _ = Describe("Injector Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))), + Value: base64.StdEncoding.EncodeToString([]byte("basic-password")), FromEnv: "SECRET_ENV", }, }, @@ -348,7 +348,7 @@ var _ = Describe("Injector Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: []byte("basic-password"), + Value: "basic-password", }, }, }, @@ -379,17 +379,17 @@ var _ = Describe("Injector Suite", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: []byte("major=1"), + Value: "major=1", }, }, { SecretSource: &options.SecretSource{ - Value: []byte("minor=2"), + Value: "minor=2", }, }, { SecretSource: &options.SecretSource{ - Value: []byte("patch=3"), + Value: "patch=3", }, }, }, diff --git a/pkg/http/http_suite_test.go b/pkg/http/http_suite_test.go index 19d4d3ff39..219f26ea0e 100644 --- a/pkg/http/http_suite_test.go +++ b/pkg/http/http_suite_test.go @@ -48,10 +48,10 @@ var _ = BeforeSuite(func() { certOut := new(bytes.Buffer) Expect(pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes})).To(Succeed()) - ipv4CertDataSource.Value = certOut.Bytes() + ipv4CertDataSource.Value = certOut.String() keyOut := new(bytes.Buffer) Expect(pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes})).To(Succeed()) - ipv4KeyDataSource.Value = keyOut.Bytes() + ipv4KeyDataSource.Value = keyOut.String() }) By("Generating a ipv6 self-signed cert for TLS tests", func() { @@ -61,16 +61,16 @@ var _ = BeforeSuite(func() { certOut := new(bytes.Buffer) Expect(pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes})).To(Succeed()) - ipv6CertDataSource.Value = certOut.Bytes() + ipv6CertDataSource.Value = certOut.String() keyOut := new(bytes.Buffer) Expect(pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes})).To(Succeed()) - ipv6KeyDataSource.Value = keyOut.Bytes() + ipv6KeyDataSource.Value = keyOut.String() }) By("Setting up a http client", func() { - ipv4cert, err := tls.X509KeyPair(ipv4CertDataSource.Value, ipv4KeyDataSource.Value) + ipv4cert, err := tls.X509KeyPair([]byte(ipv4CertDataSource.Value), []byte(ipv4KeyDataSource.Value)) Expect(err).ToNot(HaveOccurred()) - ipv6cert, err := tls.X509KeyPair(ipv6CertDataSource.Value, ipv6KeyDataSource.Value) + ipv6cert, err := tls.X509KeyPair([]byte(ipv6CertDataSource.Value), []byte(ipv6KeyDataSource.Value)) Expect(err).ToNot(HaveOccurred()) ipv4certificate, err := x509.ParseCertificate(ipv4cert.Certificate[0]) diff --git a/pkg/http/server_test.go b/pkg/http/server_test.go index 8dfa13afad..6584b75736 100644 --- a/pkg/http/server_test.go +++ b/pkg/http/server_test.go @@ -234,7 +234,7 @@ var _ = Describe("Server", func() { SecureBindAddress: "127.0.0.1:0", TLS: &options.TLS{ Key: &options.SecretSource{ - Value: []byte("invalid"), + Value: "invalid", }, Cert: &ipv4CertDataSource, }, @@ -250,7 +250,7 @@ var _ = Describe("Server", func() { TLS: &options.TLS{ Key: &ipv4KeyDataSource, Cert: &options.SecretSource{ - Value: []byte("invalid"), + Value: "invalid", }, }, }, @@ -506,7 +506,7 @@ var _ = Describe("Server", func() { SecureBindAddress: "[::1]:0", TLS: &options.TLS{ Key: &options.SecretSource{ - Value: []byte("invalid"), + Value: "invalid", }, Cert: &ipv6CertDataSource, }, @@ -523,7 +523,7 @@ var _ = Describe("Server", func() { TLS: &options.TLS{ Key: &ipv6KeyDataSource, Cert: &options.SecretSource{ - Value: []byte("invalid"), + Value: "invalid", }, }, }, diff --git a/pkg/middleware/headers_test.go b/pkg/middleware/headers_test.go index 6a60ec0162..cb8f9d110e 100644 --- a/pkg/middleware/headers_test.go +++ b/pkg/middleware/headers_test.go @@ -188,7 +188,7 @@ var _ = Describe("Headers Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))), + Value: base64.StdEncoding.EncodeToString([]byte("basic-password")), FromEnv: "SECRET_ENV", }, }, @@ -304,7 +304,7 @@ var _ = Describe("Headers Suite", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: []byte("_oauth2_proxy=ey123123123"), + Value: "_oauth2_proxy=ey123123123", }, }, }, @@ -314,7 +314,7 @@ var _ = Describe("Headers Suite", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: []byte("oauth_user"), + Value: "oauth_user", }, }, }, @@ -460,7 +460,7 @@ var _ = Describe("Headers Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))), + Value: base64.StdEncoding.EncodeToString([]byte("basic-password")), FromEnv: "SECRET_ENV", }, }, diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index c1541265ee..f81f4ec0d9 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -137,12 +137,12 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // Change default duration for waiting for an upstream response if upstream.Timeout != nil { - transport.ResponseHeaderTimeout = upstream.Timeout.Duration() + transport.ResponseHeaderTimeout = *upstream.Timeout } // Configure options on the SingleHostReverseProxy if upstream.FlushInterval != nil { - proxy.FlushInterval = upstream.FlushInterval.Duration() + proxy.FlushInterval = *upstream.FlushInterval } else { proxy.FlushInterval = options.DefaultUpstreamFlushInterval } diff --git a/pkg/upstream/http_test.go b/pkg/upstream/http_test.go index 31476df01a..df264c33ac 100644 --- a/pkg/upstream/http_test.go +++ b/pkg/upstream/http_test.go @@ -21,8 +21,8 @@ import ( ) var _ = Describe("HTTP Upstream Suite", func() { - defaultFlushInterval := options.Duration(options.DefaultUpstreamFlushInterval) - defaultTimeout := options.Duration(options.DefaultUpstreamTimeout) + defaultFlushInterval := options.DefaultUpstreamFlushInterval + defaultTimeout := options.DefaultUpstreamTimeout truth := true falsum := false @@ -57,9 +57,9 @@ var _ = Describe("HTTP Upstream Suite", func() { req = middlewareapi.AddRequestScope(req, &middlewareapi.RequestScope{}) rw := httptest.NewRecorder() - flush := options.Duration(1 * time.Second) + flush := 1 * time.Second - timeout := options.Duration(options.DefaultUpstreamTimeout) + timeout := options.DefaultUpstreamTimeout upstream := options.Upstream{ ID: in.id, @@ -373,11 +373,11 @@ var _ = Describe("HTTP Upstream Suite", func() { type newUpstreamTableInput struct { proxyWebSockets bool - flushInterval options.Duration + flushInterval time.Duration skipVerify bool sigData *options.SignatureData errorHandler func(http.ResponseWriter, *http.Request, error) - timeout options.Duration + timeout time.Duration disableKeepAlives bool } @@ -406,10 +406,10 @@ var _ = Describe("HTTP Upstream Suite", func() { proxy, ok := upstreamProxy.handler.(*httputil.ReverseProxy) Expect(ok).To(BeTrue()) - Expect(proxy.FlushInterval).To(Equal(in.flushInterval.Duration())) + Expect(proxy.FlushInterval).To(Equal(in.flushInterval)) transport, ok := proxy.Transport.(*http.Transport) Expect(ok).To(BeTrue()) - Expect(transport.ResponseHeaderTimeout).To(Equal(in.timeout.Duration())) + Expect(transport.ResponseHeaderTimeout).To(Equal(in.timeout)) Expect(proxy.ErrorHandler != nil).To(Equal(in.errorHandler != nil)) if in.skipVerify { Expect(transport.TLSClientConfig.InsecureSkipVerify).To(Equal(true)) @@ -428,7 +428,7 @@ var _ = Describe("HTTP Upstream Suite", func() { }), Entry("with a non standard flush interval", &newUpstreamTableInput{ proxyWebSockets: false, - flushInterval: options.Duration(5 * time.Second), + flushInterval: 5 * time.Second, skipVerify: false, sigData: nil, errorHandler: nil, @@ -466,7 +466,7 @@ var _ = Describe("HTTP Upstream Suite", func() { skipVerify: false, sigData: nil, errorHandler: nil, - timeout: options.Duration(5 * time.Second), + timeout: 5 * time.Second, }), Entry("with a DisableKeepAlives", &newUpstreamTableInput{ proxyWebSockets: false, @@ -483,8 +483,8 @@ var _ = Describe("HTTP Upstream Suite", func() { var proxyServer *httptest.Server BeforeEach(func() { - flush := options.Duration(1 * time.Second) - timeout := options.Duration(options.DefaultUpstreamTimeout) + flush := 1 * time.Second + timeout := options.DefaultUpstreamTimeout upstream := options.Upstream{ ID: "websocketProxy", PassHostHeader: &truth, diff --git a/pkg/validation/common_test.go b/pkg/validation/common_test.go index 9e873c357b..bb7c2dd6aa 100644 --- a/pkg/validation/common_test.go +++ b/pkg/validation/common_test.go @@ -9,12 +9,12 @@ import ( ) var _ = Describe("Common", func() { - var validSecretSourceValue []byte + var validSecretSourceValue string const validSecretSourceEnv = "OAUTH2_PROXY_TEST_SECRET_SOURCE_ENV" var validSecretSourceFile string BeforeEach(func() { - validSecretSourceValue = []byte("This is a secret source value") + validSecretSourceValue = "This is a secret source value" Expect(os.Setenv(validSecretSourceEnv, "This is a secret source env")).To(Succeed()) tmp, err := os.CreateTemp("", "oauth2-proxy-secret-source-test") Expect(err).ToNot(HaveOccurred()) diff --git a/pkg/validation/header.go b/pkg/validation/header.go index b125814465..713113f414 100644 --- a/pkg/validation/header.go +++ b/pkg/validation/header.go @@ -51,11 +51,9 @@ func validateHeaderValue(_ string, value options.HeaderValue) []string { func validateHeaderValueClaimSource(claim options.ClaimSource) []string { msgs := []string{} - if claim.Claim == "" { msgs = append(msgs, "claim should not be empty") } - if claim.BasicAuthPassword != nil { msgs = append(msgs, prefixValues("invalid basicAuthPassword: ", validateSecretSource(*claim.BasicAuthPassword))...) } diff --git a/pkg/validation/header_test.go b/pkg/validation/header_test.go index 2d9ef6ddcf..88849ea171 100644 --- a/pkg/validation/header_test.go +++ b/pkg/validation/header_test.go @@ -30,7 +30,7 @@ var _ = Describe("Headers", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: []byte(base64.StdEncoding.EncodeToString([]byte("secret"))), + Value: base64.StdEncoding.EncodeToString([]byte("secret")), }, }, }, @@ -43,7 +43,7 @@ var _ = Describe("Headers", func() { ClaimSource: &options.ClaimSource{ Claim: "email", BasicAuthPassword: &options.SecretSource{ - Value: []byte(base64.StdEncoding.EncodeToString([]byte("secret"))), + Value: base64.StdEncoding.EncodeToString([]byte("secret")), }, }, }, diff --git a/pkg/validation/upstreams.go b/pkg/validation/upstreams.go index bafed628d7..52facb4dd8 100644 --- a/pkg/validation/upstreams.go +++ b/pkg/validation/upstreams.go @@ -69,7 +69,7 @@ func validateStaticUpstream(upstream options.Upstream) []string { if upstream.InsecureSkipTLSVerify { msgs = append(msgs, fmt.Sprintf("upstream %q has insecureSkipTLSVerify, but is a static upstream, this will have no effect.", upstream.ID)) } - if upstream.FlushInterval != nil && upstream.FlushInterval.Duration() != options.DefaultUpstreamFlushInterval { + if upstream.FlushInterval != nil && *upstream.FlushInterval != options.DefaultUpstreamFlushInterval { msgs = append(msgs, fmt.Sprintf("upstream %q has flushInterval, but is a static upstream, this will have no effect.", upstream.ID)) } if upstream.PassHostHeader != nil { diff --git a/pkg/validation/upstreams_test.go b/pkg/validation/upstreams_test.go index fe431d27db..67991b767a 100644 --- a/pkg/validation/upstreams_test.go +++ b/pkg/validation/upstreams_test.go @@ -14,7 +14,7 @@ var _ = Describe("Upstreams", func() { errStrings []string } - flushInterval := options.Duration(5 * time.Second) + flushInterval := 5 * time.Second staticCode200 := 200 truth := true From 676f56a35e135ef304e6cff6886e59cd2151baa0 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 1 Feb 2025 15:57:23 +0100 Subject: [PATCH 072/125] apply review suggestions Signed-off-by: Jan Larwig --- main.go | 2 +- pkg/apis/options/load.go | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index d9fc406be0..2a09b3ce82 100644 --- a/main.go +++ b/main.go @@ -70,7 +70,7 @@ func main() { func loadConfiguration(config, yamlConfig string, extraFlags *pflag.FlagSet, args []string) (*options.Options, error) { opts, err := loadLegacyOptions(config, extraFlags, args) if err != nil { - return nil, err + return nil, fmt.Errorf("couldn't load legacy options: %w", err) } if yamlConfig != "" { diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index 22e775a80d..878199edd1 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -83,12 +83,11 @@ func Decode(input interface{}, result interface{}) error { DecodeHook: mapstructure.ComposeDecodeHookFunc(toDurationHookFunc()), Metadata: nil, // Don't track any metadata Result: result, // Decode the result into the prefilled options - TagName: "json", // Parse all fields that use the yaml tag + TagName: "json", // Parse all fields that use the json tag ZeroFields: false, // Don't clean the default values from the result map (options) ErrorUnused: true, // Throw an error if keys have been used that aren't mapped to any struct fields - IgnoreUntaggedFields: true, // Ignore fields in structures that aren't tagged with yaml + IgnoreUntaggedFields: true, // Ignore fields in structures that aren't tagged with json }) - if err != nil { return fmt.Errorf("error creating decoder for config: %w", err) } From 6720d8da608774fdc6c435f91dd9564af4ee5ba9 Mon Sep 17 00:00:00 2001 From: tuunit Date: Sun, 9 Feb 2025 16:44:07 +0100 Subject: [PATCH 073/125] add duration test Signed-off-by: Jan Larwig --- pkg/apis/options/common_test.go | 87 ------------------------------- pkg/apis/options/duration_test.go | 82 +++++++++++++++++++++++++++++ pkg/apis/options/load.go | 17 ++++-- 3 files changed, 95 insertions(+), 91 deletions(-) delete mode 100644 pkg/apis/options/common_test.go create mode 100644 pkg/apis/options/duration_test.go diff --git a/pkg/apis/options/common_test.go b/pkg/apis/options/common_test.go deleted file mode 100644 index db33a58ba5..0000000000 --- a/pkg/apis/options/common_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package options - -import ( - "encoding/json" - "errors" - "time" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" -) - -var _ = Describe("Common", func() { - Context("Duration", func() { - type marshalJSONTableInput struct { - duration Duration - expectedJSON string - } - - DescribeTable("MarshalJSON", - func(in marshalJSONTableInput) { - data, err := in.duration.MarshalJSON() - Expect(err).ToNot(HaveOccurred()) - Expect(string(data)).To(Equal(in.expectedJSON)) - - var d Duration - Expect(json.Unmarshal(data, &d)).To(Succeed()) - Expect(d).To(Equal(in.duration)) - }, - Entry("30 seconds", marshalJSONTableInput{ - duration: Duration(30 * time.Second), - expectedJSON: "\"30s\"", - }), - Entry("1 minute", marshalJSONTableInput{ - duration: Duration(1 * time.Minute), - expectedJSON: "\"1m0s\"", - }), - Entry("1 hour 15 minutes", marshalJSONTableInput{ - duration: Duration(75 * time.Minute), - expectedJSON: "\"1h15m0s\"", - }), - Entry("A zero Duration", marshalJSONTableInput{ - duration: Duration(0), - expectedJSON: "\"0s\"", - }), - ) - - type unmarshalJSONTableInput struct { - json string - expectedErr error - expectedDuration Duration - } - - DescribeTable("UnmarshalJSON", - func(in unmarshalJSONTableInput) { - // A duration must be initialised pointer before UnmarshalJSON will work. - zero := Duration(0) - d := &zero - - err := d.UnmarshalJSON([]byte(in.json)) - if in.expectedErr != nil { - Expect(err).To(MatchError(in.expectedErr.Error())) - } else { - Expect(err).ToNot(HaveOccurred()) - } - Expect(d).ToNot(BeNil()) - Expect(*d).To(Equal(in.expectedDuration)) - }, - Entry("1m", unmarshalJSONTableInput{ - json: "\"1m\"", - expectedDuration: Duration(1 * time.Minute), - }), - Entry("30s", unmarshalJSONTableInput{ - json: "\"30s\"", - expectedDuration: Duration(30 * time.Second), - }), - Entry("1h15m", unmarshalJSONTableInput{ - json: "\"1h15m\"", - expectedDuration: Duration(75 * time.Minute), - }), - Entry("am", unmarshalJSONTableInput{ - json: "\"am\"", - expectedErr: errors.New("time: invalid duration \"am\""), - expectedDuration: Duration(0), - }), - ) - }) -}) diff --git a/pkg/apis/options/duration_test.go b/pkg/apis/options/duration_test.go new file mode 100644 index 0000000000..fc1e77e354 --- /dev/null +++ b/pkg/apis/options/duration_test.go @@ -0,0 +1,82 @@ +package options + +import ( + "testing" + "time" +) + +func TestDecode(t *testing.T) { + type result struct { + Duration time.Duration `json:"duration"` + } + + tests := []struct { + name string + input map[string]interface{} + out result + expected time.Duration + expectedErr bool + }{ + { + name: "Valid String Duration with single unit", + input: map[string]interface{}{"duration": "3s"}, + out: result{}, + expected: 3 * time.Second, + expectedErr: false, + }, + { + name: "Valid String Duration with multiple units", + input: map[string]interface{}{"duration": "1h20m30s"}, + out: result{}, + expected: 1*time.Hour + 20*time.Minute + 30*time.Second, + expectedErr: false, + }, + { + name: "Valid Float Duration", + input: map[string]interface{}{"duration": 2.5}, + out: result{}, + expected: 2500 * time.Millisecond, + expectedErr: false, + }, + { + name: "Valid Int64 Duration", + input: map[string]interface{}{"duration": int64(5000000000)}, + out: result{}, + expected: 5 * time.Second, + expectedErr: false, + }, + { + name: "Invalid String", + input: map[string]interface{}{"duration": "invalid"}, + out: result{}, + expected: 0, + expectedErr: true, + }, + { + name: "Unsupported Type", + input: map[string]interface{}{"duration": true}, + out: result{}, + expected: 0, + expectedErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var result struct { + Duration time.Duration `json:"duration"` + } + + err := Decode(tt.input, &result) + if (err != nil) != tt.expectedErr { + t.Errorf("expected error: %v, got: %v", tt.expectedErr, err) + } + + if !tt.expectedErr { + if result.Duration != tt.expected { + t.Errorf("expected: %v, got: %v", tt.expected, result.Duration) + } + } + }) + } +} diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index 878199edd1..2905af5f42 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -69,16 +69,25 @@ func LoadYAML(configFileName string, opts interface{}) error { return fmt.Errorf("error unmarshalling config: %w", err) } - return Decode(intermediate, opts) -} - -func Decode(input interface{}, result interface{}) error { // Using mapstructure to decode arbitrary yaml structure into options and // merge with existing values instead of overwriting everything. This is especially // important as we have a lot of default values for boolean which are supposed to be // true by default. Normally by just parsing through yaml all booleans that aren't // referenced in the config file would be parsed as false and we cannot identify after // the fact if they have been explicitly set to false or have not been referenced. + return Decode(intermediate, opts) +} + +// Decode processes an input map and decodes it into a given struct while preserving default values. +// It ensures proper conversion of duration values from strings, floats, and int64 into time.Duration. +// +// Parameters: +// - input: A map[string]interface{} representing the input data. +// - result: A pointer to a struct where the decoded values will be stored. +// +// Returns: +// - An error if decoding fails or if there are unmapped keys. +func Decode(input interface{}, result interface{}) error { decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ DecodeHook: mapstructure.ComposeDecodeHookFunc(toDurationHookFunc()), Metadata: nil, // Don't track any metadata From c186d40675ac706cd286106b969998063e2c8fd4 Mon Sep 17 00:00:00 2001 From: tuunit Date: Sun, 9 Feb 2025 17:23:03 +0100 Subject: [PATCH 074/125] use official upstream yaml library v3 Signed-off-by: Jan Larwig --- docs/docs/configuration/alpha_config.md | 214 +++++++++++------------ go.mod | 15 +- go.sum | 31 ++-- main.go | 2 +- main_test.go | 4 +- pkg/apis/options/alpha_options.go | 12 +- pkg/apis/options/duration_test.go | 4 +- pkg/apis/options/header.go | 16 +- pkg/apis/options/load.go | 4 +- pkg/apis/options/load_test.go | 10 +- pkg/apis/options/login_url_parameters.go | 10 +- pkg/apis/options/providers.go | 136 +++++++------- pkg/apis/options/secret_source.go | 6 +- pkg/apis/options/server.go | 14 +- pkg/apis/options/upstreams.go | 28 +-- pkg/requests/result_test.go | 4 +- 16 files changed, 250 insertions(+), 260 deletions(-) diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index 67b3fe1b3c..54dfb9f1da 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -148,7 +148,7 @@ You must remove these options before starting OAuth2 Proxy with `--alpha-config` | Field | Type | Description | | ----- | ---- | ----------- | -| `skipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | +| `SkipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | ### AlphaOptions @@ -163,12 +163,12 @@ They may change between releases without notice. | Field | Type | Description | | ----- | ---- | ----------- | -| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | -| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | -| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | -| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | -| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | -| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | +| `UpstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | +| `InjectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `InjectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `Server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `MetricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `Providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | ### AzureOptions @@ -178,8 +178,8 @@ They may change between releases without notice. | Field | Type | Description | | ----- | ---- | ----------- | -| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | -| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | +| `Tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | +| `GraphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | ### BitbucketOptions @@ -189,8 +189,8 @@ They may change between releases without notice. | Field | Type | Description | | ----- | ---- | ----------- | -| `team` | _string_ | Team sets restrict logins to members of this team | -| `repository` | _string_ | Repository sets restrict logins to user with access to this repository | +| `Team` | _string_ | Team sets restrict logins to members of this team | +| `Repository` | _string_ | Repository sets restrict logins to user with access to this repository | ### ClaimSource @@ -200,9 +200,9 @@ ClaimSource allows loading a header value from a claim within the session | Field | Type | Description | | ----- | ---- | ----------- | -| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | -| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | -| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | +| `Claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `Prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `BasicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | ### GitHubOptions @@ -212,11 +212,11 @@ ClaimSource allows loading a header value from a claim within the session | Field | Type | Description | | ----- | ---- | ----------- | -| `org` | _string_ | Org sets restrict logins to members of this organisation | -| `team` | _string_ | Team sets restrict logins to members of this team | -| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository | -| `token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | -| `users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | +| `Org` | _string_ | Org sets restrict logins to members of this organisation | +| `Team` | _string_ | Team sets restrict logins to members of this team | +| `Repo` | _string_ | Repo sets restrict logins to collaborators of this repository | +| `Token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | +| `Users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | ### GitLabOptions @@ -226,8 +226,8 @@ ClaimSource allows loading a header value from a claim within the session | Field | Type | Description | | ----- | ---- | ----------- | -| `group` | _[]string_ | Group sets restrict logins to members of this group | -| `projects` | _[]string_ | Projects restricts logins to members of these projects | +| `Group` | _[]string_ | Group sets restrict logins to members of this group | +| `Projects` | _[]string_ | Projects restricts logins to members of these projects | ### GoogleOptions @@ -237,13 +237,13 @@ ClaimSource allows loading a header value from a claim within the session | Field | Type | Description | | ----- | ---- | ----------- | -| `group` | _[]string_ | Groups sets restrict logins to members of this Google group | -| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | -| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | -| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | -| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | -| `useOrganizationID` | _bool_ | UseOrganizationId indicates whether to use the organization ID as the UserName claim | -| `adminAPIUserScope` | _string_ | admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly | +| `Groups` | _[]string_ | Groups sets restrict logins to members of this Google group | +| `AdminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | +| `ServiceAccountJSON` | _string_ | ServiceAccountJSON is the path to the service account json credentials | +| `UseApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | +| `TargetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | +| `UseOrganizationID` | _bool_ | UseOrganizationId indicates whether to use the organization ID as the UserName claim | +| `AdminAPIUserScope` | _string_ | admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly | ### Header @@ -254,10 +254,10 @@ response header. | Field | Type | Description | | ----- | ---- | ----------- | -| `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | -| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `Name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | +| `PreserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | | `InsecureSkipHeaderNormalization` | _bool_ | InsecureSkipHeaderNormalization disables normalizing the header name
According to RFC 7230 Section 3.2 there aren't any rules about
capitalization of header names, but the standard practice is to use
Title-Case (e.g. X-Forwarded-For). By default, header names will be
normalized to Title-Case and any incoming headers that match will be
treated as the same header. Additionally underscores (_) in header names
will be converted to dashes (-) when normalizing.
Defaults to false (header names will be normalized). | -| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | +| `Values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | ### HeaderValue @@ -268,12 +268,12 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _string_ | Value expects a base64 encoded string value. | -| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | -| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | -| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | -| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | -| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | +| `Value` | _string_ | Value expects a base64 encoded string value. | +| `FromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `FromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `Claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `Prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `BasicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | ### KeycloakOptions @@ -283,8 +283,8 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `groups` | _[]string_ | Group enables to restrict login to members of indicated group | -| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | +| `Groups` | _[]string_ | Group enables to restrict login to members of indicated group | +| `Roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | ### LoginGovOptions @@ -294,9 +294,9 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | -| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | -| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | +| `JWTKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | +| `JWTKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | +| `PubJWKURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | ### LoginURLParameter @@ -374,9 +374,9 @@ character. | Field | Type | Description | | ----- | ---- | ----------- | -| `name` | _string_ | Name specifies the name of the query parameter. | -| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | -| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | +| `Name` | _string_ | Name specifies the name of the query parameter. | +| `Default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | +| `Allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | ### MicrosoftEntraIDOptions @@ -386,8 +386,8 @@ character. | Field | Type | Description | | ----- | ---- | ----------- | -| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | -| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | +| `AllowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | +| `FederatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | ### OIDCOptions @@ -397,18 +397,18 @@ character. | Field | Type | Description | | ----- | ---- | ----------- | -| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | -| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | -| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | -| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | -| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | -| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | -| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | -| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | -| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | -| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | -| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | -| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | +| `IssuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | +| `InsecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | +| `InsecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | +| `InsecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | +| `SkipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | +| `JwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | +| `PublicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | +| `EmailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | +| `GroupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | +| `UserIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | +| `AudienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | +| `ExtraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | ### Provider @@ -418,36 +418,36 @@ Provider holds all configuration for a single provider | Field | Type | Description | | ----- | ---- | ----------- | -| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | -| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | -| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | -| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | -| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | -| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | +| `ClientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | +| `ClientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | +| `ClientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | +| `KeycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | +| `AzureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | +| `MicrosoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | | `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. | -| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | -| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | -| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | -| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | -| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | -| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | -| `id` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | -| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | -| `name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | -| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | -| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | -| `loginURL` | _string_ | LoginURL is the authentication endpoint | -| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | -| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | -| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint | -| `profileURL` | _string_ | ProfileURL is the profile access endpoint | -| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | -| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | -| `validateURL` | _string_ | ValidateURL is the access token validation endpoint | -| `scope` | _string_ | Scope is the OAuth scope specification | -| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | -| `code_challenge_method` | _string_ | The code challenge method | -| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | +| `BitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | +| `GitHubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | +| `GitLabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | +| `GoogleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | +| `OIDCConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | +| `LoginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | +| `ID` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | +| `Type` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | +| `Name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | +| `CAFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | +| `UseSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | +| `LoginURL` | _string_ | LoginURL is the authentication endpoint | +| `LoginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | +| `AuthRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | +| `RedeemURL` | _string_ | RedeemURL is the token redemption endpoint | +| `ProfileURL` | _string_ | ProfileURL is the profile access endpoint | +| `SkipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | +| `ProtectedResource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | +| `ValidateURL` | _string_ | ValidateURL is the access token validation endpoint | +| `Scope` | _string_ | Scope is the OAuth scope specification | +| `AllowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | +| `CodeChallengeMethod` | _string_ | The code challenge method | +| `BackendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | ### ProviderType #### (`string` alias) @@ -480,9 +480,9 @@ Only one source within the struct should be defined at any time. | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _string_ | Value expects a base64 encoded string value. | -| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | -| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `Value` | _string_ | Value expects a base64 encoded string value. | +| `FromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `FromFile` | _string_ | FromFile expects a path to a file containing the secret value. | ### Server @@ -521,8 +521,8 @@ login URL. Either Value or Pattern should be supplied, not both. | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _string_ | A Value rule matches just this specific value | -| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | +| `Value` | _string_ | A Value rule matches just this specific value | +| `Pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | ### Upstream @@ -533,18 +533,18 @@ Requests will be proxied to this upstream if the path matches the request path. | Field | Type | Description | | ----- | ---- | ----------- | -| `id` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | -| `path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | -| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | -| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | -| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | -| `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | -| `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | -| `flushInterval` | _duration_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | -| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | -| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | -| `timeout` | _duration_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | -| `disableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | +| `ID` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | +| `Path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | +| `RewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | +| `URI` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | +| `InsecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | +| `Static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | +| `StaticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | +| `FlushInterval` | _duration_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `PassHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | +| `ProxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | +| `Timeout` | _duration_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | +| `DisableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | ### UpstreamConfig @@ -554,5 +554,5 @@ UpstreamConfig is a collection of definitions for upstream servers. | Field | Type | Description | | ----- | ---- | ----------- | -| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | -| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | +| `ProxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | +| `Upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | diff --git a/go.mod b/go.mod index 69ffc5fb57..9e353b0aa0 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,6 @@ require ( github.com/coreos/go-oidc/v3 v3.14.1 github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf github.com/fsnotify/fsnotify v1.9.0 - github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 github.com/go-jose/go-jose/v3 v3.0.4 github.com/go-viper/mapstructure/v2 v2.4.0 github.com/golang-jwt/jwt/v5 v5.2.3 @@ -20,9 +19,10 @@ require ( github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 github.com/justinas/alice v1.2.0 + github.com/mitchellh/mapstructure v1.5.0 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 github.com/onsi/ginkgo/v2 v2.23.4 - github.com/onsi/gomega v1.37.0 + github.com/onsi/gomega v1.38.0 github.com/pierrec/lz4/v4 v4.1.22 github.com/prometheus/client_golang v1.22.0 github.com/redis/go-redis/v9 v9.11.0 @@ -35,13 +35,14 @@ require ( golang.org/x/net v0.42.0 golang.org/x/oauth2 v0.30.0 golang.org/x/sync v0.16.0 - google.golang.org/api v0.242.0 + google.golang.org/api v0.243.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 + gopkg.in/yaml.v3 v3.0.1 k8s.io/apimachinery v0.33.3 ) require ( - cloud.google.com/go/auth v0.16.2 // indirect + cloud.google.com/go/auth v0.16.3 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect @@ -80,9 +81,7 @@ require ( golang.org/x/sys v0.34.0 // indirect golang.org/x/text v0.27.0 // indirect golang.org/x/tools v0.35.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7 // indirect - google.golang.org/grpc v1.73.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250721164621-a45f3dfb1074 // indirect + google.golang.org/grpc v1.74.2 // indirect google.golang.org/protobuf v1.36.6 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 863da770ca..34aca12f60 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -cloud.google.com/go/auth v0.16.2 h1:QvBAGFPLrDeoiNjyfVunhQ10HKNYuOwZ5noee0M5df4= -cloud.google.com/go/auth v0.16.2/go.mod h1:sRBas2Y1fB1vZTdurouM0AzuYQBMZinrUYL8EufhtEA= +cloud.google.com/go/auth v0.16.3 h1:kabzoQ9/bobUmnseYnBO6qQG7q4a/CffFRlJSxv2wCc= +cloud.google.com/go/auth v0.16.3/go.mod h1:NucRGjaXfzP1ltpcQ7On/VTZ0H4kWB5Jy+Y9Dnm76fA= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= cloud.google.com/go/compute/metadata v0.7.0 h1:PBWF+iiAerVNe8UCHxdOt6eHLVc3ydFeOCw78U8ytSU= @@ -44,8 +44,6 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= -github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 h1:Arcl6UOIS/kgO2nW3A65HN+7CMjSDP/gofXL4CZt1V4= -github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY= github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= github.com/go-jose/go-jose/v4 v4.1.1 h1:JYhSgy4mXXzAdF3nUx3ygx347LRXJRrpgyU3adRmkAI= @@ -93,16 +91,16 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0 github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/matryer/is v1.2.0 h1:92UTHpy8CDwaJ08GqLDzhhuixiBUUD1p3AU6PHddz4A= github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA= -github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa h1:hI1uC2A3vJFjwvBn0G0a7QBRdBUp6Y048BtLAHRTKPo= -github.com/mbland/hmacauth v0.0.0-20170912233209-44256dfd4bfa/go.mod h1:8vxFeeg++MqgCHwehSuwTlYCF0ALyDJbYJ1JsKi7v6s= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw= github.com/onsi/ginkgo/v2 v2.23.4 h1:ktYTpKJAVZnDT4VjxSbiBenUjmlL/5QkBEocaWXiQus= github.com/onsi/ginkgo/v2 v2.23.4/go.mod h1:Bt66ApGPBFzHyR+JO10Zbt0Gsp4uWxu5mIOTusL46e8= -github.com/onsi/gomega v1.37.0 h1:CdEG8g0S133B4OswTDC/5XPSzE1OeP29QOioj2PID2Y= -github.com/onsi/gomega v1.37.0/go.mod h1:8D9+Txp43QWKhM24yyOBEdpkzN8FvJyAwecBgsU4KU0= +github.com/onsi/gomega v1.38.0 h1:c/WX+w8SLAinvuKKQFh77WEucCnPk4j2OTUr7lt7BeY= +github.com/onsi/gomega v1.38.0/go.mod h1:OcXcwId0b9QsE7Y49u+BTrL4IdKOBOKnD6VQNTJEB6o= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU= @@ -138,8 +136,6 @@ github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4= github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= @@ -227,16 +223,16 @@ golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0= golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.242.0 h1:7Lnb1nfnpvbkCiZek6IXKdJ0MFuAZNAJKQfA1ws62xg= -google.golang.org/api v0.242.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= +google.golang.org/api v0.243.0 h1:sw+ESIJ4BVnlJcWu9S+p2Z6Qq1PjG77T8IJ1xtp4jZQ= +google.golang.org/api v0.243.0/go.mod h1:GE4QtYfaybx1KmeHMdBnNnyLzBZCVihGBXAmJu/uUr8= google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 h1:oWVWY3NzT7KJppx2UKhKmzPq4SRe0LdCijVRwvGeikY= google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822/go.mod h1:h3c4v36UTKzUiuaOKQ6gr3S+0hovBtUrXzTG/i3+XEc= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7 h1:pFyd6EwwL2TqFf8emdthzeX+gZE1ElRq3iM8pui4KBY= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= -google.golang.org/grpc v1.73.0 h1:VIWSmpI2MegBtTuFt5/JWy2oXxtjJ/e89Z70ImfD2ok= -google.golang.org/grpc v1.73.0/go.mod h1:50sbHOUqWoCQGI8V2HQLJM0B+LMlIUjNSZmow7EVBQc= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250721164621-a45f3dfb1074 h1:qJW29YvkiJmXOYMu5Tf8lyrTp3dOS+K4z6IixtLaCf8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250721164621-a45f3dfb1074/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= +google.golang.org/grpc v1.74.2 h1:WoosgB65DlWVC9FqI82dGsZhWFNBSLjQ84bjROOpMu4= +google.golang.org/grpc v1.74.2/go.mod h1:CtQ+BGjaAIXHs/5YS3i473GqwBBa1zGQNevxdeBEXrM= google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -244,9 +240,6 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntN gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go index 2a09b3ce82..a9def2f6a6 100644 --- a/main.go +++ b/main.go @@ -5,12 +5,12 @@ import ( "os" "runtime" - "github.com/ghodss/yaml" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/validation" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/version" "github.com/spf13/pflag" + "gopkg.in/yaml.v3" ) func main() { diff --git a/main_test.go b/main_test.go index a6ea83c28a..7de1ac72b2 100644 --- a/main_test.go +++ b/main_test.go @@ -2,9 +2,7 @@ package main import ( "errors" - "fmt" "os" - "strings" "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" @@ -256,7 +254,7 @@ redirect_url="http://localhost:4180/oauth2/callback" configContent: testCoreConfig, alphaConfigContent: testAlphaConfig + ":", expectedOptions: func() *options.Options { return nil }, - expectedErr: fmt.Errorf("failed to load alpha options: error unmarshalling config: error converting YAML to JSON: yaml: line %d: did not find expected key", strings.Count(testAlphaConfig, "\n")), + expectedErr: errors.New("failed to load alpha options: error unmarshalling config: yaml: line 1: did not find expected key"), }), Entry("with alpha configuration and bad core configuration", loadConfigurationTableInput{ configContent: testCoreConfig + "unknown_field=\"something\"", diff --git a/pkg/apis/options/alpha_options.go b/pkg/apis/options/alpha_options.go index 278db40110..0c78359a64 100644 --- a/pkg/apis/options/alpha_options.go +++ b/pkg/apis/options/alpha_options.go @@ -12,13 +12,13 @@ type AlphaOptions struct { // UpstreamConfig is used to configure upstream servers. // Once a user is authenticated, requests to the server will be proxied to // these upstream servers based on the path mappings defined in this list. - UpstreamConfig UpstreamConfig `json:"upstreamConfig,omitempty"` + UpstreamConfig UpstreamConfig `yaml:"upstreamConfig,omitempty"` // InjectRequestHeaders is used to configure headers that should be added // to requests to upstream servers. // Headers may source values from either the authenticated user's session // or from a static secret value. - InjectRequestHeaders []Header `json:"injectRequestHeaders,omitempty"` + InjectRequestHeaders []Header `yaml:"injectRequestHeaders,omitempty"` // InjectResponseHeaders is used to configure headers that should be added // to responses from the proxy. @@ -27,24 +27,24 @@ type AlphaOptions struct { // auth_request module. // Headers may source values from either the authenticated user's session // or from a static secret value. - InjectResponseHeaders []Header `json:"injectResponseHeaders,omitempty"` + InjectResponseHeaders []Header `yaml:"injectResponseHeaders,omitempty"` // Server is used to configure the HTTP(S) server for the proxy application. // You may choose to run both HTTP and HTTPS servers simultaneously. // This can be done by setting the BindAddress and the SecureBindAddress simultaneously. // To use the secure server you must configure a TLS certificate and key. - Server Server `json:"server,omitempty"` + Server Server `yaml:"server,omitempty"` // MetricsServer is used to configure the HTTP(S) server for metrics. // You may choose to run both HTTP and HTTPS servers simultaneously. // This can be done by setting the BindAddress and the SecureBindAddress simultaneously. // To use the secure server you must configure a TLS certificate and key. - MetricsServer Server `json:"metricsServer,omitempty"` + MetricsServer Server `yaml:"metricsServer,omitempty"` // Providers is used to configure your provider. **Multiple-providers is not // yet working.** [This feature is tracked in // #925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) - Providers Providers `json:"providers,omitempty"` + Providers Providers `yaml:"providers,omitempty"` } // Initialize alpha options with default values and settings of the core options diff --git a/pkg/apis/options/duration_test.go b/pkg/apis/options/duration_test.go index fc1e77e354..63f203a837 100644 --- a/pkg/apis/options/duration_test.go +++ b/pkg/apis/options/duration_test.go @@ -7,7 +7,7 @@ import ( func TestDecode(t *testing.T) { type result struct { - Duration time.Duration `json:"duration"` + Duration time.Duration `yaml:"duration"` } tests := []struct { @@ -64,7 +64,7 @@ func TestDecode(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var result struct { - Duration time.Duration `json:"duration"` + Duration time.Duration `yaml:"duration"` } err := Decode(tt.input, &result) diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index 164f9fee63..ab3916773b 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -5,13 +5,13 @@ package options type Header struct { // Name is the header name to be used for this set of values. // Names should be unique within a list of Headers. - Name string `json:"name,omitempty"` + Name string `yaml:"name,omitempty"` // PreserveRequestValue determines whether any values for this header // should be preserved for the request to the upstream server. // This option only applies to injected request headers. // Defaults to false (headers that match this header will be stripped). - PreserveRequestValue bool `json:"preserveRequestValue,omitempty"` + PreserveRequestValue bool `yaml:"preserveRequestValue,omitempty"` // InsecureSkipHeaderNormalization disables normalizing the header name // According to RFC 7230 Section 3.2 there aren't any rules about @@ -24,17 +24,17 @@ type Header struct { InsecureSkipHeaderNormalization bool `json:"InsecureSkipHeaderNormalization,omitempty"` // Values contains the desired values for this header - Values []HeaderValue `json:"values,omitempty"` + Values []HeaderValue `yaml:"values,omitempty"` } // HeaderValue represents a single header value and the sources that can // make up the header value type HeaderValue struct { // Allow users to load the value from a secret source - *SecretSource `json:"secretSource,omitempty"` + *SecretSource `yaml:"secretSource,omitempty"` // Allow users to load the value from a session claim - *ClaimSource `json:"claimSource,omitempty"` + *ClaimSource `yaml:"claimSource,omitempty"` } // ClaimSource allows loading a header value from a claim within the session @@ -42,14 +42,14 @@ type ClaimSource struct { // Claim is the name of the claim in the session that the value should be // loaded from. Available claims: `access_token` `id_token` `created_at` // `expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. - Claim string `json:"claim,omitempty"` + Claim string `yaml:"claim,omitempty"` // Prefix is an optional prefix that will be prepended to the value of the // claim if it is non-empty. - Prefix string `json:"prefix,omitempty"` + Prefix string `yaml:"prefix,omitempty"` // BasicAuthPassword converts this claim into a basic auth header. // Note the value of claim will become the basic auth username and the // basicAuthPassword will be used as the password value. - BasicAuthPassword *SecretSource `json:"basicAuthPassword,omitempty"` + BasicAuthPassword *SecretSource `yaml:"basicAuthPassword,omitempty"` } diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index 2905af5f42..af7f76d9f9 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -9,10 +9,10 @@ import ( "strings" "github.com/a8m/envsubst" - "github.com/ghodss/yaml" "github.com/go-viper/mapstructure/v2" "github.com/spf13/pflag" "github.com/spf13/viper" + "gopkg.in/yaml.v3" ) // Load reads in the config file at the path given, then merges in environment @@ -92,7 +92,7 @@ func Decode(input interface{}, result interface{}) error { DecodeHook: mapstructure.ComposeDecodeHookFunc(toDurationHookFunc()), Metadata: nil, // Don't track any metadata Result: result, // Decode the result into the prefilled options - TagName: "json", // Parse all fields that use the json tag + TagName: "yaml", // Parse all fields that use the json tag ZeroFields: false, // Don't clean the default values from the result map (options) ErrorUnused: true, // Throw an error if keys have been used that aren't mapped to any struct fields IgnoreUntaggedFields: true, // Ignore fields in structures that aren't tagged with json diff --git a/pkg/apis/options/load_test.go b/pkg/apis/options/load_test.go index 6f327a22c1..a007926725 100644 --- a/pkg/apis/options/load_test.go +++ b/pkg/apis/options/load_test.go @@ -355,15 +355,15 @@ var _ = Describe("Load", func() { var _ = Describe("LoadYAML", func() { Context("with a testOptions structure", func() { type TestOptionSubStruct struct { - StringSliceOption []string `json:"stringSliceOption,omitempty"` + StringSliceOption []string `yaml:"stringSliceOption,omitempty"` } type TestOptions struct { - StringOption string `json:"stringOption,omitempty"` - Sub TestOptionSubStruct `json:"sub,omitempty"` + StringOption string `yaml:"stringOption,omitempty"` + Sub TestOptionSubStruct `yaml:"sub,omitempty"` // Check that embedded fields can be unmarshalled - TestOptionSubStruct `json:",inline,squash"` + TestOptionSubStruct `yaml:",inline,squash"` } var testOptionsConfigBytesFull = []byte(` @@ -445,7 +445,7 @@ sub: configFile: []byte("\tfoo: bar"), input: &TestOptions{}, expectedOutput: &TestOptions{}, - expectedErr: errors.New("error unmarshalling config: error converting YAML to JSON: yaml: found character that cannot start any token"), + expectedErr: errors.New("error unmarshalling config: yaml: found character that cannot start any token"), }), Entry("with extra fields in the YAML", loadYAMLTableInput{ configFile: append(testOptionsConfigBytesFull, []byte("foo: bar\n")...), diff --git a/pkg/apis/options/login_url_parameters.go b/pkg/apis/options/login_url_parameters.go index 1cb763b9a8..0272976013 100644 --- a/pkg/apis/options/login_url_parameters.go +++ b/pkg/apis/options/login_url_parameters.go @@ -71,19 +71,19 @@ package options // character. type LoginURLParameter struct { // Name specifies the name of the query parameter. - Name string `json:"name"` + Name string `yaml:"name"` // Default specifies a default value or values that will be // passed to the IdP if not overridden. //+optional - Default []string `json:"default,omitempty"` + Default []string `yaml:"default,omitempty"` // Allow specifies rules about how the default (if any) may be // overridden via the query string to `/oauth2/start`. Only // values that match one or more of the allow rules will be // forwarded to the IdP. //+optional - Allow []URLParameterRule `json:"allow,omitempty"` + Allow []URLParameterRule `yaml:"allow,omitempty"` } // URLParameterRule represents a rule by which query parameters @@ -92,11 +92,11 @@ type LoginURLParameter struct { // login URL. Either Value or Pattern should be supplied, not both. type URLParameterRule struct { // A Value rule matches just this specific value - Value *string `json:"value,omitempty"` + Value *string `yaml:"value,omitempty"` // A Pattern rule gives a regular expression that must be matched by // some substring of the value. The expression is _not_ automatically // anchored to the start and end of the value, if you _want_ to restrict // the whole parameter value you must anchor it yourself with `^` and `$`. - Pattern *string `json:"pattern,omitempty"` + Pattern *string `yaml:"pattern,omitempty"` } diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index c876f46b59..0a0796e93d 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -22,78 +22,78 @@ type Providers []Provider type Provider struct { // ClientID is the OAuth Client ID that is defined in the provider // This value is required for all providers. - ClientID string `json:"clientID,omitempty"` + ClientID string `yaml:"clientID,omitempty"` // ClientSecret is the OAuth Client Secret that is defined in the provider // This value is required for all providers. - ClientSecret string `json:"clientSecret,omitempty"` + ClientSecret string `yaml:"clientSecret,omitempty"` // ClientSecretFile is the name of the file // containing the OAuth Client Secret, it will be used if ClientSecret is not set. - ClientSecretFile string `json:"clientSecretFile,omitempty"` + ClientSecretFile string `yaml:"clientSecretFile,omitempty"` // KeycloakConfig holds all configurations for Keycloak provider. - KeycloakConfig KeycloakOptions `json:"keycloakConfig,omitempty"` + KeycloakConfig KeycloakOptions `yaml:"keycloakConfig,omitempty"` // AzureConfig holds all configurations for Azure provider. - AzureConfig AzureOptions `json:"azureConfig,omitempty"` + AzureConfig AzureOptions `yaml:"azureConfig,omitempty"` // MicrosoftEntraIDConfig holds all configurations for Entra ID provider. - MicrosoftEntraIDConfig MicrosoftEntraIDOptions `json:"microsoftEntraIDConfig,omitempty"` + MicrosoftEntraIDConfig MicrosoftEntraIDOptions `yaml:"microsoftEntraIDConfig,omitempty"` // ADFSConfig holds all configurations for ADFS provider. - ADFSConfig ADFSOptions `json:"ADFSConfig,omitempty"` + ADFSConfig ADFSOptions `yaml:"ADFSConfig,omitempty"` // BitbucketConfig holds all configurations for Bitbucket provider. - BitbucketConfig BitbucketOptions `json:"bitbucketConfig,omitempty"` + BitbucketConfig BitbucketOptions `yaml:"bitbucketConfig,omitempty"` // GitHubConfig holds all configurations for GitHubC provider. - GitHubConfig GitHubOptions `json:"githubConfig,omitempty"` + GitHubConfig GitHubOptions `yaml:"githubConfig,omitempty"` // GitLabConfig holds all configurations for GitLab provider. - GitLabConfig GitLabOptions `json:"gitlabConfig,omitempty"` + GitLabConfig GitLabOptions `yaml:"gitlabConfig,omitempty"` // GoogleConfig holds all configurations for Google provider. - GoogleConfig GoogleOptions `json:"googleConfig,omitempty"` + GoogleConfig GoogleOptions `yaml:"googleConfig,omitempty"` // OIDCConfig holds all configurations for OIDC provider // or providers utilize OIDC configurations. - OIDCConfig OIDCOptions `json:"oidcConfig,omitempty"` + OIDCConfig OIDCOptions `yaml:"oidcConfig,omitempty"` // LoginGovConfig holds all configurations for LoginGov provider. - LoginGovConfig LoginGovOptions `json:"loginGovConfig,omitempty"` + LoginGovConfig LoginGovOptions `yaml:"loginGovConfig,omitempty"` // ID should be a unique identifier for the provider. // This value is required for all providers. - ID string `json:"id,omitempty"` + ID string `yaml:"id,omitempty"` // Type is the OAuth provider // must be set from the supported providers group, // otherwise 'Google' is set as default - Type ProviderType `json:"provider,omitempty"` + Type ProviderType `yaml:"provider,omitempty"` // Name is the providers display name // if set, it will be shown to the users in the login page. - Name string `json:"name,omitempty"` + Name string `yaml:"name,omitempty"` // CAFiles is a list of paths to CA certificates that should be used when connecting to the provider. // If not specified, the default Go trust sources are used instead - CAFiles []string `json:"caFiles,omitempty"` + CAFiles []string `yaml:"caFiles,omitempty"` // UseSystemTrustStore determines if your custom CA files and the system trust store are used // If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. - UseSystemTrustStore bool `json:"useSystemTrustStore,omitempty"` + UseSystemTrustStore bool `yaml:"useSystemTrustStore,omitempty"` // LoginURL is the authentication endpoint - LoginURL string `json:"loginURL,omitempty"` + LoginURL string `yaml:"loginURL,omitempty"` // LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL - LoginURLParameters []LoginURLParameter `json:"loginURLParameters,omitempty"` + LoginURLParameters []LoginURLParameter `yaml:"loginURLParameters,omitempty"` // AuthRequestResponseMode defines the response mode to request during authorization request - AuthRequestResponseMode string `json:"authRequestResponseMode,omitempty"` + AuthRequestResponseMode string `yaml:"authRequestResponseMode,omitempty"` // RedeemURL is the token redemption endpoint - RedeemURL string `json:"redeemURL,omitempty"` + RedeemURL string `yaml:"redeemURL,omitempty"` // ProfileURL is the profile access endpoint - ProfileURL string `json:"profileURL,omitempty"` + ProfileURL string `yaml:"profileURL,omitempty"` // SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token // default set to 'false' - SkipClaimsFromProfileURL bool `json:"skipClaimsFromProfileURL,omitempty"` + SkipClaimsFromProfileURL bool `yaml:"skipClaimsFromProfileURL,omitempty"` // ProtectedResource is the resource that is protected (Azure AD and ADFS only) - ProtectedResource string `json:"resource,omitempty"` + ProtectedResource string `yaml:"resource,omitempty"` // ValidateURL is the access token validation endpoint - ValidateURL string `json:"validateURL,omitempty"` + ValidateURL string `yaml:"validateURL,omitempty"` // Scope is the OAuth scope specification - Scope string `json:"scope,omitempty"` + Scope string `yaml:"scope,omitempty"` // AllowedGroups is a list of restrict logins to members of this group - AllowedGroups []string `json:"allowedGroups,omitempty"` + AllowedGroups []string `yaml:"allowedGroups,omitempty"` // The code challenge method - CodeChallengeMethod string `json:"code_challenge_method,omitempty"` + CodeChallengeMethod string `yaml:"code_challenge_method,omitempty"` // URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session - BackendLogoutURL string `json:"backendLogoutURL"` + BackendLogoutURL string `yaml:"backendLogoutURL"` } // ProviderType is used to enumerate the different provider type options @@ -157,19 +157,19 @@ const ( type KeycloakOptions struct { // Group enables to restrict login to members of indicated group - Groups []string `json:"groups,omitempty"` + Groups []string `yaml:"groups,omitempty"` // Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) - Roles []string `json:"roles,omitempty"` + Roles []string `yaml:"roles,omitempty"` } type AzureOptions struct { // Tenant directs to a tenant-specific or common (tenant-independent) endpoint // Default value is 'common' - Tenant string `json:"tenant,omitempty"` + Tenant string `yaml:"tenant,omitempty"` // GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph // Default value is 'id' - GraphGroupField string `json:"graphGroupField,omitempty"` + GraphGroupField string `yaml:"graphGroupField,omitempty"` } type MicrosoftEntraIDOptions struct { @@ -177,114 +177,114 @@ type MicrosoftEntraIDOptions struct { // 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). - AllowedTenants []string `json:"allowedTenants,omitempty"` + AllowedTenants []string `yaml:"allowedTenants,omitempty"` // FederatedTokenAuth enable oAuth2 client authentication with federated token projected // by Entra Workload Identity plugin, instead of client secret. - FederatedTokenAuth bool `json:"federatedTokenAuth,omitempty"` + FederatedTokenAuth bool `yaml:"federatedTokenAuth,omitempty"` } type ADFSOptions struct { // Skip adding the scope parameter in login request // Default value is 'false' - SkipScope bool `json:"skipScope,omitempty"` + SkipScope bool `yaml:"skipScope,omitempty"` } type BitbucketOptions struct { // Team sets restrict logins to members of this team - Team string `json:"team,omitempty"` + Team string `yaml:"team,omitempty"` // Repository sets restrict logins to user with access to this repository - Repository string `json:"repository,omitempty"` + Repository string `yaml:"repository,omitempty"` } type GitHubOptions struct { // Org sets restrict logins to members of this organisation - Org string `json:"org,omitempty"` + Org string `yaml:"org,omitempty"` // Team sets restrict logins to members of this team - Team string `json:"team,omitempty"` + Team string `yaml:"team,omitempty"` // Repo sets restrict logins to collaborators of this repository - Repo string `json:"repo,omitempty"` + Repo string `yaml:"repo,omitempty"` // Token is the token to use when verifying repository collaborators // it must have push access to the repository - Token string `json:"token,omitempty"` + Token string `yaml:"token,omitempty"` // Users allows users with these usernames to login // even if they do not belong to the specified org and team or collaborators - Users []string `json:"users,omitempty"` + Users []string `yaml:"users,omitempty"` } type GitLabOptions struct { // Group sets restrict logins to members of this group - Group []string `json:"group,omitempty"` + Group []string `yaml:"group,omitempty"` // Projects restricts logins to members of these projects - Projects []string `json:"projects,omitempty"` + Projects []string `yaml:"projects,omitempty"` } type GoogleOptions struct { // Groups sets restrict logins to members of this Google group - Groups []string `json:"group,omitempty"` + Groups []string `yaml:"group,omitempty"` // AdminEmail is the Google admin to impersonate for api calls - AdminEmail string `json:"adminEmail,omitempty"` + AdminEmail string `yaml:"adminEmail,omitempty"` // ServiceAccountJSON is the path to the service account json credentials - ServiceAccountJSON string `json:"serviceAccountJson,omitempty"` + ServiceAccountJSON string `yaml:"serviceAccountJson,omitempty"` // UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON - UseApplicationDefaultCredentials bool `json:"useApplicationDefaultCredentials,omitempty"` + UseApplicationDefaultCredentials bool `yaml:"useApplicationDefaultCredentials,omitempty"` // TargetPrincipal is the Google Service Account used for Application Default Credentials - TargetPrincipal string `json:"targetPrincipal,omitempty"` + TargetPrincipal string `yaml:"targetPrincipal,omitempty"` // UseOrganizationId indicates whether to use the organization ID as the UserName claim - UseOrganizationID bool `json:"useOrganizationID,omitempty"` + UseOrganizationID bool `yaml:"useOrganizationID,omitempty"` // admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly - AdminAPIUserScope string `json:"adminAPIUserScope,omitempty"` + AdminAPIUserScope string `yaml:"adminAPIUserScope,omitempty"` } type OIDCOptions struct { // IssuerURL is the OpenID Connect issuer URL // eg: https://accounts.google.com - IssuerURL string `json:"issuerURL,omitempty"` + IssuerURL string `yaml:"issuerURL,omitempty"` // InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified // default set to 'false' - InsecureAllowUnverifiedEmail bool `json:"insecureAllowUnverifiedEmail"` + InsecureAllowUnverifiedEmail bool `yaml:"insecureAllowUnverifiedEmail"` // InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL // default set to 'false' - InsecureSkipIssuerVerification bool `json:"insecureSkipIssuerVerification"` + InsecureSkipIssuerVerification bool `yaml:"insecureSkipIssuerVerification"` // InsecureSkipNonce skips verifying the ID Token's nonce claim that must match // the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked // after the initial OAuth redeem & subsequent token refreshes. // default set to 'true' // Warning: In a future release, this will change to 'false' by default for enhanced security. - InsecureSkipNonce bool `json:"insecureSkipNonce"` + InsecureSkipNonce bool `yaml:"insecureSkipNonce"` // SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints // default set to 'false' - SkipDiscovery bool `json:"skipDiscovery,omitempty"` + SkipDiscovery bool `yaml:"skipDiscovery,omitempty"` // JwksURL is the OpenID Connect JWKS URL // eg: https://www.googleapis.com/oauth2/v3/certs - JwksURL string `json:"jwksURL,omitempty"` + JwksURL string `yaml:"jwksURL,omitempty"` // PublicKeyFiles is a list of paths pointing to public key files in PEM format to use // for verifying JWT tokens - PublicKeyFiles []string `json:"publicKeyFiles,omitempty"` + PublicKeyFiles []string `yaml:"publicKeyFiles,omitempty"` // EmailClaim indicates which claim contains the user email, // default set to 'email' - EmailClaim string `json:"emailClaim,omitempty"` + EmailClaim string `yaml:"emailClaim,omitempty"` // GroupsClaim indicates which claim contains the user groups // default set to 'groups' - GroupsClaim string `json:"groupsClaim,omitempty"` + GroupsClaim string `yaml:"groupsClaim,omitempty"` // UserIDClaim indicates which claim contains the user ID // default set to 'email' - UserIDClaim string `json:"userIDClaim,omitempty"` + UserIDClaim string `yaml:"userIDClaim,omitempty"` // AudienceClaim allows to define any claim that is verified against the client id // By default `aud` claim is used for verification. - AudienceClaims []string `json:"audienceClaims,omitempty"` + AudienceClaims []string `yaml:"audienceClaims,omitempty"` // ExtraAudiences is a list of additional audiences that are allowed // to pass verification in addition to the client id. - ExtraAudiences []string `json:"extraAudiences,omitempty"` + ExtraAudiences []string `yaml:"extraAudiences,omitempty"` } type LoginGovOptions struct { // JWTKey is a private key in PEM format used to sign JWT, - JWTKey string `json:"jwtKey,omitempty"` + JWTKey string `yaml:"jwtKey,omitempty"` // JWTKeyFile is a path to the private key file in PEM format used to sign the JWT - JWTKeyFile string `json:"jwtKeyFile,omitempty"` + JWTKeyFile string `yaml:"jwtKeyFile,omitempty"` // PubJWKURL is the JWK pubkey access endpoint - PubJWKURL string `json:"pubjwkURL,omitempty"` + PubJWKURL string `yaml:"pubjwkURL,omitempty"` } func providerDefaults() Providers { diff --git a/pkg/apis/options/secret_source.go b/pkg/apis/options/secret_source.go index 2be4d890dc..9d82c6059a 100644 --- a/pkg/apis/options/secret_source.go +++ b/pkg/apis/options/secret_source.go @@ -4,11 +4,11 @@ package options // Only one source within the struct should be defined at any time. type SecretSource struct { // Value expects a base64 encoded string value. - Value string `json:"value,omitempty"` + Value string `yaml:"value,omitempty"` // FromEnv expects the name of an environment variable. - FromEnv string `json:"fromEnv,omitempty"` + FromEnv string `yaml:"fromEnv,omitempty"` // FromFile expects a path to a file containing the secret value. - FromFile string `json:"fromFile,omitempty"` + FromFile string `yaml:"fromFile,omitempty"` } diff --git a/pkg/apis/options/server.go b/pkg/apis/options/server.go index f423ef2c97..8fa41af878 100644 --- a/pkg/apis/options/server.go +++ b/pkg/apis/options/server.go @@ -4,15 +4,15 @@ package options type Server struct { // BindAddress is the address on which to serve traffic. // Leave blank or set to "-" to disable. - BindAddress string + BindAddress string `yaml:"bindAddress,omitempty"` // SecureBindAddress is the address on which to serve secure traffic. // Leave blank or set to "-" to disable. - SecureBindAddress string + SecureBindAddress string `yaml:"secureBindAddress,omitempty"` // TLS contains the information for loading the certificate and key for the // secure traffic and further configuration for the TLS server. - TLS *TLS + TLS *TLS `yaml:"tls,omitempty"` } // TLS contains the information for loading a TLS certificate and key @@ -20,15 +20,15 @@ type Server struct { type TLS struct { // Key is the TLS key data to use. // Typically this will come from a file. - Key *SecretSource + Key *SecretSource `yaml:"key,omitempty"` // Cert is the TLS certificate data to use. // Typically this will come from a file. - Cert *SecretSource + Cert *SecretSource `yaml:"cert,omitempty"` // MinVersion is the minimal TLS version that is acceptable. // E.g. Set to "TLS1.3" to select TLS version 1.3 - MinVersion string + MinVersion string `yaml:"minVersion,omitempty"` // CipherSuites is a list of TLS cipher suites that are allowed. // E.g.: @@ -36,5 +36,5 @@ type TLS struct { // - TLS_RSA_WITH_AES_256_GCM_SHA384 // If not specified, the default Go safe cipher list is used. // List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). - CipherSuites []string + CipherSuites []string `yaml:"cipherSuites,omitempty"` } diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index 1002ae0744..b32cc27d03 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -14,11 +14,11 @@ const ( type UpstreamConfig struct { // ProxyRawPath will pass the raw url path to upstream allowing for urls // like: "/%2F/" which would otherwise be redirected to "/" - ProxyRawPath bool `json:"proxyRawPath,omitempty"` + ProxyRawPath bool `yaml:"proxyRawPath,omitempty"` // Upstreams represents the configuration for the upstream servers. // Requests will be proxied to this upstream if the path matches the request path. - Upstreams []Upstream `json:"upstreams,omitempty"` + Upstreams []Upstream `yaml:"upstreams,omitempty"` } // Upstream represents the configuration for an upstream server. @@ -26,7 +26,7 @@ type UpstreamConfig struct { type Upstream struct { // ID should be a unique identifier for the upstream. // This value is required for all upstreams. - ID string `json:"id,omitempty"` + ID string `yaml:"id,omitempty"` // Path is used to map requests to the upstream server. // The closest match will take precedence and all Paths must be unique. @@ -36,7 +36,7 @@ type Upstream struct { // - `^/foo$`: Match only the explicit path `/foo` // - `^/bar/$`: Match any path prefixed with `/bar/` // - `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget - Path string `json:"path,omitempty"` + Path string `yaml:"path,omitempty"` // RewriteTarget allows users to rewrite the request path before it is sent to // the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem @@ -46,7 +46,7 @@ type Upstream struct { // the request `/baz/abc/123` to `/foo/abc/123` before proxying to the // upstream server. Or if the upstream were `file:///app`, a request for // `/baz/info.html` would return the contents of the file `/app/foo/info.html`. - RewriteTarget string `json:"rewriteTarget,omitempty"` + RewriteTarget string `yaml:"rewriteTarget,omitempty"` // The URI of the upstream server. This may be an HTTP(S) server of a File // based URL. It may include a path, in which case all requests will be served @@ -58,43 +58,43 @@ type Upstream struct { // - file://host/path // If the URI's path is "/base" and the incoming request was for "/dir", // the upstream request will be for "/base/dir". - URI string `json:"uri,omitempty"` + URI string `yaml:"uri,omitempty"` // InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts. // This option is insecure and will allow potential Man-In-The-Middle attacks // between OAuth2 Proxy and the upstream server. // Defaults to false. - InsecureSkipTLSVerify bool `json:"insecureSkipTLSVerify,omitempty"` + InsecureSkipTLSVerify bool `yaml:"insecureSkipTLSVerify,omitempty"` // Static will make all requests to this upstream have a static response. // The response will have a body of "Authenticated" and a response code // matching StaticCode. // If StaticCode is not set, the response will return a 200 response. - Static bool `json:"static,omitempty"` + Static bool `yaml:"static,omitempty"` // StaticCode determines the response code for the Static response. // This option can only be used with Static enabled. - StaticCode *int `json:"staticCode,omitempty"` + StaticCode *int `yaml:"staticCode,omitempty"` // FlushInterval is the period between flushing the response buffer when // streaming response from the upstream. // Defaults to 1 second. - FlushInterval *time.Duration `json:"flushInterval,omitempty"` + FlushInterval *time.Duration `yaml:"flushInterval,omitempty"` // PassHostHeader determines whether the request host header should be proxied // to the upstream server. // Defaults to true. - PassHostHeader *bool `json:"passHostHeader,omitempty"` + PassHostHeader *bool `yaml:"passHostHeader,omitempty"` // ProxyWebSockets enables proxying of websockets to upstream servers // Defaults to true. - ProxyWebSockets *bool `json:"proxyWebSockets,omitempty"` + ProxyWebSockets *bool `yaml:"proxyWebSockets,omitempty"` // Timeout is the maximum duration the server will wait for a response from the upstream server. // Defaults to 30 seconds. - Timeout *time.Duration `json:"timeout,omitempty"` + Timeout *time.Duration `yaml:"timeout,omitempty"` // DisableKeepAlives disables HTTP keep-alive connections to the upstream server. // Defaults to false. - DisableKeepAlives bool `json:"disableKeepAlives,omitempty"` + DisableKeepAlives bool `yaml:"disableKeepAlives,omitempty"` } diff --git a/pkg/requests/result_test.go b/pkg/requests/result_test.go index b6ecee74bd..7607397528 100644 --- a/pkg/requests/result_test.go +++ b/pkg/requests/result_test.go @@ -104,8 +104,8 @@ var _ = Describe("Result suite", func() { Context("UnmarshalInto", func() { type testStruct struct { - A string `json:"a"` - B int `json:"b"` + A string `yaml:"a"` + B int `yaml:"b"` } type unmarshalIntoTableInput struct { From 4c0dd28f129d9ac402c4f8eabe0b88f0d10b393b Mon Sep 17 00:00:00 2001 From: tuunit Date: Sun, 9 Feb 2025 19:29:06 +0100 Subject: [PATCH 075/125] fix alpha config example Signed-off-by: Jan Larwig --- .../oauth2-proxy-alpha-config.cfg | 3 +- .../oauth2-proxy-alpha-config.yaml | 50 +++++++++++-------- 2 files changed, 30 insertions(+), 23 deletions(-) diff --git a/contrib/local-environment/oauth2-proxy-alpha-config.cfg b/contrib/local-environment/oauth2-proxy-alpha-config.cfg index 89e5a5b24f..c913ec4fce 100644 --- a/contrib/local-environment/oauth2-proxy-alpha-config.cfg +++ b/contrib/local-environment/oauth2-proxy-alpha-config.cfg @@ -1,5 +1,4 @@ -http_address="0.0.0.0:4180" cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w=" email_domains="example.com" cookie_secure="false" -redirect_url="http://localhost:4180/oauth2/callback" +redirect_url="http://oauth2-proxy.localtest.me:4180/oauth2/callback" diff --git a/contrib/local-environment/oauth2-proxy-alpha-config.yaml b/contrib/local-environment/oauth2-proxy-alpha-config.yaml index b2c9f6a89e..41f07a03e8 100644 --- a/contrib/local-environment/oauth2-proxy-alpha-config.yaml +++ b/contrib/local-environment/oauth2-proxy-alpha-config.yaml @@ -1,23 +1,31 @@ -upstreams: - - id: httpbin - path: / - uri: http://httpbin +server: + bindAddress: "0.0.0.0:4180" +upstreamConfig: + upstreams: + - id: httpbin + path: / + uri: http://httpbin.localtest.me:8080 injectRequestHeaders: -- name: X-Forwarded-Groups - values: - - claim: groups -- name: X-Forwarded-User - values: - - claim: user -- name: X-Forwarded-Email - values: - - claim: email -- name: X-Forwarded-Preferred-Username - values: - - claim: preferred_username + - name: X-Forwarded-Groups + values: + - claimSource: + claim: groups + - name: X-Forwarded-User + values: + - claimSource: + claim: user + - name: X-Forwarded-Email + values: + - claimSource: + claim: email + - name: X-Forwarded-Preferred-Username + values: + - claimSource: + claim: preferred_username providers: -- provider: oidc - clientSecret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK - clientID: oauth2-proxy - oidcConfig: - issuerURL: http://dex.localhost:5556/dex + - id: oidc + provider: oidc + clientSecret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK + clientID: oauth2-proxy + oidcConfig: + issuerURL: http://dex.localhost:5556/dex From 18fc89812914991648664e707fb55b2f434fa53a Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 24 May 2025 17:05:33 +0200 Subject: [PATCH 076/125] resolve cipher deprecation and update mapstructures v2 Signed-off-by: Jan Larwig --- go.mod | 1 - go.sum | 2 -- pkg/apis/options/duration.go | 2 +- pkg/encryption/cipher.go | 2 +- 4 files changed, 2 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index 9e353b0aa0..be7de03bc7 100644 --- a/go.mod +++ b/go.mod @@ -19,7 +19,6 @@ require ( github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 github.com/justinas/alice v1.2.0 - github.com/mitchellh/mapstructure v1.5.0 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 github.com/onsi/ginkgo/v2 v2.23.4 github.com/onsi/gomega v1.38.0 diff --git a/go.sum b/go.sum index 34aca12f60..0928296985 100644 --- a/go.sum +++ b/go.sum @@ -91,8 +91,6 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0 github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/matryer/is v1.2.0 h1:92UTHpy8CDwaJ08GqLDzhhuixiBUUD1p3AU6PHddz4A= github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA= -github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= -github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk= diff --git a/pkg/apis/options/duration.go b/pkg/apis/options/duration.go index da13d96ecd..15f8776da3 100644 --- a/pkg/apis/options/duration.go +++ b/pkg/apis/options/duration.go @@ -4,7 +4,7 @@ import ( "reflect" "time" - "github.com/mitchellh/mapstructure" + "github.com/go-viper/mapstructure/v2" ) // Duration is an alias for time.Duration so that we can ensure the marshalling diff --git a/pkg/encryption/cipher.go b/pkg/encryption/cipher.go index 300bba3a22..ae5b50a367 100644 --- a/pkg/encryption/cipher.go +++ b/pkg/encryption/cipher.go @@ -79,7 +79,7 @@ func (c *cfbCipher) Decrypt(ciphertext []byte) ([]byte, error) { iv, ciphertext := ciphertext[:aes.BlockSize], ciphertext[aes.BlockSize:] plaintext := make([]byte, len(ciphertext)) - stream := cipher.NewCFBDecrypter(c.Block, iv) //nolint:staticcheck + stream := cipher.NewCFBEncrypter(c.Block, iv) //nolint:staticcheck stream.XORKeyStream(plaintext, ciphertext) return plaintext, nil From aaf1889b97ec265c6692a5a6663a812b83008ae8 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 24 May 2025 20:06:36 +0200 Subject: [PATCH 077/125] fix alpha config Signed-off-by: Jan Larwig --- docs/docs/configuration/alpha_config.md | 228 ++++++++++++------------ pkg/apis/options/doc.go | 2 +- pkg/encryption/cipher.go | 2 +- 3 files changed, 116 insertions(+), 116 deletions(-) diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index 54dfb9f1da..da48fafb27 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -148,7 +148,7 @@ You must remove these options before starting OAuth2 Proxy with `--alpha-config` | Field | Type | Description | | ----- | ---- | ----------- | -| `SkipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | +| `skipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | ### AlphaOptions @@ -163,12 +163,12 @@ They may change between releases without notice. | Field | Type | Description | | ----- | ---- | ----------- | -| `UpstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | -| `InjectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | -| `InjectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | -| `Server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | -| `MetricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | -| `Providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | +| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | +| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | ### AzureOptions @@ -178,8 +178,8 @@ They may change between releases without notice. | Field | Type | Description | | ----- | ---- | ----------- | -| `Tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | -| `GraphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | +| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | +| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | ### BitbucketOptions @@ -189,8 +189,8 @@ They may change between releases without notice. | Field | Type | Description | | ----- | ---- | ----------- | -| `Team` | _string_ | Team sets restrict logins to members of this team | -| `Repository` | _string_ | Repository sets restrict logins to user with access to this repository | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repository` | _string_ | Repository sets restrict logins to user with access to this repository | ### ClaimSource @@ -200,9 +200,9 @@ ClaimSource allows loading a header value from a claim within the session | Field | Type | Description | | ----- | ---- | ----------- | -| `Claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | -| `Prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | -| `BasicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | ### GitHubOptions @@ -212,11 +212,11 @@ ClaimSource allows loading a header value from a claim within the session | Field | Type | Description | | ----- | ---- | ----------- | -| `Org` | _string_ | Org sets restrict logins to members of this organisation | -| `Team` | _string_ | Team sets restrict logins to members of this team | -| `Repo` | _string_ | Repo sets restrict logins to collaborators of this repository | -| `Token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | -| `Users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | +| `org` | _string_ | Org sets restrict logins to members of this organisation | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository | +| `token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | +| `users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | ### GitLabOptions @@ -226,8 +226,8 @@ ClaimSource allows loading a header value from a claim within the session | Field | Type | Description | | ----- | ---- | ----------- | -| `Group` | _[]string_ | Group sets restrict logins to members of this group | -| `Projects` | _[]string_ | Projects restricts logins to members of these projects | +| `group` | _[]string_ | Group sets restrict logins to members of this group | +| `projects` | _[]string_ | Projects restricts logins to members of these projects | ### GoogleOptions @@ -237,13 +237,13 @@ ClaimSource allows loading a header value from a claim within the session | Field | Type | Description | | ----- | ---- | ----------- | -| `Groups` | _[]string_ | Groups sets restrict logins to members of this Google group | -| `AdminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | -| `ServiceAccountJSON` | _string_ | ServiceAccountJSON is the path to the service account json credentials | -| `UseApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | -| `TargetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | -| `UseOrganizationID` | _bool_ | UseOrganizationId indicates whether to use the organization ID as the UserName claim | -| `AdminAPIUserScope` | _string_ | admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly | +| `group` | _[]string_ | Groups sets restrict logins to members of this Google group | +| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | +| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | +| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | +| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | +| `useOrganizationID` | _bool_ | UseOrganizationId indicates whether to use the organization ID as the UserName claim | +| `adminAPIUserScope` | _string_ | admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly | ### Header @@ -254,10 +254,10 @@ response header. | Field | Type | Description | | ----- | ---- | ----------- | -| `Name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | -| `PreserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | +| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | | `InsecureSkipHeaderNormalization` | _bool_ | InsecureSkipHeaderNormalization disables normalizing the header name
According to RFC 7230 Section 3.2 there aren't any rules about
capitalization of header names, but the standard practice is to use
Title-Case (e.g. X-Forwarded-For). By default, header names will be
normalized to Title-Case and any incoming headers that match will be
treated as the same header. Additionally underscores (_) in header names
will be converted to dashes (-) when normalizing.
Defaults to false (header names will be normalized). | -| `Values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | +| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | ### HeaderValue @@ -268,12 +268,12 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `Value` | _string_ | Value expects a base64 encoded string value. | -| `FromEnv` | _string_ | FromEnv expects the name of an environment variable. | -| `FromFile` | _string_ | FromFile expects a path to a file containing the secret value. | -| `Claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | -| `Prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | -| `BasicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | +| `value` | _string_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | ### KeycloakOptions @@ -283,8 +283,8 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `Groups` | _[]string_ | Group enables to restrict login to members of indicated group | -| `Roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | +| `groups` | _[]string_ | Group enables to restrict login to members of indicated group | +| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | ### LoginGovOptions @@ -294,9 +294,9 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `JWTKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | -| `JWTKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | -| `PubJWKURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | +| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | +| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | +| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | ### LoginURLParameter @@ -374,9 +374,9 @@ character. | Field | Type | Description | | ----- | ---- | ----------- | -| `Name` | _string_ | Name specifies the name of the query parameter. | -| `Default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | -| `Allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | +| `name` | _string_ | Name specifies the name of the query parameter. | +| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | +| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | ### MicrosoftEntraIDOptions @@ -386,8 +386,8 @@ character. | Field | Type | Description | | ----- | ---- | ----------- | -| `AllowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | -| `FederatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | +| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | +| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | ### OIDCOptions @@ -397,18 +397,18 @@ character. | Field | Type | Description | | ----- | ---- | ----------- | -| `IssuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | -| `InsecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | -| `InsecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | -| `InsecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | -| `SkipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | -| `JwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | -| `PublicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | -| `EmailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | -| `GroupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | -| `UserIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | -| `AudienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | -| `ExtraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | +| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | +| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | +| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | +| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | +| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | +| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | +| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | +| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | +| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | +| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | +| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | +| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | ### Provider @@ -418,36 +418,36 @@ Provider holds all configuration for a single provider | Field | Type | Description | | ----- | ---- | ----------- | -| `ClientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | -| `ClientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | -| `ClientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | -| `KeycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | -| `AzureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | -| `MicrosoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | +| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | +| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | +| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | +| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | +| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | +| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | | `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. | -| `BitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | -| `GitHubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | -| `GitLabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | -| `GoogleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | -| `OIDCConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | -| `LoginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | -| `ID` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | -| `Type` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | -| `Name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | -| `CAFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | -| `UseSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | -| `LoginURL` | _string_ | LoginURL is the authentication endpoint | -| `LoginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | -| `AuthRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | -| `RedeemURL` | _string_ | RedeemURL is the token redemption endpoint | -| `ProfileURL` | _string_ | ProfileURL is the profile access endpoint | -| `SkipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | -| `ProtectedResource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | -| `ValidateURL` | _string_ | ValidateURL is the access token validation endpoint | -| `Scope` | _string_ | Scope is the OAuth scope specification | -| `AllowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | -| `CodeChallengeMethod` | _string_ | The code challenge method | -| `BackendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | +| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | +| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | +| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | +| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | +| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | +| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | +| `id` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | +| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | +| `name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | +| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | +| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | +| `loginURL` | _string_ | LoginURL is the authentication endpoint | +| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | +| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | +| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint | +| `profileURL` | _string_ | ProfileURL is the profile access endpoint | +| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | +| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | +| `validateURL` | _string_ | ValidateURL is the access token validation endpoint | +| `scope` | _string_ | Scope is the OAuth scope specification | +| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | +| `code_challenge_method` | _string_ | The code challenge method | +| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | ### ProviderType #### (`string` alias) @@ -480,9 +480,9 @@ Only one source within the struct should be defined at any time. | Field | Type | Description | | ----- | ---- | ----------- | -| `Value` | _string_ | Value expects a base64 encoded string value. | -| `FromEnv` | _string_ | FromEnv expects the name of an environment variable. | -| `FromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `value` | _string_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | ### Server @@ -492,9 +492,9 @@ Server represents the configuration for an HTTP(S) server | Field | Type | Description | | ----- | ---- | ----------- | -| `BindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Leave blank or set to "-" to disable. | -| `SecureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Leave blank or set to "-" to disable. | -| `TLS` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the
secure traffic and further configuration for the TLS server. | +| `bindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Leave blank or set to "-" to disable. | +| `secureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Leave blank or set to "-" to disable. | +| `tls` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the
secure traffic and further configuration for the TLS server. | ### TLS @@ -505,10 +505,10 @@ as well as an optional minimal TLS version that is acceptable. | Field | Type | Description | | ----- | ---- | ----------- | -| `Key` | _[SecretSource](#secretsource)_ | Key is the TLS key data to use.
Typically this will come from a file. | -| `Cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.
Typically this will come from a file. | -| `MinVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.
E.g. Set to "TLS1.3" to select TLS version 1.3 | -| `CipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.
E.g.:
- TLS_RSA_WITH_RC4_128_SHA
- TLS_RSA_WITH_AES_256_GCM_SHA384
If not specified, the default Go safe cipher list is used.
List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | +| `key` | _[SecretSource](#secretsource)_ | Key is the TLS key data to use.
Typically this will come from a file. | +| `cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.
Typically this will come from a file. | +| `minVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.
E.g. Set to "TLS1.3" to select TLS version 1.3 | +| `cipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.
E.g.:
- TLS_RSA_WITH_RC4_128_SHA
- TLS_RSA_WITH_AES_256_GCM_SHA384
If not specified, the default Go safe cipher list is used.
List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | ### URLParameterRule @@ -521,8 +521,8 @@ login URL. Either Value or Pattern should be supplied, not both. | Field | Type | Description | | ----- | ---- | ----------- | -| `Value` | _string_ | A Value rule matches just this specific value | -| `Pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | +| `value` | _string_ | A Value rule matches just this specific value | +| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | ### Upstream @@ -533,18 +533,18 @@ Requests will be proxied to this upstream if the path matches the request path. | Field | Type | Description | | ----- | ---- | ----------- | -| `ID` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | -| `Path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | -| `RewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | -| `URI` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | -| `InsecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | -| `Static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | -| `StaticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | -| `FlushInterval` | _duration_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | -| `PassHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | -| `ProxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | -| `Timeout` | _duration_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | -| `DisableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | +| `id` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | +| `path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | +| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | +| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | +| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | +| `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | +| `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | +| `flushInterval` | _duration_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | +| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | +| `timeout` | _duration_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | +| `disableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | ### UpstreamConfig @@ -554,5 +554,5 @@ UpstreamConfig is a collection of definitions for upstream servers. | Field | Type | Description | | ----- | ---- | ----------- | -| `ProxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | -| `Upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | +| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | +| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | diff --git a/pkg/apis/options/doc.go b/pkg/apis/options/doc.go index 8ef112dd82..d4b8862d9f 100644 --- a/pkg/apis/options/doc.go +++ b/pkg/apis/options/doc.go @@ -1,3 +1,3 @@ -//go:generate -command reference-gen go run github.com/oauth2-proxy/tools/reference-gen/cmd/reference-gen@v0.0.0-20220223111546-d3b50d1a591a +//go:generate -command reference-gen go run github.com/oauth2-proxy/tools/reference-gen/cmd/reference-gen@v0.0.0-20250404153144-32055bc45bc3 //go:generate reference-gen --package github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options --types AlphaOptions --header-file ../../../docs/docs/configuration/alpha_config.md.tmpl --out-file ../../../docs/docs/configuration/alpha_config.md package options diff --git a/pkg/encryption/cipher.go b/pkg/encryption/cipher.go index ae5b50a367..300bba3a22 100644 --- a/pkg/encryption/cipher.go +++ b/pkg/encryption/cipher.go @@ -79,7 +79,7 @@ func (c *cfbCipher) Decrypt(ciphertext []byte) ([]byte, error) { iv, ciphertext := ciphertext[:aes.BlockSize], ciphertext[aes.BlockSize:] plaintext := make([]byte, len(ciphertext)) - stream := cipher.NewCFBEncrypter(c.Block, iv) //nolint:staticcheck + stream := cipher.NewCFBDecrypter(c.Block, iv) //nolint:staticcheck stream.XORKeyStream(plaintext, ciphertext) return plaintext, nil From 810f629ee8844dc56db3605588cc5fdf0e82fbbe Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 25 Jul 2025 13:29:22 +0200 Subject: [PATCH 078/125] revert: secrets as []byte instead of string Signed-off-by: Jan Larwig --- docs/docs/configuration/alpha_config.md | 4 ++-- main_test.go | 2 +- oauthproxy_test.go | 6 +++--- pkg/apis/options/legacy_options.go | 2 +- pkg/apis/options/legacy_options_test.go | 4 ++-- pkg/apis/options/load_test.go | 2 +- pkg/apis/options/secret_source.go | 4 ++-- pkg/apis/options/util/util.go | 2 +- pkg/apis/options/util/util_test.go | 2 +- pkg/header/injector_test.go | 16 ++++++++-------- pkg/http/http_suite_test.go | 12 ++++++------ pkg/http/server_test.go | 8 ++++---- pkg/middleware/headers_test.go | 8 ++++---- pkg/validation/common_test.go | 4 ++-- pkg/validation/header.go | 2 ++ pkg/validation/header_test.go | 4 ++-- 16 files changed, 42 insertions(+), 40 deletions(-) diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index da48fafb27..c2c0aca657 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -268,7 +268,7 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _string_ | Value expects a base64 encoded string value. | +| `value` | _[]byte_ | Value expects a base64 encoded []byte | | `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | | `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | | `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | @@ -480,7 +480,7 @@ Only one source within the struct should be defined at any time. | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _string_ | Value expects a base64 encoded string value. | +| `value` | _[]byte_ | Value expects a base64 encoded []byte | | `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | | `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | diff --git a/main_test.go b/main_test.go index 7de1ac72b2..60b7eafdf5 100644 --- a/main_test.go +++ b/main_test.go @@ -139,7 +139,7 @@ redirect_url="http://localhost:4180/oauth2/callback" Claim: "user", Prefix: "Basic ", BasicAuthPassword: &options.SecretSource{ - Value: "super-secret-password", + Value: []byte("super-secret-password"), }, }, }, diff --git a/oauthproxy_test.go b/oauthproxy_test.go index d5fac782c9..44569a3583 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -215,7 +215,7 @@ func TestBasicAuthPassword(t *testing.T) { ClaimSource: &options.ClaimSource{ Claim: "email", BasicAuthPassword: &options.SecretSource{ - Value: basicAuthPassword, + Value: []byte(basicAuthPassword), }, }, }, @@ -1282,7 +1282,7 @@ func TestAuthOnlyEndpointSetBasicAuthTrueRequestHeaders(t *testing.T) { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: "This is a secure password", + Value: []byte("This is a secure password"), }, }, }, @@ -2044,7 +2044,7 @@ func baseTestOptions() *options.Options { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: base64.StdEncoding.EncodeToString([]byte("This is a secure password")), + Value: []byte(base64.StdEncoding.EncodeToString([]byte("This is a secure password"))), }, }, }, diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index 45e4b11369..ec779d8490 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -294,7 +294,7 @@ func getBasicAuthHeader(preferEmailToUser bool, basicAuthPassword string) Header Claim: claim, Prefix: "Basic ", BasicAuthPassword: &SecretSource{ - Value: basicAuthPassword, + Value: []byte(basicAuthPassword), }, }, }, diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index c5f0e4da64..98a89601a2 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -369,7 +369,7 @@ var _ = Describe("Legacy Options", func() { Claim: "user", Prefix: "Basic ", BasicAuthPassword: &SecretSource{ - Value: basicAuthSecret, + Value: []byte(basicAuthSecret), }, }, }, @@ -409,7 +409,7 @@ var _ = Describe("Legacy Options", func() { Claim: "email", Prefix: "Basic ", BasicAuthPassword: &SecretSource{ - Value: basicAuthSecret, + Value: []byte(basicAuthSecret), }, }, }, diff --git a/pkg/apis/options/load_test.go b/pkg/apis/options/load_test.go index a007926725..29d6511eb8 100644 --- a/pkg/apis/options/load_test.go +++ b/pkg/apis/options/load_test.go @@ -581,7 +581,7 @@ injectResponseHeaders: Values: []HeaderValue{ { SecretSource: &SecretSource{ - Value: "secret", + Value: []byte("secret"), }, }, }, diff --git a/pkg/apis/options/secret_source.go b/pkg/apis/options/secret_source.go index 9d82c6059a..e73d019fcc 100644 --- a/pkg/apis/options/secret_source.go +++ b/pkg/apis/options/secret_source.go @@ -3,8 +3,8 @@ package options // SecretSource references an individual secret value. // Only one source within the struct should be defined at any time. type SecretSource struct { - // Value expects a base64 encoded string value. - Value string `yaml:"value,omitempty"` + // Value expects a base64 encoded []byte + Value []byte `yaml:"value,omitempty"` // FromEnv expects the name of an environment variable. FromEnv string `yaml:"fromEnv,omitempty"` diff --git a/pkg/apis/options/util/util.go b/pkg/apis/options/util/util.go index 794a6e91fd..03f0a13469 100644 --- a/pkg/apis/options/util/util.go +++ b/pkg/apis/options/util/util.go @@ -11,7 +11,7 @@ import ( func GetSecretValue(source *options.SecretSource) ([]byte, error) { switch { case len(source.Value) > 0 && source.FromEnv == "" && source.FromFile == "": - return []byte(source.Value), nil + return source.Value, nil case len(source.Value) == 0 && source.FromEnv != "" && source.FromFile == "": return []byte(os.Getenv(source.FromEnv)), nil case len(source.Value) == 0 && source.FromEnv == "" && source.FromFile != "": diff --git a/pkg/apis/options/util/util_test.go b/pkg/apis/options/util/util_test.go index 5c4bfa6d96..e84db1ec0b 100644 --- a/pkg/apis/options/util/util_test.go +++ b/pkg/apis/options/util/util_test.go @@ -31,7 +31,7 @@ var _ = Describe("GetSecretValue", func() { It("returns the correct value from the string value", func() { value, err := GetSecretValue(&options.SecretSource{ - Value: "secret-value-1", + Value: []byte("secret-value-1"), }) Expect(err).ToNot(HaveOccurred()) Expect(string(value)).To(Equal("secret-value-1")) diff --git a/pkg/header/injector_test.go b/pkg/header/injector_test.go index bb37261dc7..25c276dcf7 100644 --- a/pkg/header/injector_test.go +++ b/pkg/header/injector_test.go @@ -55,7 +55,7 @@ var _ = Describe("Injector Suite", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: "super-secret", + Value: []byte("super-secret"), }, }, }, @@ -199,7 +199,7 @@ var _ = Describe("Injector Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: "basic-password", + Value: []byte("basic-password"), }, }, }, @@ -227,7 +227,7 @@ var _ = Describe("Injector Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: base64.StdEncoding.EncodeToString([]byte("basic-password")), + Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))), }, }, }, @@ -322,7 +322,7 @@ var _ = Describe("Injector Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: base64.StdEncoding.EncodeToString([]byte("basic-password")), + Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))), FromEnv: "SECRET_ENV", }, }, @@ -348,7 +348,7 @@ var _ = Describe("Injector Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: "basic-password", + Value: []byte("basic-password"), }, }, }, @@ -379,17 +379,17 @@ var _ = Describe("Injector Suite", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: "major=1", + Value: []byte("major=1"), }, }, { SecretSource: &options.SecretSource{ - Value: "minor=2", + Value: []byte("minor=2"), }, }, { SecretSource: &options.SecretSource{ - Value: "patch=3", + Value: []byte("patch=3"), }, }, }, diff --git a/pkg/http/http_suite_test.go b/pkg/http/http_suite_test.go index 219f26ea0e..19d4d3ff39 100644 --- a/pkg/http/http_suite_test.go +++ b/pkg/http/http_suite_test.go @@ -48,10 +48,10 @@ var _ = BeforeSuite(func() { certOut := new(bytes.Buffer) Expect(pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes})).To(Succeed()) - ipv4CertDataSource.Value = certOut.String() + ipv4CertDataSource.Value = certOut.Bytes() keyOut := new(bytes.Buffer) Expect(pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes})).To(Succeed()) - ipv4KeyDataSource.Value = keyOut.String() + ipv4KeyDataSource.Value = keyOut.Bytes() }) By("Generating a ipv6 self-signed cert for TLS tests", func() { @@ -61,16 +61,16 @@ var _ = BeforeSuite(func() { certOut := new(bytes.Buffer) Expect(pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes})).To(Succeed()) - ipv6CertDataSource.Value = certOut.String() + ipv6CertDataSource.Value = certOut.Bytes() keyOut := new(bytes.Buffer) Expect(pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes})).To(Succeed()) - ipv6KeyDataSource.Value = keyOut.String() + ipv6KeyDataSource.Value = keyOut.Bytes() }) By("Setting up a http client", func() { - ipv4cert, err := tls.X509KeyPair([]byte(ipv4CertDataSource.Value), []byte(ipv4KeyDataSource.Value)) + ipv4cert, err := tls.X509KeyPair(ipv4CertDataSource.Value, ipv4KeyDataSource.Value) Expect(err).ToNot(HaveOccurred()) - ipv6cert, err := tls.X509KeyPair([]byte(ipv6CertDataSource.Value), []byte(ipv6KeyDataSource.Value)) + ipv6cert, err := tls.X509KeyPair(ipv6CertDataSource.Value, ipv6KeyDataSource.Value) Expect(err).ToNot(HaveOccurred()) ipv4certificate, err := x509.ParseCertificate(ipv4cert.Certificate[0]) diff --git a/pkg/http/server_test.go b/pkg/http/server_test.go index 6584b75736..8dfa13afad 100644 --- a/pkg/http/server_test.go +++ b/pkg/http/server_test.go @@ -234,7 +234,7 @@ var _ = Describe("Server", func() { SecureBindAddress: "127.0.0.1:0", TLS: &options.TLS{ Key: &options.SecretSource{ - Value: "invalid", + Value: []byte("invalid"), }, Cert: &ipv4CertDataSource, }, @@ -250,7 +250,7 @@ var _ = Describe("Server", func() { TLS: &options.TLS{ Key: &ipv4KeyDataSource, Cert: &options.SecretSource{ - Value: "invalid", + Value: []byte("invalid"), }, }, }, @@ -506,7 +506,7 @@ var _ = Describe("Server", func() { SecureBindAddress: "[::1]:0", TLS: &options.TLS{ Key: &options.SecretSource{ - Value: "invalid", + Value: []byte("invalid"), }, Cert: &ipv6CertDataSource, }, @@ -523,7 +523,7 @@ var _ = Describe("Server", func() { TLS: &options.TLS{ Key: &ipv6KeyDataSource, Cert: &options.SecretSource{ - Value: "invalid", + Value: []byte("invalid"), }, }, }, diff --git a/pkg/middleware/headers_test.go b/pkg/middleware/headers_test.go index cb8f9d110e..6a60ec0162 100644 --- a/pkg/middleware/headers_test.go +++ b/pkg/middleware/headers_test.go @@ -188,7 +188,7 @@ var _ = Describe("Headers Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: base64.StdEncoding.EncodeToString([]byte("basic-password")), + Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))), FromEnv: "SECRET_ENV", }, }, @@ -304,7 +304,7 @@ var _ = Describe("Headers Suite", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: "_oauth2_proxy=ey123123123", + Value: []byte("_oauth2_proxy=ey123123123"), }, }, }, @@ -314,7 +314,7 @@ var _ = Describe("Headers Suite", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: "oauth_user", + Value: []byte("oauth_user"), }, }, }, @@ -460,7 +460,7 @@ var _ = Describe("Headers Suite", func() { ClaimSource: &options.ClaimSource{ Claim: "user", BasicAuthPassword: &options.SecretSource{ - Value: base64.StdEncoding.EncodeToString([]byte("basic-password")), + Value: []byte(base64.StdEncoding.EncodeToString([]byte("basic-password"))), FromEnv: "SECRET_ENV", }, }, diff --git a/pkg/validation/common_test.go b/pkg/validation/common_test.go index bb7c2dd6aa..9e873c357b 100644 --- a/pkg/validation/common_test.go +++ b/pkg/validation/common_test.go @@ -9,12 +9,12 @@ import ( ) var _ = Describe("Common", func() { - var validSecretSourceValue string + var validSecretSourceValue []byte const validSecretSourceEnv = "OAUTH2_PROXY_TEST_SECRET_SOURCE_ENV" var validSecretSourceFile string BeforeEach(func() { - validSecretSourceValue = "This is a secret source value" + validSecretSourceValue = []byte("This is a secret source value") Expect(os.Setenv(validSecretSourceEnv, "This is a secret source env")).To(Succeed()) tmp, err := os.CreateTemp("", "oauth2-proxy-secret-source-test") Expect(err).ToNot(HaveOccurred()) diff --git a/pkg/validation/header.go b/pkg/validation/header.go index 713113f414..b125814465 100644 --- a/pkg/validation/header.go +++ b/pkg/validation/header.go @@ -51,9 +51,11 @@ func validateHeaderValue(_ string, value options.HeaderValue) []string { func validateHeaderValueClaimSource(claim options.ClaimSource) []string { msgs := []string{} + if claim.Claim == "" { msgs = append(msgs, "claim should not be empty") } + if claim.BasicAuthPassword != nil { msgs = append(msgs, prefixValues("invalid basicAuthPassword: ", validateSecretSource(*claim.BasicAuthPassword))...) } diff --git a/pkg/validation/header_test.go b/pkg/validation/header_test.go index 88849ea171..2d9ef6ddcf 100644 --- a/pkg/validation/header_test.go +++ b/pkg/validation/header_test.go @@ -30,7 +30,7 @@ var _ = Describe("Headers", func() { Values: []options.HeaderValue{ { SecretSource: &options.SecretSource{ - Value: base64.StdEncoding.EncodeToString([]byte("secret")), + Value: []byte(base64.StdEncoding.EncodeToString([]byte("secret"))), }, }, }, @@ -43,7 +43,7 @@ var _ = Describe("Headers", func() { ClaimSource: &options.ClaimSource{ Claim: "email", BasicAuthPassword: &options.SecretSource{ - Value: base64.StdEncoding.EncodeToString([]byte("secret")), + Value: []byte(base64.StdEncoding.EncodeToString([]byte("secret"))), }, }, }, From 48bd2d7d3824682ce94b1aabb16f8e7e149c1961 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 25 Jul 2025 15:08:50 +0200 Subject: [PATCH 079/125] fix merge problems and test cases Signed-off-by: Jan Larwig --- main.go | 2 +- main_test.go | 16 ++++++++-------- pkg/apis/options/header.go | 2 +- pkg/apis/options/{duration.go => hooks.go} | 14 ++++++++++++++ .../options/{duration_test.go => hooks_test.go} | 16 +++++++++++++++- pkg/apis/options/load.go | 5 ++++- pkg/apis/options/load_test.go | 4 ++-- pkg/apis/options/providers.go | 12 ++++++------ pkg/apis/options/upstreams.go | 10 +++++----- 9 files changed, 56 insertions(+), 25 deletions(-) rename pkg/apis/options/{duration.go => hooks.go} (78%) rename pkg/apis/options/{duration_test.go => hooks_test.go} (83%) diff --git a/main.go b/main.go index a9def2f6a6..7142ae0b94 100644 --- a/main.go +++ b/main.go @@ -70,7 +70,7 @@ func main() { func loadConfiguration(config, yamlConfig string, extraFlags *pflag.FlagSet, args []string) (*options.Options, error) { opts, err := loadLegacyOptions(config, extraFlags, args) if err != nil { - return nil, fmt.Errorf("couldn't load legacy options: %w", err) + return nil, fmt.Errorf("failed to load legacy options: %w", err) } if yamlConfig != "" { diff --git a/main_test.go b/main_test.go index 60b7eafdf5..709c68571b 100644 --- a/main_test.go +++ b/main_test.go @@ -22,7 +22,7 @@ var _ = Describe("Configuration Loading Suite", func() { http_address="127.0.0.1:4180" upstreams="http://httpbin" set_basic_auth="true" -basic_auth_password="super-secret-password" +basic_auth_password="c3VwZXItc2VjcmV0LXBhc3N3b3Jk" client_id="oauth2-proxy" client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK" ` @@ -45,7 +45,7 @@ injectRequestHeaders: claim: user prefix: "Basic " basicAuthPassword: - value: super-secret-password + value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk - name: X-Forwarded-Groups values: - claimSource: @@ -69,12 +69,12 @@ injectResponseHeaders: claim: user prefix: "Basic " basicAuthPassword: - value: super-secret-password + value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk server: bindAddress: "127.0.0.1:4180" providers: -- provider: google - ID: google=oauth2-proxy +- id: google=oauth2-proxy + provider: google clientSecret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK clientID: oauth2-proxy azureConfig: @@ -139,7 +139,7 @@ redirect_url="http://localhost:4180/oauth2/callback" Claim: "user", Prefix: "Basic ", BasicAuthPassword: &options.SecretSource{ - Value: []byte("super-secret-password"), + Value: []byte("c3VwZXItc2VjcmV0LXBhc3N3b3Jk"), }, }, }, @@ -248,7 +248,7 @@ redirect_url="http://localhost:4180/oauth2/callback" Entry("with bad legacy configuration", loadConfigurationTableInput{ configContent: testCoreConfig + "unknown_field=\"something\"", expectedOptions: func() *options.Options { return nil }, - expectedErr: errors.New("failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"), + expectedErr: errors.New("failed to load legacy options: failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"), }), Entry("with bad alpha configuration", loadConfigurationTableInput{ configContent: testCoreConfig, @@ -260,7 +260,7 @@ redirect_url="http://localhost:4180/oauth2/callback" configContent: testCoreConfig + "unknown_field=\"something\"", alphaConfigContent: testAlphaConfig, expectedOptions: func() *options.Options { return nil }, - expectedErr: errors.New("failed to load core options: failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"), + expectedErr: errors.New("failed to load legacy options: failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"), }), ) }) diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index ab3916773b..a695d7d494 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -11,7 +11,7 @@ type Header struct { // should be preserved for the request to the upstream server. // This option only applies to injected request headers. // Defaults to false (headers that match this header will be stripped). - PreserveRequestValue bool `yaml:"preserveRequestValue,omitempty"` + PreserveRequestValue bool `yaml:"preserveRequestValue"` // InsecureSkipHeaderNormalization disables normalizing the header name // According to RFC 7230 Section 3.2 there aren't any rules about diff --git a/pkg/apis/options/duration.go b/pkg/apis/options/hooks.go similarity index 78% rename from pkg/apis/options/duration.go rename to pkg/apis/options/hooks.go index 15f8776da3..79653ecba6 100644 --- a/pkg/apis/options/duration.go +++ b/pkg/apis/options/hooks.go @@ -41,3 +41,17 @@ func toDurationHookFunc() mapstructure.DecodeHookFunc { } } } + +// StringToBytesHookFunc returns a DecodeHookFunc that converts string to []byte. +func stringToBytesHookFunc() mapstructure.DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() == reflect.String && t == reflect.TypeOf([]byte{}) { + return []byte(data.(string)), nil + } + return data, nil + } +} diff --git a/pkg/apis/options/duration_test.go b/pkg/apis/options/hooks_test.go similarity index 83% rename from pkg/apis/options/duration_test.go rename to pkg/apis/options/hooks_test.go index 63f203a837..99514a7c6b 100644 --- a/pkg/apis/options/duration_test.go +++ b/pkg/apis/options/hooks_test.go @@ -5,7 +5,7 @@ import ( "time" ) -func TestDecode(t *testing.T) { +func TestToDurationHook(t *testing.T) { type result struct { Duration time.Duration `yaml:"duration"` } @@ -80,3 +80,17 @@ func TestDecode(t *testing.T) { }) } } + +func TestStringToBytesHook(t *testing.T) { + var result struct { + Value []byte `yaml:"value"` + } + + if err := Decode(map[string]interface{}{"value": "hello-world"}, &result); err != nil { + t.Fatal(err) + } + + if string(result.Value) != "hello-world" { + t.Errorf("expected %q, got %q", "hello-world", string(result.Value)) + } +} diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index af7f76d9f9..fdd20c7a0e 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -89,7 +89,10 @@ func LoadYAML(configFileName string, opts interface{}) error { // - An error if decoding fails or if there are unmapped keys. func Decode(input interface{}, result interface{}) error { decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ - DecodeHook: mapstructure.ComposeDecodeHookFunc(toDurationHookFunc()), + DecodeHook: mapstructure.ComposeDecodeHookFunc( + toDurationHookFunc(), + stringToBytesHookFunc(), + ), Metadata: nil, // Don't track any metadata Result: result, // Decode the result into the prefilled options TagName: "yaml", // Parse all fields that use the json tag diff --git a/pkg/apis/options/load_test.go b/pkg/apis/options/load_test.go index 29d6511eb8..42083f769b 100644 --- a/pkg/apis/options/load_test.go +++ b/pkg/apis/options/load_test.go @@ -155,7 +155,7 @@ var _ = Describe("Load", func() { } err := Load(configFileName, flagSet, input) if o.expectedErr != nil { - Expect(err).To(MatchError(o.expectedErr.Error())) + Expect(err).To(MatchError(ContainSubstring(o.expectedErr.Error()))) } else { Expect(err).ToNot(HaveOccurred()) } @@ -471,7 +471,7 @@ sub: configFile: []byte(`stringSliceOption: "a"`), input: &TestOptions{}, expectedOutput: &TestOptions{}, - expectedErr: errors.New("error unmarshalling config: error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go struct field TestOptions.TestOptionSubStruct.StringSliceOption of type []string"), + expectedErr: errors.New("error decoding config: decoding failed due to the following error(s):\n\n'stringSliceOption' source data must be an array or slice, got string"), }), Entry("with a config file containing environment variable references", loadYAMLTableInput{ configFile: []byte("stringOption: ${TESTUSER}"), diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 0a0796e93d..9ddc2a84d9 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -67,7 +67,7 @@ type Provider struct { CAFiles []string `yaml:"caFiles,omitempty"` // UseSystemTrustStore determines if your custom CA files and the system trust store are used // If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. - UseSystemTrustStore bool `yaml:"useSystemTrustStore,omitempty"` + UseSystemTrustStore bool `yaml:"useSystemTrustStore"` // LoginURL is the authentication endpoint LoginURL string `yaml:"loginURL,omitempty"` // LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL @@ -80,7 +80,7 @@ type Provider struct { ProfileURL string `yaml:"profileURL,omitempty"` // SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token // default set to 'false' - SkipClaimsFromProfileURL bool `yaml:"skipClaimsFromProfileURL,omitempty"` + SkipClaimsFromProfileURL bool `yaml:"skipClaimsFromProfileURL"` // ProtectedResource is the resource that is protected (Azure AD and ADFS only) ProtectedResource string `yaml:"resource,omitempty"` // ValidateURL is the access token validation endpoint @@ -181,13 +181,13 @@ type MicrosoftEntraIDOptions struct { // FederatedTokenAuth enable oAuth2 client authentication with federated token projected // by Entra Workload Identity plugin, instead of client secret. - FederatedTokenAuth bool `yaml:"federatedTokenAuth,omitempty"` + FederatedTokenAuth bool `yaml:"federatedTokenAuth"` } type ADFSOptions struct { // Skip adding the scope parameter in login request // Default value is 'false' - SkipScope bool `yaml:"skipScope,omitempty"` + SkipScope bool `yaml:"skipScope"` } type BitbucketOptions struct { @@ -227,7 +227,7 @@ type GoogleOptions struct { // ServiceAccountJSON is the path to the service account json credentials ServiceAccountJSON string `yaml:"serviceAccountJson,omitempty"` // UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON - UseApplicationDefaultCredentials bool `yaml:"useApplicationDefaultCredentials,omitempty"` + UseApplicationDefaultCredentials bool `yaml:"useApplicationDefaultCredentials"` // TargetPrincipal is the Google Service Account used for Application Default Credentials TargetPrincipal string `yaml:"targetPrincipal,omitempty"` // UseOrganizationId indicates whether to use the organization ID as the UserName claim @@ -254,7 +254,7 @@ type OIDCOptions struct { InsecureSkipNonce bool `yaml:"insecureSkipNonce"` // SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints // default set to 'false' - SkipDiscovery bool `yaml:"skipDiscovery,omitempty"` + SkipDiscovery bool `yaml:"skipDiscovery"` // JwksURL is the OpenID Connect JWKS URL // eg: https://www.googleapis.com/oauth2/v3/certs JwksURL string `yaml:"jwksURL,omitempty"` diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index b32cc27d03..2b90e632ff 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -14,7 +14,7 @@ const ( type UpstreamConfig struct { // ProxyRawPath will pass the raw url path to upstream allowing for urls // like: "/%2F/" which would otherwise be redirected to "/" - ProxyRawPath bool `yaml:"proxyRawPath,omitempty"` + ProxyRawPath bool `yaml:"proxyRawPath"` // Upstreams represents the configuration for the upstream servers. // Requests will be proxied to this upstream if the path matches the request path. @@ -64,13 +64,13 @@ type Upstream struct { // This option is insecure and will allow potential Man-In-The-Middle attacks // between OAuth2 Proxy and the upstream server. // Defaults to false. - InsecureSkipTLSVerify bool `yaml:"insecureSkipTLSVerify,omitempty"` + InsecureSkipTLSVerify bool `yaml:"insecureSkipTLSVerify"` // Static will make all requests to this upstream have a static response. // The response will have a body of "Authenticated" and a response code // matching StaticCode. // If StaticCode is not set, the response will return a 200 response. - Static bool `yaml:"static,omitempty"` + Static bool `yaml:"static"` // StaticCode determines the response code for the Static response. // This option can only be used with Static enabled. @@ -84,11 +84,11 @@ type Upstream struct { // PassHostHeader determines whether the request host header should be proxied // to the upstream server. // Defaults to true. - PassHostHeader *bool `yaml:"passHostHeader,omitempty"` + PassHostHeader *bool `yaml:"passHostHeader"` // ProxyWebSockets enables proxying of websockets to upstream servers // Defaults to true. - ProxyWebSockets *bool `yaml:"proxyWebSockets,omitempty"` + ProxyWebSockets *bool `yaml:"proxyWebSockets"` // Timeout is the maximum duration the server will wait for a response from the upstream server. // Defaults to 30 seconds. From 955ab6b41bec78ac384b0b1f7bbbc6f297898734 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 26 Jul 2025 12:46:17 +0200 Subject: [PATCH 080/125] fix test setup and add local image build make target Signed-off-by: Jan Larwig --- Makefile | 4 ++ .../docker-compose-alpha-config.yaml | 49 ++++++++++++++++++- contrib/local-environment/docker-compose.yaml | 2 +- .../oauth2-proxy-alpha-config.yaml | 12 +---- docs/docs/configuration/alpha_config.md | 4 +- pkg/apis/options/secret_source.go | 2 +- 6 files changed, 58 insertions(+), 15 deletions(-) diff --git a/Makefile b/Makefile index 0647110037..38b2f94943 100644 --- a/Makefile +++ b/Makefile @@ -74,6 +74,10 @@ DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE := $(DOCKER_BUILDX_X_PLATFORM_ALPINE) --pus .PHONY: build-docker build-docker: build-distroless build-alpine ## Build multi architecture docker images in both flavours (distroless / alpine) +.PHONY: build-docker-local +build-docker-local: ## Build distroless docker image and locally load into docker images + $(DOCKER_BUILDX) --load -t $(REGISTRY)/$(REPOSITORY):${VERSION}-local . + .PHONY: build-distroless build-distroless: ## Build multi architecture distroless based docker image $(DOCKER_BUILDX_X_PLATFORM) -t $(REGISTRY)/$(REPOSITORY):latest -t $(REGISTRY)/$(REPOSITORY):${VERSION} . diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index 57d330407c..16e6a3cadf 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -10,11 +10,58 @@ # make alpha-config- (eg make nginx-up, make nginx-down) # # Access http://localhost:4180 to initiate a login cycle -version: '3.0' +version: "3.0" services: oauth2-proxy: + container_name: oauth2-proxy image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml + hostname: oauth2-proxy volumes: - "./oauth2-proxy-alpha-config.cfg:/oauth2-proxy.cfg" - "./oauth2-proxy-alpha-config.yaml:/oauth2-proxy-alpha-config.yaml" + restart: unless-stopped + ports: + - 4180:4180/tcp + networks: + dex: {} + httpbin: {} + depends_on: + - dex + - httpbin + dex: + container_name: dex + image: ghcr.io/dexidp/dex:v2.43.1 + command: dex serve /dex.yaml + hostname: dex + volumes: + - "./dex.yaml:/dex.yaml" + restart: unless-stopped + ports: + - 5556:5556/tcp + networks: + dex: + aliases: + - dex.localtest.me + etcd: {} + depends_on: + - etcd + httpbin: + container_name: httpbin + image: kennethreitz/httpbin + ports: [] + networks: + httpbin: {} + etcd: + container_name: etcd + image: gcr.io/etcd-development/etcd:v3.6.2 + entrypoint: /usr/local/bin/etcd + command: + - --listen-client-urls=http://0.0.0.0:2379 + - --advertise-client-urls=http://etcd:2379 + networks: + etcd: {} +networks: + dex: {} + etcd: {} + httpbin: {} diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index f1e7a23d53..fef0e32f94 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -9,7 +9,7 @@ # make (eg. make up, make down) # # Access http://oauth2-proxy.localtest.me:4180 to initiate a login cycle -version: '3.0' +version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy diff --git a/contrib/local-environment/oauth2-proxy-alpha-config.yaml b/contrib/local-environment/oauth2-proxy-alpha-config.yaml index 41f07a03e8..e423db98cd 100644 --- a/contrib/local-environment/oauth2-proxy-alpha-config.yaml +++ b/contrib/local-environment/oauth2-proxy-alpha-config.yaml @@ -4,12 +4,8 @@ upstreamConfig: upstreams: - id: httpbin path: / - uri: http://httpbin.localtest.me:8080 + uri: http://httpbin injectRequestHeaders: - - name: X-Forwarded-Groups - values: - - claimSource: - claim: groups - name: X-Forwarded-User values: - claimSource: @@ -18,14 +14,10 @@ injectRequestHeaders: values: - claimSource: claim: email - - name: X-Forwarded-Preferred-Username - values: - - claimSource: - claim: preferred_username providers: - id: oidc provider: oidc clientSecret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK clientID: oauth2-proxy oidcConfig: - issuerURL: http://dex.localhost:5556/dex + issuerURL: http://dex.localtest.me:5556/dex diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index c2c0aca657..495bc20691 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -268,7 +268,7 @@ make up the header value | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _[]byte_ | Value expects a base64 encoded []byte | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | | `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | | `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | | `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | @@ -480,7 +480,7 @@ Only one source within the struct should be defined at any time. | Field | Type | Description | | ----- | ---- | ----------- | -| `value` | _[]byte_ | Value expects a base64 encoded []byte | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | | `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | | `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | diff --git a/pkg/apis/options/secret_source.go b/pkg/apis/options/secret_source.go index e73d019fcc..848f163518 100644 --- a/pkg/apis/options/secret_source.go +++ b/pkg/apis/options/secret_source.go @@ -3,7 +3,7 @@ package options // SecretSource references an individual secret value. // Only one source within the struct should be defined at any time. type SecretSource struct { - // Value expects a base64 encoded []byte + // Value expects a base64 encoded string value. Value []byte `yaml:"value,omitempty"` // FromEnv expects the name of an environment variable. From 50414356e83506ff1965fca6ccbcab45cf731024 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Tue, 19 Aug 2025 14:43:32 +0200 Subject: [PATCH 081/125] return nil directly Signed-off-by: Jan Larwig --- main.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index 7142ae0b94..1525e94c6c 100644 --- a/main.go +++ b/main.go @@ -77,7 +77,8 @@ func loadConfiguration(config, yamlConfig string, extraFlags *pflag.FlagSet, arg logger.Printf("WARNING: You are using alpha configuration. The structure in this configuration file may change without notice. You MUST remove conflicting options from your existing configuration.") return loadYamlOptions(yamlConfig, config, extraFlags, args) } - return opts, err + + return opts, nil } // loadLegacyOptions loads the old toml options using the legacy flagset From 9d70e04262f91739f78c25f3e61015410e412ceb Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Tue, 19 Aug 2025 16:27:53 +0200 Subject: [PATCH 082/125] feat: migrate all alpha config booleans to pointers Signed-off-by: Jan Larwig --- main_test.go | 73 +++++++++++++------- oauthproxy_test.go | 5 +- pkg/apis/options/header.go | 2 +- pkg/apis/options/legacy_options.go | 29 ++++---- pkg/apis/options/legacy_options_test.go | 88 ++++++++++++------------- pkg/apis/options/providers.go | 26 ++++---- pkg/apis/options/upstreams.go | 12 ++-- pkg/middleware/headers.go | 2 +- pkg/middleware/headers_test.go | 9 +-- pkg/upstream/http.go | 6 +- pkg/upstream/http_test.go | 23 ++++--- pkg/upstream/proxy.go | 4 +- pkg/upstream/proxy_test.go | 11 ++-- pkg/util/ptr/ptr.go | 14 ++++ pkg/util/ptr/ptr_test.go | 38 +++++++++++ pkg/validation/options.go | 2 +- pkg/validation/options_test.go | 5 +- pkg/validation/providers.go | 7 +- pkg/validation/upstreams.go | 10 +-- pkg/validation/upstreams_test.go | 12 ++-- providers/adfs.go | 2 +- providers/adfs_test.go | 3 +- providers/google.go | 5 +- providers/ms_entra_id.go | 2 +- providers/ms_entra_id_test.go | 7 +- providers/oidc.go | 2 +- providers/oidc_test.go | 2 +- providers/providers.go | 8 +-- providers/providers_test.go | 9 +-- 29 files changed, 253 insertions(+), 165 deletions(-) create mode 100644 pkg/util/ptr/ptr.go create mode 100644 pkg/util/ptr/ptr_test.go diff --git a/main_test.go b/main_test.go index 709c68571b..b9ec39fb5f 100644 --- a/main_test.go +++ b/main_test.go @@ -7,6 +7,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" . "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options/testutil" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/format" @@ -25,11 +26,12 @@ set_basic_auth="true" basic_auth_password="c3VwZXItc2VjcmV0LXBhc3N3b3Jk" client_id="oauth2-proxy" client_secret="b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK" +google_admin_email="admin@example.com" +google_target_principal="principal" ` const testAlphaConfig = ` upstreamConfig: - proxyrawpath: false upstreams: - id: / path: / @@ -38,8 +40,11 @@ upstreamConfig: passHostHeader: true proxyWebSockets: true timeout: 30s + insecureSkipTLSVerify: false + disableKeepAlives: false injectRequestHeaders: - name: Authorization + preserveRequestValue: false values: - claimSource: claim: user @@ -47,18 +52,22 @@ injectRequestHeaders: basicAuthPassword: value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk - name: X-Forwarded-Groups + preserveRequestValue: false values: - claimSource: claim: groups - name: X-Forwarded-User + preserveRequestValue: false values: - claimSource: claim: user - name: X-Forwarded-Email + preserveRequestValue: false values: - claimSource: claim: email - name: X-Forwarded-Preferred-Username + preserveRequestValue: false values: - claimSource: claim: preferred_username @@ -77,12 +86,17 @@ providers: provider: google clientSecret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK clientID: oauth2-proxy - azureConfig: - tenant: common + useSystemTrustStore: false + skipClaimsFromProfileURL: false + googleConfig: + adminEmail: admin@example.com + targetPrincipal: principal + useApplicationDefaultCredentials: false oidcConfig: groupsClaim: groups emailClaim: email userIDClaim: email + insecureSkipIssuerVerification: false insecureSkipNonce: true audienceClaims: [aud] extraAudiences: [] @@ -100,10 +114,6 @@ cookie_secure="false" redirect_url="http://localhost:4180/oauth2/callback" ` - boolPtr := func(b bool) *bool { - return &b - } - durationPtr := func(d time.Duration) *time.Duration { return &d } @@ -120,13 +130,15 @@ redirect_url="http://localhost:4180/oauth2/callback" opts.UpstreamServers = options.UpstreamConfig{ Upstreams: []options.Upstream{ { - ID: "/", - Path: "/", - URI: "http://httpbin", - FlushInterval: durationPtr(options.DefaultUpstreamFlushInterval), - PassHostHeader: boolPtr(true), - ProxyWebSockets: boolPtr(true), - Timeout: durationPtr(options.DefaultUpstreamTimeout), + ID: "/", + Path: "/", + URI: "http://httpbin", + FlushInterval: durationPtr(options.DefaultUpstreamFlushInterval), + PassHostHeader: ptr.Ptr(true), + ProxyWebSockets: ptr.Ptr(true), + Timeout: durationPtr(options.DefaultUpstreamTimeout), + InsecureSkipTLSVerify: ptr.Ptr(false), + DisableKeepAlives: ptr.Ptr(false), }, }, } @@ -146,25 +158,38 @@ redirect_url="http://localhost:4180/oauth2/callback" }, } + authHeader.PreserveRequestValue = ptr.Ptr(false) opts.InjectRequestHeaders = append([]options.Header{authHeader}, opts.InjectRequestHeaders...) + + authHeader.PreserveRequestValue = nil opts.InjectResponseHeaders = append(opts.InjectResponseHeaders, authHeader) opts.Providers = options.Providers{ options.Provider{ - ID: "google=oauth2-proxy", - Type: "google", - ClientSecret: "b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK", - ClientID: "oauth2-proxy", + ID: "google=oauth2-proxy", + Type: "google", + ClientSecret: "b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK", + ClientID: "oauth2-proxy", + UseSystemTrustStore: ptr.Ptr(false), + SkipClaimsFromProfileURL: ptr.Ptr(false), + GoogleConfig: options.GoogleOptions{ + AdminEmail: "admin@example.com", + UseApplicationDefaultCredentials: ptr.Ptr(false), + TargetPrincipal: "principal", + }, AzureConfig: options.AzureOptions{ Tenant: "common", }, OIDCConfig: options.OIDCOptions{ - GroupsClaim: "groups", - EmailClaim: "email", - UserIDClaim: "email", - AudienceClaims: []string{"aud"}, - ExtraAudiences: []string{}, - InsecureSkipNonce: true, + GroupsClaim: "groups", + EmailClaim: "email", + UserIDClaim: "email", + AudienceClaims: []string{"aud"}, + ExtraAudiences: []string{}, + InsecureSkipNonce: ptr.Ptr(true), + InsecureAllowUnverifiedEmail: ptr.Ptr(false), + InsecureSkipIssuerVerification: ptr.Ptr(false), + SkipDiscovery: ptr.Ptr(false), }, LoginURLParameters: []options.LoginURLParameter{ {Name: "approval_prompt", Default: []string{"force"}}, diff --git a/oauthproxy_test.go b/oauthproxy_test.go index 44569a3583..0463c9dd40 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -23,6 +23,7 @@ import ( internaloidc "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/providers/oidc" sessionscookie "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/sessions/cookie" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/upstream" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/validation" "github.com/oauth2-proxy/oauth2-proxy/v7/providers" "github.com/stretchr/testify/assert" @@ -506,7 +507,7 @@ func TestStaticProxyUpstream(t *testing.T) { ProxyUpstream: options.Upstream{ ID: "static-proxy", Path: "/static-proxy", - Static: true, + Static: ptr.Ptr(true), }, }) if err != nil { @@ -2223,7 +2224,7 @@ func TestTrustedIPs(t *testing.T) { { ID: "static", Path: "/", - Static: true, + Static: ptr.Ptr(true), }, }, } diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index a695d7d494..048b19741f 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -11,7 +11,7 @@ type Header struct { // should be preserved for the request to the upstream server. // This option only applies to injected request headers. // Defaults to false (headers that match this header will be stripped). - PreserveRequestValue bool `yaml:"preserveRequestValue"` + PreserveRequestValue *bool `yaml:"preserveRequestValue,omitempty"` // InsecureSkipHeaderNormalization disables normalizing the header name // According to RFC 7230 Section 3.2 there aren't any rules about diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index ec779d8490..672d6c63fd 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -9,6 +9,7 @@ import ( "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" "github.com/spf13/pflag" ) @@ -142,12 +143,12 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { ID: u.Path, Path: u.Path, URI: upstreamString, - InsecureSkipTLSVerify: l.SSLUpstreamInsecureSkipVerify, + InsecureSkipTLSVerify: &l.SSLUpstreamInsecureSkipVerify, PassHostHeader: &l.PassHostHeader, ProxyWebSockets: &l.ProxyWebSockets, FlushInterval: &flushInterval, Timeout: &timeout, - DisableKeepAlives: l.DisableKeepAlives, + DisableKeepAlives: &l.DisableKeepAlives, } switch u.Scheme { @@ -164,7 +165,7 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { logger.Errorf("unable to convert %q to int, use default \"200\"", u.Host) responseCode = 200 } - upstream.Static = true + upstream.Static = ptr.Ptr(true) upstream.StaticCode = &responseCode // This is not allowed to be empty and must be unique @@ -175,12 +176,12 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { // Force defaults compatible with static responses upstream.URI = "" - upstream.InsecureSkipTLSVerify = false + upstream.InsecureSkipTLSVerify = ptr.Ptr(false) upstream.PassHostHeader = nil upstream.ProxyWebSockets = nil upstream.FlushInterval = nil upstream.Timeout = nil - upstream.DisableKeepAlives = false + upstream.DisableKeepAlives = ptr.Ptr(false) case "unix": upstream.Path = "/" } @@ -253,7 +254,7 @@ func (l *LegacyHeaders) getRequestHeaders() []Header { } for i := range requestHeaders { - requestHeaders[i].PreserveRequestValue = !l.SkipAuthStripHeaders + requestHeaders[i].PreserveRequestValue = ptr.Ptr(!l.SkipAuthStripHeaders) } return requestHeaders @@ -684,11 +685,11 @@ func (l *LegacyProvider) convert() (Providers, error) { ClientSecretFile: l.ClientSecretFile, Type: ProviderType(l.ProviderType), CAFiles: l.ProviderCAFiles, - UseSystemTrustStore: l.UseSystemTrustStore, + UseSystemTrustStore: &l.UseSystemTrustStore, LoginURL: l.LoginURL, RedeemURL: l.RedeemURL, ProfileURL: l.ProfileURL, - SkipClaimsFromProfileURL: l.SkipClaimsFromProfileURL, + SkipClaimsFromProfileURL: &l.SkipClaimsFromProfileURL, ProtectedResource: l.ProtectedResource, ValidateURL: l.ValidateURL, Scope: l.Scope, @@ -701,10 +702,10 @@ func (l *LegacyProvider) convert() (Providers, error) { // This part is out of the switch section for all providers that support OIDC provider.OIDCConfig = OIDCOptions{ IssuerURL: l.OIDCIssuerURL, - InsecureAllowUnverifiedEmail: l.InsecureOIDCAllowUnverifiedEmail, - InsecureSkipIssuerVerification: l.InsecureOIDCSkipIssuerVerification, - InsecureSkipNonce: l.InsecureOIDCSkipNonce, - SkipDiscovery: l.SkipOIDCDiscovery, + InsecureAllowUnverifiedEmail: &l.InsecureOIDCAllowUnverifiedEmail, + InsecureSkipIssuerVerification: &l.InsecureOIDCSkipIssuerVerification, + InsecureSkipNonce: &l.InsecureOIDCSkipNonce, + SkipDiscovery: &l.SkipOIDCDiscovery, JwksURL: l.OIDCJwksURL, UserIDClaim: l.UserIDClaim, EmailClaim: l.OIDCEmailClaim, @@ -772,7 +773,7 @@ func (l *LegacyProvider) convert() (Providers, error) { Groups: l.GoogleGroups, AdminEmail: l.GoogleAdminEmail, ServiceAccountJSON: l.GoogleServiceAccountJSON, - UseApplicationDefaultCredentials: l.GoogleUseApplicationDefaultCredentials, + UseApplicationDefaultCredentials: &l.GoogleUseApplicationDefaultCredentials, TargetPrincipal: l.GoogleTargetPrincipal, UseOrganizationID: l.GoogleUseOrganizationID, AdminAPIUserScope: l.GoogleAdminAPIUserScope, @@ -780,7 +781,7 @@ func (l *LegacyProvider) convert() (Providers, error) { case "entra-id": provider.MicrosoftEntraIDConfig = MicrosoftEntraIDOptions{ AllowedTenants: l.EntraIDAllowedTenants, - FederatedTokenAuth: l.EntraIDFederatedTokenAuth, + FederatedTokenAuth: &l.EntraIDFederatedTokenAuth, } } diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index 98a89601a2..4348021b1e 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -3,6 +3,7 @@ package options import ( "time" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -26,7 +27,6 @@ var _ = Describe("Legacy Options", func() { legacyOpts.LegacyProvider.ClientID = "oauth-proxy" legacyOpts.LegacyUpstreams.DisableKeepAlives = false - truth := true staticCode := 204 opts.UpstreamServers = UpstreamConfig{ Upstreams: []Upstream{ @@ -35,35 +35,35 @@ var _ = Describe("Legacy Options", func() { Path: "/baz", URI: "http://foo.bar/baz", FlushInterval: &flushInterval, - InsecureSkipTLSVerify: true, - PassHostHeader: &truth, - ProxyWebSockets: &truth, + InsecureSkipTLSVerify: ptr.Ptr(true), + PassHostHeader: ptr.Ptr(true), + ProxyWebSockets: ptr.Ptr(true), Timeout: &timeout, - DisableKeepAlives: legacyOpts.LegacyUpstreams.DisableKeepAlives, + DisableKeepAlives: &legacyOpts.LegacyUpstreams.DisableKeepAlives, }, { ID: "/bar", Path: "/bar", URI: "file:///var/lib/website", FlushInterval: &flushInterval, - InsecureSkipTLSVerify: true, - PassHostHeader: &truth, - ProxyWebSockets: &truth, + InsecureSkipTLSVerify: ptr.Ptr(true), + PassHostHeader: ptr.Ptr(true), + ProxyWebSockets: ptr.Ptr(true), Timeout: &timeout, - DisableKeepAlives: legacyOpts.LegacyUpstreams.DisableKeepAlives, + DisableKeepAlives: &legacyOpts.LegacyUpstreams.DisableKeepAlives, }, { ID: "static://204", Path: "/", URI: "", - Static: true, + Static: ptr.Ptr(true), StaticCode: &staticCode, FlushInterval: nil, - InsecureSkipTLSVerify: false, + InsecureSkipTLSVerify: ptr.Ptr(false), PassHostHeader: nil, ProxyWebSockets: nil, Timeout: nil, - DisableKeepAlives: legacyOpts.LegacyUpstreams.DisableKeepAlives, + DisableKeepAlives: &legacyOpts.LegacyUpstreams.DisableKeepAlives, }, }, } @@ -71,7 +71,7 @@ var _ = Describe("Legacy Options", func() { opts.InjectRequestHeaders = []Header{ { Name: "X-Forwarded-Groups", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -82,7 +82,7 @@ var _ = Describe("Legacy Options", func() { }, { Name: "X-Forwarded-User", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -93,7 +93,7 @@ var _ = Describe("Legacy Options", func() { }, { Name: "X-Forwarded-Email", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -104,7 +104,7 @@ var _ = Describe("Legacy Options", func() { }, { Name: "X-Forwarded-Preferred-Username", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -123,7 +123,7 @@ var _ = Describe("Legacy Options", func() { opts.Providers[0].ClientID = "oauth-proxy" opts.Providers[0].ID = "google=oauth-proxy" - opts.Providers[0].OIDCConfig.InsecureSkipNonce = true + opts.Providers[0].OIDCConfig.InsecureSkipNonce = ptr.Ptr(true) opts.Providers[0].OIDCConfig.AudienceClaims = []string{"aud"} opts.Providers[0].OIDCConfig.ExtraAudiences = []string{} opts.Providers[0].LoginURLParameters = []LoginURLParameter{ @@ -157,12 +157,12 @@ var _ = Describe("Legacy Options", func() { ID: "/baz", Path: "/baz", URI: validHTTP, - InsecureSkipTLSVerify: skipVerify, + InsecureSkipTLSVerify: &skipVerify, PassHostHeader: &passHostHeader, ProxyWebSockets: &proxyWebSockets, FlushInterval: &flushInterval, Timeout: &timeout, - DisableKeepAlives: disableKeepAlives, + DisableKeepAlives: &disableKeepAlives, } // Test cases and expected outcomes @@ -171,12 +171,12 @@ var _ = Describe("Legacy Options", func() { ID: "/", Path: "/", URI: emptyPathHTTP, - InsecureSkipTLSVerify: skipVerify, + InsecureSkipTLSVerify: &skipVerify, PassHostHeader: &passHostHeader, ProxyWebSockets: &proxyWebSockets, FlushInterval: &flushInterval, Timeout: &timeout, - DisableKeepAlives: disableKeepAlives, + DisableKeepAlives: &disableKeepAlives, } validFileWithFragment := "file:///var/lib/website#/bar" @@ -184,12 +184,12 @@ var _ = Describe("Legacy Options", func() { ID: "/bar", Path: "/bar", URI: "file:///var/lib/website", - InsecureSkipTLSVerify: skipVerify, + InsecureSkipTLSVerify: &skipVerify, PassHostHeader: &passHostHeader, ProxyWebSockets: &proxyWebSockets, FlushInterval: &flushInterval, Timeout: &timeout, - DisableKeepAlives: disableKeepAlives, + DisableKeepAlives: &disableKeepAlives, } validStatic := "static://204" @@ -198,14 +198,14 @@ var _ = Describe("Legacy Options", func() { ID: validStatic, Path: "/", URI: "", - Static: true, + Static: ptr.Ptr(true), StaticCode: &validStaticCode, - InsecureSkipTLSVerify: false, + InsecureSkipTLSVerify: ptr.Ptr(false), PassHostHeader: nil, ProxyWebSockets: nil, FlushInterval: nil, Timeout: nil, - DisableKeepAlives: false, + DisableKeepAlives: ptr.Ptr(false), } invalidStatic := "static://abc" @@ -214,14 +214,14 @@ var _ = Describe("Legacy Options", func() { ID: invalidStatic, Path: "/", URI: "", - Static: true, + Static: ptr.Ptr(true), StaticCode: &invalidStaticCode, - InsecureSkipTLSVerify: false, + InsecureSkipTLSVerify: ptr.Ptr(false), PassHostHeader: nil, ProxyWebSockets: nil, FlushInterval: nil, Timeout: nil, - DisableKeepAlives: false, + DisableKeepAlives: ptr.Ptr(false), } invalidHTTP := ":foo" @@ -308,13 +308,13 @@ var _ = Describe("Legacy Options", func() { } withPreserveRequestValue := func(h Header, preserve bool) Header { - h.PreserveRequestValue = preserve + h.PreserveRequestValue = &preserve return h } xForwardedUser := Header{ Name: "X-Forwarded-User", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -326,7 +326,7 @@ var _ = Describe("Legacy Options", func() { xForwardedEmail := Header{ Name: "X-Forwarded-Email", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -338,7 +338,7 @@ var _ = Describe("Legacy Options", func() { xForwardedGroups := Header{ Name: "X-Forwarded-Groups", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -350,7 +350,7 @@ var _ = Describe("Legacy Options", func() { xForwardedPreferredUsername := Header{ Name: "X-Forwarded-Preferred-Username", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -362,7 +362,7 @@ var _ = Describe("Legacy Options", func() { basicAuthHeader := Header{ Name: "Authorization", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -378,7 +378,7 @@ var _ = Describe("Legacy Options", func() { xForwardedUserWithEmail := Header{ Name: "X-Forwarded-User", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -390,7 +390,7 @@ var _ = Describe("Legacy Options", func() { xForwardedAccessToken := Header{ Name: "X-Forwarded-Access-Token", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -402,7 +402,7 @@ var _ = Describe("Legacy Options", func() { basicAuthHeaderWithEmail := Header{ Name: "Authorization", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -418,7 +418,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestUser := Header{ Name: "X-Auth-Request-User", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -430,7 +430,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestEmail := Header{ Name: "X-Auth-Request-Email", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -442,7 +442,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestGroups := Header{ Name: "X-Auth-Request-Groups", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -454,7 +454,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestPreferredUsername := Header{ Name: "X-Auth-Request-Preferred-Username", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -466,7 +466,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestAccessToken := Header{ Name: "X-Auth-Request-Access-Token", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -478,7 +478,7 @@ var _ = Describe("Legacy Options", func() { authorizationHeader := Header{ Name: "Authorization", - PreserveRequestValue: false, + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 9ddc2a84d9..027464de42 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -1,5 +1,7 @@ package options +import "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" + const ( // OIDCEmailClaim is the generic email claim used by the OIDC provider. OIDCEmailClaim = "email" @@ -67,7 +69,7 @@ type Provider struct { CAFiles []string `yaml:"caFiles,omitempty"` // UseSystemTrustStore determines if your custom CA files and the system trust store are used // If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. - UseSystemTrustStore bool `yaml:"useSystemTrustStore"` + UseSystemTrustStore *bool `yaml:"useSystemTrustStore,omitempty"` // LoginURL is the authentication endpoint LoginURL string `yaml:"loginURL,omitempty"` // LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL @@ -80,7 +82,7 @@ type Provider struct { ProfileURL string `yaml:"profileURL,omitempty"` // SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token // default set to 'false' - SkipClaimsFromProfileURL bool `yaml:"skipClaimsFromProfileURL"` + SkipClaimsFromProfileURL *bool `yaml:"skipClaimsFromProfileURL,omitempty"` // ProtectedResource is the resource that is protected (Azure AD and ADFS only) ProtectedResource string `yaml:"resource,omitempty"` // ValidateURL is the access token validation endpoint @@ -181,13 +183,13 @@ type MicrosoftEntraIDOptions struct { // FederatedTokenAuth enable oAuth2 client authentication with federated token projected // by Entra Workload Identity plugin, instead of client secret. - FederatedTokenAuth bool `yaml:"federatedTokenAuth"` + FederatedTokenAuth *bool `yaml:"federatedTokenAuth,omitempty"` } type ADFSOptions struct { // Skip adding the scope parameter in login request // Default value is 'false' - SkipScope bool `yaml:"skipScope"` + SkipScope *bool `yaml:"skipScope,omitempty"` } type BitbucketOptions struct { @@ -227,7 +229,7 @@ type GoogleOptions struct { // ServiceAccountJSON is the path to the service account json credentials ServiceAccountJSON string `yaml:"serviceAccountJson,omitempty"` // UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON - UseApplicationDefaultCredentials bool `yaml:"useApplicationDefaultCredentials"` + UseApplicationDefaultCredentials *bool `yaml:"useApplicationDefaultCredentials,omitempty"` // TargetPrincipal is the Google Service Account used for Application Default Credentials TargetPrincipal string `yaml:"targetPrincipal,omitempty"` // UseOrganizationId indicates whether to use the organization ID as the UserName claim @@ -242,19 +244,19 @@ type OIDCOptions struct { IssuerURL string `yaml:"issuerURL,omitempty"` // InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified // default set to 'false' - InsecureAllowUnverifiedEmail bool `yaml:"insecureAllowUnverifiedEmail"` + InsecureAllowUnverifiedEmail *bool `yaml:"insecureAllowUnverifiedEmail,omitempty"` // InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL // default set to 'false' - InsecureSkipIssuerVerification bool `yaml:"insecureSkipIssuerVerification"` + InsecureSkipIssuerVerification *bool `yaml:"insecureSkipIssuerVerification,omitempty"` // InsecureSkipNonce skips verifying the ID Token's nonce claim that must match // the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked // after the initial OAuth redeem & subsequent token refreshes. // default set to 'true' // Warning: In a future release, this will change to 'false' by default for enhanced security. - InsecureSkipNonce bool `yaml:"insecureSkipNonce"` + InsecureSkipNonce *bool `yaml:"insecureSkipNonce,omitempty"` // SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints // default set to 'false' - SkipDiscovery bool `yaml:"skipDiscovery"` + SkipDiscovery *bool `yaml:"skipDiscovery,omitempty"` // JwksURL is the OpenID Connect JWKS URL // eg: https://www.googleapis.com/oauth2/v3/certs JwksURL string `yaml:"jwksURL,omitempty"` @@ -295,9 +297,9 @@ func providerDefaults() Providers { Tenant: "common", }, OIDCConfig: OIDCOptions{ - InsecureAllowUnverifiedEmail: false, - InsecureSkipNonce: true, - SkipDiscovery: false, + InsecureAllowUnverifiedEmail: ptr.Ptr(false), + InsecureSkipNonce: ptr.Ptr(true), + SkipDiscovery: ptr.Ptr(false), UserIDClaim: OIDCEmailClaim, // Deprecated: Use OIDCEmailClaim EmailClaim: OIDCEmailClaim, GroupsClaim: OIDCGroupsClaim, diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index 2b90e632ff..f12a4bf3f1 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -14,7 +14,7 @@ const ( type UpstreamConfig struct { // ProxyRawPath will pass the raw url path to upstream allowing for urls // like: "/%2F/" which would otherwise be redirected to "/" - ProxyRawPath bool `yaml:"proxyRawPath"` + ProxyRawPath *bool `yaml:"proxyRawPath,omitempty"` // Upstreams represents the configuration for the upstream servers. // Requests will be proxied to this upstream if the path matches the request path. @@ -64,13 +64,13 @@ type Upstream struct { // This option is insecure and will allow potential Man-In-The-Middle attacks // between OAuth2 Proxy and the upstream server. // Defaults to false. - InsecureSkipTLSVerify bool `yaml:"insecureSkipTLSVerify"` + InsecureSkipTLSVerify *bool `yaml:"insecureSkipTLSVerify,omitempty"` // Static will make all requests to this upstream have a static response. // The response will have a body of "Authenticated" and a response code // matching StaticCode. // If StaticCode is not set, the response will return a 200 response. - Static bool `yaml:"static"` + Static *bool `yaml:"static,omitempty"` // StaticCode determines the response code for the Static response. // This option can only be used with Static enabled. @@ -84,11 +84,11 @@ type Upstream struct { // PassHostHeader determines whether the request host header should be proxied // to the upstream server. // Defaults to true. - PassHostHeader *bool `yaml:"passHostHeader"` + PassHostHeader *bool `yaml:"passHostHeader,omitempty"` // ProxyWebSockets enables proxying of websockets to upstream servers // Defaults to true. - ProxyWebSockets *bool `yaml:"proxyWebSockets"` + ProxyWebSockets *bool `yaml:"proxyWebSockets,omitempty"` // Timeout is the maximum duration the server will wait for a response from the upstream server. // Defaults to 30 seconds. @@ -96,5 +96,5 @@ type Upstream struct { // DisableKeepAlives disables HTTP keep-alive connections to the upstream server. // Defaults to false. - DisableKeepAlives bool `yaml:"disableKeepAlives,omitempty"` + DisableKeepAlives *bool `yaml:"disableKeepAlives,omitempty"` } diff --git a/pkg/middleware/headers.go b/pkg/middleware/headers.go index 623d50e9f0..d9287505e8 100644 --- a/pkg/middleware/headers.go +++ b/pkg/middleware/headers.go @@ -27,7 +27,7 @@ func NewRequestHeaderInjector(headers []options.Header) (alice.Constructor, erro func newStripHeaders(headers []options.Header) alice.Constructor { headersToStrip := []options.Header{} for _, header := range headers { - if !header.PreserveRequestValue { + if !(*header.PreserveRequestValue) { headersToStrip = append(headersToStrip, header) } } diff --git a/pkg/middleware/headers_test.go b/pkg/middleware/headers_test.go index 6a60ec0162..89f6510728 100644 --- a/pkg/middleware/headers_test.go +++ b/pkg/middleware/headers_test.go @@ -8,6 +8,7 @@ import ( middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" sessionsapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -115,7 +116,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "Claim", - PreserveRequestValue: true, + PreserveRequestValue: ptr.Ptr(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ @@ -160,7 +161,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "Claim", - PreserveRequestValue: true, + PreserveRequestValue: ptr.Ptr(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ @@ -385,7 +386,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "Claim", - PreserveRequestValue: true, + PreserveRequestValue: ptr.Ptr(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ @@ -432,7 +433,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "Claim", - PreserveRequestValue: true, + PreserveRequestValue: ptr.Ptr(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index f81f4ec0d9..38e0e7a961 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -54,7 +54,7 @@ func newHTTPUpstreamProxy(upstream options.Upstream, u *url.URL, sigData *option // Set up a WebSocket proxy if required var wsProxy http.Handler if upstream.ProxyWebSockets == nil || *upstream.ProxyWebSockets { - wsProxy = newWebSocketReverseProxy(u, upstream.InsecureSkipTLSVerify) + wsProxy = newWebSocketReverseProxy(u, *upstream.InsecureSkipTLSVerify) } var auth hmacauth.HmacAuth @@ -149,7 +149,7 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // InsecureSkipVerify is a configurable option we allow /* #nosec G402 */ - if upstream.InsecureSkipTLSVerify { + if *upstream.InsecureSkipTLSVerify { transport.TLSClientConfig.InsecureSkipVerify = true } @@ -168,7 +168,7 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // Pass on DisableKeepAlives to the transport settings // to allow for disabling HTTP keep-alive connections - transport.DisableKeepAlives = upstream.DisableKeepAlives + transport.DisableKeepAlives = *upstream.DisableKeepAlives // Apply the customized transport to our proxy before returning it proxy.Transport = transport diff --git a/pkg/upstream/http_test.go b/pkg/upstream/http_test.go index df264c33ac..7c1831bfe1 100644 --- a/pkg/upstream/http_test.go +++ b/pkg/upstream/http_test.go @@ -15,6 +15,7 @@ import ( middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/middleware" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "golang.org/x/net/websocket" @@ -23,8 +24,6 @@ import ( var _ = Describe("HTTP Upstream Suite", func() { defaultFlushInterval := options.DefaultUpstreamFlushInterval defaultTimeout := options.DefaultUpstreamTimeout - truth := true - falsum := false type httpUpstreamTableInput struct { id string @@ -64,8 +63,8 @@ var _ = Describe("HTTP Upstream Suite", func() { upstream := options.Upstream{ ID: in.id, PassHostHeader: &in.passUpstreamHostHeader, - ProxyWebSockets: &falsum, - InsecureSkipTLSVerify: false, + ProxyWebSockets: ptr.Ptr(false), + InsecureSkipTLSVerify: ptr.Ptr(false), FlushInterval: &flush, Timeout: &timeout, } @@ -343,9 +342,9 @@ var _ = Describe("HTTP Upstream Suite", func() { upstream := options.Upstream{ ID: "noPassHost", - PassHostHeader: &falsum, - ProxyWebSockets: &falsum, - InsecureSkipTLSVerify: false, + PassHostHeader: ptr.Ptr(false), + ProxyWebSockets: ptr.Ptr(false), + InsecureSkipTLSVerify: ptr.Ptr(false), FlushInterval: &defaultFlushInterval, Timeout: &defaultTimeout, } @@ -389,10 +388,10 @@ var _ = Describe("HTTP Upstream Suite", func() { upstream := options.Upstream{ ID: "foo123", FlushInterval: &in.flushInterval, - InsecureSkipTLSVerify: in.skipVerify, + InsecureSkipTLSVerify: &in.skipVerify, ProxyWebSockets: &in.proxyWebSockets, Timeout: &in.timeout, - DisableKeepAlives: in.disableKeepAlives, + DisableKeepAlives: &in.disableKeepAlives, } handler := newHTTPUpstreamProxy(upstream, u, in.sigData, in.errorHandler) @@ -487,9 +486,9 @@ var _ = Describe("HTTP Upstream Suite", func() { timeout := options.DefaultUpstreamTimeout upstream := options.Upstream{ ID: "websocketProxy", - PassHostHeader: &truth, - ProxyWebSockets: &truth, - InsecureSkipTLSVerify: false, + PassHostHeader: ptr.Ptr(true), + ProxyWebSockets: ptr.Ptr(true), + InsecureSkipTLSVerify: ptr.Ptr(false), FlushInterval: &flush, Timeout: &timeout, } diff --git a/pkg/upstream/proxy.go b/pkg/upstream/proxy.go index 74b0d02d1b..0d2286ea9a 100644 --- a/pkg/upstream/proxy.go +++ b/pkg/upstream/proxy.go @@ -27,12 +27,12 @@ func NewProxy(upstreams options.UpstreamConfig, sigData *options.SignatureData, serveMux: mux.NewRouter(), } - if upstreams.ProxyRawPath { + if *upstreams.ProxyRawPath { m.serveMux.UseEncodedPath() } for _, upstream := range sortByPathLongest(upstreams.Upstreams) { - if upstream.Static { + if *upstream.Static { if err := m.registerStaticResponseHandler(upstream, writer); err != nil { return nil, fmt.Errorf("could not register static upstream %q: %v", upstream.ID, err) } diff --git a/pkg/upstream/proxy_test.go b/pkg/upstream/proxy_test.go index 5252bd421b..87aae7fa8f 100644 --- a/pkg/upstream/proxy_test.go +++ b/pkg/upstream/proxy_test.go @@ -10,6 +10,7 @@ import ( middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/app/pagewriter" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -60,19 +61,19 @@ var _ = Describe("Proxy Suite", func() { { ID: "static-backend", Path: "/static/", - Static: true, + Static: ptr.Ptr(true), StaticCode: &ok, }, { ID: "static-backend-no-trailing-slash", Path: "/static", - Static: true, + Static: ptr.Ptr(true), StaticCode: &accepted, }, { ID: "static-backend-long", Path: "/static/long", - Static: true, + Static: ptr.Ptr(true), StaticCode: &accepted, }, { @@ -83,7 +84,7 @@ var _ = Describe("Proxy Suite", func() { { ID: "single-path-backend", Path: "/single-path", - Static: true, + Static: ptr.Ptr(true), StaticCode: &ok, }, { @@ -346,7 +347,7 @@ var _ = Describe("Proxy Suite", func() { upstream: "", }), Entry("containing an escaped '/' with ProxyRawPath", &proxyTableInput{ - upstreams: options.UpstreamConfig{ProxyRawPath: true}, + upstreams: options.UpstreamConfig{ProxyRawPath: ptr.Ptr(true)}, target: "http://example.localhost/%2F/test1/%2F/test2", response: testHTTPResponse{ code: 404, diff --git a/pkg/util/ptr/ptr.go b/pkg/util/ptr/ptr.go new file mode 100644 index 0000000000..9242773cbf --- /dev/null +++ b/pkg/util/ptr/ptr.go @@ -0,0 +1,14 @@ +package ptr + +// Ptr generically returns a pointer to the given value. +func Ptr[T any](v T) *T { + return &v +} + +// Deref returns the value of the pointer or def(ault) if nil. +func Deref[T any](p *T, def T) T { + if p == nil { + return def + } + return *p +} diff --git a/pkg/util/ptr/ptr_test.go b/pkg/util/ptr/ptr_test.go new file mode 100644 index 0000000000..c4817a6b3f --- /dev/null +++ b/pkg/util/ptr/ptr_test.go @@ -0,0 +1,38 @@ +package ptr + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestPtr(t *testing.T) { + p := Ptr(42) + assert.NotNil(t, p) + assert.Equal(t, 42, *p) + + s := Ptr("hello") + assert.NotNil(t, s) + assert.Equal(t, "hello", *s) + + b := Ptr(true) + assert.NotNil(t, b) + assert.True(t, *b) +} + +func TestDeref(t *testing.T) { + v := Deref(Ptr(99), 0) + assert.Equal(t, 99, v) + + v = Deref[int](nil, 123) + assert.Equal(t, 123, v) + + s := Deref[string](nil, "default") + assert.Equal(t, "default", s) + + b := Deref(Ptr(true), false) + assert.True(t, b) + + b = Deref[bool](nil, false) + assert.False(t, b) +} diff --git a/pkg/validation/options.go b/pkg/validation/options.go index 0f648d6cc9..d5aba4e4ec 100644 --- a/pkg/validation/options.go +++ b/pkg/validation/options.go @@ -34,7 +34,7 @@ func Validate(o *options.Options) error { transport := requests.DefaultTransport.(*http.Transport) transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} // #nosec G402 -- InsecureSkipVerify is a configurable option we allow } else if len(o.Providers[0].CAFiles) > 0 { - pool, err := util.GetCertPool(o.Providers[0].CAFiles, o.Providers[0].UseSystemTrustStore) + pool, err := util.GetCertPool(o.Providers[0].CAFiles, *o.Providers[0].UseSystemTrustStore) if err == nil { transport := requests.DefaultTransport.(*http.Transport) transport.TLSClientConfig = &tls.Config{ diff --git a/pkg/validation/options_test.go b/pkg/validation/options_test.go index 5c28354593..6657e8476a 100644 --- a/pkg/validation/options_test.go +++ b/pkg/validation/options_test.go @@ -9,6 +9,7 @@ import ( "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" "github.com/stretchr/testify/assert" ) @@ -68,7 +69,7 @@ func TestGoogleGroupOptionsWithoutServiceAccountJSON(t *testing.T) { func TestGoogleGroupOptionsWithoutAdminEmail(t *testing.T) { o := testOptions() - o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = true + o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = ptr.Ptr(true) err := Validate(o) assert.NotEqual(t, nil, err) @@ -81,7 +82,7 @@ func TestGoogleGroupOptionsWithoutGroups(t *testing.T) { o := testOptions() // Set admin email and application default credentials but no groups - should still require them o.Providers[0].GoogleConfig.AdminEmail = "admin@example.com" - o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = true + o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = ptr.Ptr(true) err := Validate(o) // Should pass validation since google-group is now optional assert.Equal(t, nil, err) diff --git a/pkg/validation/providers.go b/pkg/validation/providers.go index 4527b84160..3abf69d40a 100644 --- a/pkg/validation/providers.go +++ b/pkg/validation/providers.go @@ -5,6 +5,7 @@ import ( "os" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) // validateProviders is the initial validation migration for multiple providrers @@ -64,7 +65,7 @@ func validateProvider(provider options.Provider, providerIDs map[string]struct{} // providerRequiresClientSecret checks if provider requires client secret to be set // or it can be omitted in favor of JWT token to authenticate oAuth client func providerRequiresClientSecret(provider options.Provider) bool { - if provider.Type == "entra-id" && provider.MicrosoftEntraIDConfig.FederatedTokenAuth { + if provider.Type == "entra-id" && *provider.MicrosoftEntraIDConfig.FederatedTokenAuth { return false } @@ -96,7 +97,7 @@ func validateGoogleConfig(provider options.Provider) []string { hasAdminEmail := provider.GoogleConfig.AdminEmail != "" hasSAJSON := provider.GoogleConfig.ServiceAccountJSON != "" - useADC := provider.GoogleConfig.UseApplicationDefaultCredentials + useADC := ptr.Deref(provider.GoogleConfig.UseApplicationDefaultCredentials, false) if !hasAdminEmail && !hasSAJSON && !useADC { return msgs @@ -123,7 +124,7 @@ func validateGoogleConfig(provider options.Provider) []string { func validateEntraConfig(provider options.Provider) []string { msgs := []string{} - if provider.MicrosoftEntraIDConfig.FederatedTokenAuth { + if *provider.MicrosoftEntraIDConfig.FederatedTokenAuth { federatedTokenPath := os.Getenv("AZURE_FEDERATED_TOKEN_FILE") if federatedTokenPath == "" { diff --git a/pkg/validation/upstreams.go b/pkg/validation/upstreams.go index 52facb4dd8..05d441e3a5 100644 --- a/pkg/validation/upstreams.go +++ b/pkg/validation/upstreams.go @@ -54,19 +54,19 @@ func validateUpstream(upstream options.Upstream, ids, paths map[string]struct{}) func validateStaticUpstream(upstream options.Upstream) []string { msgs := []string{} - if !upstream.Static && upstream.StaticCode != nil { + if !*upstream.Static && upstream.StaticCode != nil { msgs = append(msgs, fmt.Sprintf("upstream %q has staticCode (%d), but is not a static upstream, set 'static' for a static response", upstream.ID, *upstream.StaticCode)) } // Checks after this only make sense when the upstream is static - if !upstream.Static { + if !*upstream.Static { return msgs } if upstream.URI != "" { msgs = append(msgs, fmt.Sprintf("upstream %q has uri, but is a static upstream, this will have no effect.", upstream.ID)) } - if upstream.InsecureSkipTLSVerify { + if *upstream.InsecureSkipTLSVerify { msgs = append(msgs, fmt.Sprintf("upstream %q has insecureSkipTLSVerify, but is a static upstream, this will have no effect.", upstream.ID)) } if upstream.FlushInterval != nil && *upstream.FlushInterval != options.DefaultUpstreamFlushInterval { @@ -85,13 +85,13 @@ func validateStaticUpstream(upstream options.Upstream) []string { func validateUpstreamURI(upstream options.Upstream) []string { msgs := []string{} - if !upstream.Static && upstream.URI == "" { + if !*upstream.Static && upstream.URI == "" { msgs = append(msgs, fmt.Sprintf("upstream %q has empty uri: uris are required for all non-static upstreams", upstream.ID)) return msgs } // Checks after this only make sense the upstream is not static - if upstream.Static { + if *upstream.Static { return msgs } diff --git a/pkg/validation/upstreams_test.go b/pkg/validation/upstreams_test.go index 67991b767a..580e2f2926 100644 --- a/pkg/validation/upstreams_test.go +++ b/pkg/validation/upstreams_test.go @@ -4,6 +4,7 @@ import ( "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -16,7 +17,6 @@ var _ = Describe("Upstreams", func() { flushInterval := 5 * time.Second staticCode200 := 200 - truth := true validHTTPUpstream := options.Upstream{ ID: "validHTTPUpstream", @@ -26,7 +26,7 @@ var _ = Describe("Upstreams", func() { validStaticUpstream := options.Upstream{ ID: "validStaticUpstream", Path: "/validStaticUpstream", - Static: true, + Static: ptr.Ptr(true), } validFileUpstream := options.Upstream{ ID: "validFileUpstream", @@ -145,11 +145,11 @@ var _ = Describe("Upstreams", func() { ID: "foo", Path: "/foo", URI: "ftp://foo", - Static: true, + Static: ptr.Ptr(true), FlushInterval: &flushInterval, - PassHostHeader: &truth, - ProxyWebSockets: &truth, - InsecureSkipTLSVerify: true, + PassHostHeader: ptr.Ptr(true), + ProxyWebSockets: ptr.Ptr(true), + InsecureSkipTLSVerify: ptr.Ptr(true), }, }, }, diff --git a/providers/adfs.go b/providers/adfs.go index 0facfdcfee..6615f38c28 100644 --- a/providers/adfs.go +++ b/providers/adfs.go @@ -50,7 +50,7 @@ func NewADFSProvider(p *ProviderData, opts options.Provider) *ADFSProvider { return &ADFSProvider{ OIDCProvider: oidcProvider, - skipScope: opts.ADFSConfig.SkipScope, + skipScope: *opts.ADFSConfig.SkipScope, oidcEnrichFunc: oidcProvider.EnrichSession, oidcRefreshFunc: oidcProvider.RefreshSession, } diff --git a/providers/adfs_test.go b/providers/adfs_test.go index 0b73043081..edcb93073e 100755 --- a/providers/adfs_test.go +++ b/providers/adfs_test.go @@ -16,6 +16,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" internaloidc "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/providers/oidc" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -172,7 +173,7 @@ var _ = Describe("ADFS Provider Tests", func() { ProtectedResource: resource, Scope: "", }, options.Provider{ - ADFSConfig: options.ADFSOptions{SkipScope: true}, + ADFSConfig: options.ADFSOptions{SkipScope: ptr.Ptr(true)}, }) result := p.GetLoginURL("https://example.com/adfs/oauth2/", "", "", url.Values{}) diff --git a/providers/google.go b/providers/google.go index a6a9d283f1..64102ebcb9 100644 --- a/providers/google.go +++ b/providers/google.go @@ -108,7 +108,8 @@ func NewGoogleProvider(p *ProviderData, opts options.GoogleOptions) (*GoogleProv }, } - if opts.UseOrganizationID || opts.ServiceAccountJSON != "" || opts.UseApplicationDefaultCredentials { + if opts.UseOrganizationID || opts.ServiceAccountJSON != "" || *opts.UseApplicationDefaultCredentials { + provider.configureGroups(opts) // reuse admin service to avoid multiple calls for token var adminService *admin.Service @@ -304,7 +305,7 @@ var possibleScopesList = [...]string{ } func getOauth2TokenSource(ctx context.Context, opts options.GoogleOptions, scope string) oauth2.TokenSource { - if opts.UseApplicationDefaultCredentials { + if *opts.UseApplicationDefaultCredentials { ts, err := impersonate.CredentialsTokenSource(ctx, impersonate.CredentialsConfig{ TargetPrincipal: getTargetPrincipal(ctx, opts), Scopes: strings.Split(scope, " "), diff --git a/providers/ms_entra_id.go b/providers/ms_entra_id.go index df1f38a4cf..752f9f44e2 100644 --- a/providers/ms_entra_id.go +++ b/providers/ms_entra_id.go @@ -51,7 +51,7 @@ func NewMicrosoftEntraIDProvider(p *ProviderData, opts options.Provider) *Micros OIDCProvider: NewOIDCProvider(p, opts.OIDCConfig), multiTenantAllowedTenants: opts.MicrosoftEntraIDConfig.AllowedTenants, - federatedTokenAuth: opts.MicrosoftEntraIDConfig.FederatedTokenAuth, + federatedTokenAuth: *opts.MicrosoftEntraIDConfig.FederatedTokenAuth, microsoftGraphURL: microsoftGraphURL, } } diff --git a/providers/ms_entra_id_test.go b/providers/ms_entra_id_test.go index dfd1ef9981..7b720c91b0 100644 --- a/providers/ms_entra_id_test.go +++ b/providers/ms_entra_id_test.go @@ -13,6 +13,7 @@ import ( "github.com/coreos/go-oidc/v3/oidc" "github.com/golang-jwt/jwt/v5" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" "github.com/stretchr/testify/assert" . "github.com/onsi/gomega" @@ -24,7 +25,7 @@ func TestAzureEntraOIDCProviderNewMultiTenant(t *testing.T) { provider := NewMicrosoftEntraIDProvider(&ProviderData{}, options.Provider{OIDCConfig: options.OIDCOptions{ IssuerURL: "https://login.microsoftonline.com/common/v2.0", - InsecureSkipIssuerVerification: true, + InsecureSkipIssuerVerification: ptr.Ptr(true), }}, ) g.Expect(provider.Data().ProviderName).To(Equal("Microsoft Entra ID")) @@ -90,8 +91,8 @@ func TestAzureEntraOIDCProviderValidateSessionAllowedTenants(t *testing.T) { options.Provider{ OIDCConfig: options.OIDCOptions{ IssuerURL: "https://login.microsoftonline.com/common/v2.0", - InsecureSkipIssuerVerification: true, - InsecureSkipNonce: true, + InsecureSkipIssuerVerification: ptr.Ptr(true), + InsecureSkipNonce: ptr.Ptr(true), }, MicrosoftEntraIDConfig: options.MicrosoftEntraIDOptions{ AllowedTenants: []string{"85d7d600-7804-4d92-8d43-9c33c21c130c"}, diff --git a/providers/oidc.go b/providers/oidc.go index eeac407322..fa65e83953 100644 --- a/providers/oidc.go +++ b/providers/oidc.go @@ -50,7 +50,7 @@ func NewOIDCProvider(p *ProviderData, opts options.OIDCOptions) *OIDCProvider { return &OIDCProvider{ ProviderData: p, - SkipNonce: opts.InsecureSkipNonce, + SkipNonce: *opts.InsecureSkipNonce, } } diff --git a/providers/oidc_test.go b/providers/oidc_test.go index 81a70eb410..61f4762e72 100644 --- a/providers/oidc_test.go +++ b/providers/oidc_test.go @@ -63,7 +63,7 @@ func newOIDCProvider(serverURL *url.URL, skipNonce bool) *OIDCProvider { } p := NewOIDCProvider(providerData, options.OIDCOptions{ - InsecureSkipNonce: skipNonce, + InsecureSkipNonce: &skipNonce, }) return p diff --git a/providers/providers.go b/providers/providers.go index ec00f41265..84f5ec91ca 100644 --- a/providers/providers.go +++ b/providers/providers.go @@ -98,8 +98,8 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData, IssuerURL: providerConfig.OIDCConfig.IssuerURL, JWKsURL: providerConfig.OIDCConfig.JwksURL, PublicKeyFiles: providerConfig.OIDCConfig.PublicKeyFiles, - SkipDiscovery: providerConfig.OIDCConfig.SkipDiscovery, - SkipIssuerVerification: providerConfig.OIDCConfig.InsecureSkipIssuerVerification, + SkipDiscovery: *providerConfig.OIDCConfig.SkipDiscovery, + SkipIssuerVerification: *providerConfig.OIDCConfig.InsecureSkipIssuerVerification, }) if err != nil { return nil, fmt.Errorf("error building OIDC ProviderVerifier: %v", err) @@ -143,10 +143,10 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData, } // Make the OIDC options available to all providers that support it - p.AllowUnverifiedEmail = providerConfig.OIDCConfig.InsecureAllowUnverifiedEmail + p.AllowUnverifiedEmail = *providerConfig.OIDCConfig.InsecureAllowUnverifiedEmail p.EmailClaim = providerConfig.OIDCConfig.EmailClaim p.GroupsClaim = providerConfig.OIDCConfig.GroupsClaim - p.SkipClaimsFromProfileURL = providerConfig.SkipClaimsFromProfileURL + p.SkipClaimsFromProfileURL = *providerConfig.SkipClaimsFromProfileURL // Set PKCE enabled or disabled based on discovery and force options p.CodeChallengeMethod = parseCodeChallengeMethod(providerConfig) diff --git a/providers/providers_test.go b/providers/providers_test.go index 82961d8408..9591dc655f 100644 --- a/providers/providers_test.go +++ b/providers/providers_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/gomega" ) @@ -81,7 +82,7 @@ func TestSkipOIDCDiscovery(t *testing.T) { ClientSecretFile: clientSecret, OIDCConfig: options.OIDCOptions{ IssuerURL: msIssuerURL, - SkipDiscovery: true, + SkipDiscovery: ptr.Ptr(true), }, } @@ -108,7 +109,7 @@ func TestURLsCorrectlyParsed(t *testing.T) { RedeemURL: msTokenURL, OIDCConfig: options.OIDCOptions{ IssuerURL: msIssuerURL, - SkipDiscovery: true, + SkipDiscovery: ptr.Ptr(true), JwksURL: msKeysURL, }, } @@ -216,7 +217,7 @@ func TestScope(t *testing.T) { AllowedGroups: tc.allowedGroups, OIDCConfig: options.OIDCOptions{ IssuerURL: msIssuerURL, - SkipDiscovery: true, + SkipDiscovery: ptr.Ptr(true), JwksURL: msKeysURL, }, } @@ -297,7 +298,7 @@ func TestEmailClaimCorrectlySet(t *testing.T) { RedeemURL: msTokenURL, OIDCConfig: options.OIDCOptions{ IssuerURL: msIssuerURL, - SkipDiscovery: true, + SkipDiscovery: ptr.Ptr(true), JwksURL: msKeysURL, UserIDClaim: tc.userIDClaim, EmailClaim: tc.emailClaim, From 51b1fd0510973af134e128c65f5689dab0f10177 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Thu, 30 Oct 2025 08:36:13 +0100 Subject: [PATCH 083/125] chore(deps): replace with forked official yaml library Signed-off-by: Jan Larwig --- go.mod | 78 ++++++++-------- go.sum | 194 ++++++++++++++++++++++----------------- main.go | 2 +- pkg/apis/options/load.go | 2 +- 4 files changed, 151 insertions(+), 125 deletions(-) diff --git a/go.mod b/go.mod index be7de03bc7..99195a4ecf 100644 --- a/go.mod +++ b/go.mod @@ -3,56 +3,57 @@ module github.com/oauth2-proxy/oauth2-proxy/v7 go 1.25.3 require ( - cloud.google.com/go/compute/metadata v0.7.0 + cloud.google.com/go/compute/metadata v0.9.0 github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb github.com/a8m/envsubst v1.4.3 github.com/alicebob/miniredis/v2 v2.35.0 github.com/bitly/go-simplejson v0.5.1 github.com/bsm/redislock v0.9.4 - github.com/coreos/go-oidc/v3 v3.14.1 + github.com/coreos/go-oidc/v3 v3.16.0 github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf github.com/fsnotify/fsnotify v1.9.0 github.com/go-jose/go-jose/v3 v3.0.4 github.com/go-viper/mapstructure/v2 v2.4.0 - github.com/golang-jwt/jwt/v5 v5.2.3 + github.com/golang-jwt/jwt/v5 v5.3.0 github.com/google/go-cmp v0.7.0 github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 github.com/justinas/alice v1.2.0 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 - github.com/onsi/ginkgo/v2 v2.23.4 - github.com/onsi/gomega v1.38.0 + github.com/onsi/ginkgo/v2 v2.27.2 + github.com/onsi/gomega v1.38.2 github.com/pierrec/lz4/v4 v4.1.22 - github.com/prometheus/client_golang v1.22.0 - github.com/redis/go-redis/v9 v9.11.0 - github.com/spf13/cast v1.9.2 - github.com/spf13/pflag v1.0.7 - github.com/spf13/viper v1.20.1 + github.com/prometheus/client_golang v1.23.2 + github.com/redis/go-redis/v9 v9.16.0 + github.com/spf13/cast v1.10.0 + github.com/spf13/pflag v1.0.10 + github.com/spf13/viper v1.21.0 github.com/stretchr/testify v1.11.1 github.com/vmihailenco/msgpack/v5 v5.4.1 - golang.org/x/crypto v0.40.0 - golang.org/x/net v0.42.0 - golang.org/x/oauth2 v0.30.0 - golang.org/x/sync v0.16.0 - google.golang.org/api v0.243.0 + go.yaml.in/yaml/v3 v3.0.4 + golang.org/x/crypto v0.43.0 + golang.org/x/net v0.46.0 + golang.org/x/oauth2 v0.32.0 + golang.org/x/sync v0.17.0 + google.golang.org/api v0.254.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 - gopkg.in/yaml.v3 v3.0.1 - k8s.io/apimachinery v0.33.3 + k8s.io/apimachinery v0.34.1 ) require ( - cloud.google.com/go/auth v0.16.3 // indirect + cloud.google.com/go/auth v0.17.0 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect + github.com/Masterminds/semver/v3 v3.4.0 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/go-jose/go-jose/v4 v4.1.1 // indirect + github.com/go-jose/go-jose/v4 v4.1.3 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-task/slim-sprig/v3 v3.0.0 // indirect - github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5 // indirect + github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d // indirect github.com/google/s2a-go v0.1.9 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect github.com/googleapis/gax-go/v2 v2.15.0 // indirect @@ -61,26 +62,25 @@ require ( github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.65.0 // indirect - github.com/prometheus/procfs v0.17.0 // indirect - github.com/rogpeppe/go-internal v1.14.1 // indirect - github.com/sagikazarmark/locafero v0.9.0 // indirect - github.com/sourcegraph/conc v0.3.0 // indirect - github.com/spf13/afero v1.14.0 // indirect + github.com/prometheus/common v0.67.2 // indirect + github.com/prometheus/procfs v0.19.1 // indirect + github.com/sagikazarmark/locafero v0.12.0 // indirect + github.com/spf13/afero v1.15.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/yuin/gopher-lua v1.1.1 // indirect - go.opentelemetry.io/auto/sdk v1.1.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0 // indirect - go.opentelemetry.io/otel v1.37.0 // indirect - go.opentelemetry.io/otel/metric v1.37.0 // indirect - go.opentelemetry.io/otel/trace v1.37.0 // indirect - go.uber.org/automaxprocs v1.6.0 // indirect - go.uber.org/multierr v1.11.0 // indirect - golang.org/x/sys v0.34.0 // indirect - golang.org/x/text v0.27.0 // indirect - golang.org/x/tools v0.35.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250721164621-a45f3dfb1074 // indirect - google.golang.org/grpc v1.74.2 // indirect - google.golang.org/protobuf v1.36.6 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect + go.opentelemetry.io/otel v1.38.0 // indirect + go.opentelemetry.io/otel/metric v1.38.0 // indirect + go.opentelemetry.io/otel/trace v1.38.0 // indirect + go.yaml.in/yaml/v2 v2.4.3 // indirect + golang.org/x/mod v0.29.0 // indirect + golang.org/x/sys v0.37.0 // indirect + golang.org/x/text v0.30.0 // indirect + golang.org/x/tools v0.38.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda // indirect + google.golang.org/grpc v1.76.0 // indirect + google.golang.org/protobuf v1.36.10 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 0928296985..8344be120d 100644 --- a/go.sum +++ b/go.sum @@ -1,13 +1,15 @@ -cloud.google.com/go/auth v0.16.3 h1:kabzoQ9/bobUmnseYnBO6qQG7q4a/CffFRlJSxv2wCc= -cloud.google.com/go/auth v0.16.3/go.mod h1:NucRGjaXfzP1ltpcQ7On/VTZ0H4kWB5Jy+Y9Dnm76fA= +cloud.google.com/go/auth v0.17.0 h1:74yCm7hCj2rUyyAocqnFzsAYXgJhrG26XCFimrc/Kz4= +cloud.google.com/go/auth v0.17.0/go.mod h1:6wv/t5/6rOPAX4fJiRjKkJCvswLwdet7G8+UGXt7nCQ= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= -cloud.google.com/go/compute/metadata v0.7.0 h1:PBWF+iiAerVNe8UCHxdOt6eHLVc3ydFeOCw78U8ytSU= -cloud.google.com/go/compute/metadata v0.7.0/go.mod h1:j5MvL9PprKL39t166CoB1uVHfQMs4tFQZZcKwksXUjo= +cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= +cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb h1:ZVN4Iat3runWOFLaBCDVU5a9X/XikSRBosye++6gojw= github.com/Bose/minisentinel v0.0.0-20200130220412-917c5a9223bb/go.mod h1:WsAABbY4HQBgd3mGuG4KMNTbHJCPvx9IVBHzysbknss= github.com/FZambia/sentinel v1.0.0 h1:KJ0ryjKTZk5WMp0dXvSdNqp3lFaW1fNFuEYfrkLOYIc= github.com/FZambia/sentinel v1.0.0/go.mod h1:ytL1Am/RLlAoAXG6Kj5LNuw/TRRQrv2rt2FT26vP5gI= +github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= +github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= github.com/a8m/envsubst v1.4.3 h1:kDF7paGK8QACWYaQo6KtyYBozY2jhQrTuNNuUxQkhJY= github.com/a8m/envsubst v1.4.3/go.mod h1:4jjHWQlZoaXPoLQUb7H2qT4iLkZDdmEQiOUogdUmqVU= github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= @@ -29,8 +31,8 @@ github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/coreos/go-oidc/v3 v3.14.1 h1:9ePWwfdwC4QKRlCXsJGou56adA/owXczOzwKdOumLqk= -github.com/coreos/go-oidc/v3 v3.14.1/go.mod h1:HaZ3szPaZ0e4r6ebqvsLWlk2Tn+aejfmrfah6hnSYEU= +github.com/coreos/go-oidc/v3 v3.16.0 h1:qRQUCFstKpXwmEjDQTIbyY/5jF00+asXzSkmkoa/mow= +github.com/coreos/go-oidc/v3 v3.16.0/go.mod h1:wqPbKFrVnE90vty060SB40FCJ8fTHTxSwyXJqZH+sI8= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf h1:iW4rZ826su+pqaw19uhpSCzhj44qo35pNgKFGqzDKkU= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -44,10 +46,16 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/gkampitakis/ciinfo v0.3.2 h1:JcuOPk8ZU7nZQjdUhctuhQofk7BGHuIy0c9Ez8BNhXs= +github.com/gkampitakis/ciinfo v0.3.2/go.mod h1:1NIwaOcFChN4fa/B0hEBdAb6npDlFL8Bwx4dfRLRqAo= +github.com/gkampitakis/go-diff v1.3.2 h1:Qyn0J9XJSDTgnsgHRdz9Zp24RaJeKMUHg2+PDZZdC4M= +github.com/gkampitakis/go-diff v1.3.2/go.mod h1:LLgOrpqleQe26cte8s36HTWcTmMEur6OPYerdAAS9tk= +github.com/gkampitakis/go-snaps v0.5.15 h1:amyJrvM1D33cPHwVrjo9jQxX8g/7E2wYdZ+01KS3zGE= +github.com/gkampitakis/go-snaps v0.5.15/go.mod h1:HNpx/9GoKisdhw9AFOBT1N7DBs9DiHo/hGheFGBZ+mc= github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY= github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= -github.com/go-jose/go-jose/v4 v4.1.1 h1:JYhSgy4mXXzAdF3nUx3ygx347LRXJRrpgyU3adRmkAI= -github.com/go-jose/go-jose/v4 v4.1.1/go.mod h1:BdsZGqgdO3b6tTc6LSE56wcDbMMLuPsw5d4ZD5f94kA= +github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs= +github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -57,8 +65,10 @@ github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1v github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= -github.com/golang-jwt/jwt/v5 v5.2.3 h1:kkGXqQOBSDDWRhWNXTFpqGSCMyh/PLnqUvMGJPDJDs0= -github.com/golang-jwt/jwt/v5 v5.2.3/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= +github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo= +github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3 h1:6amM4HsNPOvMLVc2ZnyqrjeQ92YAVWn7T4WBKK87inY= @@ -66,8 +76,8 @@ github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3/go.mod h1:B4C85q github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5 h1:xhMrHhTJ6zxu3gA4enFM9MLn9AY7613teCdFnlUVbSQ= -github.com/google/pprof v0.0.0-20250630185457-6e76a2b096b5/go.mod h1:5hDyRhoBCxViHszMt12TnOpEI4VVi+U8Gm9iphldiMA= +github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d h1:KJIErDwbSHjnp/SGzE5ed8Aol7JsKiI5X7yWKAtzhM0= +github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -79,6 +89,8 @@ github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81 github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= +github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE= +github.com/joshdk/go-junit v1.0.0/go.mod h1:TiiV0PqkaNfFXjEiyjWM3XXrhVyCa1K4Zfga6W52ung= github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo= github.com/justinas/alice v1.2.0/go.mod h1:fN5HRH/reO/zrUflLfTN43t3vXvKzvZIENsNEe7i7qA= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= @@ -89,16 +101,20 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/maruel/natural v1.1.1 h1:Hja7XhhmvEFhcByqDoHz9QZbkWey+COd9xWfCfn1ioo= +github.com/maruel/natural v1.1.1/go.mod h1:v+Rfd79xlw1AgVBjbO0BEQmptqb5HvL/k9GRHB7ZKEg= github.com/matryer/is v1.2.0 h1:92UTHpy8CDwaJ08GqLDzhhuixiBUUD1p3AU6PHddz4A= github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA= +github.com/mfridman/tparse v0.18.0 h1:wh6dzOKaIwkUGyKgOntDW4liXSo37qg5AXbIhkMV3vE= +github.com/mfridman/tparse v0.18.0/go.mod h1:gEvqZTuCgEhPbYk/2lS3Kcxg1GmTxxU7kTC8DvP0i/A= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw= -github.com/onsi/ginkgo/v2 v2.23.4 h1:ktYTpKJAVZnDT4VjxSbiBenUjmlL/5QkBEocaWXiQus= -github.com/onsi/ginkgo/v2 v2.23.4/go.mod h1:Bt66ApGPBFzHyR+JO10Zbt0Gsp4uWxu5mIOTusL46e8= -github.com/onsi/gomega v1.38.0 h1:c/WX+w8SLAinvuKKQFh77WEucCnPk4j2OTUr7lt7BeY= -github.com/onsi/gomega v1.38.0/go.mod h1:OcXcwId0b9QsE7Y49u+BTrL4IdKOBOKnD6VQNTJEB6o= +github.com/onsi/ginkgo/v2 v2.27.2 h1:LzwLj0b89qtIy6SSASkzlNvX6WktqurSHwkk2ipF/Ns= +github.com/onsi/ginkgo/v2 v2.27.2/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= +github.com/onsi/gomega v1.38.2 h1:eZCjf2xjZAqe+LeWvKb5weQ+NcPwX84kqJ0cZNxok2A= +github.com/onsi/gomega v1.38.2/go.mod h1:W2MJcYxRGV63b418Ai34Ud0hEdTVXq9NW9+Sx6uXf3k= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU= @@ -106,38 +122,42 @@ github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFu github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g= -github.com/prashantv/gostub v1.1.0/go.mod h1:A5zLQHz7ieHGG7is6LLXLz7I8+3LZzsrV0P1IAHhP5U= -github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q= -github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0= +github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= +github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= -github.com/prometheus/common v0.65.0 h1:QDwzd+G1twt//Kwj/Ww6E9FQq1iVMmODnILtW1t2VzE= -github.com/prometheus/common v0.65.0/go.mod h1:0gZns+BLRQ3V6NdaerOhMbwwRbNh9hkGINtQAsP5GS8= -github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0= -github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw= -github.com/redis/go-redis/v9 v9.11.0 h1:E3S08Gl/nJNn5vkxd2i78wZxWAPNZgUNTp8WIJUAiIs= -github.com/redis/go-redis/v9 v9.11.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw= +github.com/prometheus/common v0.67.2 h1:PcBAckGFTIHt2+L3I33uNRTlKTplNzFctXcWhPyAEN8= +github.com/prometheus/common v0.67.2/go.mod h1:63W3KZb1JOKgcjlIr64WW/LvFGAqKPj0atm+knVGEko= +github.com/prometheus/procfs v0.19.1 h1:QVtROpTkphuXuNlnCv3m1ut3JytkXHtQ3xvck/YmzMM= +github.com/prometheus/procfs v0.19.1/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw= +github.com/redis/go-redis/v9 v9.16.0 h1:OotgqgLSRCmzfqChbQyG1PHC3tLNR89DG4jdOERSEP4= +github.com/redis/go-redis/v9 v9.16.0/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/sagikazarmark/locafero v0.9.0 h1:GbgQGNtTrEmddYDSAH9QLRyfAHY12md+8YFTqyMTC9k= -github.com/sagikazarmark/locafero v0.9.0/go.mod h1:UBUyz37V+EdMS3hDF3QWIiVr/2dPrx49OMO0Bn0hJqk= -github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= -github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= -github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA= -github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo= -github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE= -github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= -github.com/spf13/pflag v1.0.7 h1:vN6T9TfwStFPFM5XzjsvmzZkLuaLX+HS+0SeFLRgU6M= -github.com/spf13/pflag v1.0.7/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4= -github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4= +github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4= +github.com/sagikazarmark/locafero v0.12.0/go.mod h1:sZh36u/YSZ918v0Io+U9ogLYQJ9tLLBmM4eneO6WwsI= +github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= +github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= +github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= +github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= +github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= +github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= +github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= +github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8= github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= @@ -147,47 +167,51 @@ github.com/yuin/gopher-lua v0.0.0-20190206043414-8bfc7677f583/go.mod h1:gqRgreBU github.com/yuin/gopher-lua v0.0.0-20191213034115-f46add6fdb5c/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ= github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M= github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= -go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= -go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0 h1:Hf9xI/XLML9ElpiHVDNwvqI0hIFlzV8dgIr35kV1kRU= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0/go.mod h1:NfchwuyNoMcZ5MLHwPrODwUF1HWCXWrL31s8gSAdIKY= -go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ= -go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I= -go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE= -go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E= -go.opentelemetry.io/otel/sdk v1.37.0 h1:ItB0QUqnjesGRvNcmAcU0LyvkVyGJ2xftD29bWdDvKI= -go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg= -go.opentelemetry.io/otel/sdk/metric v1.37.0 h1:90lI228XrB9jCMuSdA0673aubgRobVZFhbjxHHspCPc= -go.opentelemetry.io/otel/sdk/metric v1.37.0/go.mod h1:cNen4ZWfiD37l5NhS+Keb5RXVWZWpRE+9WyVCpbo5ps= -go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4= -go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0= -go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs= -go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8= -go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= -go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg= +go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= +go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= +go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= +go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= +go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= +go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg= +go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= +go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA= +go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= +go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0= +go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= -golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM= -golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY= +golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04= +golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA= +golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs= -golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8= -golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= -golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU= +golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4= +golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210= +golang.org/x/oauth2 v0.32.0 h1:jsCblLleRMDrxMN29H3z/k1KliIvpLgCkE6R8FXXNgY= +golang.org/x/oauth2 v0.32.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw= -golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= +golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -197,8 +221,8 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA= -golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ= +golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -210,29 +234,31 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4= -golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU= -golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= -golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= +golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k= +golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM= +golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= +golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0= -golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw= +golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ= +golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.243.0 h1:sw+ESIJ4BVnlJcWu9S+p2Z6Qq1PjG77T8IJ1xtp4jZQ= -google.golang.org/api v0.243.0/go.mod h1:GE4QtYfaybx1KmeHMdBnNnyLzBZCVihGBXAmJu/uUr8= +gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= +gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= +google.golang.org/api v0.254.0 h1:jl3XrGj7lRjnlUvZAbAdhINTLbsg5dbjmR90+pTQvt4= +google.golang.org/api v0.254.0/go.mod h1:5BkSURm3D9kAqjGvBNgf0EcbX6Rnrf6UArKkwBzAyqQ= google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= -google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 h1:oWVWY3NzT7KJppx2UKhKmzPq4SRe0LdCijVRwvGeikY= -google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822/go.mod h1:h3c4v36UTKzUiuaOKQ6gr3S+0hovBtUrXzTG/i3+XEc= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250721164621-a45f3dfb1074 h1:qJW29YvkiJmXOYMu5Tf8lyrTp3dOS+K4z6IixtLaCf8= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250721164621-a45f3dfb1074/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= -google.golang.org/grpc v1.74.2 h1:WoosgB65DlWVC9FqI82dGsZhWFNBSLjQ84bjROOpMu4= -google.golang.org/grpc v1.74.2/go.mod h1:CtQ+BGjaAIXHs/5YS3i473GqwBBa1zGQNevxdeBEXrM= -google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= -google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= +google.golang.org/genproto/googleapis/api v0.0.0-20250804133106-a7a43d27e69b h1:ULiyYQ0FdsJhwwZUwbaXpZF5yUE3h+RA+gxvBu37ucc= +google.golang.org/genproto/googleapis/api v0.0.0-20250804133106-a7a43d27e69b/go.mod h1:oDOGiMSXHL4sDTJvFvIB9nRQCGdLP1o/iVaqQK8zB+M= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda h1:i/Q+bfisr7gq6feoJnS/DlpdwEL4ihp41fvRiM3Ork0= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= +google.golang.org/grpc v1.76.0 h1:UnVkv1+uMLYXoIz6o7chp59WfQUYA2ex/BXQ9rHZu7A= +google.golang.org/grpc v1.76.0/go.mod h1:Ju12QI8M6iQJtbcsV+awF5a4hfJMLi4X0JLo94ULZ6c= +google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= +google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= @@ -241,5 +267,5 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYs gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/apimachinery v0.33.3 h1:4ZSrmNa0c/ZpZJhAgRdcsFcZOw1PQU1bALVQ0B3I5LA= -k8s.io/apimachinery v0.33.3/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= +k8s.io/apimachinery v0.34.1 h1:dTlxFls/eikpJxmAC7MVE8oOeP1zryV7iRyIjB0gky4= +k8s.io/apimachinery v0.34.1/go.mod h1:/GwIlEcWuTX9zKIg2mbw0LRFIsXwrfoVxn+ef0X13lw= diff --git a/main.go b/main.go index 1525e94c6c..12ca273933 100644 --- a/main.go +++ b/main.go @@ -10,7 +10,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/validation" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/version" "github.com/spf13/pflag" - "gopkg.in/yaml.v3" + "go.yaml.in/yaml/v3" ) func main() { diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index fdd20c7a0e..20d0438325 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -12,7 +12,7 @@ import ( "github.com/go-viper/mapstructure/v2" "github.com/spf13/pflag" "github.com/spf13/viper" - "gopkg.in/yaml.v3" + "go.yaml.in/yaml/v3" ) // Load reads in the config file at the path given, then merges in environment From 527c72f23f5aeceeb9cc4b3e7dd10fdaab8d67c2 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Thu, 30 Oct 2025 09:26:14 +0100 Subject: [PATCH 084/125] feat: add ensure defaults to all migrated structs Signed-off-by: Jan Larwig --- main.go | 6 ++- main_test.go | 9 +--- pkg/apis/middleware/session.go | 3 +- pkg/apis/options/alpha_options.go | 6 +-- pkg/apis/options/header.go | 27 ++++++++++ pkg/apis/options/legacy_options.go | 4 -- pkg/apis/options/legacy_options_test.go | 3 +- pkg/apis/options/options.go | 20 +++++++ pkg/apis/options/providers.go | 70 +++++++++++++++++++++++++ pkg/apis/options/secret_source.go | 5 ++ pkg/apis/options/upstreams.go | 41 ++++++++++++++- pkg/upstream/http.go | 11 ++-- pkg/validation/providers.go | 7 ++- pkg/validation/upstreams.go | 10 ++-- 14 files changed, 189 insertions(+), 33 deletions(-) diff --git a/main.go b/main.go index 12ca273933..7e18b95fc1 100644 --- a/main.go +++ b/main.go @@ -20,7 +20,7 @@ func main() { // Because we parse early to determine alpha vs legacy config, we have to // ignore any unknown flags for now - configFlagSet.ParseErrorsWhitelist.UnknownFlags = true + configFlagSet.ParseErrorsAllowlist.UnknownFlags = true config := configFlagSet.String("config", "", "path to config file") 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)") @@ -78,6 +78,8 @@ func loadConfiguration(config, yamlConfig string, extraFlags *pflag.FlagSet, arg return loadYamlOptions(yamlConfig, config, extraFlags, args) } + opts.EnsureDefaults() + return opts, nil } @@ -117,7 +119,7 @@ func loadYamlOptions(yamlConfig, config string, extraFlags *pflag.FlagSet, args return nil, fmt.Errorf("failed to load alpha options: %v", err) } - alphaOpts.MergeInto(opts) + alphaOpts.MergeOptionsWithDefaults(opts) return opts, nil } diff --git a/main_test.go b/main_test.go index b9ec39fb5f..0323c838c9 100644 --- a/main_test.go +++ b/main_test.go @@ -3,7 +3,6 @@ package main import ( "errors" "os" - "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" . "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options/testutil" @@ -114,10 +113,6 @@ cookie_secure="false" redirect_url="http://localhost:4180/oauth2/callback" ` - durationPtr := func(d time.Duration) *time.Duration { - return &d - } - testExpectedOptions := func() *options.Options { opts, err := options.NewLegacyOptions().ToOptions() Expect(err).ToNot(HaveOccurred()) @@ -133,10 +128,10 @@ redirect_url="http://localhost:4180/oauth2/callback" ID: "/", Path: "/", URI: "http://httpbin", - FlushInterval: durationPtr(options.DefaultUpstreamFlushInterval), + FlushInterval: ptr.Ptr(options.DefaultUpstreamFlushInterval), PassHostHeader: ptr.Ptr(true), ProxyWebSockets: ptr.Ptr(true), - Timeout: durationPtr(options.DefaultUpstreamTimeout), + Timeout: ptr.Ptr(options.DefaultUpstreamTimeout), InsecureSkipTLSVerify: ptr.Ptr(false), DisableKeepAlives: ptr.Ptr(false), }, diff --git a/pkg/apis/middleware/session.go b/pkg/apis/middleware/session.go index 9fcd974b89..e17c0249fd 100644 --- a/pkg/apis/middleware/session.go +++ b/pkg/apis/middleware/session.go @@ -6,6 +6,7 @@ import ( "github.com/coreos/go-oidc/v3/oidc" sessionsapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) // TokenToSessionFunc takes a raw ID Token and converts it into a SessionState. @@ -40,7 +41,7 @@ func CreateTokenToSessionFunc(verify VerifyFunc) TokenToSessionFunc { claims.Email = claims.Subject } - if claims.Verified != nil && !*claims.Verified { + if !ptr.Deref(claims.Verified, false) { return nil, fmt.Errorf("email in id_token (%s) isn't verified", claims.Email) } diff --git a/pkg/apis/options/alpha_options.go b/pkg/apis/options/alpha_options.go index 0c78359a64..33daf17fe8 100644 --- a/pkg/apis/options/alpha_options.go +++ b/pkg/apis/options/alpha_options.go @@ -65,9 +65,9 @@ func (a *AlphaOptions) ExtractFrom(opts *Options) { a.Providers = opts.Providers } -// MergeInto replaces alpha options in the Options struct with the values -// from the AlphaOptions -func (a *AlphaOptions) MergeInto(opts *Options) { +// MergeOptionsWithDefaults replaces alpha options in the Options struct +// with the values from the AlphaOptions and ensures the defaults +func (a *AlphaOptions) MergeOptionsWithDefaults(opts *Options) { opts.UpstreamServers = a.UpstreamConfig opts.InjectRequestHeaders = a.InjectRequestHeaders opts.InjectResponseHeaders = a.InjectResponseHeaders diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index 048b19741f..a47e8a9527 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -1,5 +1,7 @@ package options +import "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" + // Header represents an individual header that will be added to a request or // response header. type Header struct { @@ -53,3 +55,28 @@ type ClaimSource struct { // basicAuthPassword will be used as the password value. BasicAuthPassword *SecretSource `yaml:"basicAuthPassword,omitempty"` } + +// EnsureDefaults sets any default values for Header fields. +func (h *Header) EnsureDefaults() { + if h.PreserveRequestValue == nil { + h.PreserveRequestValue = ptr.Ptr(false) + } + for i := range h.Values { + h.Values[i].EnsureDefaults() + } +} + +// EnsureDefaults sets any default values for HeaderValue fields. +func (hv *HeaderValue) EnsureDefaults() { + if hv.ClaimSource != nil { + hv.ClaimSource.EnsureDefaults() + } + if hv.SecretSource != nil { + hv.SecretSource.EnsureDefaults() + } +} + +// EnsureDefaults sets any default values for ClaimSource fields. +func (hc *ClaimSource) EnsureDefaults() { + // No defaults to set currently +} diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index 672d6c63fd..ffd98bd1b2 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -177,10 +177,6 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { // Force defaults compatible with static responses upstream.URI = "" upstream.InsecureSkipTLSVerify = ptr.Ptr(false) - upstream.PassHostHeader = nil - upstream.ProxyWebSockets = nil - upstream.FlushInterval = nil - upstream.Timeout = nil upstream.DisableKeepAlives = ptr.Ptr(false) case "unix": upstream.Path = "/" diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index 4348021b1e..cc2a76e5be 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -3,6 +3,7 @@ package options import ( "time" + . "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options/testutil" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -132,7 +133,7 @@ var _ = Describe("Legacy Options", func() { converted, err := legacyOpts.ToOptions() Expect(err).ToNot(HaveOccurred()) - Expect(converted).To(Equal(opts)) + Expect(converted).To(EqualOpts(opts)) }) }) diff --git a/pkg/apis/options/options.go b/pkg/apis/options/options.go index 8fa72c7c5d..b57d5aeda5 100644 --- a/pkg/apis/options/options.go +++ b/pkg/apis/options/options.go @@ -168,3 +168,23 @@ func NewFlagSet() *pflag.FlagSet { return flagSet } + +// EnsureDefaults configures the defaults for all options +// to ensure no unexpected empty strings for enum types or nils for booleans +func (o *Options) EnsureDefaults() { + o.Providers.EnsureDefaults() + o.UpstreamServers.EnsureDefaults() + + for i := range o.InjectRequestHeaders { + o.InjectRequestHeaders[i].EnsureDefaults() + } + for i := range o.InjectResponseHeaders { + o.InjectResponseHeaders[i].EnsureDefaults() + } + + // TBD: Uncomment as we add EnsureDefaults methods + // o.Cookie.EnsureDefaults() + // o.Session.EnsureDefaults() + // o.Templates.EnsureDefaults() + // o.Logging.EnsureDefaults() +} diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 027464de42..ed836656f4 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -289,6 +289,7 @@ type LoginGovOptions struct { PubJWKURL string `yaml:"pubjwkURL,omitempty"` } +// Legacy default providers configuration func providerDefaults() Providers { providers := Providers{ { @@ -310,3 +311,72 @@ func providerDefaults() Providers { } return providers } + +// EnsureDefaults sets any default values for Providers fields. +func (p Providers) EnsureDefaults() { + for i := range p { + p[i].EnsureDefaults() + } +} + +// EnsureDefaults sets any default values for Provider fields. +func (p *Provider) EnsureDefaults() { + if p.SkipClaimsFromProfileURL == nil { + p.SkipClaimsFromProfileURL = ptr.Ptr(false) + } + if p.UseSystemTrustStore == nil { + p.UseSystemTrustStore = ptr.Ptr(true) + } + + p.OIDCConfig.EnsureDefaults() + p.MicrosoftEntraIDConfig.EnsureDefaults() + p.ADFSConfig.EnsureDefaults() + p.GoogleConfig.EnsureDefaults() +} + +// EnsureDefaults sets any default values for OIDCOptions fields. +func (o *OIDCOptions) EnsureDefaults() { + // Ensure OIDC defaults + if o.InsecureAllowUnverifiedEmail == nil { + o.InsecureAllowUnverifiedEmail = ptr.Ptr(false) + } + if o.InsecureSkipNonce == nil { + o.InsecureSkipNonce = ptr.Ptr(true) + } + if o.SkipDiscovery == nil { + o.SkipDiscovery = ptr.Ptr(false) + } + if o.UserIDClaim == "" { + o.UserIDClaim = OIDCEmailClaim + } + if o.EmailClaim == "" { + o.EmailClaim = OIDCEmailClaim + } + if o.GroupsClaim == "" { + o.GroupsClaim = OIDCGroupsClaim + } + if len(o.AudienceClaims) == 0 { + o.AudienceClaims = OIDCAudienceClaims + } +} + +// EnsureDefaults sets any default values for MicrosoftEntraIDOptions fields. +func (me *MicrosoftEntraIDOptions) EnsureDefaults() { + if me.FederatedTokenAuth == nil { + me.FederatedTokenAuth = ptr.Ptr(false) + } +} + +// EnsureDefaults sets any default values for ADFSOptions fields. +func (a *ADFSOptions) EnsureDefaults() { + if a.SkipScope == nil { + a.SkipScope = ptr.Ptr(false) + } +} + +// EnsureDefaults sets any default values for GoogleOptions fields. +func (g *GoogleOptions) EnsureDefaults() { + if g.UseApplicationDefaultCredentials == nil { + g.UseApplicationDefaultCredentials = ptr.Ptr(false) + } +} diff --git a/pkg/apis/options/secret_source.go b/pkg/apis/options/secret_source.go index 848f163518..8b78334265 100644 --- a/pkg/apis/options/secret_source.go +++ b/pkg/apis/options/secret_source.go @@ -12,3 +12,8 @@ type SecretSource struct { // FromFile expects a path to a file containing the secret value. FromFile string `yaml:"fromFile,omitempty"` } + +// EnsureDefaults sets any default values for SecretSource fields. +func (ss *SecretSource) EnsureDefaults() { + // No defaults to set currently +} diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index f12a4bf3f1..05c12e0330 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -1,6 +1,10 @@ package options -import "time" +import ( + "time" + + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" +) const ( // DefaultUpstreamFlushInterval is the default value for the Upstream FlushInterval. @@ -98,3 +102,38 @@ type Upstream struct { // Defaults to false. DisableKeepAlives *bool `yaml:"disableKeepAlives,omitempty"` } + +// EnsureDefaults sets any default values for UpstreamConfig fields. +func (uc *UpstreamConfig) EnsureDefaults() { + if uc.ProxyRawPath == nil { + uc.ProxyRawPath = ptr.Ptr(false) + } + for i := range uc.Upstreams { + uc.Upstreams[i].EnsureDefaults() + } +} + +// EnsureDefaults sets any default values for Upstream fields. +func (u *Upstream) EnsureDefaults() { + if u.InsecureSkipTLSVerify == nil { + u.InsecureSkipTLSVerify = ptr.Ptr(false) + } + if u.Static == nil { + u.Static = ptr.Ptr(false) + } + if u.FlushInterval == nil { + u.FlushInterval = ptr.Ptr(DefaultUpstreamFlushInterval) + } + if u.PassHostHeader == nil { + u.PassHostHeader = ptr.Ptr(true) + } + if u.ProxyWebSockets == nil { + u.ProxyWebSockets = ptr.Ptr(true) + } + if u.Timeout == nil { + u.Timeout = ptr.Ptr(DefaultUpstreamTimeout) + } + if u.DisableKeepAlives == nil { + u.DisableKeepAlives = ptr.Ptr(false) + } +} diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index 38e0e7a961..59580ee335 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -11,6 +11,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/hmacauth" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) const ( @@ -53,8 +54,8 @@ func newHTTPUpstreamProxy(upstream options.Upstream, u *url.URL, sigData *option // Set up a WebSocket proxy if required var wsProxy http.Handler - if upstream.ProxyWebSockets == nil || *upstream.ProxyWebSockets { - wsProxy = newWebSocketReverseProxy(u, *upstream.InsecureSkipTLSVerify) + if *upstream.ProxyWebSockets { + wsProxy = newWebSocketReverseProxy(u, upstream.InsecureSkipTLSVerify) } var auth hmacauth.HmacAuth @@ -156,7 +157,7 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // Ensure we always pass the original request path setProxyDirector(proxy) - if upstream.PassHostHeader != nil && !*upstream.PassHostHeader { + if upstream.PassHostHeader != nil && !(*upstream.PassHostHeader) { setProxyUpstreamHostHeader(proxy, target) } @@ -200,14 +201,14 @@ func setProxyDirector(proxy *httputil.ReverseProxy) { } // newWebSocketReverseProxy creates a new reverse proxy for proxying websocket connections. -func newWebSocketReverseProxy(u *url.URL, skipTLSVerify bool) http.Handler { +func newWebSocketReverseProxy(u *url.URL, skipTLSVerify *bool) http.Handler { wsProxy := httputil.NewSingleHostReverseProxy(u) // Inherit default transport options from Go's stdlib transport := http.DefaultTransport.(*http.Transport).Clone() /* #nosec G402 */ - if skipTLSVerify { + if ptr.Deref(skipTLSVerify, false) { transport.TLSClientConfig.InsecureSkipVerify = true } diff --git a/pkg/validation/providers.go b/pkg/validation/providers.go index 3abf69d40a..345274d897 100644 --- a/pkg/validation/providers.go +++ b/pkg/validation/providers.go @@ -5,7 +5,6 @@ import ( "os" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" - "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) // validateProviders is the initial validation migration for multiple providrers @@ -97,9 +96,9 @@ func validateGoogleConfig(provider options.Provider) []string { hasAdminEmail := provider.GoogleConfig.AdminEmail != "" hasSAJSON := provider.GoogleConfig.ServiceAccountJSON != "" - useADC := ptr.Deref(provider.GoogleConfig.UseApplicationDefaultCredentials, false) + useADC := provider.GoogleConfig.UseApplicationDefaultCredentials - if !hasAdminEmail && !hasSAJSON && !useADC { + if !hasAdminEmail && !hasSAJSON && !(*useADC) { return msgs } @@ -108,7 +107,7 @@ func validateGoogleConfig(provider options.Provider) []string { } _, err := os.Stat(provider.GoogleConfig.ServiceAccountJSON) - if !useADC { + if !(*useADC) { if !hasSAJSON { msgs = append(msgs, "missing setting: google-service-account-json or google-use-application-default-credentials") } else if err != nil { diff --git a/pkg/validation/upstreams.go b/pkg/validation/upstreams.go index 05d441e3a5..2750e22c93 100644 --- a/pkg/validation/upstreams.go +++ b/pkg/validation/upstreams.go @@ -54,12 +54,12 @@ func validateUpstream(upstream options.Upstream, ids, paths map[string]struct{}) func validateStaticUpstream(upstream options.Upstream) []string { msgs := []string{} - if !*upstream.Static && upstream.StaticCode != nil { + if !(*upstream.Static) && upstream.StaticCode != nil { msgs = append(msgs, fmt.Sprintf("upstream %q has staticCode (%d), but is not a static upstream, set 'static' for a static response", upstream.ID, *upstream.StaticCode)) } // Checks after this only make sense when the upstream is static - if !*upstream.Static { + if !(*upstream.Static) { return msgs } @@ -72,10 +72,10 @@ func validateStaticUpstream(upstream options.Upstream) []string { if upstream.FlushInterval != nil && *upstream.FlushInterval != options.DefaultUpstreamFlushInterval { msgs = append(msgs, fmt.Sprintf("upstream %q has flushInterval, but is a static upstream, this will have no effect.", upstream.ID)) } - if upstream.PassHostHeader != nil { + if *upstream.PassHostHeader { msgs = append(msgs, fmt.Sprintf("upstream %q has passHostHeader, but is a static upstream, this will have no effect.", upstream.ID)) } - if upstream.ProxyWebSockets != nil { + if *upstream.ProxyWebSockets { msgs = append(msgs, fmt.Sprintf("upstream %q has proxyWebSockets, but is a static upstream, this will have no effect.", upstream.ID)) } @@ -85,7 +85,7 @@ func validateStaticUpstream(upstream options.Upstream) []string { func validateUpstreamURI(upstream options.Upstream) []string { msgs := []string{} - if !*upstream.Static && upstream.URI == "" { + if !(*upstream.Static) && upstream.URI == "" { msgs = append(msgs, fmt.Sprintf("upstream %q has empty uri: uris are required for all non-static upstreams", upstream.ID)) return msgs } From ceb9a387b12b06230e4e03fef67edbb4931bc1a1 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 31 Oct 2025 16:11:54 +0100 Subject: [PATCH 085/125] deref everything... but why? Signed-off-by: Jan Larwig --- main.go | 7 +++++-- main_test.go | 17 ++++++++++++----- pkg/middleware/headers.go | 3 ++- pkg/upstream/http.go | 8 ++++---- pkg/upstream/proxy.go | 7 ++++--- pkg/upstream/static.go | 13 ++----------- pkg/validation/options.go | 3 ++- pkg/validation/providers.go | 11 ++++++----- pkg/validation/upstreams.go | 17 +++++++++-------- providers/adfs.go | 3 ++- providers/google.go | 9 ++++----- providers/ms_entra_id.go | 3 ++- providers/oidc.go | 3 ++- providers/providers.go | 9 +++++---- 14 files changed, 61 insertions(+), 52 deletions(-) diff --git a/main.go b/main.go index 7e18b95fc1..42e8bab066 100644 --- a/main.go +++ b/main.go @@ -75,11 +75,14 @@ func loadConfiguration(config, yamlConfig string, extraFlags *pflag.FlagSet, arg if yamlConfig != "" { logger.Printf("WARNING: You are using alpha configuration. The structure in this configuration file may change without notice. You MUST remove conflicting options from your existing configuration.") - return loadYamlOptions(yamlConfig, config, extraFlags, args) + opts, err = loadYamlOptions(yamlConfig, config, extraFlags, args) + if err != nil { + return nil, fmt.Errorf("failed to load yaml options: %w", err) + } } + // Ensure defaults after loading configuration opts.EnsureDefaults() - return opts, nil } diff --git a/main_test.go b/main_test.go index 0323c838c9..1d9102d7d1 100644 --- a/main_test.go +++ b/main_test.go @@ -123,6 +123,7 @@ redirect_url="http://localhost:4180/oauth2/callback" opts.RawRedirectURL = "http://localhost:4180/oauth2/callback" opts.UpstreamServers = options.UpstreamConfig{ + ProxyRawPath: ptr.Ptr(false), Upstreams: []options.Upstream{ { ID: "/", @@ -132,6 +133,7 @@ redirect_url="http://localhost:4180/oauth2/callback" PassHostHeader: ptr.Ptr(true), ProxyWebSockets: ptr.Ptr(true), Timeout: ptr.Ptr(options.DefaultUpstreamTimeout), + Static: ptr.Ptr(false), InsecureSkipTLSVerify: ptr.Ptr(false), DisableKeepAlives: ptr.Ptr(false), }, @@ -139,7 +141,8 @@ redirect_url="http://localhost:4180/oauth2/callback" } authHeader := options.Header{ - Name: "Authorization", + Name: "Authorization", + PreserveRequestValue: ptr.Ptr(false), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ @@ -153,10 +156,7 @@ redirect_url="http://localhost:4180/oauth2/callback" }, } - authHeader.PreserveRequestValue = ptr.Ptr(false) opts.InjectRequestHeaders = append([]options.Header{authHeader}, opts.InjectRequestHeaders...) - - authHeader.PreserveRequestValue = nil opts.InjectResponseHeaders = append(opts.InjectResponseHeaders, authHeader) opts.Providers = options.Providers{ @@ -186,6 +186,12 @@ redirect_url="http://localhost:4180/oauth2/callback" InsecureSkipIssuerVerification: ptr.Ptr(false), SkipDiscovery: ptr.Ptr(false), }, + MicrosoftEntraIDConfig: options.MicrosoftEntraIDOptions{ + FederatedTokenAuth: ptr.Ptr(false), + }, + ADFSConfig: options.ADFSOptions{ + SkipScope: ptr.Ptr(false), + }, LoginURLParameters: []options.LoginURLParameter{ {Name: "approval_prompt", Default: []string{"force"}}, }, @@ -254,7 +260,8 @@ redirect_url="http://localhost:4180/oauth2/callback" Expect(err).ToNot(HaveOccurred()) } Expect(in.expectedOptions).ToNot(BeNil()) - Expect(opts).To(EqualOpts(in.expectedOptions())) + expectedOpts := in.expectedOptions() + Expect(opts).To(EqualOpts(expectedOpts)) }, Entry("with legacy configuration", loadConfigurationTableInput{ configContent: testCoreConfig + testLegacyConfig, diff --git a/pkg/middleware/headers.go b/pkg/middleware/headers.go index d9287505e8..ed82a30b01 100644 --- a/pkg/middleware/headers.go +++ b/pkg/middleware/headers.go @@ -9,6 +9,7 @@ import ( middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/header" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) func NewRequestHeaderInjector(headers []options.Header) (alice.Constructor, error) { @@ -27,7 +28,7 @@ func NewRequestHeaderInjector(headers []options.Header) (alice.Constructor, erro func newStripHeaders(headers []options.Header) alice.Constructor { headersToStrip := []options.Header{} for _, header := range headers { - if !(*header.PreserveRequestValue) { + if !ptr.Deref(header.PreserveRequestValue, false) { headersToStrip = append(headersToStrip, header) } } diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index 59580ee335..9c33f96cd2 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -54,7 +54,7 @@ func newHTTPUpstreamProxy(upstream options.Upstream, u *url.URL, sigData *option // Set up a WebSocket proxy if required var wsProxy http.Handler - if *upstream.ProxyWebSockets { + if ptr.Deref(upstream.ProxyWebSockets, false) { wsProxy = newWebSocketReverseProxy(u, upstream.InsecureSkipTLSVerify) } @@ -150,14 +150,14 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // InsecureSkipVerify is a configurable option we allow /* #nosec G402 */ - if *upstream.InsecureSkipTLSVerify { + if ptr.Deref(upstream.InsecureSkipTLSVerify, false) { transport.TLSClientConfig.InsecureSkipVerify = true } // Ensure we always pass the original request path setProxyDirector(proxy) - if upstream.PassHostHeader != nil && !(*upstream.PassHostHeader) { + if !ptr.Deref(upstream.PassHostHeader, false) { setProxyUpstreamHostHeader(proxy, target) } @@ -169,7 +169,7 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // Pass on DisableKeepAlives to the transport settings // to allow for disabling HTTP keep-alive connections - transport.DisableKeepAlives = *upstream.DisableKeepAlives + transport.DisableKeepAlives = ptr.Deref(upstream.DisableKeepAlives, false) // Apply the customized transport to our proxy before returning it proxy.Transport = transport diff --git a/pkg/upstream/proxy.go b/pkg/upstream/proxy.go index 0d2286ea9a..acf24d1a59 100644 --- a/pkg/upstream/proxy.go +++ b/pkg/upstream/proxy.go @@ -14,6 +14,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/app/pagewriter" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) // ProxyErrorHandler is a function that will be used to render error pages when @@ -27,12 +28,12 @@ func NewProxy(upstreams options.UpstreamConfig, sigData *options.SignatureData, serveMux: mux.NewRouter(), } - if *upstreams.ProxyRawPath { + if ptr.Deref(upstreams.ProxyRawPath, false) { m.serveMux.UseEncodedPath() } for _, upstream := range sortByPathLongest(upstreams.Upstreams) { - if *upstream.Static { + if ptr.Deref(upstream.Static, false) { if err := m.registerStaticResponseHandler(upstream, writer); err != nil { return nil, fmt.Errorf("could not register static upstream %q: %v", upstream.ID, err) } @@ -74,7 +75,7 @@ func (m *multiUpstreamProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request // registerStaticResponseHandler registers a static response handler with at the given path. func (m *multiUpstreamProxy) registerStaticResponseHandler(upstream options.Upstream, writer pagewriter.Writer) error { - logger.Printf("mapping path %q => static response %d", upstream.Path, derefStaticCode(upstream.StaticCode)) + logger.Printf("mapping path %q => static response %d", upstream.Path, ptr.Deref(upstream.StaticCode, 200)) return m.registerHandler(upstream, newStaticResponseHandler(upstream.ID, upstream.StaticCode), writer) } diff --git a/pkg/upstream/static.go b/pkg/upstream/static.go index 027f3e7454..d7d037bfd9 100644 --- a/pkg/upstream/static.go +++ b/pkg/upstream/static.go @@ -6,15 +6,14 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) -const defaultStaticResponseCode = 200 - // newStaticResponseHandler creates a new staticResponseHandler that serves a // a static response code. func newStaticResponseHandler(upstream string, code *int) http.Handler { return &staticResponseHandler{ - code: derefStaticCode(code), + code: ptr.Deref(code, 200), upstream: upstream, } } @@ -38,11 +37,3 @@ func (s *staticResponseHandler) ServeHTTP(rw http.ResponseWriter, req *http.Requ logger.Errorf("Error writing static response: %v", err) } } - -// derefStaticCode returns the derefenced value, or the default if the value is nil -func derefStaticCode(code *int) int { - if code != nil { - return *code - } - return defaultStaticResponseCode -} diff --git a/pkg/validation/options.go b/pkg/validation/options.go index d5aba4e4ec..ffb0accc0a 100644 --- a/pkg/validation/options.go +++ b/pkg/validation/options.go @@ -15,6 +15,7 @@ import ( internaloidc "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/providers/oidc" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) // Validate checks that required options are set and validates those that they @@ -34,7 +35,7 @@ func Validate(o *options.Options) error { transport := requests.DefaultTransport.(*http.Transport) transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} // #nosec G402 -- InsecureSkipVerify is a configurable option we allow } else if len(o.Providers[0].CAFiles) > 0 { - pool, err := util.GetCertPool(o.Providers[0].CAFiles, *o.Providers[0].UseSystemTrustStore) + pool, err := util.GetCertPool(o.Providers[0].CAFiles, ptr.Deref(o.Providers[0].UseSystemTrustStore, false)) if err == nil { transport := requests.DefaultTransport.(*http.Transport) transport.TLSClientConfig = &tls.Config{ diff --git a/pkg/validation/providers.go b/pkg/validation/providers.go index 345274d897..1acdee65a7 100644 --- a/pkg/validation/providers.go +++ b/pkg/validation/providers.go @@ -5,6 +5,7 @@ import ( "os" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) // validateProviders is the initial validation migration for multiple providrers @@ -64,7 +65,7 @@ func validateProvider(provider options.Provider, providerIDs map[string]struct{} // providerRequiresClientSecret checks if provider requires client secret to be set // or it can be omitted in favor of JWT token to authenticate oAuth client func providerRequiresClientSecret(provider options.Provider) bool { - if provider.Type == "entra-id" && *provider.MicrosoftEntraIDConfig.FederatedTokenAuth { + if provider.Type == "entra-id" && ptr.Deref(provider.MicrosoftEntraIDConfig.FederatedTokenAuth, false) { return false } @@ -96,9 +97,9 @@ func validateGoogleConfig(provider options.Provider) []string { hasAdminEmail := provider.GoogleConfig.AdminEmail != "" hasSAJSON := provider.GoogleConfig.ServiceAccountJSON != "" - useADC := provider.GoogleConfig.UseApplicationDefaultCredentials + useADC := ptr.Deref(provider.GoogleConfig.UseApplicationDefaultCredentials, false) - if !hasAdminEmail && !hasSAJSON && !(*useADC) { + if !hasAdminEmail && !hasSAJSON && !useADC { return msgs } @@ -107,7 +108,7 @@ func validateGoogleConfig(provider options.Provider) []string { } _, err := os.Stat(provider.GoogleConfig.ServiceAccountJSON) - if !(*useADC) { + if !useADC { if !hasSAJSON { msgs = append(msgs, "missing setting: google-service-account-json or google-use-application-default-credentials") } else if err != nil { @@ -123,7 +124,7 @@ func validateGoogleConfig(provider options.Provider) []string { func validateEntraConfig(provider options.Provider) []string { msgs := []string{} - if *provider.MicrosoftEntraIDConfig.FederatedTokenAuth { + if ptr.Deref(provider.MicrosoftEntraIDConfig.FederatedTokenAuth, false) { federatedTokenPath := os.Getenv("AZURE_FEDERATED_TOKEN_FILE") if federatedTokenPath == "" { diff --git a/pkg/validation/upstreams.go b/pkg/validation/upstreams.go index 2750e22c93..4c5376782b 100644 --- a/pkg/validation/upstreams.go +++ b/pkg/validation/upstreams.go @@ -5,6 +5,7 @@ import ( "net/url" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) func validateUpstreams(upstreams options.UpstreamConfig) []string { @@ -54,28 +55,28 @@ func validateUpstream(upstream options.Upstream, ids, paths map[string]struct{}) func validateStaticUpstream(upstream options.Upstream) []string { msgs := []string{} - if !(*upstream.Static) && upstream.StaticCode != nil { + if !ptr.Deref(upstream.Static, false) && upstream.StaticCode != nil { msgs = append(msgs, fmt.Sprintf("upstream %q has staticCode (%d), but is not a static upstream, set 'static' for a static response", upstream.ID, *upstream.StaticCode)) } // Checks after this only make sense when the upstream is static - if !(*upstream.Static) { + if !ptr.Deref(upstream.Static, false) { return msgs } if upstream.URI != "" { msgs = append(msgs, fmt.Sprintf("upstream %q has uri, but is a static upstream, this will have no effect.", upstream.ID)) } - if *upstream.InsecureSkipTLSVerify { + if ptr.Deref(upstream.InsecureSkipTLSVerify, false) { msgs = append(msgs, fmt.Sprintf("upstream %q has insecureSkipTLSVerify, but is a static upstream, this will have no effect.", upstream.ID)) } - if upstream.FlushInterval != nil && *upstream.FlushInterval != options.DefaultUpstreamFlushInterval { + if ptr.Deref(upstream.FlushInterval, options.DefaultUpstreamFlushInterval) != options.DefaultUpstreamFlushInterval { msgs = append(msgs, fmt.Sprintf("upstream %q has flushInterval, but is a static upstream, this will have no effect.", upstream.ID)) } - if *upstream.PassHostHeader { + if ptr.Deref(upstream.PassHostHeader, false) { msgs = append(msgs, fmt.Sprintf("upstream %q has passHostHeader, but is a static upstream, this will have no effect.", upstream.ID)) } - if *upstream.ProxyWebSockets { + if ptr.Deref(upstream.ProxyWebSockets, false) { msgs = append(msgs, fmt.Sprintf("upstream %q has proxyWebSockets, but is a static upstream, this will have no effect.", upstream.ID)) } @@ -85,13 +86,13 @@ func validateStaticUpstream(upstream options.Upstream) []string { func validateUpstreamURI(upstream options.Upstream) []string { msgs := []string{} - if !(*upstream.Static) && upstream.URI == "" { + if !ptr.Deref(upstream.Static, false) && upstream.URI == "" { msgs = append(msgs, fmt.Sprintf("upstream %q has empty uri: uris are required for all non-static upstreams", upstream.ID)) return msgs } // Checks after this only make sense the upstream is not static - if *upstream.Static { + if !ptr.Deref(upstream.Static, false) { return msgs } diff --git a/providers/adfs.go b/providers/adfs.go index 6615f38c28..ebf91f71c9 100644 --- a/providers/adfs.go +++ b/providers/adfs.go @@ -8,6 +8,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) // ADFSProvider represents an ADFS based Identity Provider @@ -50,7 +51,7 @@ func NewADFSProvider(p *ProviderData, opts options.Provider) *ADFSProvider { return &ADFSProvider{ OIDCProvider: oidcProvider, - skipScope: *opts.ADFSConfig.SkipScope, + skipScope: ptr.Deref(opts.ADFSConfig.SkipScope, false), oidcEnrichFunc: oidcProvider.EnrichSession, oidcRefreshFunc: oidcProvider.RefreshSession, } diff --git a/providers/google.go b/providers/google.go index 64102ebcb9..ac38980f0d 100644 --- a/providers/google.go +++ b/providers/google.go @@ -19,6 +19,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" "golang.org/x/oauth2" "golang.org/x/oauth2/google" admin "google.golang.org/api/admin/directory/v1" @@ -108,9 +109,7 @@ func NewGoogleProvider(p *ProviderData, opts options.GoogleOptions) (*GoogleProv }, } - if opts.UseOrganizationID || opts.ServiceAccountJSON != "" || *opts.UseApplicationDefaultCredentials { - provider.configureGroups(opts) - + if opts.UseOrganizationID || opts.ServiceAccountJSON != "" || ptr.Deref(opts.UseApplicationDefaultCredentials, false) { // reuse admin service to avoid multiple calls for token var adminService *admin.Service @@ -133,7 +132,7 @@ func NewGoogleProvider(p *ProviderData, opts options.GoogleOptions) (*GoogleProv } } - if opts.ServiceAccountJSON != "" || opts.UseApplicationDefaultCredentials { + if opts.ServiceAccountJSON != "" || ptr.Deref(opts.UseApplicationDefaultCredentials, false) { if adminService == nil { adminService = getAdminService(opts) } @@ -305,7 +304,7 @@ var possibleScopesList = [...]string{ } func getOauth2TokenSource(ctx context.Context, opts options.GoogleOptions, scope string) oauth2.TokenSource { - if *opts.UseApplicationDefaultCredentials { + if ptr.Deref(opts.UseApplicationDefaultCredentials, false) { ts, err := impersonate.CredentialsTokenSource(ctx, impersonate.CredentialsConfig{ TargetPrincipal: getTargetPrincipal(ctx, opts), Scopes: strings.Split(scope, " "), diff --git a/providers/ms_entra_id.go b/providers/ms_entra_id.go index 752f9f44e2..57c4fae194 100644 --- a/providers/ms_entra_id.go +++ b/providers/ms_entra_id.go @@ -16,6 +16,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" "github.com/spf13/cast" "golang.org/x/oauth2" ) @@ -51,7 +52,7 @@ func NewMicrosoftEntraIDProvider(p *ProviderData, opts options.Provider) *Micros OIDCProvider: NewOIDCProvider(p, opts.OIDCConfig), multiTenantAllowedTenants: opts.MicrosoftEntraIDConfig.AllowedTenants, - federatedTokenAuth: *opts.MicrosoftEntraIDConfig.FederatedTokenAuth, + federatedTokenAuth: ptr.Deref(opts.MicrosoftEntraIDConfig.FederatedTokenAuth, false), microsoftGraphURL: microsoftGraphURL, } } diff --git a/providers/oidc.go b/providers/oidc.go index fa65e83953..5e28039d3f 100644 --- a/providers/oidc.go +++ b/providers/oidc.go @@ -12,6 +12,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" "golang.org/x/oauth2" ) @@ -50,7 +51,7 @@ func NewOIDCProvider(p *ProviderData, opts options.OIDCOptions) *OIDCProvider { return &OIDCProvider{ ProviderData: p, - SkipNonce: *opts.InsecureSkipNonce, + SkipNonce: ptr.Deref(opts.InsecureSkipNonce, false), } } diff --git a/providers/providers.go b/providers/providers.go index 84f5ec91ca..1c7ac652f6 100644 --- a/providers/providers.go +++ b/providers/providers.go @@ -9,6 +9,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" internaloidc "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/providers/oidc" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" k8serrors "k8s.io/apimachinery/pkg/util/errors" ) @@ -98,8 +99,8 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData, IssuerURL: providerConfig.OIDCConfig.IssuerURL, JWKsURL: providerConfig.OIDCConfig.JwksURL, PublicKeyFiles: providerConfig.OIDCConfig.PublicKeyFiles, - SkipDiscovery: *providerConfig.OIDCConfig.SkipDiscovery, - SkipIssuerVerification: *providerConfig.OIDCConfig.InsecureSkipIssuerVerification, + SkipDiscovery: ptr.Deref(providerConfig.OIDCConfig.SkipDiscovery, false), + SkipIssuerVerification: ptr.Deref(providerConfig.OIDCConfig.InsecureSkipIssuerVerification, false), }) if err != nil { return nil, fmt.Errorf("error building OIDC ProviderVerifier: %v", err) @@ -143,10 +144,10 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData, } // Make the OIDC options available to all providers that support it - p.AllowUnverifiedEmail = *providerConfig.OIDCConfig.InsecureAllowUnverifiedEmail + p.AllowUnverifiedEmail = ptr.Deref(providerConfig.OIDCConfig.InsecureAllowUnverifiedEmail, false) p.EmailClaim = providerConfig.OIDCConfig.EmailClaim p.GroupsClaim = providerConfig.OIDCConfig.GroupsClaim - p.SkipClaimsFromProfileURL = *providerConfig.SkipClaimsFromProfileURL + p.SkipClaimsFromProfileURL = ptr.Deref(providerConfig.SkipClaimsFromProfileURL, false) // Set PKCE enabled or disabled based on discovery and force options p.CodeChallengeMethod = parseCodeChallengeMethod(providerConfig) From 638fba417f25c4c9fd09fc0de6a4fa44b2555b95 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 7 Nov 2025 22:31:48 +0100 Subject: [PATCH 086/125] deref everything but now with default constants Signed-off-by: Jan Larwig --- pkg/apis/options/header.go | 7 +++- pkg/apis/options/providers.go | 62 +++++++++++++++++++++++++++-------- pkg/apis/options/upstreams.go | 38 ++++++++++++++++----- pkg/middleware/headers.go | 2 +- pkg/upstream/http.go | 8 ++--- pkg/upstream/proxy.go | 6 ++-- pkg/upstream/static.go | 3 +- pkg/validation/options.go | 2 +- pkg/validation/providers.go | 6 ++-- pkg/validation/upstreams.go | 14 ++++---- providers/adfs.go | 2 +- providers/adfs_test.go | 0 providers/google.go | 6 ++-- providers/ms_entra_id.go | 2 +- providers/oidc.go | 2 +- providers/providers.go | 8 ++--- 16 files changed, 116 insertions(+), 52 deletions(-) mode change 100755 => 100644 providers/adfs_test.go diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index a47e8a9527..a35955082b 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -2,6 +2,11 @@ package options import "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" +const ( + // DefaultHeaderPreserveRequestValue is the default value for Header.PreserveRequestValue + DefaultHeaderPreserveRequestValue bool = false +) + // Header represents an individual header that will be added to a request or // response header. type Header struct { @@ -59,7 +64,7 @@ type ClaimSource struct { // EnsureDefaults sets any default values for Header fields. func (h *Header) EnsureDefaults() { if h.PreserveRequestValue == nil { - h.PreserveRequestValue = ptr.Ptr(false) + h.PreserveRequestValue = ptr.Ptr(DefaultHeaderPreserveRequestValue) } for i := range h.Values { h.Values[i].EnsureDefaults() diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index ed836656f4..e8c3922694 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -4,10 +4,46 @@ import "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" const ( // OIDCEmailClaim is the generic email claim used by the OIDC provider. - OIDCEmailClaim = "email" + OIDCEmailClaim string = "email" // OIDCGroupsClaim is the generic groups claim used by the OIDC provider. - OIDCGroupsClaim = "groups" + OIDCGroupsClaim string = "groups" + + // DefaultSkipDiscovery is the default value + // for OIDCOptions.SkipDiscovery + DefaultSkipDiscovery bool = false + + // DefaultInsecureSkipNonce is the default value + // for OIDCOptions.InsecureSkipNonce + DefaultInsecureSkipNonce bool = true + + // DefaultInsecureAllowUnverifiedEmail is the default value + // for OIDCOptions.InsecureAllowUnverifiedEmail + DefaultInsecureAllowUnverifiedEmail bool = false + + // DefaultInsecureSkipIssuerVerification is the default value + // for OIDCOptions.InsecureSkipIssuerVerification + DefaultInsecureSkipIssuerVerification bool = false + + // DefaultSkipClaimsFromProfileURL is the default value + // for Provider.SkipClaimsFromProfileURL + DefaultSkipClaimsFromProfileURL bool = false + + // DefaultADFSSkipScope is the default value + // for ADFSOptions.SkipScope + DefaultADFSSkipScope bool = false + + // DefaultMicrosoftEntraIDUseFederatedToken is the default value + // for MicrosoftEntraIDOptions.FederatedTokenAuth + DefaultMicrosoftEntraIDUseFederatedToken bool = false + + // DefaultGoogleUseApplicationDefaultCredentials is the default values + // for GoogleOptions.UseApplicationDefaultCredentials + DefaultUseApplicationDefaultCredentials bool = false + + // DefaultUseSystemTrustStore is the default value + // for Provider.UseSystemTrustStore + DefaultUseSystemTrustStore bool = true ) // OIDCAudienceClaims is the generic audience claim list used by the OIDC provider. @@ -298,9 +334,9 @@ func providerDefaults() Providers { Tenant: "common", }, OIDCConfig: OIDCOptions{ - InsecureAllowUnverifiedEmail: ptr.Ptr(false), - InsecureSkipNonce: ptr.Ptr(true), - SkipDiscovery: ptr.Ptr(false), + InsecureAllowUnverifiedEmail: ptr.Ptr(DefaultInsecureAllowUnverifiedEmail), + InsecureSkipNonce: ptr.Ptr(DefaultInsecureSkipNonce), + SkipDiscovery: ptr.Ptr(DefaultSkipDiscovery), UserIDClaim: OIDCEmailClaim, // Deprecated: Use OIDCEmailClaim EmailClaim: OIDCEmailClaim, GroupsClaim: OIDCGroupsClaim, @@ -322,10 +358,10 @@ func (p Providers) EnsureDefaults() { // EnsureDefaults sets any default values for Provider fields. func (p *Provider) EnsureDefaults() { if p.SkipClaimsFromProfileURL == nil { - p.SkipClaimsFromProfileURL = ptr.Ptr(false) + p.SkipClaimsFromProfileURL = ptr.Ptr(DefaultSkipClaimsFromProfileURL) } if p.UseSystemTrustStore == nil { - p.UseSystemTrustStore = ptr.Ptr(true) + p.UseSystemTrustStore = ptr.Ptr(DefaultUseSystemTrustStore) } p.OIDCConfig.EnsureDefaults() @@ -338,13 +374,13 @@ func (p *Provider) EnsureDefaults() { func (o *OIDCOptions) EnsureDefaults() { // Ensure OIDC defaults if o.InsecureAllowUnverifiedEmail == nil { - o.InsecureAllowUnverifiedEmail = ptr.Ptr(false) + o.InsecureAllowUnverifiedEmail = ptr.Ptr(DefaultInsecureAllowUnverifiedEmail) } if o.InsecureSkipNonce == nil { - o.InsecureSkipNonce = ptr.Ptr(true) + o.InsecureSkipNonce = ptr.Ptr(DefaultInsecureSkipNonce) } if o.SkipDiscovery == nil { - o.SkipDiscovery = ptr.Ptr(false) + o.SkipDiscovery = ptr.Ptr(DefaultSkipDiscovery) } if o.UserIDClaim == "" { o.UserIDClaim = OIDCEmailClaim @@ -363,20 +399,20 @@ func (o *OIDCOptions) EnsureDefaults() { // EnsureDefaults sets any default values for MicrosoftEntraIDOptions fields. func (me *MicrosoftEntraIDOptions) EnsureDefaults() { if me.FederatedTokenAuth == nil { - me.FederatedTokenAuth = ptr.Ptr(false) + me.FederatedTokenAuth = ptr.Ptr(DefaultMicrosoftEntraIDUseFederatedToken) } } // EnsureDefaults sets any default values for ADFSOptions fields. func (a *ADFSOptions) EnsureDefaults() { if a.SkipScope == nil { - a.SkipScope = ptr.Ptr(false) + a.SkipScope = ptr.Ptr(DefaultADFSSkipScope) } } // EnsureDefaults sets any default values for GoogleOptions fields. func (g *GoogleOptions) EnsureDefaults() { if g.UseApplicationDefaultCredentials == nil { - g.UseApplicationDefaultCredentials = ptr.Ptr(false) + g.UseApplicationDefaultCredentials = ptr.Ptr(DefaultUseApplicationDefaultCredentials) } } diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index 05c12e0330..f69fec90dd 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -1,6 +1,7 @@ package options import ( + "net/http" "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" @@ -8,10 +9,31 @@ import ( const ( // DefaultUpstreamFlushInterval is the default value for the Upstream FlushInterval. - DefaultUpstreamFlushInterval = 1 * time.Second + DefaultUpstreamFlushInterval time.Duration = 1 * time.Second // DefaultUpstreamTimeout is the maximum duration a network dial to a upstream server for a response. - DefaultUpstreamTimeout = 30 * time.Second + DefaultUpstreamTimeout time.Duration = 30 * time.Second + + // DefaultUpstreamStatic determines if upstreams are static by default. + DefaultUpstreamStatic bool = false + + // DefaultUpstreamStaticCode is the default response code for static upstreams. + DefaultUpstreamStaticCode int = http.StatusOK // 200 + + // DefaultUpstreamProxyRawPath determines if upstreams will proxy the raw url path by default. + DefaultUpstreamProxyRawPath bool = false + + // DefaultUpstreamInsecureSkipTLSVerify determines if upstreams will skip TLS verification by default. + DefaultUpsteamInsecureSkipTLSVerify bool = false + + // DefaultUpstreamPassHostHeader determines if upstreams will pass the host header by default. + DefaultUpstreamPassHostHeader bool = true + + // DefaultUpstreamProxyWebSockets determines if upstreams will proxy websockets by default. + DefaultUpstreamProxyWebSockets bool = true + + // DefaultUpstreamDisableKeepAlives determines if upstreams will disable keep-alives by default. + DefaultUpstreamDisableKeepAlives bool = false ) // UpstreamConfig is a collection of definitions for upstream servers. @@ -106,7 +128,7 @@ type Upstream struct { // EnsureDefaults sets any default values for UpstreamConfig fields. func (uc *UpstreamConfig) EnsureDefaults() { if uc.ProxyRawPath == nil { - uc.ProxyRawPath = ptr.Ptr(false) + uc.ProxyRawPath = ptr.Ptr(DefaultUpstreamProxyRawPath) } for i := range uc.Upstreams { uc.Upstreams[i].EnsureDefaults() @@ -116,24 +138,24 @@ func (uc *UpstreamConfig) EnsureDefaults() { // EnsureDefaults sets any default values for Upstream fields. func (u *Upstream) EnsureDefaults() { if u.InsecureSkipTLSVerify == nil { - u.InsecureSkipTLSVerify = ptr.Ptr(false) + u.InsecureSkipTLSVerify = ptr.Ptr(DefaultUpsteamInsecureSkipTLSVerify) } if u.Static == nil { - u.Static = ptr.Ptr(false) + u.Static = ptr.Ptr(DefaultUpstreamStatic) } if u.FlushInterval == nil { u.FlushInterval = ptr.Ptr(DefaultUpstreamFlushInterval) } if u.PassHostHeader == nil { - u.PassHostHeader = ptr.Ptr(true) + u.PassHostHeader = ptr.Ptr(DefaultUpstreamPassHostHeader) } if u.ProxyWebSockets == nil { - u.ProxyWebSockets = ptr.Ptr(true) + u.ProxyWebSockets = ptr.Ptr(DefaultUpstreamProxyWebSockets) } if u.Timeout == nil { u.Timeout = ptr.Ptr(DefaultUpstreamTimeout) } if u.DisableKeepAlives == nil { - u.DisableKeepAlives = ptr.Ptr(false) + u.DisableKeepAlives = ptr.Ptr(DefaultUpstreamDisableKeepAlives) } } diff --git a/pkg/middleware/headers.go b/pkg/middleware/headers.go index ed82a30b01..b567f4f5b8 100644 --- a/pkg/middleware/headers.go +++ b/pkg/middleware/headers.go @@ -28,7 +28,7 @@ func NewRequestHeaderInjector(headers []options.Header) (alice.Constructor, erro func newStripHeaders(headers []options.Header) alice.Constructor { headersToStrip := []options.Header{} for _, header := range headers { - if !ptr.Deref(header.PreserveRequestValue, false) { + if !ptr.Deref(header.PreserveRequestValue, options.DefaultHeaderPreserveRequestValue) { headersToStrip = append(headersToStrip, header) } } diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index 9c33f96cd2..e8283144c8 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -54,7 +54,7 @@ func newHTTPUpstreamProxy(upstream options.Upstream, u *url.URL, sigData *option // Set up a WebSocket proxy if required var wsProxy http.Handler - if ptr.Deref(upstream.ProxyWebSockets, false) { + if ptr.Deref(upstream.ProxyWebSockets, options.DefaultUpstreamProxyWebSockets) { wsProxy = newWebSocketReverseProxy(u, upstream.InsecureSkipTLSVerify) } @@ -150,14 +150,14 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // InsecureSkipVerify is a configurable option we allow /* #nosec G402 */ - if ptr.Deref(upstream.InsecureSkipTLSVerify, false) { + if ptr.Deref(upstream.InsecureSkipTLSVerify, options.DefaultUpsteamInsecureSkipTLSVerify) { transport.TLSClientConfig.InsecureSkipVerify = true } // Ensure we always pass the original request path setProxyDirector(proxy) - if !ptr.Deref(upstream.PassHostHeader, false) { + if !ptr.Deref(upstream.PassHostHeader, options.DefaultUpstreamPassHostHeader) { setProxyUpstreamHostHeader(proxy, target) } @@ -169,7 +169,7 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // Pass on DisableKeepAlives to the transport settings // to allow for disabling HTTP keep-alive connections - transport.DisableKeepAlives = ptr.Deref(upstream.DisableKeepAlives, false) + transport.DisableKeepAlives = ptr.Deref(upstream.DisableKeepAlives, options.DefaultUpstreamDisableKeepAlives) // Apply the customized transport to our proxy before returning it proxy.Transport = transport diff --git a/pkg/upstream/proxy.go b/pkg/upstream/proxy.go index acf24d1a59..af4d2e84e0 100644 --- a/pkg/upstream/proxy.go +++ b/pkg/upstream/proxy.go @@ -28,12 +28,12 @@ func NewProxy(upstreams options.UpstreamConfig, sigData *options.SignatureData, serveMux: mux.NewRouter(), } - if ptr.Deref(upstreams.ProxyRawPath, false) { + if ptr.Deref(upstreams.ProxyRawPath, options.DefaultUpstreamProxyRawPath) { m.serveMux.UseEncodedPath() } for _, upstream := range sortByPathLongest(upstreams.Upstreams) { - if ptr.Deref(upstream.Static, false) { + if ptr.Deref(upstream.Static, options.DefaultUpstreamStatic) { if err := m.registerStaticResponseHandler(upstream, writer); err != nil { return nil, fmt.Errorf("could not register static upstream %q: %v", upstream.ID, err) } @@ -75,7 +75,7 @@ func (m *multiUpstreamProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request // registerStaticResponseHandler registers a static response handler with at the given path. func (m *multiUpstreamProxy) registerStaticResponseHandler(upstream options.Upstream, writer pagewriter.Writer) error { - logger.Printf("mapping path %q => static response %d", upstream.Path, ptr.Deref(upstream.StaticCode, 200)) + logger.Printf("mapping path %q => static response %d", upstream.Path, ptr.Deref(upstream.StaticCode, options.DefaultUpstreamStaticCode)) return m.registerHandler(upstream, newStaticResponseHandler(upstream.ID, upstream.StaticCode), writer) } diff --git a/pkg/upstream/static.go b/pkg/upstream/static.go index d7d037bfd9..6f002b8fe7 100644 --- a/pkg/upstream/static.go +++ b/pkg/upstream/static.go @@ -5,6 +5,7 @@ import ( "net/http" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" ) @@ -13,7 +14,7 @@ import ( // a static response code. func newStaticResponseHandler(upstream string, code *int) http.Handler { return &staticResponseHandler{ - code: ptr.Deref(code, 200), + code: ptr.Deref(code, options.DefaultUpstreamStaticCode), upstream: upstream, } } diff --git a/pkg/validation/options.go b/pkg/validation/options.go index ffb0accc0a..13ce2e0bf4 100644 --- a/pkg/validation/options.go +++ b/pkg/validation/options.go @@ -35,7 +35,7 @@ func Validate(o *options.Options) error { transport := requests.DefaultTransport.(*http.Transport) transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} // #nosec G402 -- InsecureSkipVerify is a configurable option we allow } else if len(o.Providers[0].CAFiles) > 0 { - pool, err := util.GetCertPool(o.Providers[0].CAFiles, ptr.Deref(o.Providers[0].UseSystemTrustStore, false)) + pool, err := util.GetCertPool(o.Providers[0].CAFiles, ptr.Deref(o.Providers[0].UseSystemTrustStore, options.DefaultUseSystemTrustStore)) if err == nil { transport := requests.DefaultTransport.(*http.Transport) transport.TLSClientConfig = &tls.Config{ diff --git a/pkg/validation/providers.go b/pkg/validation/providers.go index 1acdee65a7..9e62e98a45 100644 --- a/pkg/validation/providers.go +++ b/pkg/validation/providers.go @@ -65,7 +65,7 @@ func validateProvider(provider options.Provider, providerIDs map[string]struct{} // providerRequiresClientSecret checks if provider requires client secret to be set // or it can be omitted in favor of JWT token to authenticate oAuth client func providerRequiresClientSecret(provider options.Provider) bool { - if provider.Type == "entra-id" && ptr.Deref(provider.MicrosoftEntraIDConfig.FederatedTokenAuth, false) { + if provider.Type == "entra-id" && ptr.Deref(provider.MicrosoftEntraIDConfig.FederatedTokenAuth, options.DefaultMicrosoftEntraIDUseFederatedToken) { return false } @@ -97,7 +97,7 @@ func validateGoogleConfig(provider options.Provider) []string { hasAdminEmail := provider.GoogleConfig.AdminEmail != "" hasSAJSON := provider.GoogleConfig.ServiceAccountJSON != "" - useADC := ptr.Deref(provider.GoogleConfig.UseApplicationDefaultCredentials, false) + useADC := ptr.Deref(provider.GoogleConfig.UseApplicationDefaultCredentials, options.DefaultUseApplicationDefaultCredentials) if !hasAdminEmail && !hasSAJSON && !useADC { return msgs @@ -124,7 +124,7 @@ func validateGoogleConfig(provider options.Provider) []string { func validateEntraConfig(provider options.Provider) []string { msgs := []string{} - if ptr.Deref(provider.MicrosoftEntraIDConfig.FederatedTokenAuth, false) { + if ptr.Deref(provider.MicrosoftEntraIDConfig.FederatedTokenAuth, options.DefaultMicrosoftEntraIDUseFederatedToken) { federatedTokenPath := os.Getenv("AZURE_FEDERATED_TOKEN_FILE") if federatedTokenPath == "" { diff --git a/pkg/validation/upstreams.go b/pkg/validation/upstreams.go index 4c5376782b..4c566659d1 100644 --- a/pkg/validation/upstreams.go +++ b/pkg/validation/upstreams.go @@ -55,28 +55,28 @@ func validateUpstream(upstream options.Upstream, ids, paths map[string]struct{}) func validateStaticUpstream(upstream options.Upstream) []string { msgs := []string{} - if !ptr.Deref(upstream.Static, false) && upstream.StaticCode != nil { + if !ptr.Deref(upstream.Static, options.DefaultUpstreamStatic) && upstream.StaticCode != nil { msgs = append(msgs, fmt.Sprintf("upstream %q has staticCode (%d), but is not a static upstream, set 'static' for a static response", upstream.ID, *upstream.StaticCode)) } // Checks after this only make sense when the upstream is static - if !ptr.Deref(upstream.Static, false) { + if !ptr.Deref(upstream.Static, options.DefaultUpstreamStatic) { return msgs } if upstream.URI != "" { msgs = append(msgs, fmt.Sprintf("upstream %q has uri, but is a static upstream, this will have no effect.", upstream.ID)) } - if ptr.Deref(upstream.InsecureSkipTLSVerify, false) { + if ptr.Deref(upstream.InsecureSkipTLSVerify, options.DefaultUpsteamInsecureSkipTLSVerify) { msgs = append(msgs, fmt.Sprintf("upstream %q has insecureSkipTLSVerify, but is a static upstream, this will have no effect.", upstream.ID)) } if ptr.Deref(upstream.FlushInterval, options.DefaultUpstreamFlushInterval) != options.DefaultUpstreamFlushInterval { msgs = append(msgs, fmt.Sprintf("upstream %q has flushInterval, but is a static upstream, this will have no effect.", upstream.ID)) } - if ptr.Deref(upstream.PassHostHeader, false) { + if ptr.Deref(upstream.PassHostHeader, options.DefaultUpstreamPassHostHeader) { msgs = append(msgs, fmt.Sprintf("upstream %q has passHostHeader, but is a static upstream, this will have no effect.", upstream.ID)) } - if ptr.Deref(upstream.ProxyWebSockets, false) { + if ptr.Deref(upstream.ProxyWebSockets, options.DefaultUpstreamProxyWebSockets) { msgs = append(msgs, fmt.Sprintf("upstream %q has proxyWebSockets, but is a static upstream, this will have no effect.", upstream.ID)) } @@ -86,13 +86,13 @@ func validateStaticUpstream(upstream options.Upstream) []string { func validateUpstreamURI(upstream options.Upstream) []string { msgs := []string{} - if !ptr.Deref(upstream.Static, false) && upstream.URI == "" { + if !ptr.Deref(upstream.Static, options.DefaultUpstreamStatic) && upstream.URI == "" { msgs = append(msgs, fmt.Sprintf("upstream %q has empty uri: uris are required for all non-static upstreams", upstream.ID)) return msgs } // Checks after this only make sense the upstream is not static - if !ptr.Deref(upstream.Static, false) { + if !ptr.Deref(upstream.Static, options.DefaultUpstreamStatic) { return msgs } diff --git a/providers/adfs.go b/providers/adfs.go index ebf91f71c9..bc583df0b6 100644 --- a/providers/adfs.go +++ b/providers/adfs.go @@ -51,7 +51,7 @@ func NewADFSProvider(p *ProviderData, opts options.Provider) *ADFSProvider { return &ADFSProvider{ OIDCProvider: oidcProvider, - skipScope: ptr.Deref(opts.ADFSConfig.SkipScope, false), + skipScope: ptr.Deref(opts.ADFSConfig.SkipScope, options.DefaultADFSSkipScope), oidcEnrichFunc: oidcProvider.EnrichSession, oidcRefreshFunc: oidcProvider.RefreshSession, } diff --git a/providers/adfs_test.go b/providers/adfs_test.go old mode 100755 new mode 100644 diff --git a/providers/google.go b/providers/google.go index ac38980f0d..92d782247f 100644 --- a/providers/google.go +++ b/providers/google.go @@ -109,7 +109,7 @@ func NewGoogleProvider(p *ProviderData, opts options.GoogleOptions) (*GoogleProv }, } - if opts.UseOrganizationID || opts.ServiceAccountJSON != "" || ptr.Deref(opts.UseApplicationDefaultCredentials, false) { + if opts.UseOrganizationID || opts.ServiceAccountJSON != "" || ptr.Deref(opts.UseApplicationDefaultCredentials, options.DefaultUseApplicationDefaultCredentials) { // reuse admin service to avoid multiple calls for token var adminService *admin.Service @@ -132,7 +132,7 @@ func NewGoogleProvider(p *ProviderData, opts options.GoogleOptions) (*GoogleProv } } - if opts.ServiceAccountJSON != "" || ptr.Deref(opts.UseApplicationDefaultCredentials, false) { + if opts.ServiceAccountJSON != "" || ptr.Deref(opts.UseApplicationDefaultCredentials, options.DefaultUseApplicationDefaultCredentials) { if adminService == nil { adminService = getAdminService(opts) } @@ -304,7 +304,7 @@ var possibleScopesList = [...]string{ } func getOauth2TokenSource(ctx context.Context, opts options.GoogleOptions, scope string) oauth2.TokenSource { - if ptr.Deref(opts.UseApplicationDefaultCredentials, false) { + if ptr.Deref(opts.UseApplicationDefaultCredentials, options.DefaultUseApplicationDefaultCredentials) { ts, err := impersonate.CredentialsTokenSource(ctx, impersonate.CredentialsConfig{ TargetPrincipal: getTargetPrincipal(ctx, opts), Scopes: strings.Split(scope, " "), diff --git a/providers/ms_entra_id.go b/providers/ms_entra_id.go index 57c4fae194..f9445d69ff 100644 --- a/providers/ms_entra_id.go +++ b/providers/ms_entra_id.go @@ -52,7 +52,7 @@ func NewMicrosoftEntraIDProvider(p *ProviderData, opts options.Provider) *Micros OIDCProvider: NewOIDCProvider(p, opts.OIDCConfig), multiTenantAllowedTenants: opts.MicrosoftEntraIDConfig.AllowedTenants, - federatedTokenAuth: ptr.Deref(opts.MicrosoftEntraIDConfig.FederatedTokenAuth, false), + federatedTokenAuth: ptr.Deref(opts.MicrosoftEntraIDConfig.FederatedTokenAuth, options.DefaultMicrosoftEntraIDUseFederatedToken), microsoftGraphURL: microsoftGraphURL, } } diff --git a/providers/oidc.go b/providers/oidc.go index 5e28039d3f..b0be63bc7a 100644 --- a/providers/oidc.go +++ b/providers/oidc.go @@ -51,7 +51,7 @@ func NewOIDCProvider(p *ProviderData, opts options.OIDCOptions) *OIDCProvider { return &OIDCProvider{ ProviderData: p, - SkipNonce: ptr.Deref(opts.InsecureSkipNonce, false), + SkipNonce: ptr.Deref(opts.InsecureSkipNonce, options.DefaultInsecureSkipNonce), } } diff --git a/providers/providers.go b/providers/providers.go index 1c7ac652f6..6af51ecf01 100644 --- a/providers/providers.go +++ b/providers/providers.go @@ -99,8 +99,8 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData, IssuerURL: providerConfig.OIDCConfig.IssuerURL, JWKsURL: providerConfig.OIDCConfig.JwksURL, PublicKeyFiles: providerConfig.OIDCConfig.PublicKeyFiles, - SkipDiscovery: ptr.Deref(providerConfig.OIDCConfig.SkipDiscovery, false), - SkipIssuerVerification: ptr.Deref(providerConfig.OIDCConfig.InsecureSkipIssuerVerification, false), + SkipDiscovery: ptr.Deref(providerConfig.OIDCConfig.SkipDiscovery, options.DefaultSkipDiscovery), + SkipIssuerVerification: ptr.Deref(providerConfig.OIDCConfig.InsecureSkipIssuerVerification, options.DefaultInsecureSkipIssuerVerification), }) if err != nil { return nil, fmt.Errorf("error building OIDC ProviderVerifier: %v", err) @@ -144,10 +144,10 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData, } // Make the OIDC options available to all providers that support it - p.AllowUnverifiedEmail = ptr.Deref(providerConfig.OIDCConfig.InsecureAllowUnverifiedEmail, false) + p.AllowUnverifiedEmail = ptr.Deref(providerConfig.OIDCConfig.InsecureAllowUnverifiedEmail, options.DefaultInsecureAllowUnverifiedEmail) p.EmailClaim = providerConfig.OIDCConfig.EmailClaim p.GroupsClaim = providerConfig.OIDCConfig.GroupsClaim - p.SkipClaimsFromProfileURL = ptr.Deref(providerConfig.SkipClaimsFromProfileURL, false) + p.SkipClaimsFromProfileURL = ptr.Deref(providerConfig.SkipClaimsFromProfileURL, options.DefaultSkipClaimsFromProfileURL) // Set PKCE enabled or disabled based on discovery and force options p.CodeChallengeMethod = parseCodeChallengeMethod(providerConfig) From 137decb1ec59efc2eaa44df49372567272ca6dcc Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 7 Nov 2025 23:26:00 +0100 Subject: [PATCH 087/125] adapting unit tests and fixing minor issues introduced with the derefing Signed-off-by: Jan Larwig --- pkg/apis/middleware/session.go | 5 +- pkg/apis/options/legacy_options.go | 44 +++++++++---- pkg/apis/options/legacy_options_test.go | 86 +++++++++++++++++-------- pkg/apis/options/providers.go | 2 +- pkg/middleware/jwt_session_test.go | 4 +- pkg/validation/sessions_test.go | 4 +- pkg/validation/upstreams.go | 8 +-- 7 files changed, 103 insertions(+), 50 deletions(-) diff --git a/pkg/apis/middleware/session.go b/pkg/apis/middleware/session.go index e17c0249fd..afa56e9d68 100644 --- a/pkg/apis/middleware/session.go +++ b/pkg/apis/middleware/session.go @@ -41,7 +41,10 @@ func CreateTokenToSessionFunc(verify VerifyFunc) TokenToSessionFunc { claims.Email = claims.Subject } - if !ptr.Deref(claims.Verified, false) { + // Ensure email is verified + // If the email is not verified, return an error + // If the email_verified claim is missing, assume it is verified + if !ptr.Deref(claims.Verified, true) { return nil, fmt.Errorf("email in id_token (%s) isn't verified", claims.Email) } diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index ffd98bd1b2..5f4efe578c 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -96,6 +96,7 @@ func (l *LegacyOptions) ToOptions() (*Options, error) { return nil, fmt.Errorf("error converting provider: %v", err) } l.Options.Providers = providers + l.Options.EnsureDefaults() return &l.Options, nil } @@ -178,6 +179,10 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { upstream.URI = "" upstream.InsecureSkipTLSVerify = ptr.Ptr(false) upstream.DisableKeepAlives = ptr.Ptr(false) + upstream.PassHostHeader = nil + upstream.ProxyWebSockets = nil + upstream.FlushInterval = nil + upstream.Timeout = nil case "unix": upstream.Path = "/" } @@ -284,7 +289,8 @@ func getBasicAuthHeader(preferEmailToUser bool, basicAuthPassword string) Header } return Header{ - Name: "Authorization", + Name: "Authorization", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -302,7 +308,8 @@ func getBasicAuthHeader(preferEmailToUser bool, basicAuthPassword string) Header func getPassUserHeaders(preferEmailToUser bool) []Header { headers := []Header{ { - Name: "X-Forwarded-Groups", + Name: "X-Forwarded-Groups", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -316,7 +323,8 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { if preferEmailToUser { return append(headers, Header{ - Name: "X-Forwarded-User", + Name: "X-Forwarded-User", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -330,7 +338,8 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { return append(headers, Header{ - Name: "X-Forwarded-User", + Name: "X-Forwarded-User", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -340,7 +349,8 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { }, }, Header{ - Name: "X-Forwarded-Email", + Name: "X-Forwarded-Email", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -354,7 +364,8 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { func getPassAccessTokenHeader() Header { return Header{ - Name: "X-Forwarded-Access-Token", + Name: "X-Forwarded-Access-Token", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -367,7 +378,8 @@ func getPassAccessTokenHeader() Header { func getAuthorizationHeader() Header { return Header{ - Name: "Authorization", + Name: "Authorization", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -381,7 +393,8 @@ func getAuthorizationHeader() Header { func getPreferredUsernameHeader() Header { return Header{ - Name: "X-Forwarded-Preferred-Username", + Name: "X-Forwarded-Preferred-Username", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -395,7 +408,8 @@ func getPreferredUsernameHeader() Header { func getXAuthRequestHeaders() []Header { headers := []Header{ { - Name: "X-Auth-Request-User", + Name: "X-Auth-Request-User", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -405,7 +419,8 @@ func getXAuthRequestHeaders() []Header { }, }, { - Name: "X-Auth-Request-Email", + Name: "X-Auth-Request-Email", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -415,7 +430,8 @@ func getXAuthRequestHeaders() []Header { }, }, { - Name: "X-Auth-Request-Preferred-Username", + Name: "X-Auth-Request-Preferred-Username", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -425,7 +441,8 @@ func getXAuthRequestHeaders() []Header { }, }, { - Name: "X-Auth-Request-Groups", + Name: "X-Auth-Request-Groups", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -441,7 +458,8 @@ func getXAuthRequestHeaders() []Header { func getXAuthRequestAccessTokenHeader() Header { return Header{ - Name: "X-Auth-Request-Access-Token", + Name: "X-Auth-Request-Access-Token", + PreserveRequestValue: ptr.Ptr(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index cc2a76e5be..65813c801b 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -122,16 +122,19 @@ var _ = Describe("Legacy Options", func() { BindAddress: "127.0.0.1:4180", } - opts.Providers[0].ClientID = "oauth-proxy" opts.Providers[0].ID = "google=oauth-proxy" - opts.Providers[0].OIDCConfig.InsecureSkipNonce = ptr.Ptr(true) + opts.Providers[0].ClientID = "oauth-proxy" opts.Providers[0].OIDCConfig.AudienceClaims = []string{"aud"} opts.Providers[0].OIDCConfig.ExtraAudiences = []string{} + opts.Providers[0].OIDCConfig.InsecureSkipNonce = ptr.Ptr(true) + opts.Providers[0].OIDCConfig.InsecureSkipIssuerVerification = ptr.Ptr(false) opts.Providers[0].LoginURLParameters = []LoginURLParameter{ {Name: "approval_prompt", Default: []string{"force"}}, } converted, err := legacyOpts.ToOptions() + opts.EnsureDefaults() + Expect(err).ToNot(HaveOccurred()) Expect(converted).To(EqualOpts(opts)) }) @@ -944,37 +947,50 @@ var _ = Describe("Legacy Options", func() { {Name: "approval_prompt", Default: []string{"force"}}, } - defaultProvider := Provider{ - ID: "google=" + clientID, - ClientID: clientID, - Type: "google", - LoginURLParameters: defaultURLParams, + defaultOIDCOptions := OIDCOptions{ + SkipDiscovery: ptr.Ptr(false), + InsecureSkipNonce: ptr.Ptr(false), + InsecureAllowUnverifiedEmail: ptr.Ptr(false), + InsecureSkipIssuerVerification: ptr.Ptr(false), } + + defaultGoogleOptions := GoogleOptions{ + UseApplicationDefaultCredentials: ptr.Ptr(false), + } + defaultLegacyProvider := LegacyProvider{ ClientID: clientID, ProviderType: "google", } - defaultProviderWithPrompt := Provider{ - ID: "google=" + clientID, - ClientID: clientID, - Type: "google", - LoginURLParameters: []LoginURLParameter{ - {Name: "prompt", Default: []string{"switch_user"}}, - }, + defaultProvider := Provider{ + ID: "google=" + clientID, + ClientID: clientID, + Type: "google", + OIDCConfig: defaultOIDCOptions, + GoogleConfig: defaultGoogleOptions, + LoginURLParameters: defaultURLParams, + UseSystemTrustStore: ptr.Ptr(false), + SkipClaimsFromProfileURL: ptr.Ptr(false), } + defaultLegacyProviderWithPrompt := LegacyProvider{ ClientID: clientID, ProviderType: "google", Prompt: "switch_user", } - displayNameProvider := Provider{ - ID: "displayName", - Name: "displayName", - ClientID: clientID, - Type: "google", - LoginURLParameters: defaultURLParams, + defaultProviderWithPrompt := Provider{ + ID: "google=" + clientID, + ClientID: clientID, + Type: "google", + OIDCConfig: defaultOIDCOptions, + GoogleConfig: defaultGoogleOptions, + LoginURLParameters: []LoginURLParameter{ + {Name: "prompt", Default: []string{"switch_user"}}, + }, + UseSystemTrustStore: ptr.Ptr(false), + SkipClaimsFromProfileURL: ptr.Ptr(false), } displayNameLegacyProvider := LegacyProvider{ @@ -983,16 +999,32 @@ var _ = Describe("Legacy Options", func() { ProviderType: "google", } + displayNameProvider := Provider{ + ID: "displayName", + Name: "displayName", + ClientID: clientID, + Type: "google", + OIDCConfig: defaultOIDCOptions, + GoogleConfig: defaultGoogleOptions, + LoginURLParameters: defaultURLParams, + UseSystemTrustStore: ptr.Ptr(false), + SkipClaimsFromProfileURL: ptr.Ptr(false), + } + internalConfigProvider := Provider{ - ID: "google=" + clientID, - ClientID: clientID, - Type: "google", + ID: "google=" + clientID, + ClientID: clientID, + Type: "google", + OIDCConfig: defaultOIDCOptions, GoogleConfig: GoogleOptions{ - AdminEmail: "email@email.com", - ServiceAccountJSON: "test.json", - Groups: []string{"1", "2"}, + AdminEmail: "email@email.com", + ServiceAccountJSON: "test.json", + Groups: []string{"1", "2"}, + UseApplicationDefaultCredentials: ptr.Ptr(false), }, - LoginURLParameters: defaultURLParams, + LoginURLParameters: defaultURLParams, + UseSystemTrustStore: ptr.Ptr(false), + SkipClaimsFromProfileURL: ptr.Ptr(false), } internalConfigLegacyProvider := LegacyProvider{ diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index e8c3922694..b93fb7adb5 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -43,7 +43,7 @@ const ( // DefaultUseSystemTrustStore is the default value // for Provider.UseSystemTrustStore - DefaultUseSystemTrustStore bool = true + DefaultUseSystemTrustStore bool = false ) // OIDCAudienceClaims is the generic audience claim list used by the OIDC provider. diff --git a/pkg/middleware/jwt_session_test.go b/pkg/middleware/jwt_session_test.go index 12f30f5c9c..7b724280d6 100644 --- a/pkg/middleware/jwt_session_test.go +++ b/pkg/middleware/jwt_session_test.go @@ -304,7 +304,7 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=` authorizationHeader: fmt.Sprintf("Bearer %s", nonVerifiedToken), expectedErr: k8serrors.NewAggregate([]error{ errors.New("unable to verify bearer token"), - errors.New("oidc: malformed jwt: oidc: malformed jwt payload: illegal base64 data at input byte 8"), + errors.New("oidc: malformed jwt: illegal base64 data at input byte 8"), }), expectedSession: nil, }), @@ -317,7 +317,7 @@ Nnc3a3lGVWFCNUMxQnNJcnJMTWxka1dFaHluYmI4Ongtb2F1dGgtYmFzaWM=` authorizationHeader: "Basic ZXlKZm9vYmFyLmV5SmZvb2Jhci4xMjM0NWFzZGY6", expectedErr: k8serrors.NewAggregate([]error{ errors.New("unable to verify bearer token"), - errors.New("oidc: malformed jwt: oidc: malformed jwt payload: illegal base64 data at input byte 8"), + errors.New("oidc: malformed jwt: illegal base64 data at input byte 8"), }), expectedSession: nil, }), diff --git a/pkg/validation/sessions_test.go b/pkg/validation/sessions_test.go index 6f590ac5d8..cb54c5714e 100644 --- a/pkg/validation/sessions_test.go +++ b/pkg/validation/sessions_test.go @@ -193,8 +193,8 @@ var _ = Describe("Sessions", func() { unreachableRedisDelMsg = "unable to delete the redis initialization key: dial tcp 127.0.0.1:65535: connect: connection refused" unreachableSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: redis: nil" unrechableSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable: redis: nil" - refusedSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: dial tcp 127.0.0.1:65535: connect: connection refused" - refusedSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable: dial tcp 127.0.0.1:65535: connect: connection refused" + refusedSentinelSetMsg = "unable to set a redis initialization key: redis: all sentinels specified in configuration are unreachable: context deadline exceeded" + refusedSentinelDelMsg = "unable to delete the redis initialization key: redis: all sentinels specified in configuration are unreachable: context deadline exceeded" ) type redisStoreTableInput struct { diff --git a/pkg/validation/upstreams.go b/pkg/validation/upstreams.go index 4c566659d1..9a3819180e 100644 --- a/pkg/validation/upstreams.go +++ b/pkg/validation/upstreams.go @@ -70,13 +70,13 @@ func validateStaticUpstream(upstream options.Upstream) []string { if ptr.Deref(upstream.InsecureSkipTLSVerify, options.DefaultUpsteamInsecureSkipTLSVerify) { msgs = append(msgs, fmt.Sprintf("upstream %q has insecureSkipTLSVerify, but is a static upstream, this will have no effect.", upstream.ID)) } - if ptr.Deref(upstream.FlushInterval, options.DefaultUpstreamFlushInterval) != options.DefaultUpstreamFlushInterval { + if upstream.FlushInterval != nil && *upstream.FlushInterval != options.DefaultUpstreamFlushInterval { msgs = append(msgs, fmt.Sprintf("upstream %q has flushInterval, but is a static upstream, this will have no effect.", upstream.ID)) } - if ptr.Deref(upstream.PassHostHeader, options.DefaultUpstreamPassHostHeader) { + if upstream.PassHostHeader != nil { msgs = append(msgs, fmt.Sprintf("upstream %q has passHostHeader, but is a static upstream, this will have no effect.", upstream.ID)) } - if ptr.Deref(upstream.ProxyWebSockets, options.DefaultUpstreamProxyWebSockets) { + if upstream.ProxyWebSockets != nil { msgs = append(msgs, fmt.Sprintf("upstream %q has proxyWebSockets, but is a static upstream, this will have no effect.", upstream.ID)) } @@ -92,7 +92,7 @@ func validateUpstreamURI(upstream options.Upstream) []string { } // Checks after this only make sense the upstream is not static - if !ptr.Deref(upstream.Static, options.DefaultUpstreamStatic) { + if ptr.Deref(upstream.Static, options.DefaultUpstreamStatic) { return msgs } From 0eec65e230219c389e837bfd97b21e00410b1e95 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sun, 16 Nov 2025 22:04:22 +0100 Subject: [PATCH 088/125] refactor: ptr.Ptr to ptr.To Signed-off-by: Jan Larwig --- main_test.go | 36 +++++----- oauthproxy_test.go | 4 +- pkg/apis/options/header.go | 2 +- pkg/apis/options/legacy_options.go | 34 ++++----- pkg/apis/options/legacy_options_test.go | 96 ++++++++++++------------- pkg/apis/options/providers.go | 22 +++--- pkg/apis/options/upstreams.go | 16 ++--- pkg/apis/sessions/session_state_test.go | 11 ++- pkg/middleware/headers_test.go | 8 +-- pkg/upstream/http_test.go | 16 ++--- pkg/upstream/proxy_test.go | 10 +-- pkg/util/ptr/ptr.go | 4 +- pkg/util/ptr/ptr_test.go | 12 ++-- pkg/validation/options_test.go | 4 +- pkg/validation/upstreams_test.go | 10 +-- providers/adfs_test.go | 2 +- providers/ms_entra_id_test.go | 6 +- providers/providers_test.go | 8 +-- 18 files changed, 149 insertions(+), 152 deletions(-) diff --git a/main_test.go b/main_test.go index 1d9102d7d1..dce11fcced 100644 --- a/main_test.go +++ b/main_test.go @@ -123,26 +123,26 @@ redirect_url="http://localhost:4180/oauth2/callback" opts.RawRedirectURL = "http://localhost:4180/oauth2/callback" opts.UpstreamServers = options.UpstreamConfig{ - ProxyRawPath: ptr.Ptr(false), + ProxyRawPath: ptr.To(false), Upstreams: []options.Upstream{ { ID: "/", Path: "/", URI: "http://httpbin", - FlushInterval: ptr.Ptr(options.DefaultUpstreamFlushInterval), - PassHostHeader: ptr.Ptr(true), - ProxyWebSockets: ptr.Ptr(true), - Timeout: ptr.Ptr(options.DefaultUpstreamTimeout), - Static: ptr.Ptr(false), - InsecureSkipTLSVerify: ptr.Ptr(false), - DisableKeepAlives: ptr.Ptr(false), + FlushInterval: ptr.To(options.DefaultUpstreamFlushInterval), + PassHostHeader: ptr.To(true), + ProxyWebSockets: ptr.To(true), + Timeout: ptr.To(options.DefaultUpstreamTimeout), + Static: ptr.To(false), + InsecureSkipTLSVerify: ptr.To(false), + DisableKeepAlives: ptr.To(false), }, }, } authHeader := options.Header{ Name: "Authorization", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ @@ -165,11 +165,11 @@ redirect_url="http://localhost:4180/oauth2/callback" Type: "google", ClientSecret: "b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK", ClientID: "oauth2-proxy", - UseSystemTrustStore: ptr.Ptr(false), - SkipClaimsFromProfileURL: ptr.Ptr(false), + UseSystemTrustStore: ptr.To(false), + SkipClaimsFromProfileURL: ptr.To(false), GoogleConfig: options.GoogleOptions{ AdminEmail: "admin@example.com", - UseApplicationDefaultCredentials: ptr.Ptr(false), + UseApplicationDefaultCredentials: ptr.To(false), TargetPrincipal: "principal", }, AzureConfig: options.AzureOptions{ @@ -181,16 +181,16 @@ redirect_url="http://localhost:4180/oauth2/callback" UserIDClaim: "email", AudienceClaims: []string{"aud"}, ExtraAudiences: []string{}, - InsecureSkipNonce: ptr.Ptr(true), - InsecureAllowUnverifiedEmail: ptr.Ptr(false), - InsecureSkipIssuerVerification: ptr.Ptr(false), - SkipDiscovery: ptr.Ptr(false), + InsecureSkipNonce: ptr.To(true), + InsecureAllowUnverifiedEmail: ptr.To(false), + InsecureSkipIssuerVerification: ptr.To(false), + SkipDiscovery: ptr.To(false), }, MicrosoftEntraIDConfig: options.MicrosoftEntraIDOptions{ - FederatedTokenAuth: ptr.Ptr(false), + FederatedTokenAuth: ptr.To(false), }, ADFSConfig: options.ADFSOptions{ - SkipScope: ptr.Ptr(false), + SkipScope: ptr.To(false), }, LoginURLParameters: []options.LoginURLParameter{ {Name: "approval_prompt", Default: []string{"force"}}, diff --git a/oauthproxy_test.go b/oauthproxy_test.go index 0463c9dd40..ccabdbbd01 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -507,7 +507,7 @@ func TestStaticProxyUpstream(t *testing.T) { ProxyUpstream: options.Upstream{ ID: "static-proxy", Path: "/static-proxy", - Static: ptr.Ptr(true), + Static: ptr.To(true), }, }) if err != nil { @@ -2224,7 +2224,7 @@ func TestTrustedIPs(t *testing.T) { { ID: "static", Path: "/", - Static: ptr.Ptr(true), + Static: ptr.To(true), }, }, } diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index a35955082b..525523970c 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -64,7 +64,7 @@ type ClaimSource struct { // EnsureDefaults sets any default values for Header fields. func (h *Header) EnsureDefaults() { if h.PreserveRequestValue == nil { - h.PreserveRequestValue = ptr.Ptr(DefaultHeaderPreserveRequestValue) + h.PreserveRequestValue = ptr.To(DefaultHeaderPreserveRequestValue) } for i := range h.Values { h.Values[i].EnsureDefaults() diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index 5f4efe578c..0f9f0829c1 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -166,7 +166,7 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { logger.Errorf("unable to convert %q to int, use default \"200\"", u.Host) responseCode = 200 } - upstream.Static = ptr.Ptr(true) + upstream.Static = ptr.To(true) upstream.StaticCode = &responseCode // This is not allowed to be empty and must be unique @@ -177,8 +177,8 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { // Force defaults compatible with static responses upstream.URI = "" - upstream.InsecureSkipTLSVerify = ptr.Ptr(false) - upstream.DisableKeepAlives = ptr.Ptr(false) + upstream.InsecureSkipTLSVerify = ptr.To(false) + upstream.DisableKeepAlives = ptr.To(false) upstream.PassHostHeader = nil upstream.ProxyWebSockets = nil upstream.FlushInterval = nil @@ -255,7 +255,7 @@ func (l *LegacyHeaders) getRequestHeaders() []Header { } for i := range requestHeaders { - requestHeaders[i].PreserveRequestValue = ptr.Ptr(!l.SkipAuthStripHeaders) + requestHeaders[i].PreserveRequestValue = ptr.To(!l.SkipAuthStripHeaders) } return requestHeaders @@ -290,7 +290,7 @@ func getBasicAuthHeader(preferEmailToUser bool, basicAuthPassword string) Header return Header{ Name: "Authorization", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -309,7 +309,7 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { headers := []Header{ { Name: "X-Forwarded-Groups", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -324,7 +324,7 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { return append(headers, Header{ Name: "X-Forwarded-User", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -339,7 +339,7 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { return append(headers, Header{ Name: "X-Forwarded-User", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -350,7 +350,7 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { }, Header{ Name: "X-Forwarded-Email", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -365,7 +365,7 @@ func getPassUserHeaders(preferEmailToUser bool) []Header { func getPassAccessTokenHeader() Header { return Header{ Name: "X-Forwarded-Access-Token", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -379,7 +379,7 @@ func getPassAccessTokenHeader() Header { func getAuthorizationHeader() Header { return Header{ Name: "Authorization", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -394,7 +394,7 @@ func getAuthorizationHeader() Header { func getPreferredUsernameHeader() Header { return Header{ Name: "X-Forwarded-Preferred-Username", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -409,7 +409,7 @@ func getXAuthRequestHeaders() []Header { headers := []Header{ { Name: "X-Auth-Request-User", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -420,7 +420,7 @@ func getXAuthRequestHeaders() []Header { }, { Name: "X-Auth-Request-Email", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -431,7 +431,7 @@ func getXAuthRequestHeaders() []Header { }, { Name: "X-Auth-Request-Preferred-Username", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -442,7 +442,7 @@ func getXAuthRequestHeaders() []Header { }, { Name: "X-Auth-Request-Groups", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -459,7 +459,7 @@ func getXAuthRequestHeaders() []Header { func getXAuthRequestAccessTokenHeader() Header { return Header{ Name: "X-Auth-Request-Access-Token", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index 65813c801b..3fe9c1e576 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -36,9 +36,9 @@ var _ = Describe("Legacy Options", func() { Path: "/baz", URI: "http://foo.bar/baz", FlushInterval: &flushInterval, - InsecureSkipTLSVerify: ptr.Ptr(true), - PassHostHeader: ptr.Ptr(true), - ProxyWebSockets: ptr.Ptr(true), + InsecureSkipTLSVerify: ptr.To(true), + PassHostHeader: ptr.To(true), + ProxyWebSockets: ptr.To(true), Timeout: &timeout, DisableKeepAlives: &legacyOpts.LegacyUpstreams.DisableKeepAlives, }, @@ -47,9 +47,9 @@ var _ = Describe("Legacy Options", func() { Path: "/bar", URI: "file:///var/lib/website", FlushInterval: &flushInterval, - InsecureSkipTLSVerify: ptr.Ptr(true), - PassHostHeader: ptr.Ptr(true), - ProxyWebSockets: ptr.Ptr(true), + InsecureSkipTLSVerify: ptr.To(true), + PassHostHeader: ptr.To(true), + ProxyWebSockets: ptr.To(true), Timeout: &timeout, DisableKeepAlives: &legacyOpts.LegacyUpstreams.DisableKeepAlives, }, @@ -57,10 +57,10 @@ var _ = Describe("Legacy Options", func() { ID: "static://204", Path: "/", URI: "", - Static: ptr.Ptr(true), + Static: ptr.To(true), StaticCode: &staticCode, FlushInterval: nil, - InsecureSkipTLSVerify: ptr.Ptr(false), + InsecureSkipTLSVerify: ptr.To(false), PassHostHeader: nil, ProxyWebSockets: nil, Timeout: nil, @@ -72,7 +72,7 @@ var _ = Describe("Legacy Options", func() { opts.InjectRequestHeaders = []Header{ { Name: "X-Forwarded-Groups", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -83,7 +83,7 @@ var _ = Describe("Legacy Options", func() { }, { Name: "X-Forwarded-User", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -94,7 +94,7 @@ var _ = Describe("Legacy Options", func() { }, { Name: "X-Forwarded-Email", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -105,7 +105,7 @@ var _ = Describe("Legacy Options", func() { }, { Name: "X-Forwarded-Preferred-Username", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -126,8 +126,8 @@ var _ = Describe("Legacy Options", func() { opts.Providers[0].ClientID = "oauth-proxy" opts.Providers[0].OIDCConfig.AudienceClaims = []string{"aud"} opts.Providers[0].OIDCConfig.ExtraAudiences = []string{} - opts.Providers[0].OIDCConfig.InsecureSkipNonce = ptr.Ptr(true) - opts.Providers[0].OIDCConfig.InsecureSkipIssuerVerification = ptr.Ptr(false) + opts.Providers[0].OIDCConfig.InsecureSkipNonce = ptr.To(true) + opts.Providers[0].OIDCConfig.InsecureSkipIssuerVerification = ptr.To(false) opts.Providers[0].LoginURLParameters = []LoginURLParameter{ {Name: "approval_prompt", Default: []string{"force"}}, } @@ -202,14 +202,14 @@ var _ = Describe("Legacy Options", func() { ID: validStatic, Path: "/", URI: "", - Static: ptr.Ptr(true), + Static: ptr.To(true), StaticCode: &validStaticCode, - InsecureSkipTLSVerify: ptr.Ptr(false), + InsecureSkipTLSVerify: ptr.To(false), PassHostHeader: nil, ProxyWebSockets: nil, FlushInterval: nil, Timeout: nil, - DisableKeepAlives: ptr.Ptr(false), + DisableKeepAlives: ptr.To(false), } invalidStatic := "static://abc" @@ -218,14 +218,14 @@ var _ = Describe("Legacy Options", func() { ID: invalidStatic, Path: "/", URI: "", - Static: ptr.Ptr(true), + Static: ptr.To(true), StaticCode: &invalidStaticCode, - InsecureSkipTLSVerify: ptr.Ptr(false), + InsecureSkipTLSVerify: ptr.To(false), PassHostHeader: nil, ProxyWebSockets: nil, FlushInterval: nil, Timeout: nil, - DisableKeepAlives: ptr.Ptr(false), + DisableKeepAlives: ptr.To(false), } invalidHTTP := ":foo" @@ -318,7 +318,7 @@ var _ = Describe("Legacy Options", func() { xForwardedUser := Header{ Name: "X-Forwarded-User", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -330,7 +330,7 @@ var _ = Describe("Legacy Options", func() { xForwardedEmail := Header{ Name: "X-Forwarded-Email", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -342,7 +342,7 @@ var _ = Describe("Legacy Options", func() { xForwardedGroups := Header{ Name: "X-Forwarded-Groups", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -354,7 +354,7 @@ var _ = Describe("Legacy Options", func() { xForwardedPreferredUsername := Header{ Name: "X-Forwarded-Preferred-Username", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -366,7 +366,7 @@ var _ = Describe("Legacy Options", func() { basicAuthHeader := Header{ Name: "Authorization", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -382,7 +382,7 @@ var _ = Describe("Legacy Options", func() { xForwardedUserWithEmail := Header{ Name: "X-Forwarded-User", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -394,7 +394,7 @@ var _ = Describe("Legacy Options", func() { xForwardedAccessToken := Header{ Name: "X-Forwarded-Access-Token", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -406,7 +406,7 @@ var _ = Describe("Legacy Options", func() { basicAuthHeaderWithEmail := Header{ Name: "Authorization", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -422,7 +422,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestUser := Header{ Name: "X-Auth-Request-User", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -434,7 +434,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestEmail := Header{ Name: "X-Auth-Request-Email", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -446,7 +446,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestGroups := Header{ Name: "X-Auth-Request-Groups", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -458,7 +458,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestPreferredUsername := Header{ Name: "X-Auth-Request-Preferred-Username", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -470,7 +470,7 @@ var _ = Describe("Legacy Options", func() { xAuthRequestAccessToken := Header{ Name: "X-Auth-Request-Access-Token", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -482,7 +482,7 @@ var _ = Describe("Legacy Options", func() { authorizationHeader := Header{ Name: "Authorization", - PreserveRequestValue: ptr.Ptr(false), + PreserveRequestValue: ptr.To(false), Values: []HeaderValue{ { ClaimSource: &ClaimSource{ @@ -948,14 +948,14 @@ var _ = Describe("Legacy Options", func() { } defaultOIDCOptions := OIDCOptions{ - SkipDiscovery: ptr.Ptr(false), - InsecureSkipNonce: ptr.Ptr(false), - InsecureAllowUnverifiedEmail: ptr.Ptr(false), - InsecureSkipIssuerVerification: ptr.Ptr(false), + SkipDiscovery: ptr.To(false), + InsecureSkipNonce: ptr.To(false), + InsecureAllowUnverifiedEmail: ptr.To(false), + InsecureSkipIssuerVerification: ptr.To(false), } defaultGoogleOptions := GoogleOptions{ - UseApplicationDefaultCredentials: ptr.Ptr(false), + UseApplicationDefaultCredentials: ptr.To(false), } defaultLegacyProvider := LegacyProvider{ @@ -970,8 +970,8 @@ var _ = Describe("Legacy Options", func() { OIDCConfig: defaultOIDCOptions, GoogleConfig: defaultGoogleOptions, LoginURLParameters: defaultURLParams, - UseSystemTrustStore: ptr.Ptr(false), - SkipClaimsFromProfileURL: ptr.Ptr(false), + UseSystemTrustStore: ptr.To(false), + SkipClaimsFromProfileURL: ptr.To(false), } defaultLegacyProviderWithPrompt := LegacyProvider{ @@ -989,8 +989,8 @@ var _ = Describe("Legacy Options", func() { LoginURLParameters: []LoginURLParameter{ {Name: "prompt", Default: []string{"switch_user"}}, }, - UseSystemTrustStore: ptr.Ptr(false), - SkipClaimsFromProfileURL: ptr.Ptr(false), + UseSystemTrustStore: ptr.To(false), + SkipClaimsFromProfileURL: ptr.To(false), } displayNameLegacyProvider := LegacyProvider{ @@ -1007,8 +1007,8 @@ var _ = Describe("Legacy Options", func() { OIDCConfig: defaultOIDCOptions, GoogleConfig: defaultGoogleOptions, LoginURLParameters: defaultURLParams, - UseSystemTrustStore: ptr.Ptr(false), - SkipClaimsFromProfileURL: ptr.Ptr(false), + UseSystemTrustStore: ptr.To(false), + SkipClaimsFromProfileURL: ptr.To(false), } internalConfigProvider := Provider{ @@ -1020,11 +1020,11 @@ var _ = Describe("Legacy Options", func() { AdminEmail: "email@email.com", ServiceAccountJSON: "test.json", Groups: []string{"1", "2"}, - UseApplicationDefaultCredentials: ptr.Ptr(false), + UseApplicationDefaultCredentials: ptr.To(false), }, LoginURLParameters: defaultURLParams, - UseSystemTrustStore: ptr.Ptr(false), - SkipClaimsFromProfileURL: ptr.Ptr(false), + UseSystemTrustStore: ptr.To(false), + SkipClaimsFromProfileURL: ptr.To(false), } internalConfigLegacyProvider := LegacyProvider{ diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index b93fb7adb5..2d89eb2ce1 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -334,9 +334,9 @@ func providerDefaults() Providers { Tenant: "common", }, OIDCConfig: OIDCOptions{ - InsecureAllowUnverifiedEmail: ptr.Ptr(DefaultInsecureAllowUnverifiedEmail), - InsecureSkipNonce: ptr.Ptr(DefaultInsecureSkipNonce), - SkipDiscovery: ptr.Ptr(DefaultSkipDiscovery), + InsecureAllowUnverifiedEmail: ptr.To(DefaultInsecureAllowUnverifiedEmail), + InsecureSkipNonce: ptr.To(DefaultInsecureSkipNonce), + SkipDiscovery: ptr.To(DefaultSkipDiscovery), UserIDClaim: OIDCEmailClaim, // Deprecated: Use OIDCEmailClaim EmailClaim: OIDCEmailClaim, GroupsClaim: OIDCGroupsClaim, @@ -358,10 +358,10 @@ func (p Providers) EnsureDefaults() { // EnsureDefaults sets any default values for Provider fields. func (p *Provider) EnsureDefaults() { if p.SkipClaimsFromProfileURL == nil { - p.SkipClaimsFromProfileURL = ptr.Ptr(DefaultSkipClaimsFromProfileURL) + p.SkipClaimsFromProfileURL = ptr.To(DefaultSkipClaimsFromProfileURL) } if p.UseSystemTrustStore == nil { - p.UseSystemTrustStore = ptr.Ptr(DefaultUseSystemTrustStore) + p.UseSystemTrustStore = ptr.To(DefaultUseSystemTrustStore) } p.OIDCConfig.EnsureDefaults() @@ -374,13 +374,13 @@ func (p *Provider) EnsureDefaults() { func (o *OIDCOptions) EnsureDefaults() { // Ensure OIDC defaults if o.InsecureAllowUnverifiedEmail == nil { - o.InsecureAllowUnverifiedEmail = ptr.Ptr(DefaultInsecureAllowUnverifiedEmail) + o.InsecureAllowUnverifiedEmail = ptr.To(DefaultInsecureAllowUnverifiedEmail) } if o.InsecureSkipNonce == nil { - o.InsecureSkipNonce = ptr.Ptr(DefaultInsecureSkipNonce) + o.InsecureSkipNonce = ptr.To(DefaultInsecureSkipNonce) } if o.SkipDiscovery == nil { - o.SkipDiscovery = ptr.Ptr(DefaultSkipDiscovery) + o.SkipDiscovery = ptr.To(DefaultSkipDiscovery) } if o.UserIDClaim == "" { o.UserIDClaim = OIDCEmailClaim @@ -399,20 +399,20 @@ func (o *OIDCOptions) EnsureDefaults() { // EnsureDefaults sets any default values for MicrosoftEntraIDOptions fields. func (me *MicrosoftEntraIDOptions) EnsureDefaults() { if me.FederatedTokenAuth == nil { - me.FederatedTokenAuth = ptr.Ptr(DefaultMicrosoftEntraIDUseFederatedToken) + me.FederatedTokenAuth = ptr.To(DefaultMicrosoftEntraIDUseFederatedToken) } } // EnsureDefaults sets any default values for ADFSOptions fields. func (a *ADFSOptions) EnsureDefaults() { if a.SkipScope == nil { - a.SkipScope = ptr.Ptr(DefaultADFSSkipScope) + a.SkipScope = ptr.To(DefaultADFSSkipScope) } } // EnsureDefaults sets any default values for GoogleOptions fields. func (g *GoogleOptions) EnsureDefaults() { if g.UseApplicationDefaultCredentials == nil { - g.UseApplicationDefaultCredentials = ptr.Ptr(DefaultUseApplicationDefaultCredentials) + g.UseApplicationDefaultCredentials = ptr.To(DefaultUseApplicationDefaultCredentials) } } diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index f69fec90dd..a56fca612b 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -128,7 +128,7 @@ type Upstream struct { // EnsureDefaults sets any default values for UpstreamConfig fields. func (uc *UpstreamConfig) EnsureDefaults() { if uc.ProxyRawPath == nil { - uc.ProxyRawPath = ptr.Ptr(DefaultUpstreamProxyRawPath) + uc.ProxyRawPath = ptr.To(DefaultUpstreamProxyRawPath) } for i := range uc.Upstreams { uc.Upstreams[i].EnsureDefaults() @@ -138,24 +138,24 @@ func (uc *UpstreamConfig) EnsureDefaults() { // EnsureDefaults sets any default values for Upstream fields. func (u *Upstream) EnsureDefaults() { if u.InsecureSkipTLSVerify == nil { - u.InsecureSkipTLSVerify = ptr.Ptr(DefaultUpsteamInsecureSkipTLSVerify) + u.InsecureSkipTLSVerify = ptr.To(DefaultUpsteamInsecureSkipTLSVerify) } if u.Static == nil { - u.Static = ptr.Ptr(DefaultUpstreamStatic) + u.Static = ptr.To(DefaultUpstreamStatic) } if u.FlushInterval == nil { - u.FlushInterval = ptr.Ptr(DefaultUpstreamFlushInterval) + u.FlushInterval = ptr.To(DefaultUpstreamFlushInterval) } if u.PassHostHeader == nil { - u.PassHostHeader = ptr.Ptr(DefaultUpstreamPassHostHeader) + u.PassHostHeader = ptr.To(DefaultUpstreamPassHostHeader) } if u.ProxyWebSockets == nil { - u.ProxyWebSockets = ptr.Ptr(DefaultUpstreamProxyWebSockets) + u.ProxyWebSockets = ptr.To(DefaultUpstreamProxyWebSockets) } if u.Timeout == nil { - u.Timeout = ptr.Ptr(DefaultUpstreamTimeout) + u.Timeout = ptr.To(DefaultUpstreamTimeout) } if u.DisableKeepAlives == nil { - u.DisableKeepAlives = ptr.Ptr(DefaultUpstreamDisableKeepAlives) + u.DisableKeepAlives = ptr.To(DefaultUpstreamDisableKeepAlives) } } diff --git a/pkg/apis/sessions/session_state_test.go b/pkg/apis/sessions/session_state_test.go index 442fcea8bd..87b97614f8 100644 --- a/pkg/apis/sessions/session_state_test.go +++ b/pkg/apis/sessions/session_state_test.go @@ -8,15 +8,12 @@ import ( "time" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" . "github.com/onsi/gomega" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func timePtr(t time.Time) *time.Time { - return &t -} - func TestCreatedAtNow(t *testing.T) { g := NewWithT(t) ss := &SessionState{} @@ -137,10 +134,10 @@ func TestString(t *testing.T) { } func TestIsExpired(t *testing.T) { - s := &SessionState{ExpiresOn: timePtr(time.Now().Add(time.Duration(-1) * time.Minute))} + s := &SessionState{ExpiresOn: ptr.To(time.Now().Add(time.Duration(-1) * time.Minute))} assert.Equal(t, true, s.IsExpired()) - s = &SessionState{ExpiresOn: timePtr(time.Now().Add(time.Duration(1) * time.Minute))} + s = &SessionState{ExpiresOn: ptr.To(time.Now().Add(time.Duration(1) * time.Minute))} assert.Equal(t, false, s.IsExpired()) s = &SessionState{} @@ -154,7 +151,7 @@ func TestAge(t *testing.T) { assert.Equal(t, time.Duration(0), ss.Age()) // Set CreatedAt to 1 hour ago - ss.CreatedAt = timePtr(time.Now().Add(-1 * time.Hour)) + ss.CreatedAt = ptr.To(time.Now().Add(-1 * time.Hour)) assert.Equal(t, time.Hour, ss.Age().Round(time.Minute)) } diff --git a/pkg/middleware/headers_test.go b/pkg/middleware/headers_test.go index 89f6510728..393ade9c7b 100644 --- a/pkg/middleware/headers_test.go +++ b/pkg/middleware/headers_test.go @@ -116,7 +116,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "Claim", - PreserveRequestValue: ptr.Ptr(true), + PreserveRequestValue: ptr.To(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ @@ -161,7 +161,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "Claim", - PreserveRequestValue: ptr.Ptr(true), + PreserveRequestValue: ptr.To(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ @@ -386,7 +386,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "Claim", - PreserveRequestValue: ptr.Ptr(true), + PreserveRequestValue: ptr.To(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ @@ -433,7 +433,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "Claim", - PreserveRequestValue: ptr.Ptr(true), + PreserveRequestValue: ptr.To(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{ diff --git a/pkg/upstream/http_test.go b/pkg/upstream/http_test.go index 7c1831bfe1..79dc0e4aa6 100644 --- a/pkg/upstream/http_test.go +++ b/pkg/upstream/http_test.go @@ -63,8 +63,8 @@ var _ = Describe("HTTP Upstream Suite", func() { upstream := options.Upstream{ ID: in.id, PassHostHeader: &in.passUpstreamHostHeader, - ProxyWebSockets: ptr.Ptr(false), - InsecureSkipTLSVerify: ptr.Ptr(false), + ProxyWebSockets: ptr.To(false), + InsecureSkipTLSVerify: ptr.To(false), FlushInterval: &flush, Timeout: &timeout, } @@ -342,9 +342,9 @@ var _ = Describe("HTTP Upstream Suite", func() { upstream := options.Upstream{ ID: "noPassHost", - PassHostHeader: ptr.Ptr(false), - ProxyWebSockets: ptr.Ptr(false), - InsecureSkipTLSVerify: ptr.Ptr(false), + PassHostHeader: ptr.To(false), + ProxyWebSockets: ptr.To(false), + InsecureSkipTLSVerify: ptr.To(false), FlushInterval: &defaultFlushInterval, Timeout: &defaultTimeout, } @@ -486,9 +486,9 @@ var _ = Describe("HTTP Upstream Suite", func() { timeout := options.DefaultUpstreamTimeout upstream := options.Upstream{ ID: "websocketProxy", - PassHostHeader: ptr.Ptr(true), - ProxyWebSockets: ptr.Ptr(true), - InsecureSkipTLSVerify: ptr.Ptr(false), + PassHostHeader: ptr.To(true), + ProxyWebSockets: ptr.To(true), + InsecureSkipTLSVerify: ptr.To(false), FlushInterval: &flush, Timeout: &timeout, } diff --git a/pkg/upstream/proxy_test.go b/pkg/upstream/proxy_test.go index 87aae7fa8f..b9b8cf9cc9 100644 --- a/pkg/upstream/proxy_test.go +++ b/pkg/upstream/proxy_test.go @@ -61,19 +61,19 @@ var _ = Describe("Proxy Suite", func() { { ID: "static-backend", Path: "/static/", - Static: ptr.Ptr(true), + Static: ptr.To(true), StaticCode: &ok, }, { ID: "static-backend-no-trailing-slash", Path: "/static", - Static: ptr.Ptr(true), + Static: ptr.To(true), StaticCode: &accepted, }, { ID: "static-backend-long", Path: "/static/long", - Static: ptr.Ptr(true), + Static: ptr.To(true), StaticCode: &accepted, }, { @@ -84,7 +84,7 @@ var _ = Describe("Proxy Suite", func() { { ID: "single-path-backend", Path: "/single-path", - Static: ptr.Ptr(true), + Static: ptr.To(true), StaticCode: &ok, }, { @@ -347,7 +347,7 @@ var _ = Describe("Proxy Suite", func() { upstream: "", }), Entry("containing an escaped '/' with ProxyRawPath", &proxyTableInput{ - upstreams: options.UpstreamConfig{ProxyRawPath: ptr.Ptr(true)}, + upstreams: options.UpstreamConfig{ProxyRawPath: ptr.To(true)}, target: "http://example.localhost/%2F/test1/%2F/test2", response: testHTTPResponse{ code: 404, diff --git a/pkg/util/ptr/ptr.go b/pkg/util/ptr/ptr.go index 9242773cbf..d2b294a23c 100644 --- a/pkg/util/ptr/ptr.go +++ b/pkg/util/ptr/ptr.go @@ -1,7 +1,7 @@ package ptr -// Ptr generically returns a pointer to the given value. -func Ptr[T any](v T) *T { +// To generically returns a pointer to the given value. +func To[T any](v T) *T { return &v } diff --git a/pkg/util/ptr/ptr_test.go b/pkg/util/ptr/ptr_test.go index c4817a6b3f..459e7cc9df 100644 --- a/pkg/util/ptr/ptr_test.go +++ b/pkg/util/ptr/ptr_test.go @@ -6,22 +6,22 @@ import ( "github.com/stretchr/testify/assert" ) -func TestPtr(t *testing.T) { - p := Ptr(42) +func TestTo(t *testing.T) { + p := To(42) assert.NotNil(t, p) assert.Equal(t, 42, *p) - s := Ptr("hello") + s := To("hello") assert.NotNil(t, s) assert.Equal(t, "hello", *s) - b := Ptr(true) + b := To(true) assert.NotNil(t, b) assert.True(t, *b) } func TestDeref(t *testing.T) { - v := Deref(Ptr(99), 0) + v := Deref(To(99), 0) assert.Equal(t, 99, v) v = Deref[int](nil, 123) @@ -30,7 +30,7 @@ func TestDeref(t *testing.T) { s := Deref[string](nil, "default") assert.Equal(t, "default", s) - b := Deref(Ptr(true), false) + b := Deref(To(true), false) assert.True(t, b) b = Deref[bool](nil, false) diff --git a/pkg/validation/options_test.go b/pkg/validation/options_test.go index 6657e8476a..5ea748c16f 100644 --- a/pkg/validation/options_test.go +++ b/pkg/validation/options_test.go @@ -69,7 +69,7 @@ func TestGoogleGroupOptionsWithoutServiceAccountJSON(t *testing.T) { func TestGoogleGroupOptionsWithoutAdminEmail(t *testing.T) { o := testOptions() - o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = ptr.Ptr(true) + o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = ptr.To(true) err := Validate(o) assert.NotEqual(t, nil, err) @@ -82,7 +82,7 @@ func TestGoogleGroupOptionsWithoutGroups(t *testing.T) { o := testOptions() // Set admin email and application default credentials but no groups - should still require them o.Providers[0].GoogleConfig.AdminEmail = "admin@example.com" - o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = ptr.Ptr(true) + o.Providers[0].GoogleConfig.UseApplicationDefaultCredentials = ptr.To(true) err := Validate(o) // Should pass validation since google-group is now optional assert.Equal(t, nil, err) diff --git a/pkg/validation/upstreams_test.go b/pkg/validation/upstreams_test.go index 580e2f2926..79b29a2226 100644 --- a/pkg/validation/upstreams_test.go +++ b/pkg/validation/upstreams_test.go @@ -26,7 +26,7 @@ var _ = Describe("Upstreams", func() { validStaticUpstream := options.Upstream{ ID: "validStaticUpstream", Path: "/validStaticUpstream", - Static: ptr.Ptr(true), + Static: ptr.To(true), } validFileUpstream := options.Upstream{ ID: "validFileUpstream", @@ -145,11 +145,11 @@ var _ = Describe("Upstreams", func() { ID: "foo", Path: "/foo", URI: "ftp://foo", - Static: ptr.Ptr(true), + Static: ptr.To(true), FlushInterval: &flushInterval, - PassHostHeader: ptr.Ptr(true), - ProxyWebSockets: ptr.Ptr(true), - InsecureSkipTLSVerify: ptr.Ptr(true), + PassHostHeader: ptr.To(true), + ProxyWebSockets: ptr.To(true), + InsecureSkipTLSVerify: ptr.To(true), }, }, }, diff --git a/providers/adfs_test.go b/providers/adfs_test.go index edcb93073e..75be7d0b0e 100644 --- a/providers/adfs_test.go +++ b/providers/adfs_test.go @@ -173,7 +173,7 @@ var _ = Describe("ADFS Provider Tests", func() { ProtectedResource: resource, Scope: "", }, options.Provider{ - ADFSConfig: options.ADFSOptions{SkipScope: ptr.Ptr(true)}, + ADFSConfig: options.ADFSOptions{SkipScope: ptr.To(true)}, }) result := p.GetLoginURL("https://example.com/adfs/oauth2/", "", "", url.Values{}) diff --git a/providers/ms_entra_id_test.go b/providers/ms_entra_id_test.go index 7b720c91b0..b153006e7c 100644 --- a/providers/ms_entra_id_test.go +++ b/providers/ms_entra_id_test.go @@ -25,7 +25,7 @@ func TestAzureEntraOIDCProviderNewMultiTenant(t *testing.T) { provider := NewMicrosoftEntraIDProvider(&ProviderData{}, options.Provider{OIDCConfig: options.OIDCOptions{ IssuerURL: "https://login.microsoftonline.com/common/v2.0", - InsecureSkipIssuerVerification: ptr.Ptr(true), + InsecureSkipIssuerVerification: ptr.To(true), }}, ) g.Expect(provider.Data().ProviderName).To(Equal("Microsoft Entra ID")) @@ -91,8 +91,8 @@ func TestAzureEntraOIDCProviderValidateSessionAllowedTenants(t *testing.T) { options.Provider{ OIDCConfig: options.OIDCOptions{ IssuerURL: "https://login.microsoftonline.com/common/v2.0", - InsecureSkipIssuerVerification: ptr.Ptr(true), - InsecureSkipNonce: ptr.Ptr(true), + InsecureSkipIssuerVerification: ptr.To(true), + InsecureSkipNonce: ptr.To(true), }, MicrosoftEntraIDConfig: options.MicrosoftEntraIDOptions{ AllowedTenants: []string{"85d7d600-7804-4d92-8d43-9c33c21c130c"}, diff --git a/providers/providers_test.go b/providers/providers_test.go index 9591dc655f..8e3b8d7794 100644 --- a/providers/providers_test.go +++ b/providers/providers_test.go @@ -82,7 +82,7 @@ func TestSkipOIDCDiscovery(t *testing.T) { ClientSecretFile: clientSecret, OIDCConfig: options.OIDCOptions{ IssuerURL: msIssuerURL, - SkipDiscovery: ptr.Ptr(true), + SkipDiscovery: ptr.To(true), }, } @@ -109,7 +109,7 @@ func TestURLsCorrectlyParsed(t *testing.T) { RedeemURL: msTokenURL, OIDCConfig: options.OIDCOptions{ IssuerURL: msIssuerURL, - SkipDiscovery: ptr.Ptr(true), + SkipDiscovery: ptr.To(true), JwksURL: msKeysURL, }, } @@ -217,7 +217,7 @@ func TestScope(t *testing.T) { AllowedGroups: tc.allowedGroups, OIDCConfig: options.OIDCOptions{ IssuerURL: msIssuerURL, - SkipDiscovery: ptr.Ptr(true), + SkipDiscovery: ptr.To(true), JwksURL: msKeysURL, }, } @@ -298,7 +298,7 @@ func TestEmailClaimCorrectlySet(t *testing.T) { RedeemURL: msTokenURL, OIDCConfig: options.OIDCOptions{ IssuerURL: msIssuerURL, - SkipDiscovery: ptr.Ptr(true), + SkipDiscovery: ptr.To(true), JwksURL: msKeysURL, UserIDClaim: tc.userIDClaim, EmailClaim: tc.emailClaim, From 15041dd116456b2d66440f4f96991aa226f8b4f1 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sun, 16 Nov 2025 22:36:05 +0100 Subject: [PATCH 089/125] feat: migrate google used organization id and header normalization booleans to pointers Signed-off-by: Jan Larwig --- main_test.go | 3 ++- pkg/apis/options/header.go | 4 +++- pkg/apis/options/legacy_options.go | 2 +- pkg/apis/options/legacy_options_test.go | 2 ++ pkg/apis/options/providers.go | 8 +++++++- pkg/middleware/headers.go | 2 +- pkg/middleware/headers_test.go | 2 +- providers/google.go | 4 ++-- 8 files changed, 19 insertions(+), 8 deletions(-) diff --git a/main_test.go b/main_test.go index dce11fcced..cbe79683d9 100644 --- a/main_test.go +++ b/main_test.go @@ -169,8 +169,9 @@ redirect_url="http://localhost:4180/oauth2/callback" SkipClaimsFromProfileURL: ptr.To(false), GoogleConfig: options.GoogleOptions{ AdminEmail: "admin@example.com", - UseApplicationDefaultCredentials: ptr.To(false), TargetPrincipal: "principal", + UseOrganizationID: ptr.To(false), + UseApplicationDefaultCredentials: ptr.To(false), }, AzureConfig: options.AzureOptions{ Tenant: "common", diff --git a/pkg/apis/options/header.go b/pkg/apis/options/header.go index 525523970c..d9509de06d 100644 --- a/pkg/apis/options/header.go +++ b/pkg/apis/options/header.go @@ -5,6 +5,8 @@ import "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr" const ( // DefaultHeaderPreserveRequestValue is the default value for Header.PreserveRequestValue DefaultHeaderPreserveRequestValue bool = false + // DefaultInsecureSkipHeaderNormalization is the default value for Header.InsecureSkipHeaderNormalization + DefaultInsecureSkipHeaderNormalization bool = false ) // Header represents an individual header that will be added to a request or @@ -28,7 +30,7 @@ type Header struct { // treated as the same header. Additionally underscores (_) in header names // will be converted to dashes (-) when normalizing. // Defaults to false (header names will be normalized). - InsecureSkipHeaderNormalization bool `json:"InsecureSkipHeaderNormalization,omitempty"` + InsecureSkipHeaderNormalization *bool `yaml:"InsecureSkipHeaderNormalization,omitempty"` // Values contains the desired values for this header Values []HeaderValue `yaml:"values,omitempty"` diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index 0f9f0829c1..6ce730fd8e 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -789,7 +789,7 @@ func (l *LegacyProvider) convert() (Providers, error) { ServiceAccountJSON: l.GoogleServiceAccountJSON, UseApplicationDefaultCredentials: &l.GoogleUseApplicationDefaultCredentials, TargetPrincipal: l.GoogleTargetPrincipal, - UseOrganizationID: l.GoogleUseOrganizationID, + UseOrganizationID: &l.GoogleUseOrganizationID, AdminAPIUserScope: l.GoogleAdminAPIUserScope, } case "entra-id": diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index 3fe9c1e576..ceba53afa1 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -955,6 +955,7 @@ var _ = Describe("Legacy Options", func() { } defaultGoogleOptions := GoogleOptions{ + UseOrganizationID: ptr.To(false), UseApplicationDefaultCredentials: ptr.To(false), } @@ -1020,6 +1021,7 @@ var _ = Describe("Legacy Options", func() { AdminEmail: "email@email.com", ServiceAccountJSON: "test.json", Groups: []string{"1", "2"}, + UseOrganizationID: ptr.To(false), UseApplicationDefaultCredentials: ptr.To(false), }, LoginURLParameters: defaultURLParams, diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 2d89eb2ce1..4dd206e26b 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -37,6 +37,10 @@ const ( // for MicrosoftEntraIDOptions.FederatedTokenAuth DefaultMicrosoftEntraIDUseFederatedToken bool = false + // DefaultGoogleUseOrganizationID is the default value + // for GoogleOptions.UseOrganizationID + DefaultGoogleUseOrganizationID bool = false + // DefaultGoogleUseApplicationDefaultCredentials is the default values // for GoogleOptions.UseApplicationDefaultCredentials DefaultUseApplicationDefaultCredentials bool = false @@ -269,7 +273,7 @@ type GoogleOptions struct { // TargetPrincipal is the Google Service Account used for Application Default Credentials TargetPrincipal string `yaml:"targetPrincipal,omitempty"` // UseOrganizationId indicates whether to use the organization ID as the UserName claim - UseOrganizationID bool `yaml:"useOrganizationID,omitempty"` + UseOrganizationID *bool `yaml:"useOrganizationID,omitempty"` // admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly AdminAPIUserScope string `yaml:"adminAPIUserScope,omitempty"` } @@ -412,6 +416,8 @@ func (a *ADFSOptions) EnsureDefaults() { // EnsureDefaults sets any default values for GoogleOptions fields. func (g *GoogleOptions) EnsureDefaults() { + g.UseOrganizationID = ptr.To(DefaultGoogleUseOrganizationID) + if g.UseApplicationDefaultCredentials == nil { g.UseApplicationDefaultCredentials = ptr.To(DefaultUseApplicationDefaultCredentials) } diff --git a/pkg/middleware/headers.go b/pkg/middleware/headers.go index b567f4f5b8..39f8367a70 100644 --- a/pkg/middleware/headers.go +++ b/pkg/middleware/headers.go @@ -54,7 +54,7 @@ func flattenHeaders(headers http.Header) { func stripHeaders(headers []options.Header, next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { for _, header := range headers { - if header.InsecureSkipHeaderNormalization { + if ptr.Deref(header.InsecureSkipHeaderNormalization, options.DefaultInsecureSkipHeaderNormalization) { req.Header.Del(header.Name) continue } diff --git a/pkg/middleware/headers_test.go b/pkg/middleware/headers_test.go index 393ade9c7b..c3c402f0b0 100644 --- a/pkg/middleware/headers_test.go +++ b/pkg/middleware/headers_test.go @@ -231,7 +231,7 @@ var _ = Describe("Headers Suite", func() { headers: []options.Header{ { Name: "X-Auth-Request-User", - InsecureSkipHeaderNormalization: true, + InsecureSkipHeaderNormalization: ptr.To(true), Values: []options.HeaderValue{ { ClaimSource: &options.ClaimSource{Claim: "user"}, diff --git a/providers/google.go b/providers/google.go index 92d782247f..d8e4dec850 100644 --- a/providers/google.go +++ b/providers/google.go @@ -109,11 +109,11 @@ func NewGoogleProvider(p *ProviderData, opts options.GoogleOptions) (*GoogleProv }, } - if opts.UseOrganizationID || opts.ServiceAccountJSON != "" || ptr.Deref(opts.UseApplicationDefaultCredentials, options.DefaultUseApplicationDefaultCredentials) { + if ptr.Deref(opts.UseOrganizationID, options.DefaultGoogleUseOrganizationID) || opts.ServiceAccountJSON != "" || ptr.Deref(opts.UseApplicationDefaultCredentials, options.DefaultUseApplicationDefaultCredentials) { // reuse admin service to avoid multiple calls for token var adminService *admin.Service - if opts.UseOrganizationID { + if ptr.Deref(opts.UseOrganizationID, options.DefaultGoogleUseOrganizationID) { // add user scopes to admin api userScope := getAdminAPIUserScope(opts.AdminAPIUserScope) for index, scope := range possibleScopesList { From aee540a27741090b28bad3952d752dee8f65ad20 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 28 Nov 2025 17:20:15 +0100 Subject: [PATCH 090/125] doc: fix mapstructure configuration comments Signed-off-by: Jan Larwig --- pkg/apis/options/load.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/apis/options/load.go b/pkg/apis/options/load.go index 20d0438325..d0dd22df94 100644 --- a/pkg/apis/options/load.go +++ b/pkg/apis/options/load.go @@ -95,10 +95,10 @@ func Decode(input interface{}, result interface{}) error { ), Metadata: nil, // Don't track any metadata Result: result, // Decode the result into the prefilled options - TagName: "yaml", // Parse all fields that use the json tag + TagName: "yaml", // Parse all fields that use the yaml tag ZeroFields: false, // Don't clean the default values from the result map (options) ErrorUnused: true, // Throw an error if keys have been used that aren't mapped to any struct fields - IgnoreUntaggedFields: true, // Ignore fields in structures that aren't tagged with json + IgnoreUntaggedFields: true, // Ignore fields in structures that aren't tagged with yaml }) if err != nil { return fmt.Errorf("error creating decoder for config: %w", err) From 4956bab3fea5bbcc8c55ca9e25ca762f9158be15 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 24 Dec 2025 10:55:38 +0100 Subject: [PATCH 091/125] chore(deps): update module golang.org/x/crypto to v0.45.0 [security] (#3266) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- go.mod | 10 +++++----- go.sum | 10 ++++++++++ 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index 99195a4ecf..caa1464e15 100644 --- a/go.mod +++ b/go.mod @@ -31,10 +31,10 @@ require ( github.com/stretchr/testify v1.11.1 github.com/vmihailenco/msgpack/v5 v5.4.1 go.yaml.in/yaml/v3 v3.0.4 - golang.org/x/crypto v0.43.0 - golang.org/x/net v0.46.0 + golang.org/x/crypto v0.45.0 + golang.org/x/net v0.47.0 golang.org/x/oauth2 v0.32.0 - golang.org/x/sync v0.17.0 + golang.org/x/sync v0.18.0 google.golang.org/api v0.254.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 k8s.io/apimachinery v0.34.1 @@ -76,8 +76,8 @@ require ( go.opentelemetry.io/otel/trace v1.38.0 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect golang.org/x/mod v0.29.0 // indirect - golang.org/x/sys v0.37.0 // indirect - golang.org/x/text v0.30.0 // indirect + golang.org/x/sys v0.38.0 // indirect + golang.org/x/text v0.31.0 // indirect golang.org/x/tools v0.38.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda // indirect google.golang.org/grpc v1.76.0 // indirect diff --git a/go.sum b/go.sum index 8344be120d..824d53add4 100644 --- a/go.sum +++ b/go.sum @@ -194,6 +194,8 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04= golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0= +golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= +golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA= @@ -205,6 +207,8 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4= golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210= +golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= +golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= golang.org/x/oauth2 v0.32.0 h1:jsCblLleRMDrxMN29H3z/k1KliIvpLgCkE6R8FXXNgY= golang.org/x/oauth2 v0.32.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -212,6 +216,8 @@ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I= +golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -223,6 +229,8 @@ golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ= golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= +golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -236,6 +244,8 @@ golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k= golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM= +golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= +golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= From 699f3671156782f6afb813c155814646cca92402 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Wed, 24 Dec 2025 11:30:23 +0100 Subject: [PATCH 092/125] chore(deps): upgrade gomod and bump to golang v1.25.5 (#3292) Signed-off-by: Jan Larwig --- CHANGELOG.md | 1 + go.mod | 58 +++++++++++----------- go.sum | 138 ++++++++++++++++++++++++--------------------------- 3 files changed, 94 insertions(+), 103 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2aa2ef46b8..51aa5aa54a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ## Changes since v7.13.0 - [#3197](https://github.com/oauth2-proxy/oauth2-proxy/pull/3197) fix: NewRemoteKeySet is not using DefaultHTTPClient (@rsrdesarrollo / @tuunit) +- [#3292](https://github.com/oauth2-proxy/oauth2-proxy/pull/3292) chore(deps): upgrade gomod and bump to golang v1.25.5 (@tuunit) # V7.13.0 diff --git a/go.mod b/go.mod index caa1464e15..895f55fa91 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/oauth2-proxy/oauth2-proxy/v7 -go 1.25.3 +go 1.25.5 require ( cloud.google.com/go/compute/metadata v0.9.0 @@ -9,7 +9,7 @@ require ( github.com/alicebob/miniredis/v2 v2.35.0 github.com/bitly/go-simplejson v0.5.1 github.com/bsm/redislock v0.9.4 - github.com/coreos/go-oidc/v3 v3.16.0 + github.com/coreos/go-oidc/v3 v3.17.0 github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf github.com/fsnotify/fsnotify v1.9.0 github.com/go-jose/go-jose/v3 v3.0.4 @@ -20,28 +20,28 @@ require ( github.com/gorilla/mux v1.8.1 github.com/justinas/alice v1.2.0 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 - github.com/onsi/ginkgo/v2 v2.27.2 - github.com/onsi/gomega v1.38.2 - github.com/pierrec/lz4/v4 v4.1.22 + github.com/onsi/ginkgo/v2 v2.27.3 + github.com/onsi/gomega v1.38.3 + github.com/pierrec/lz4/v4 v4.1.23 github.com/prometheus/client_golang v1.23.2 - github.com/redis/go-redis/v9 v9.16.0 + github.com/redis/go-redis/v9 v9.17.2 github.com/spf13/cast v1.10.0 github.com/spf13/pflag v1.0.10 github.com/spf13/viper v1.21.0 github.com/stretchr/testify v1.11.1 github.com/vmihailenco/msgpack/v5 v5.4.1 go.yaml.in/yaml/v3 v3.0.4 - golang.org/x/crypto v0.45.0 - golang.org/x/net v0.47.0 - golang.org/x/oauth2 v0.32.0 - golang.org/x/sync v0.18.0 - google.golang.org/api v0.254.0 + golang.org/x/crypto v0.46.0 + golang.org/x/net v0.48.0 + golang.org/x/oauth2 v0.34.0 + golang.org/x/sync v0.19.0 + google.golang.org/api v0.258.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 - k8s.io/apimachinery v0.34.1 + k8s.io/apimachinery v0.35.0 ) require ( - cloud.google.com/go/auth v0.17.0 // indirect + cloud.google.com/go/auth v0.18.0 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect github.com/Masterminds/semver/v3 v3.4.0 // indirect github.com/beorn7/perks v1.0.1 // indirect @@ -53,34 +53,34 @@ require ( github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-task/slim-sprig/v3 v3.0.0 // indirect - github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d // indirect + github.com/google/pprof v0.0.0-20251213031049-b05bdaca462f // indirect github.com/google/s2a-go v0.1.9 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect - github.com/googleapis/gax-go/v2 v2.15.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.7 // indirect + github.com/googleapis/gax-go/v2 v2.16.0 // indirect github.com/kylelemons/godebug v1.1.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.67.2 // indirect - github.com/prometheus/procfs v0.19.1 // indirect + github.com/prometheus/common v0.67.4 // indirect + github.com/prometheus/procfs v0.19.2 // indirect github.com/sagikazarmark/locafero v0.12.0 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/yuin/gopher-lua v1.1.1 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect - go.opentelemetry.io/otel v1.38.0 // indirect - go.opentelemetry.io/otel/metric v1.38.0 // indirect - go.opentelemetry.io/otel/trace v1.38.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0 // indirect + go.opentelemetry.io/otel v1.39.0 // indirect + go.opentelemetry.io/otel/metric v1.39.0 // indirect + go.opentelemetry.io/otel/trace v1.39.0 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect - golang.org/x/mod v0.29.0 // indirect - golang.org/x/sys v0.38.0 // indirect - golang.org/x/text v0.31.0 // indirect - golang.org/x/tools v0.38.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda // indirect - google.golang.org/grpc v1.76.0 // indirect - google.golang.org/protobuf v1.36.10 // indirect + golang.org/x/mod v0.31.0 // indirect + golang.org/x/sys v0.39.0 // indirect + golang.org/x/text v0.32.0 // indirect + golang.org/x/tools v0.40.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect + google.golang.org/grpc v1.78.0 // indirect + google.golang.org/protobuf v1.36.11 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 824d53add4..3d6948ed85 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -cloud.google.com/go/auth v0.17.0 h1:74yCm7hCj2rUyyAocqnFzsAYXgJhrG26XCFimrc/Kz4= -cloud.google.com/go/auth v0.17.0/go.mod h1:6wv/t5/6rOPAX4fJiRjKkJCvswLwdet7G8+UGXt7nCQ= +cloud.google.com/go/auth v0.18.0 h1:wnqy5hrv7p3k7cShwAU/Br3nzod7fxoqG+k0VZ+/Pk0= +cloud.google.com/go/auth v0.18.0/go.mod h1:wwkPM1AgE1f2u6dG443MiWoD8C3BtOywNsUMcUTVDRo= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= @@ -31,8 +31,8 @@ github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/coreos/go-oidc/v3 v3.16.0 h1:qRQUCFstKpXwmEjDQTIbyY/5jF00+asXzSkmkoa/mow= -github.com/coreos/go-oidc/v3 v3.16.0/go.mod h1:wqPbKFrVnE90vty060SB40FCJ8fTHTxSwyXJqZH+sI8= +github.com/coreos/go-oidc/v3 v3.17.0 h1:hWBGaQfbi0iVviX4ibC7bk8OKT5qNr4klBaCHVNvehc= +github.com/coreos/go-oidc/v3 v3.17.0/go.mod h1:wqPbKFrVnE90vty060SB40FCJ8fTHTxSwyXJqZH+sI8= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf h1:iW4rZ826su+pqaw19uhpSCzhj44qo35pNgKFGqzDKkU= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -76,17 +76,17 @@ github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3/go.mod h1:B4C85q github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d h1:KJIErDwbSHjnp/SGzE5ed8Aol7JsKiI5X7yWKAtzhM0= -github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U= +github.com/google/pprof v0.0.0-20251213031049-b05bdaca462f h1:HU1RgM6NALf/KW9HEY6zry3ADbDKcmpQ+hJedoNGQYQ= +github.com/google/pprof v0.0.0-20251213031049-b05bdaca462f/go.mod h1:67FPmZWbr+KDT/VlpWtw6sO9XSjpJmLuHpoLmWiTGgY= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU9uHLo7OnF5tL52HFAgMmyrf4= -github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= -github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81vgd/bo= -github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= +github.com/googleapis/enterprise-certificate-proxy v0.3.7 h1:zrn2Ee/nWmHulBx5sAVrGgAa0f2/R35S4DJwfFaUPFQ= +github.com/googleapis/enterprise-certificate-proxy v0.3.7/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= +github.com/googleapis/gax-go/v2 v2.16.0 h1:iHbQmKLLZrexmb0OSsNGTeSTS0HO4YvFOG8g5E4Zd0Y= +github.com/googleapis/gax-go/v2 v2.16.0/go.mod h1:o1vfQjjNZn4+dPnRdl/4ZD7S9414Y4xA+a/6Icj6l14= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE= @@ -111,14 +111,14 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw= -github.com/onsi/ginkgo/v2 v2.27.2 h1:LzwLj0b89qtIy6SSASkzlNvX6WktqurSHwkk2ipF/Ns= -github.com/onsi/ginkgo/v2 v2.27.2/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= -github.com/onsi/gomega v1.38.2 h1:eZCjf2xjZAqe+LeWvKb5weQ+NcPwX84kqJ0cZNxok2A= -github.com/onsi/gomega v1.38.2/go.mod h1:W2MJcYxRGV63b418Ai34Ud0hEdTVXq9NW9+Sx6uXf3k= +github.com/onsi/ginkgo/v2 v2.27.3 h1:ICsZJ8JoYafeXFFlFAG75a7CxMsJHwgKwtO+82SE9L8= +github.com/onsi/ginkgo/v2 v2.27.3/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= +github.com/onsi/gomega v1.38.3 h1:eTX+W6dobAYfFeGC2PV6RwXRu/MyT+cQguijutvkpSM= +github.com/onsi/gomega v1.38.3/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= -github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU= -github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pierrec/lz4/v4 v4.1.23 h1:oJE7T90aYBGtFNrI8+KbETnPymobAhzRrR8Mu8n1yfU= +github.com/pierrec/lz4/v4 v4.1.23/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -126,12 +126,12 @@ github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= -github.com/prometheus/common v0.67.2 h1:PcBAckGFTIHt2+L3I33uNRTlKTplNzFctXcWhPyAEN8= -github.com/prometheus/common v0.67.2/go.mod h1:63W3KZb1JOKgcjlIr64WW/LvFGAqKPj0atm+knVGEko= -github.com/prometheus/procfs v0.19.1 h1:QVtROpTkphuXuNlnCv3m1ut3JytkXHtQ3xvck/YmzMM= -github.com/prometheus/procfs v0.19.1/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw= -github.com/redis/go-redis/v9 v9.16.0 h1:OotgqgLSRCmzfqChbQyG1PHC3tLNR89DG4jdOERSEP4= -github.com/redis/go-redis/v9 v9.16.0/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370= +github.com/prometheus/common v0.67.4 h1:yR3NqWO1/UyO1w2PhUvXlGQs/PtFmoveVO0KZ4+Lvsc= +github.com/prometheus/common v0.67.4/go.mod h1:gP0fq6YjjNCLssJCQp0yk4M8W6ikLURwkdd/YKtTbyI= +github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws= +github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw= +github.com/redis/go-redis/v9 v9.17.2 h1:P2EGsA4qVIM3Pp+aPocCJ7DguDHhqrXNhVcEp4ViluI= +github.com/redis/go-redis/v9 v9.17.2/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4= @@ -171,18 +171,18 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg= -go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= -go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= -go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= -go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= -go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= -go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg= -go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM= -go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA= -go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= -go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0 h1:ssfIgGNANqpVFCndZvcuyKbl0g+UAVcbBcqGkG28H0Y= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0/go.mod h1:GQ/474YrbE4Jx8gZ4q5I4hrhUzM6UPzyrqJYV2AqPoQ= +go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48= +go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8= +go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0= +go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs= +go.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18= +go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE= +go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8= +go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew= +go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI= +go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0= @@ -192,32 +192,26 @@ go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= -golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04= -golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0= -golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= -golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= +golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= +golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA= -golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w= +golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI= +golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4= -golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210= -golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= -golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= -golang.org/x/oauth2 v0.32.0 h1:jsCblLleRMDrxMN29H3z/k1KliIvpLgCkE6R8FXXNgY= -golang.org/x/oauth2 v0.32.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= +golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= +golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= +golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw= +golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= -golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= -golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I= -golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -227,10 +221,8 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ= -golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= -golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= +golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -242,33 +234,31 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k= -golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM= -golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= -golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= +golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= +golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ= -golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs= +golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA= +golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= -google.golang.org/api v0.254.0 h1:jl3XrGj7lRjnlUvZAbAdhINTLbsg5dbjmR90+pTQvt4= -google.golang.org/api v0.254.0/go.mod h1:5BkSURm3D9kAqjGvBNgf0EcbX6Rnrf6UArKkwBzAyqQ= -google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= -google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= -google.golang.org/genproto/googleapis/api v0.0.0-20250804133106-a7a43d27e69b h1:ULiyYQ0FdsJhwwZUwbaXpZF5yUE3h+RA+gxvBu37ucc= -google.golang.org/genproto/googleapis/api v0.0.0-20250804133106-a7a43d27e69b/go.mod h1:oDOGiMSXHL4sDTJvFvIB9nRQCGdLP1o/iVaqQK8zB+M= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda h1:i/Q+bfisr7gq6feoJnS/DlpdwEL4ihp41fvRiM3Ork0= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= -google.golang.org/grpc v1.76.0 h1:UnVkv1+uMLYXoIz6o7chp59WfQUYA2ex/BXQ9rHZu7A= -google.golang.org/grpc v1.76.0/go.mod h1:Ju12QI8M6iQJtbcsV+awF5a4hfJMLi4X0JLo94ULZ6c= -google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= -google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +google.golang.org/api v0.258.0 h1:IKo1j5FBlN74fe5isA2PVozN3Y5pwNKriEgAXPOkDAc= +google.golang.org/api v0.258.0/go.mod h1:qhOMTQEZ6lUps63ZNq9jhODswwjkjYYguA7fA3TBFww= +google.golang.org/genproto v0.0.0-20251202230838-ff82c1b0f217 h1:GvESR9BIyHUahIb0NcTum6itIWtdoglGX+rnGxm2934= +google.golang.org/genproto v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:yJ2HH4EHEDTd3JiLmhds6NkJ17ITVYOdV3m3VKOnws0= +google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls= +google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:+rXWjjaukWZun3mLfjmVnQi18E1AsFbDN9QdJ5YXLto= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ= +google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc= +google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= @@ -277,5 +267,5 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYs gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/apimachinery v0.34.1 h1:dTlxFls/eikpJxmAC7MVE8oOeP1zryV7iRyIjB0gky4= -k8s.io/apimachinery v0.34.1/go.mod h1:/GwIlEcWuTX9zKIg2mbw0LRFIsXwrfoVxn+ef0X13lw= +k8s.io/apimachinery v0.35.0 h1:Z2L3IHvPVv/MJ7xRxHEtk6GoJElaAqDCCU0S6ncYok8= +k8s.io/apimachinery v0.35.0/go.mod h1:jQCgFZFR1F4Ik7hvr2g84RTJSZegBc8yHgFWKn//hns= From 12564e02d09634a2e9da4e183c6fc58d02925b2d Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 24 Dec 2025 11:30:58 +0100 Subject: [PATCH 093/125] chore(deps): update docker-compose (#3272) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/docker-compose-alpha-config.yaml | 4 ++-- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index 16e6a3cadf..e524933ebc 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -31,7 +31,7 @@ services: - httpbin dex: container_name: dex - image: ghcr.io/dexidp/dex:v2.43.1 + image: ghcr.io/dexidp/dex:v2.44.0 command: dex serve /dex.yaml hostname: dex volumes: @@ -54,7 +54,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.2 + image: gcr.io/etcd-development/etcd:v3.6.7 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index f6defb5a6e..ea908106f6 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -39,7 +39,7 @@ services: httpbin: {} gitea: - image: gitea/gitea:1.25.1 + image: gitea/gitea:1.25.3 container_name: gitea environment: - USER_UID=1000 diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 201bfe8d20..f7dcb4d1a2 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -78,7 +78,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.5 + image: gcr.io/etcd-development/etcd:v3.6.7 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 1e6f66204e..8a10e5c7cb 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -34,7 +34,7 @@ services: # Reverse proxy gateway: container_name: traefik - image: traefik:v2.11.30 + image: traefik:v2.11.33 volumes: - "./traefik:/etc/traefik" ports: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index fef0e32f94..631249abbf 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -52,7 +52,7 @@ services: httpbin: {} etcd: container_name: etcd - image: gcr.io/etcd-development/etcd:v3.6.5 + image: gcr.io/etcd-development/etcd:v3.6.7 entrypoint: /usr/local/bin/etcd command: - --listen-client-urls=http://0.0.0.0:2379 From 6a0d821df81010b69145f9fe45ce49844ba7bed5 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 24 Dec 2025 11:31:18 +0100 Subject: [PATCH 094/125] chore(deps): update actions/checkout action to v6 (#3273) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 4 ++-- .github/workflows/codeql.yml | 2 +- .github/workflows/create-release.yml | 2 +- .github/workflows/docs.yml | 4 ++-- .github/workflows/nightly.yml | 2 +- .github/workflows/publish-release.yml | 4 ++-- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4764c81302..fc235aa545 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,7 +14,7 @@ jobs: COVER: true steps: - name: Check out code - uses: actions/checkout@v5 + uses: actions/checkout@v6 - name: Set up Go uses: actions/setup-go@v6 @@ -60,7 +60,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out code - uses: actions/checkout@v5 + uses: actions/checkout@v6 - name: Set up QEMU uses: docker/setup-qemu-action@v3 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index d3ebda1d75..9c90fd6116 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -32,7 +32,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v5 + uses: actions/checkout@v6 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL diff --git a/.github/workflows/create-release.yml b/.github/workflows/create-release.yml index ea8fcb02b3..67547d92e9 100644 --- a/.github/workflows/create-release.yml +++ b/.github/workflows/create-release.yml @@ -17,7 +17,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out code - uses: actions/checkout@v5 + uses: actions/checkout@v6 with: ref: master fetch-depth: 0 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 5f4bbe4f7a..afe3325071 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -14,7 +14,7 @@ jobs: if: github.event_name == 'pull_request' runs-on: ubuntu-latest steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Setup Pages id: pages @@ -35,7 +35,7 @@ jobs: if: github.event_name == 'push' || github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - uses: actions/setup-node@v6 with: diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 8b14174b2e..e3a1998df2 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -12,7 +12,7 @@ jobs: if: github.repository == 'oauth2-proxy/oauth2-proxy' steps: - name: Check out code - uses: actions/checkout@v5 + uses: actions/checkout@v6 with: ref: master fetch-depth: 0 diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index ccefd1c939..19201161c6 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -20,7 +20,7 @@ jobs: tag: ${{ steps.tag.outputs.version }} steps: - name: Check out code - uses: actions/checkout@v5 + uses: actions/checkout@v6 with: ref: ${{ github.event.pull_request.merge_commit_sha }} fetch-depth: 0 @@ -100,7 +100,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out code - uses: actions/checkout@v5 + uses: actions/checkout@v6 with: ref: ${{ needs.publish.outputs.tag }} fetch-depth: 0 From 854a74793bb40583c96e6256c22868b07d5f5140 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sun, 4 Jan 2026 10:23:26 +0100 Subject: [PATCH 095/125] chore(deps): update dependency golangci/golangci-lint to v2.7.2 (#3254) * chore(deps): update dependency golangci/golangci-lint to v2.7.2 * chore(linter): fix gocritic deprecation message issue Signed-off-by: Jan Larwig * chore(lint): fix var-naming: avoid package names that conflict with Go standard library package names (revive) Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Jan Larwig --- .github/workflows/ci.yml | 2 +- .github/workflows/publish-release.yml | 2 +- oauthproxy.go | 2 +- pkg/{http => proxyhttp}/http_suite_test.go | 2 +- pkg/{http => proxyhttp}/server.go | 2 +- pkg/{http => proxyhttp}/server_group.go | 2 +- pkg/{http => proxyhttp}/server_group_test.go | 2 +- pkg/{http => proxyhttp}/server_test.go | 2 +- pkg/{http => proxyhttp}/systemd_socket.go | 2 +- pkg/{http => proxyhttp}/systemd_unsupported.go | 2 +- providers/provider_default.go | 1 + 11 files changed, 11 insertions(+), 10 deletions(-) rename pkg/{http => proxyhttp}/http_suite_test.go (99%) rename pkg/{http => proxyhttp}/server.go (99%) rename pkg/{http => proxyhttp}/server_group.go (97%) rename pkg/{http => proxyhttp}/server_group_test.go (99%) rename pkg/{http => proxyhttp}/server_test.go (99%) rename pkg/{http => proxyhttp}/systemd_socket.go (98%) rename pkg/{http => proxyhttp}/systemd_unsupported.go (95%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fc235aa545..aa77fbf4df 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,7 +25,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.5.0 + GOLANGCI_LINT_VERSION: v2.7.2 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 19201161c6..64b334e572 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -50,7 +50,7 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.5.0 + GOLANGCI_LINT_VERSION: v2.7.2 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter diff --git a/oauthproxy.go b/oauthproxy.go index c6db18a766..d933d930cc 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -28,7 +28,7 @@ import ( "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/authentication/basic" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/cookies" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption" - proxyhttp "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/http" + "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/proxyhttp" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util" "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/version" diff --git a/pkg/http/http_suite_test.go b/pkg/proxyhttp/http_suite_test.go similarity index 99% rename from pkg/http/http_suite_test.go rename to pkg/proxyhttp/http_suite_test.go index 19d4d3ff39..4241c7b6ae 100644 --- a/pkg/http/http_suite_test.go +++ b/pkg/proxyhttp/http_suite_test.go @@ -1,4 +1,4 @@ -package http +package proxyhttp import ( "bytes" diff --git a/pkg/http/server.go b/pkg/proxyhttp/server.go similarity index 99% rename from pkg/http/server.go rename to pkg/proxyhttp/server.go index fe76427a07..a0fc605414 100644 --- a/pkg/http/server.go +++ b/pkg/proxyhttp/server.go @@ -1,4 +1,4 @@ -package http +package proxyhttp import ( "context" diff --git a/pkg/http/server_group.go b/pkg/proxyhttp/server_group.go similarity index 97% rename from pkg/http/server_group.go rename to pkg/proxyhttp/server_group.go index 261d9837f2..ae6903578a 100644 --- a/pkg/http/server_group.go +++ b/pkg/proxyhttp/server_group.go @@ -1,4 +1,4 @@ -package http +package proxyhttp import ( "context" diff --git a/pkg/http/server_group_test.go b/pkg/proxyhttp/server_group_test.go similarity index 99% rename from pkg/http/server_group_test.go rename to pkg/proxyhttp/server_group_test.go index 74e5c3159f..261902dc58 100644 --- a/pkg/http/server_group_test.go +++ b/pkg/proxyhttp/server_group_test.go @@ -1,4 +1,4 @@ -package http +package proxyhttp import ( "context" diff --git a/pkg/http/server_test.go b/pkg/proxyhttp/server_test.go similarity index 99% rename from pkg/http/server_test.go rename to pkg/proxyhttp/server_test.go index 8dfa13afad..d97dcec266 100644 --- a/pkg/http/server_test.go +++ b/pkg/proxyhttp/server_test.go @@ -1,4 +1,4 @@ -package http +package proxyhttp import ( "context" diff --git a/pkg/http/systemd_socket.go b/pkg/proxyhttp/systemd_socket.go similarity index 98% rename from pkg/http/systemd_socket.go rename to pkg/proxyhttp/systemd_socket.go index b0627f3f1a..d5f7c49cc3 100644 --- a/pkg/http/systemd_socket.go +++ b/pkg/proxyhttp/systemd_socket.go @@ -1,7 +1,7 @@ //go:build !windows // +build !windows -package http +package proxyhttp import ( "errors" diff --git a/pkg/http/systemd_unsupported.go b/pkg/proxyhttp/systemd_unsupported.go similarity index 95% rename from pkg/http/systemd_unsupported.go rename to pkg/proxyhttp/systemd_unsupported.go index 3fe163f3aa..b3413ccea3 100644 --- a/pkg/http/systemd_unsupported.go +++ b/pkg/proxyhttp/systemd_unsupported.go @@ -1,7 +1,7 @@ //go:build windows // +build windows -package http +package proxyhttp import ( "fmt" diff --git a/providers/provider_default.go b/providers/provider_default.go index 1735ddd3ef..dbd93c91b5 100644 --- a/providers/provider_default.go +++ b/providers/provider_default.go @@ -107,6 +107,7 @@ func (p *ProviderData) Redeem(ctx context.Context, redirectURL, code, codeVerifi } // GetEmailAddress returns the Account email address +// // Deprecated: Migrate to EnrichSession func (p *ProviderData) GetEmailAddress(_ context.Context, _ *sessions.SessionState) (string, error) { return "", ErrNotImplemented From 0100ca9403399716586f56a08c784fc690c6fc79 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 6 Jan 2026 19:42:27 +0100 Subject: [PATCH 096/125] chore(deps): update alpine docker tag to v3.23.2 (#3296) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 38b2f94943..735075601f 100644 --- a/Makefile +++ b/Makefile @@ -66,7 +66,7 @@ DOCKER_BUILDX_PUSH := $(DOCKER_BUILDX) --push DOCKER_BUILDX_PUSH_X_PLATFORM := $(DOCKER_BUILDX_PUSH) --platform ${DOCKER_BUILD_PLATFORM} DOCKER_BUILD_PLATFORM_ALPINE ?= linux/amd64,linux/arm64,linux/ppc64le,linux/arm/v6,linux/arm/v7,linux/s390x -DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.22.2 +DOCKER_BUILD_RUNTIME_IMAGE_ALPINE ?= alpine:3.23.2 DOCKER_BUILDX_ARGS_ALPINE ?= --build-arg RUNTIME_IMAGE=${DOCKER_BUILD_RUNTIME_IMAGE_ALPINE} ${DOCKER_BUILDX_COMMON_ARGS} DOCKER_BUILDX_X_PLATFORM_ALPINE := docker buildx build ${DOCKER_BUILDX_ARGS_ALPINE} --platform ${DOCKER_BUILD_PLATFORM_ALPINE} DOCKER_BUILDX_PUSH_X_PLATFORM_ALPINE := $(DOCKER_BUILDX_X_PLATFORM_ALPINE) --push From a2f2223d2b71068f2c34aadca77fb6a1f3c70617 Mon Sep 17 00:00:00 2001 From: NirronCD Date: Wed, 14 Jan 2026 17:26:50 -0300 Subject: [PATCH 097/125] doc: improved clarity and correctness of proxy behaviour (#3305) * doc: adjust regarding description of behaviour Signed-off-by: NirronCD * doc:changed style, added suggested Signed-off-by: NirronCD * doc: minor fix to docusaurus metadata syntax Signed-off-by: NirronCD * docs: improved clarity for how the proxy behaves in different scenarios Signed-off-by: Jan Larwig --------- Signed-off-by: NirronCD Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- docs/docs/behaviour.md | 25 +++++++++++++++---- .../versioned_docs/version-7.0.x/behaviour.md | 2 +- .../versioned_docs/version-7.1.x/behaviour.md | 2 +- .../version-7.10.x/behaviour.md | 25 +++++++++++++++---- .../version-7.11.x/behaviour.md | 25 +++++++++++++++---- .../version-7.12.x/behaviour.md | 25 +++++++++++++++---- .../version-7.13.x/behaviour.md | 25 +++++++++++++++---- .../versioned_docs/version-7.2.x/behaviour.md | 25 +++++++++++++++---- .../versioned_docs/version-7.3.x/behaviour.md | 25 +++++++++++++++---- .../versioned_docs/version-7.4.x/behaviour.md | 25 +++++++++++++++---- .../versioned_docs/version-7.5.x/behaviour.md | 25 +++++++++++++++---- .../versioned_docs/version-7.6.x/behaviour.md | 25 +++++++++++++++---- .../versioned_docs/version-7.7.x/behaviour.md | 25 +++++++++++++++---- .../versioned_docs/version-7.8.x/behaviour.md | 25 +++++++++++++++---- .../versioned_docs/version-7.9.x/behaviour.md | 25 +++++++++++++++---- 15 files changed, 262 insertions(+), 67 deletions(-) diff --git a/docs/docs/behaviour.md b/docs/docs/behaviour.md index e063d4f966..d0be452ec5 100644 --- a/docs/docs/behaviour.md +++ b/docs/docs/behaviour.md @@ -3,9 +3,24 @@ id: behaviour title: Behaviour --- -1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). -2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) -3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set -4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) +1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints. + - Exception: If the request matches a skipped route (configured via `--skip-auth-route`): + - Authentication is not enforced, but the proxy will opportunistically attempt to validate a session cookie (`--cookie-name`) or JWT (`--skip-jwt-bearer-tokens`) if present in the request. + - Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds. -Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). +2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default. + - Ajax Requests: If the request has `Accept: application/json` header: + - Returns `401 Unauthorized`. + - Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT: + - Redirects to the login page by default. + - Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`. + +3. Post-Authentication: After successful authentication with the IdP, OAuth tokens are stored in the configured session store (cookie or Redis), and a cookie is set. + +4. Request Forwarding: The authenticated request is processed based on configuration: + - Forwarded to the configured upstream application with added user info and authentication headers, or + - Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik). + +--- + +Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management. diff --git a/docs/versioned_docs/version-7.0.x/behaviour.md b/docs/versioned_docs/version-7.0.x/behaviour.md index e063d4f966..f6f18eb553 100644 --- a/docs/versioned_docs/version-7.0.x/behaviour.md +++ b/docs/versioned_docs/version-7.0.x/behaviour.md @@ -3,7 +3,7 @@ id: behaviour title: Behaviour --- -1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). +1. Any request passing through the proxy (and not matched by `--skip-auth-route`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). 2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) 3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set 4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) diff --git a/docs/versioned_docs/version-7.1.x/behaviour.md b/docs/versioned_docs/version-7.1.x/behaviour.md index e063d4f966..f6f18eb553 100644 --- a/docs/versioned_docs/version-7.1.x/behaviour.md +++ b/docs/versioned_docs/version-7.1.x/behaviour.md @@ -3,7 +3,7 @@ id: behaviour title: Behaviour --- -1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). +1. Any request passing through the proxy (and not matched by `--skip-auth-route`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). 2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) 3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set 4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) diff --git a/docs/versioned_docs/version-7.10.x/behaviour.md b/docs/versioned_docs/version-7.10.x/behaviour.md index e063d4f966..d0be452ec5 100644 --- a/docs/versioned_docs/version-7.10.x/behaviour.md +++ b/docs/versioned_docs/version-7.10.x/behaviour.md @@ -3,9 +3,24 @@ id: behaviour title: Behaviour --- -1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). -2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) -3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set -4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) +1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints. + - Exception: If the request matches a skipped route (configured via `--skip-auth-route`): + - Authentication is not enforced, but the proxy will opportunistically attempt to validate a session cookie (`--cookie-name`) or JWT (`--skip-jwt-bearer-tokens`) if present in the request. + - Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds. -Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). +2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default. + - Ajax Requests: If the request has `Accept: application/json` header: + - Returns `401 Unauthorized`. + - Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT: + - Redirects to the login page by default. + - Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`. + +3. Post-Authentication: After successful authentication with the IdP, OAuth tokens are stored in the configured session store (cookie or Redis), and a cookie is set. + +4. Request Forwarding: The authenticated request is processed based on configuration: + - Forwarded to the configured upstream application with added user info and authentication headers, or + - Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik). + +--- + +Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management. diff --git a/docs/versioned_docs/version-7.11.x/behaviour.md b/docs/versioned_docs/version-7.11.x/behaviour.md index e063d4f966..d0be452ec5 100644 --- a/docs/versioned_docs/version-7.11.x/behaviour.md +++ b/docs/versioned_docs/version-7.11.x/behaviour.md @@ -3,9 +3,24 @@ id: behaviour title: Behaviour --- -1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). -2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) -3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set -4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) +1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints. + - Exception: If the request matches a skipped route (configured via `--skip-auth-route`): + - Authentication is not enforced, but the proxy will opportunistically attempt to validate a session cookie (`--cookie-name`) or JWT (`--skip-jwt-bearer-tokens`) if present in the request. + - Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds. -Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). +2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default. + - Ajax Requests: If the request has `Accept: application/json` header: + - Returns `401 Unauthorized`. + - Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT: + - Redirects to the login page by default. + - Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`. + +3. Post-Authentication: After successful authentication with the IdP, OAuth tokens are stored in the configured session store (cookie or Redis), and a cookie is set. + +4. Request Forwarding: The authenticated request is processed based on configuration: + - Forwarded to the configured upstream application with added user info and authentication headers, or + - Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik). + +--- + +Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management. diff --git a/docs/versioned_docs/version-7.12.x/behaviour.md b/docs/versioned_docs/version-7.12.x/behaviour.md index e063d4f966..d0be452ec5 100644 --- a/docs/versioned_docs/version-7.12.x/behaviour.md +++ b/docs/versioned_docs/version-7.12.x/behaviour.md @@ -3,9 +3,24 @@ id: behaviour title: Behaviour --- -1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). -2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) -3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set -4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) +1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints. + - Exception: If the request matches a skipped route (configured via `--skip-auth-route`): + - Authentication is not enforced, but the proxy will opportunistically attempt to validate a session cookie (`--cookie-name`) or JWT (`--skip-jwt-bearer-tokens`) if present in the request. + - Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds. -Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). +2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default. + - Ajax Requests: If the request has `Accept: application/json` header: + - Returns `401 Unauthorized`. + - Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT: + - Redirects to the login page by default. + - Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`. + +3. Post-Authentication: After successful authentication with the IdP, OAuth tokens are stored in the configured session store (cookie or Redis), and a cookie is set. + +4. Request Forwarding: The authenticated request is processed based on configuration: + - Forwarded to the configured upstream application with added user info and authentication headers, or + - Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik). + +--- + +Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management. diff --git a/docs/versioned_docs/version-7.13.x/behaviour.md b/docs/versioned_docs/version-7.13.x/behaviour.md index e063d4f966..d0be452ec5 100644 --- a/docs/versioned_docs/version-7.13.x/behaviour.md +++ b/docs/versioned_docs/version-7.13.x/behaviour.md @@ -3,9 +3,24 @@ id: behaviour title: Behaviour --- -1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). -2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) -3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set -4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) +1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints. + - Exception: If the request matches a skipped route (configured via `--skip-auth-route`): + - Authentication is not enforced, but the proxy will opportunistically attempt to validate a session cookie (`--cookie-name`) or JWT (`--skip-jwt-bearer-tokens`) if present in the request. + - Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds. -Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). +2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default. + - Ajax Requests: If the request has `Accept: application/json` header: + - Returns `401 Unauthorized`. + - Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT: + - Redirects to the login page by default. + - Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`. + +3. Post-Authentication: After successful authentication with the IdP, OAuth tokens are stored in the configured session store (cookie or Redis), and a cookie is set. + +4. Request Forwarding: The authenticated request is processed based on configuration: + - Forwarded to the configured upstream application with added user info and authentication headers, or + - Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik). + +--- + +Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management. diff --git a/docs/versioned_docs/version-7.2.x/behaviour.md b/docs/versioned_docs/version-7.2.x/behaviour.md index e063d4f966..d0be452ec5 100644 --- a/docs/versioned_docs/version-7.2.x/behaviour.md +++ b/docs/versioned_docs/version-7.2.x/behaviour.md @@ -3,9 +3,24 @@ id: behaviour title: Behaviour --- -1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). -2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) -3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set -4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) +1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints. + - Exception: If the request matches a skipped route (configured via `--skip-auth-route`): + - Authentication is not enforced, but the proxy will opportunistically attempt to validate a session cookie (`--cookie-name`) or JWT (`--skip-jwt-bearer-tokens`) if present in the request. + - Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds. -Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). +2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default. + - Ajax Requests: If the request has `Accept: application/json` header: + - Returns `401 Unauthorized`. + - Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT: + - Redirects to the login page by default. + - Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`. + +3. Post-Authentication: After successful authentication with the IdP, OAuth tokens are stored in the configured session store (cookie or Redis), and a cookie is set. + +4. Request Forwarding: The authenticated request is processed based on configuration: + - Forwarded to the configured upstream application with added user info and authentication headers, or + - Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik). + +--- + +Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management. diff --git a/docs/versioned_docs/version-7.3.x/behaviour.md b/docs/versioned_docs/version-7.3.x/behaviour.md index e063d4f966..d0be452ec5 100644 --- a/docs/versioned_docs/version-7.3.x/behaviour.md +++ b/docs/versioned_docs/version-7.3.x/behaviour.md @@ -3,9 +3,24 @@ id: behaviour title: Behaviour --- -1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). -2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) -3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set -4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) +1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints. + - Exception: If the request matches a skipped route (configured via `--skip-auth-route`): + - Authentication is not enforced, but the proxy will opportunistically attempt to validate a session cookie (`--cookie-name`) or JWT (`--skip-jwt-bearer-tokens`) if present in the request. + - Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds. -Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). +2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default. + - Ajax Requests: If the request has `Accept: application/json` header: + - Returns `401 Unauthorized`. + - Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT: + - Redirects to the login page by default. + - Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`. + +3. Post-Authentication: After successful authentication with the IdP, OAuth tokens are stored in the configured session store (cookie or Redis), and a cookie is set. + +4. Request Forwarding: The authenticated request is processed based on configuration: + - Forwarded to the configured upstream application with added user info and authentication headers, or + - Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik). + +--- + +Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management. diff --git a/docs/versioned_docs/version-7.4.x/behaviour.md b/docs/versioned_docs/version-7.4.x/behaviour.md index e063d4f966..d0be452ec5 100644 --- a/docs/versioned_docs/version-7.4.x/behaviour.md +++ b/docs/versioned_docs/version-7.4.x/behaviour.md @@ -3,9 +3,24 @@ id: behaviour title: Behaviour --- -1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). -2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) -3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set -4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) +1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints. + - Exception: If the request matches a skipped route (configured via `--skip-auth-route`): + - Authentication is not enforced, but the proxy will opportunistically attempt to validate a session cookie (`--cookie-name`) or JWT (`--skip-jwt-bearer-tokens`) if present in the request. + - Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds. -Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). +2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default. + - Ajax Requests: If the request has `Accept: application/json` header: + - Returns `401 Unauthorized`. + - Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT: + - Redirects to the login page by default. + - Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`. + +3. Post-Authentication: After successful authentication with the IdP, OAuth tokens are stored in the configured session store (cookie or Redis), and a cookie is set. + +4. Request Forwarding: The authenticated request is processed based on configuration: + - Forwarded to the configured upstream application with added user info and authentication headers, or + - Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik). + +--- + +Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management. diff --git a/docs/versioned_docs/version-7.5.x/behaviour.md b/docs/versioned_docs/version-7.5.x/behaviour.md index e063d4f966..d0be452ec5 100644 --- a/docs/versioned_docs/version-7.5.x/behaviour.md +++ b/docs/versioned_docs/version-7.5.x/behaviour.md @@ -3,9 +3,24 @@ id: behaviour title: Behaviour --- -1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). -2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) -3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set -4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) +1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints. + - Exception: If the request matches a skipped route (configured via `--skip-auth-route`): + - Authentication is not enforced, but the proxy will opportunistically attempt to validate a session cookie (`--cookie-name`) or JWT (`--skip-jwt-bearer-tokens`) if present in the request. + - Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds. -Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). +2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default. + - Ajax Requests: If the request has `Accept: application/json` header: + - Returns `401 Unauthorized`. + - Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT: + - Redirects to the login page by default. + - Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`. + +3. Post-Authentication: After successful authentication with the IdP, OAuth tokens are stored in the configured session store (cookie or Redis), and a cookie is set. + +4. Request Forwarding: The authenticated request is processed based on configuration: + - Forwarded to the configured upstream application with added user info and authentication headers, or + - Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik). + +--- + +Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management. diff --git a/docs/versioned_docs/version-7.6.x/behaviour.md b/docs/versioned_docs/version-7.6.x/behaviour.md index e063d4f966..d0be452ec5 100644 --- a/docs/versioned_docs/version-7.6.x/behaviour.md +++ b/docs/versioned_docs/version-7.6.x/behaviour.md @@ -3,9 +3,24 @@ id: behaviour title: Behaviour --- -1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). -2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) -3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set -4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) +1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints. + - Exception: If the request matches a skipped route (configured via `--skip-auth-route`): + - Authentication is not enforced, but the proxy will opportunistically attempt to validate a session cookie (`--cookie-name`) or JWT (`--skip-jwt-bearer-tokens`) if present in the request. + - Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds. -Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). +2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default. + - Ajax Requests: If the request has `Accept: application/json` header: + - Returns `401 Unauthorized`. + - Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT: + - Redirects to the login page by default. + - Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`. + +3. Post-Authentication: After successful authentication with the IdP, OAuth tokens are stored in the configured session store (cookie or Redis), and a cookie is set. + +4. Request Forwarding: The authenticated request is processed based on configuration: + - Forwarded to the configured upstream application with added user info and authentication headers, or + - Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik). + +--- + +Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management. diff --git a/docs/versioned_docs/version-7.7.x/behaviour.md b/docs/versioned_docs/version-7.7.x/behaviour.md index e063d4f966..d0be452ec5 100644 --- a/docs/versioned_docs/version-7.7.x/behaviour.md +++ b/docs/versioned_docs/version-7.7.x/behaviour.md @@ -3,9 +3,24 @@ id: behaviour title: Behaviour --- -1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). -2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) -3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set -4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) +1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints. + - Exception: If the request matches a skipped route (configured via `--skip-auth-route`): + - Authentication is not enforced, but the proxy will opportunistically attempt to validate a session cookie (`--cookie-name`) or JWT (`--skip-jwt-bearer-tokens`) if present in the request. + - Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds. -Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). +2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default. + - Ajax Requests: If the request has `Accept: application/json` header: + - Returns `401 Unauthorized`. + - Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT: + - Redirects to the login page by default. + - Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`. + +3. Post-Authentication: After successful authentication with the IdP, OAuth tokens are stored in the configured session store (cookie or Redis), and a cookie is set. + +4. Request Forwarding: The authenticated request is processed based on configuration: + - Forwarded to the configured upstream application with added user info and authentication headers, or + - Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik). + +--- + +Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management. diff --git a/docs/versioned_docs/version-7.8.x/behaviour.md b/docs/versioned_docs/version-7.8.x/behaviour.md index e063d4f966..d0be452ec5 100644 --- a/docs/versioned_docs/version-7.8.x/behaviour.md +++ b/docs/versioned_docs/version-7.8.x/behaviour.md @@ -3,9 +3,24 @@ id: behaviour title: Behaviour --- -1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). -2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) -3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set -4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) +1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints. + - Exception: If the request matches a skipped route (configured via `--skip-auth-route`): + - Authentication is not enforced, but the proxy will opportunistically attempt to validate a session cookie (`--cookie-name`) or JWT (`--skip-jwt-bearer-tokens`) if present in the request. + - Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds. -Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). +2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default. + - Ajax Requests: If the request has `Accept: application/json` header: + - Returns `401 Unauthorized`. + - Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT: + - Redirects to the login page by default. + - Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`. + +3. Post-Authentication: After successful authentication with the IdP, OAuth tokens are stored in the configured session store (cookie or Redis), and a cookie is set. + +4. Request Forwarding: The authenticated request is processed based on configuration: + - Forwarded to the configured upstream application with added user info and authentication headers, or + - Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik). + +--- + +Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management. diff --git a/docs/versioned_docs/version-7.9.x/behaviour.md b/docs/versioned_docs/version-7.9.x/behaviour.md index e063d4f966..d0be452ec5 100644 --- a/docs/versioned_docs/version-7.9.x/behaviour.md +++ b/docs/versioned_docs/version-7.9.x/behaviour.md @@ -3,9 +3,24 @@ id: behaviour title: Behaviour --- -1. Any request passing through the proxy (and not matched by `--skip-auth-regex`) is checked for the proxy's session cookie (`--cookie-name`) (or, if allowed, a JWT token - see `--skip-jwt-bearer-tokens`). -2. If authentication is required but missing then the user is asked to log in and redirected to the authentication provider (unless it is an Ajax request, i.e. one with `Accept: application/json`, in which case 401 Unauthorized is returned) -3. After returning from the authentication provider, the oauth tokens are stored in the configured session store (cookie, redis, ...) and a cookie is set -4. The request is forwarded to the upstream server with added user info and authentication headers (depending on the configuration) +1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints. + - Exception: If the request matches a skipped route (configured via `--skip-auth-route`): + - Authentication is not enforced, but the proxy will opportunistically attempt to validate a session cookie (`--cookie-name`) or JWT (`--skip-jwt-bearer-tokens`) if present in the request. + - Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds. -Notice that the proxy also provides a number of useful [endpoints](features/endpoints.md). +2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default. + - Ajax Requests: If the request has `Accept: application/json` header: + - Returns `401 Unauthorized`. + - Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT: + - Redirects to the login page by default. + - Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`. + +3. Post-Authentication: After successful authentication with the IdP, OAuth tokens are stored in the configured session store (cookie or Redis), and a cookie is set. + +4. Request Forwarding: The authenticated request is processed based on configuration: + - Forwarded to the configured upstream application with added user info and authentication headers, or + - Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik). + +--- + +Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management. From a8e208430e728784b4b7f44d140d7b66b5b26167 Mon Sep 17 00:00:00 2001 From: Shriya Kamat Tarcar <73349138+shri3016@users.noreply.github.com> Date: Thu, 15 Jan 2026 02:47:15 +0530 Subject: [PATCH 098/125] docs: add Cisco Duo SSO provider documentation (#3306) * docs: add Cisco Duo SSO provider documentation Signed-off-by: Jan Larwig * doc: backport to versioned docs 7.13 and fix alphabetical order of entries Signed-off-by: Jan Larwig * doc: improved clarity for the cisco duo configuration steps Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- .../docs/configuration/providers/cisco_duo.md | 44 +++++++++++++++++++ docs/docs/configuration/providers/index.md | 1 + docs/sidebars.js | 2 + .../configuration/providers/cisco_duo.md | 44 +++++++++++++++++++ .../configuration/providers/index.md | 1 + .../version-7.13.x-sidebars.json | 2 + 6 files changed, 94 insertions(+) create mode 100644 docs/docs/configuration/providers/cisco_duo.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/providers/cisco_duo.md diff --git a/docs/docs/configuration/providers/cisco_duo.md b/docs/docs/configuration/providers/cisco_duo.md new file mode 100644 index 0000000000..a92eccdbb3 --- /dev/null +++ b/docs/docs/configuration/providers/cisco_duo.md @@ -0,0 +1,44 @@ +--- +id: cisco_duo +title: Cisco Duo +--- + +Cisco Duo SSO can be configured with OAuth2 Proxy using the OIDC provider. + +1. Create a new **Generic OIDC Relying Party - Single Sign-On** application in the Duo Admin Portal +2. Configure OAuth2 Proxy with the following options: + +``` +provider = "oidc" +provider_display_name = "Duo SSO" +scope = "openid email profile" +pass_access_token = true +code_challenge_method = "S256" +``` + +3. Configure Provider endpoints. Copy the following values from the corresponding fields in the Duo Admin Portal: + +``` +# Copy from "Client ID" field +client_id = "XXXXXXXX" + +# Copy from "Client Secret" field +client_secret = "XXXXXXXX" + +# Copy from "Issuer" field +oidc_issuer_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx" + +# Copy from "JWKS URL" field +oidc_jwks_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/jwks" + +# Copy from "Token Introspection URL" field +validate_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/token_introspection" + +# Copy from "UserInfo" field +profile_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/userinfo" + +# Copy from "Token URL" field +redeem_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/token" +``` + +4. Complete Configuration by filling in any remaining required fields and save your configuration. diff --git a/docs/docs/configuration/providers/index.md b/docs/docs/configuration/providers/index.md index 3d3938ff65..6f333e5af2 100644 --- a/docs/docs/configuration/providers/index.md +++ b/docs/docs/configuration/providers/index.md @@ -11,6 +11,7 @@ Valid providers are : - [ADFS](adfs.md) - [Bitbucket](bitbucket.md) - [Cidaas](cidaas.md) +- [CiscoDuo](cisco_duo.md) - [DigitalOcean](digitalocean.md) - [Facebook](facebook.md) - [Gitea](gitea.md) diff --git a/docs/sidebars.js b/docs/sidebars.js index 0a1bf0b458..7af8cf4715 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -34,6 +34,8 @@ const sidebars = { "configuration/providers/adfs", "configuration/providers/azure", "configuration/providers/bitbucket", + "configuration/providers/cidaas", + "configuration/providers/cisco_duo", "configuration/providers/digitalocean", "configuration/providers/facebook", "configuration/providers/gitea", diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/cisco_duo.md b/docs/versioned_docs/version-7.13.x/configuration/providers/cisco_duo.md new file mode 100644 index 0000000000..a92eccdbb3 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/cisco_duo.md @@ -0,0 +1,44 @@ +--- +id: cisco_duo +title: Cisco Duo +--- + +Cisco Duo SSO can be configured with OAuth2 Proxy using the OIDC provider. + +1. Create a new **Generic OIDC Relying Party - Single Sign-On** application in the Duo Admin Portal +2. Configure OAuth2 Proxy with the following options: + +``` +provider = "oidc" +provider_display_name = "Duo SSO" +scope = "openid email profile" +pass_access_token = true +code_challenge_method = "S256" +``` + +3. Configure Provider endpoints. Copy the following values from the corresponding fields in the Duo Admin Portal: + +``` +# Copy from "Client ID" field +client_id = "XXXXXXXX" + +# Copy from "Client Secret" field +client_secret = "XXXXXXXX" + +# Copy from "Issuer" field +oidc_issuer_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx" + +# Copy from "JWKS URL" field +oidc_jwks_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/jwks" + +# Copy from "Token Introspection URL" field +validate_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/token_introspection" + +# Copy from "UserInfo" field +profile_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/userinfo" + +# Copy from "Token URL" field +redeem_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/token" +``` + +4. Complete Configuration by filling in any remaining required fields and save your configuration. diff --git a/docs/versioned_docs/version-7.13.x/configuration/providers/index.md b/docs/versioned_docs/version-7.13.x/configuration/providers/index.md index 3d3938ff65..6f333e5af2 100644 --- a/docs/versioned_docs/version-7.13.x/configuration/providers/index.md +++ b/docs/versioned_docs/version-7.13.x/configuration/providers/index.md @@ -11,6 +11,7 @@ Valid providers are : - [ADFS](adfs.md) - [Bitbucket](bitbucket.md) - [Cidaas](cidaas.md) +- [CiscoDuo](cisco_duo.md) - [DigitalOcean](digitalocean.md) - [Facebook](facebook.md) - [Gitea](gitea.md) diff --git a/docs/versioned_sidebars/version-7.13.x-sidebars.json b/docs/versioned_sidebars/version-7.13.x-sidebars.json index 3f5eb854ba..debf449177 100644 --- a/docs/versioned_sidebars/version-7.13.x-sidebars.json +++ b/docs/versioned_sidebars/version-7.13.x-sidebars.json @@ -34,6 +34,8 @@ "configuration/providers/adfs", "configuration/providers/azure", "configuration/providers/bitbucket", + "configuration/providers/cidaas", + "configuration/providers/cisco_duo", "configuration/providers/digitalocean", "configuration/providers/facebook", "configuration/providers/gitea", From 3c37312f3cadb9d365a1ad9e34a57b6220f43a2e Mon Sep 17 00:00:00 2001 From: Drew Foehn Date: Wed, 14 Jan 2026 16:18:52 -0500 Subject: [PATCH 099/125] fix: added conditional so default is not always set and env vars are honored #3303 (#3304) Signed-off-by: Drew Foehn --- CHANGELOG.md | 1 + pkg/apis/options/providers.go | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 51aa5aa54a..642be59408 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - [#3197](https://github.com/oauth2-proxy/oauth2-proxy/pull/3197) fix: NewRemoteKeySet is not using DefaultHTTPClient (@rsrdesarrollo / @tuunit) - [#3292](https://github.com/oauth2-proxy/oauth2-proxy/pull/3292) chore(deps): upgrade gomod and bump to golang v1.25.5 (@tuunit) +- [#3304](https://github.com/oauth2-proxy/oauth2-proxy/pull/3304) fix: added conditional so default is not always set and env vars are honored fixes 3303 (@pixeldrew) # V7.13.0 diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 4dd206e26b..94bdb592bf 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -416,7 +416,9 @@ func (a *ADFSOptions) EnsureDefaults() { // EnsureDefaults sets any default values for GoogleOptions fields. func (g *GoogleOptions) EnsureDefaults() { - g.UseOrganizationID = ptr.To(DefaultGoogleUseOrganizationID) + if g.UseOrganizationID == nil { + g.UseOrganizationID = ptr.To(DefaultGoogleUseOrganizationID) + } if g.UseApplicationDefaultCredentials == nil { g.UseApplicationDefaultCredentials = ptr.To(DefaultUseApplicationDefaultCredentials) From f3dcffed27452d00a6b22bea73a8f822a74bdcc7 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 14 Jan 2026 22:28:27 +0100 Subject: [PATCH 100/125] chore(deps): update traefik docker tag to v2.11.35 (#3295) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- contrib/local-environment/docker-compose-traefik.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 8a10e5c7cb..1399d829aa 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -34,7 +34,7 @@ services: # Reverse proxy gateway: container_name: traefik - image: traefik:v2.11.33 + image: traefik:v2.11.35 volumes: - "./traefik:/etc/traefik" ports: From b4eb611c07568934ef87845647718c317a921f57 Mon Sep 17 00:00:00 2001 From: dawg Date: Wed, 14 Jan 2026 23:12:51 +0100 Subject: [PATCH 101/125] feat: more aggressively truncate logged access_token (#3264) * partly address #2120 and more aggressively truncate access_token - leaking half of the access token to the logs seems problematic from a security point of view - also noisier than necessary logging - fixed by truncating to at most first 5 chars (e.g. `ya29.`) Signed-off-by: Martin Nowak * feat: more aggressively truncate logged access_token; add unit test and changelog Signed-off-by: Jan Larwig --------- Signed-off-by: Martin Nowak Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + providers/internal_util.go | 3 ++- providers/internal_util_test.go | 6 ++++++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 642be59408..70cfaa3e86 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - [#3197](https://github.com/oauth2-proxy/oauth2-proxy/pull/3197) fix: NewRemoteKeySet is not using DefaultHTTPClient (@rsrdesarrollo / @tuunit) - [#3292](https://github.com/oauth2-proxy/oauth2-proxy/pull/3292) chore(deps): upgrade gomod and bump to golang v1.25.5 (@tuunit) - [#3304](https://github.com/oauth2-proxy/oauth2-proxy/pull/3304) fix: added conditional so default is not always set and env vars are honored fixes 3303 (@pixeldrew) +- [#3264](https://github.com/oauth2-proxy/oauth2-proxy/pull/3264) fix: more aggressively truncate logged access_token (@MartinNowak / @tuunit) # V7.13.0 diff --git a/providers/internal_util.go b/providers/internal_util.go index 52cfd0a75f..49e1fd9473 100644 --- a/providers/internal_util.go +++ b/providers/internal_util.go @@ -36,7 +36,8 @@ func stripParam(param, endpoint string) string { } if val := values.Get(param); val != "" { - values.Set(param, val[:(len(val)/2)]+"...") + // Truncate by at least half and allow for a maximum of 5 characters + values.Set(param, val[:min(len(val)/2, 5)]+"...") u.RawQuery = values.Encode() return u.String() } diff --git a/providers/internal_util_test.go b/providers/internal_util_test.go index 545e83cbb6..319526227c 100644 --- a/providers/internal_util_test.go +++ b/providers/internal_util_test.go @@ -149,3 +149,9 @@ func TestStripToken(t *testing.T) { expected := "http://local.test/api/test?access_token=dead...&b=1&c=2" assert.Equal(t, expected, stripToken(test)) } + +func TestStripLongToken(t *testing.T) { + test := "http://local.test/api/test?access_token=deadbeefwithsupersecret&b=1&c=2" + expected := "http://local.test/api/test?access_token=deadb...&b=1&c=2" + assert.Equal(t, expected, stripToken(test)) +} From 49536035a2ae26adb2d663ba2fa1d80257cb3ca8 Mon Sep 17 00:00:00 2001 From: Michi Gysel Date: Wed, 14 Jan 2026 23:18:27 +0100 Subject: [PATCH 102/125] fix: session refresh handling in OIDC provider (#3267) * Fix session refresh handling in OIDC provider - `s.Refreshed` was always `false` as the session object was not updated - `ValidateURL` is, by default, not configured for OIDC providers. Access token validation now only happens when a validation endpoint is available. Signed-off-by: Michael Gysel * Update changelog Signed-off-by: Michael Gysel --------- Signed-off-by: Michael Gysel --- CHANGELOG.md | 1 + providers/oidc.go | 12 +++++------- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 70cfaa3e86..1467837fe2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ - [#3292](https://github.com/oauth2-proxy/oauth2-proxy/pull/3292) chore(deps): upgrade gomod and bump to golang v1.25.5 (@tuunit) - [#3304](https://github.com/oauth2-proxy/oauth2-proxy/pull/3304) fix: added conditional so default is not always set and env vars are honored fixes 3303 (@pixeldrew) - [#3264](https://github.com/oauth2-proxy/oauth2-proxy/pull/3264) fix: more aggressively truncate logged access_token (@MartinNowak / @tuunit) +- [#3267](https://github.com/oauth2-proxy/oauth2-proxy/pull/3267) fix: Session refresh handling in OIDC provider (@gysel) # V7.13.0 diff --git a/providers/oidc.go b/providers/oidc.go index b0be63bc7a..aa022f63c7 100644 --- a/providers/oidc.go +++ b/providers/oidc.go @@ -117,14 +117,12 @@ func (p *OIDCProvider) ValidateSession(ctx context.Context, s *sessions.SessionS // https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse // The ID Token is optional in the Refresh Token Response - // TODO: @tuunit remove dependency on refreshed flag and only rely on presence of access_token - // in accordance with the spec. For now, keep existing behavior. if s.Refreshed { - if !validateToken(ctx, p, s.AccessToken, makeOIDCHeader(s.AccessToken)) { + validateEndpointAvailable := p.Data().ValidateURL != nil && p.Data().ValidateURL.String() != "" + if validateEndpointAvailable && !validateToken(ctx, p, s.AccessToken, makeOIDCHeader(s.AccessToken)) { logger.Errorf("access_token validation failed") return false } - return true } @@ -190,9 +188,8 @@ func (p *OIDCProvider) redeemRefreshToken(ctx context.Context, s *sessions.Sessi return fmt.Errorf("unable create new session state from response: %v", err) } - // It's possible that if the refresh token isn't in the token response the - // session will not contain an id token. - // If it doesn't it's probably better to retain the old one + // It's possible that a refresh does not renew the ID Token. + // If it doesn't, it's probably better to retain the old one. if newSession.IDToken != "" { s.IDToken = newSession.IDToken s.Email = newSession.Email @@ -205,6 +202,7 @@ func (p *OIDCProvider) redeemRefreshToken(ctx context.Context, s *sessions.Sessi s.RefreshToken = newSession.RefreshToken s.CreatedAt = newSession.CreatedAt s.ExpiresOn = newSession.ExpiresOn + s.Refreshed = newSession.Refreshed return nil } From 3c22bc787758fa792114c5614ae2152636021740 Mon Sep 17 00:00:00 2001 From: Pierluigi Lenoci Date: Fri, 16 Jan 2026 09:37:52 +0100 Subject: [PATCH 103/125] docs: split integration.md into separate integration guides (#3299) * docs: add Kubernetes Dashboard integration guide for Azure Entra ID Add comprehensive documentation for integrating oauth2-proxy with Kubernetes Dashboard on Azure Kubernetes Service (AKS) using Azure Entra ID authentication. Changes: - Add new section "Kubernetes Dashboard on AKS" to ms_entra_id.md with complete configuration examples including: - Architecture overview and integration flow - Alpha configuration for oauth2-proxy Helm chart - Dashboard Ingress with proper auth annotations - RBAC configuration (user-based and group-based) - Troubleshooting guide for common issues - Workload Identity (passwordless) setup - Add reference link in integration.md pointing to the new section for users looking for Kubernetes Dashboard integration examples This addresses common issues users face when integrating Dashboard with Entra ID, particularly: - Missing Authorization header in auth-response-headers - Insufficient buffer sizes for large Entra ID tokens - RBAC permission configuration - Group claims setup Closes: oauth2-proxy/manifests#348 Signed-off-by: Pierluigi Lenoci * docs: split integration.md into separate integration guides Split the monolithic integration.md file into a structured integrations directory with individual pages for each tool as requested by maintainer. Changes: - Create new docs/configuration/integrations/ directory structure - Split content into separate files: - nginx.md: Nginx auth_request directive configuration - traefik.md: Traefik v2 ForwardAuth middleware setup - caddy.md: Caddy v2 forward_auth directive configuration - kubernetes-dashboard.md: K8s Dashboard integration (with deprecation notice) - headlamp.md: Headlamp integration guide (recommended alternative) - Transform integration.md into an index/overview page linking to all integrations - Update docs/sidebars.js to use new Integration Guides category structure The content has been preserved as-is from the original file, only reorganized into separate files for better maintainability and navigation. Added deprecation notice for Kubernetes Dashboard per https://github.com/kubernetes/dashboard/commit/0ba796dce6916bb6ca5da5ca0b3ab22cecfd1e18 Addresses maintainer feedback from PR #3299 Signed-off-by: Pierluigi Lenoci * fix: restore Kubernetes Dashboard tip box in nginx integration docs Add back the tip box referencing the Kubernetes Dashboard Azure Entra ID integration example that was present in the original integration.md file. This ensures all content from the original file is preserved in the split documentation structure. Signed-off-by: Pierluigi Lenoci * refactor: move Kubernetes Dashboard details to integration guide Move the detailed Kubernetes Dashboard integration content from the ms_entra_id provider documentation to the integrations section where it logically belongs. Changes: - Move complete K8s Dashboard guide from ms_entra_id.md to integrations/kubernetes-dashboard.md (architecture, configuration, RBAC, troubleshooting, Workload Identity) - Replace detailed section in ms_entra_id.md with brief reference to integration guide - Reorder sidebar: Headlamp before Kubernetes Dashboard - Update integration.md index to show Headlamp first (recommended), Dashboard last (deprecated) This improves documentation organization by keeping integration guides in the integrations/ directory and provider docs focused on provider configuration. Signed-off-by: Pierluigi Lenoci * docs: move integration.md to integrations/index.md Signed-off-by: Jan Larwig --------- Signed-off-by: Pierluigi Lenoci Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- docs/docs/configuration/integration.md | 310 ------------------ docs/docs/configuration/integrations/caddy.md | 63 ++++ .../configuration/integrations/headlamp.md | 105 ++++++ docs/docs/configuration/integrations/index.md | 41 +++ .../integrations/kubernetes-dashboard.md | 289 ++++++++++++++++ docs/docs/configuration/integrations/nginx.md | 107 ++++++ .../configuration/integrations/traefik.md | 184 +++++++++++ .../configuration/providers/ms_entra_id.md | 4 + docs/docs/features/endpoints.md | 2 +- docs/sidebars.js | 16 +- 10 files changed, 809 insertions(+), 312 deletions(-) delete mode 100644 docs/docs/configuration/integration.md create mode 100644 docs/docs/configuration/integrations/caddy.md create mode 100644 docs/docs/configuration/integrations/headlamp.md create mode 100644 docs/docs/configuration/integrations/index.md create mode 100644 docs/docs/configuration/integrations/kubernetes-dashboard.md create mode 100644 docs/docs/configuration/integrations/nginx.md create mode 100644 docs/docs/configuration/integrations/traefik.md diff --git a/docs/docs/configuration/integration.md b/docs/docs/configuration/integration.md deleted file mode 100644 index c57cfa6b36..0000000000 --- a/docs/docs/configuration/integration.md +++ /dev/null @@ -1,310 +0,0 @@ ---- -id: integration -title: Integration ---- - -## Configuring for use with the Nginx `auth_request` directive - -**This option requires `--reverse-proxy` option to be set.** - -The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: - -```nginx -server { - listen 443 ssl; - server_name ...; - include ssl/ssl.conf; - - location /oauth2/ { - proxy_pass http://127.0.0.1:4180; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Auth-Request-Redirect $request_uri; - # or, if you are handling multiple domains: - # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; - } - location = /oauth2/auth { - proxy_pass http://127.0.0.1:4180; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-Uri $request_uri; - # nginx auth_request includes headers but not body - proxy_set_header Content-Length ""; - proxy_pass_request_body off; - } - - location / { - auth_request /oauth2/auth; - error_page 401 =403 /oauth2/sign_in; - - # pass information via X-User and X-Email headers to backend, - # requires running with --set-xauthrequest flag - auth_request_set $user $upstream_http_x_auth_request_user; - auth_request_set $email $upstream_http_x_auth_request_email; - proxy_set_header X-User $user; - proxy_set_header X-Email $email; - - # if you enabled --pass-access-token, this will pass the token to the backend - auth_request_set $token $upstream_http_x_auth_request_access_token; - proxy_set_header X-Access-Token $token; - - # if you enabled --cookie-refresh, this is needed for it to work with auth_request - auth_request_set $auth_cookie $upstream_http_set_cookie; - add_header Set-Cookie $auth_cookie; - - # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb - # limit and so the OAuth2 Proxy splits these into multiple parts. - # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, - # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. - auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; - - # Extract the Cookie attributes from the first Set-Cookie header and append them - # to the second part ($upstream_cookie_* variables only contain the raw cookie content) - if ($auth_cookie ~* "(; .*)") { - set $auth_cookie_name_0 $auth_cookie; - set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; - } - - # Send both Set-Cookie headers now if there was a second part - if ($auth_cookie_name_upstream_1) { - add_header Set-Cookie $auth_cookie_name_0; - add_header Set-Cookie $auth_cookie_name_1; - } - - proxy_pass http://backend/; - # or "root /path/to/site;" or "fastcgi_pass ..." etc - } -} -``` - -When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: - -```yaml -nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" -nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" -``` - -This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. - -It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). - -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=". - -## Configuring for use with the Traefik (v2) `ForwardAuth` middleware - -**This option requires `--reverse-proxy` option to be set.** - -### ForwardAuth with 401 errors middleware - -The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: - -```yaml -http: - routers: - a-service: - rule: "Host(`a-service.example.com`)" - service: a-service-backend - middlewares: - - oauth-errors - - oauth-auth - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - oauth: - rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" - middlewares: - - auth-headers - service: oauth-backend - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - - services: - a-service-backend: - loadBalancer: - servers: - - url: http://172.16.0.2:7555 - oauth-backend: - loadBalancer: - servers: - - url: http://172.16.0.1:4180 - - middlewares: - auth-headers: - headers: - sslRedirect: true - stsSeconds: 315360000 - browserXssFilter: true - contentTypeNosniff: true - forceSTSHeader: true - sslHost: example.com - stsIncludeSubdomains: true - stsPreload: true - frameDeny: true - oauth-auth: - forwardAuth: - address: https://oauth.example.com/oauth2/auth - trustForwardHeader: true - oauth-errors: - errors: - status: - - "401-403" - service: oauth-backend - query: "/oauth2/sign_in?rd={url}" -``` - -### ForwardAuth with static upstreams configuration - -Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint - -**Following options need to be set on `oauth2-proxy`:** -- `--upstream=static://202`: Configures a static response for authenticated sessions -- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly - -```yaml -http: - routers: - a-service-route-1: - rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" - service: a-service-backend - middlewares: - - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - a-service-route-2: - rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" - service: a-service-backend - middlewares: - - oauth-auth-wo-redirect # unauthenticated session will return a 401 - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - services-oauth2-route: - rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" - middlewares: - - auth-headers - service: oauth-backend - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - oauth2-proxy-route: - rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" - middlewares: - - auth-headers - service: oauth-backend - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - - services: - a-service-backend: - loadBalancer: - servers: - - url: http://172.16.0.2:7555 - b-service-backend: - loadBalancer: - servers: - - url: http://172.16.0.3:7555 - oauth-backend: - loadBalancer: - servers: - - url: http://172.16.0.1:4180 - - middlewares: - auth-headers: - headers: - sslRedirect: true - stsSeconds: 315360000 - browserXssFilter: true - contentTypeNosniff: true - forceSTSHeader: true - sslHost: example.com - stsIncludeSubdomains: true - stsPreload: true - frameDeny: true - oauth-auth-redirect: - forwardAuth: - address: https://oauth.example.com/ - trustForwardHeader: true - authResponseHeaders: - - X-Auth-Request-Access-Token - - Authorization - oauth-auth-wo-redirect: - forwardAuth: - address: https://oauth.example.com/oauth2/auth - trustForwardHeader: true - authResponseHeaders: - - X-Auth-Request-Access-Token - - Authorization -``` - -## Configuring for use with the Caddy (v2) `forward_auth` directive - -The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. - -This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. - -**Following options need to be set on `oauth2-proxy`:** -- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly - -```nginx title="Caddyfile" -example.com { - # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. - # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. - handle /oauth2/* { - reverse_proxy oauth2-proxy.internal:4180 { - # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. - # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. - header_up X-Real-IP {remote_host} - header_up X-Forwarded-Uri {uri} - } - } - - # Requests to other paths are first processed by oauth2-proxy for authentication. - handle { - forward_auth oauth2-proxy.internal:4180 { - uri /oauth2/auth - - # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. - # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. - header_up X-Real-IP {remote_host} - - # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. - # Make sure to configure the --set-xauthrequest flag to enable this feature. - #copy_headers X-Auth-Request-User X-Auth-Request-Email - - # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. - @error status 401 - handle_response @error { - redir * /oauth2/sign_in?rd={scheme}://{host}{uri} - } - } - - # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. - reverse_proxy upstream.internal:3000 - } -} -``` - -:::note -If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. -::: diff --git a/docs/docs/configuration/integrations/caddy.md b/docs/docs/configuration/integrations/caddy.md new file mode 100644 index 0000000000..1805e55996 --- /dev/null +++ b/docs/docs/configuration/integrations/caddy.md @@ -0,0 +1,63 @@ +--- +id: caddy +title: Caddy +--- + +Integrate OAuth2 Proxy with Caddy v2 using the `forward_auth` directive. + +**Key features:** +- Simple forward_auth setup +- Automatic header handling +- Custom error handling and redirects + +## Configuring for use with the Caddy (v2) `forward_auth` directive + +The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. + +This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. + +**Following options need to be set on `oauth2-proxy`:** +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```nginx title="Caddyfile" +example.com { + # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. + # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. + handle /oauth2/* { + reverse_proxy oauth2-proxy.internal:4180 { + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. + header_up X-Real-IP {remote_host} + header_up X-Forwarded-Uri {uri} + } + } + + # Requests to other paths are first processed by oauth2-proxy for authentication. + handle { + forward_auth oauth2-proxy.internal:4180 { + uri /oauth2/auth + + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. + header_up X-Real-IP {remote_host} + + # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. + # Make sure to configure the --set-xauthrequest flag to enable this feature. + #copy_headers X-Auth-Request-User X-Auth-Request-Email + + # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. + @error status 401 + handle_response @error { + redir * /oauth2/sign_in?rd={scheme}://{host}{uri} + } + } + + # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. + reverse_proxy upstream.internal:3000 + } +} +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/docs/configuration/integrations/headlamp.md b/docs/docs/configuration/integrations/headlamp.md new file mode 100644 index 0000000000..a6f6ac7316 --- /dev/null +++ b/docs/docs/configuration/integrations/headlamp.md @@ -0,0 +1,105 @@ +--- +id: headlamp +title: Headlamp +--- + +Modern, actively maintained Kubernetes web UI with OAuth2 Proxy integration examples. + +**Key features:** +- Active development and maintenance +- Modern, intuitive interface +- Multi-cluster support +- Plugin system +- Works with all OAuth2 providers + +## Configuring for use with Headlamp + +[Headlamp](https://headlamp.dev/) is a modern, user-friendly Kubernetes web UI that can be integrated with OAuth2 Proxy for authentication. This is a recommended alternative to the deprecated Kubernetes Dashboard. + +### Architecture + +``` +User → Ingress → OAuth2 Proxy → Authentication Provider (e.g., Azure Entra ID) + ↓ + Headlamp +``` + +### Prerequisites + +- Kubernetes cluster (e.g., AKS, EKS, GKE, or self-hosted) +- Headlamp installed in the cluster +- OAuth2 provider configured (Azure Entra ID, Google, GitHub, etc.) +- Ingress controller (Nginx, Traefik, etc.) + +### Configuration Overview + +When integrating Headlamp with OAuth2 Proxy, the OAuth2 Proxy acts as a reverse proxy in front of Headlamp: + +1. User requests access to Headlamp +2. Ingress forwards to OAuth2 Proxy +3. OAuth2 Proxy authenticates the user via the OAuth2 provider +4. After successful authentication, OAuth2 Proxy proxies requests to Headlamp +5. Headlamp receives the authenticated user information via headers + +### OAuth2 Proxy Configuration + +Configure OAuth2 Proxy to proxy to the Headlamp service: + +```yaml +upstreamConfig: + upstreams: + - id: headlamp + path: / + uri: http://headlamp-service.headlamp-namespace.svc.cluster.local:4466 +``` + +Enable the necessary headers: + +```yaml +extraArgs: + reverse-proxy: true + pass-authorization-header: true + set-xauthrequest: true + email-domain: "*" # Or restrict to your organization +``` + +### Example with Azure Entra ID on AKS + +For detailed instructions on deploying Headlamp with OAuth2 Proxy on Azure Kubernetes Service using Azure Entra ID, see the official Headlamp documentation: + +https://headlamp.dev/docs/latest/installation/in-cluster/aks-cluster-oauth/ + +Key steps include: + +1. **Set up AKS with OIDC**: Enable Microsoft Entra ID authentication with Kubernetes RBAC +2. **Create Azure App Registration**: Configure redirect URI and create client secret +3. **Deploy Headlamp**: Install Headlamp via Helm in your cluster +4. **Deploy OAuth2 Proxy**: Configure OAuth2 Proxy with Entra ID provider settings and upstream pointing to Headlamp +5. **Configure Ingress**: Set up Ingress to route traffic through OAuth2 Proxy to Headlamp +6. **Set RBAC Policies**: Apply Kubernetes RBAC bindings based on users or groups + +### Integration with Other Providers + +The same integration pattern works with other OAuth2 providers supported by OAuth2 Proxy: + +- **Google**: Use the Google provider configuration +- **GitHub**: Use the GitHub provider configuration +- **GitLab**: Use the GitLab provider configuration +- **Keycloak**: Use the Keycloak OIDC provider configuration +- **Any OIDC Provider**: Use the generic OIDC provider configuration + +For provider-specific configuration examples, see the [OAuth Provider Configuration](../providers/index.md) documentation. + +### Benefits Over Kubernetes Dashboard + +Headlamp offers several advantages: + +- **Active Development**: Headlamp is actively maintained and developed +- **Modern UI**: Clean, intuitive interface with better UX +- **Plugin System**: Extensible with custom plugins +- **Multi-cluster Support**: Built-in support for managing multiple clusters +- **Desktop App**: Available as both web UI and desktop application + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/docs/configuration/integrations/index.md b/docs/docs/configuration/integrations/index.md new file mode 100644 index 0000000000..b773910b05 --- /dev/null +++ b/docs/docs/configuration/integrations/index.md @@ -0,0 +1,41 @@ +--- +id: index +title: Integrations +--- + +This section provides configuration examples for integrating OAuth2 Proxy with various reverse proxies, ingress controllers, and Kubernetes web UIs. + +## Reverse Proxies and Ingress Controllers + +OAuth2 Proxy can be integrated with popular reverse proxies and ingress controllers to add authentication to your applications: + +- [Nginx](nginx.md) +- [Traefik](traefik.md) +- [caddy](caddy.md) + +## Kubernetes Web UIs + +OAuth2 Proxy can also be used to add authentication to Kubernetes web user interfaces: + +- [Headlamp](headlamp.md) ✨ *Recommended* +- [Kubernetes Dashboard](kubernetes-dashboard.md) ⚠️ *Deprecated* + +:::tip +When integrating with Kubernetes web UIs, make sure to: +1. Configure the Ingress to pass the Authorization header with the bearer token +2. Increase buffer sizes for large OIDC tokens (especially with Azure Entra ID) +3. Set up appropriate Kubernetes RBAC permissions for your users or groups +::: + +## General Requirements + +Most integrations require the following OAuth2 Proxy configuration: + +- `--reverse-proxy=true`: Required to correctly handle `X-Forwarded-*` headers +- **Session storage**: For production deployments with large tokens due to a lot of claims like AD groups, use `--session-store-type=redis` + +For provider-specific configuration, see the [OAuth Provider Configuration](../providers/index.md) documentation. + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/docs/configuration/integrations/kubernetes-dashboard.md b/docs/docs/configuration/integrations/kubernetes-dashboard.md new file mode 100644 index 0000000000..5f21076872 --- /dev/null +++ b/docs/docs/configuration/integrations/kubernetes-dashboard.md @@ -0,0 +1,289 @@ +--- +id: kubernetes-dashboard +title: Kubernetes Dashboard +--- + +:::warning Deprecated Project +Kubernetes Dashboard has been deprecated and discontinued as of January 2025. See the [official announcement](https://github.com/kubernetes/dashboard/commit/0ba796dce6916bb6ca5da5ca0b3ab22cecfd1e18) for more information. + +You may want to consider alternative solutions such as [Headlamp](./headlamp.md). +::: + +## Kubernetes Dashboard on AKS with Azure Entra ID + +Integration guide for the deprecated Kubernetes Dashboard, including comprehensive Azure Entra ID configuration on AKS with detailed troubleshooting and RBAC setup. + +### Architecture + +``` +User → Nginx Ingress → OAuth2 Proxy → Entra ID + ↓ + Kubernetes Dashboard +``` + +The integration flow: +1. Unauthenticated requests to Dashboard are intercepted by Nginx Ingress +2. Nginx redirects to OAuth2 Proxy for authentication +3. OAuth2 Proxy redirects to Entra ID login +4. After successful authentication, OAuth2 Proxy receives ID token from Entra ID +5. OAuth2 Proxy sets Authorization header with the bearer token +6. Nginx forwards the request with token to Kubernetes Dashboard +7. Dashboard validates the token and grants access based on AKS RBAC configuration + +### Prerequisites + +- AKS cluster with Entra ID integration enabled +- Kubernetes Dashboard installed (version 7.x or later) +- NGINX Ingress Controller installed +- Entra ID App Registration configured with: + - Redirect URI: `https://your-oauth2-domain.com/oauth2/callback` + - API Permissions: `openid`, `email`, `profile` + - Groups claim enabled (if using group-based RBAC) +- Users or groups assigned appropriate Kubernetes RBAC permissions + +### Alpha Configuration Example + +Using [Alpha Configuration](../alpha_config.md) with the OAuth2 Proxy Helm chart: + +```yaml +alphaConfig: + enabled: true + configData: + providers: + - id: azure-entra + provider: entra-id + clientID: YOUR_CLIENT_ID + clientSecret: YOUR_CLIENT_SECRET + oidcConfig: + issuerURL: https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0 + audienceClaims: + - aud + emailClaim: email + groupsClaim: groups + userIDClaim: oid + scope: openid email profile + + upstreamConfig: + upstreams: + - id: static + path: / + static: true + staticCode: 200 + + # Response headers passed to Dashboard via Nginx + injectResponseHeaders: + - name: Authorization + values: + - claim: id_token + prefix: "Bearer " + - name: X-Auth-Request-User + values: + - claim: email + - name: X-Auth-Request-Email + values: + - claim: email + - name: X-Auth-Request-Groups + values: + - claim: groups + + server: + BindAddress: "0.0.0.0:4180" + +extraArgs: + cookie-domain: ".your-domain.com" + whitelist-domain: ".your-domain.com" + email-domain: "*" # Or restrict to your organization + skip-provider-button: true + reverse-proxy: true + pass-authorization-header: true + set-xauthrequest: true + +sessionStorage: + type: redis + +redis: + enabled: true + auth: + enabled: true + +ingress: + enabled: true + className: nginx + hosts: + - OAuth2 Proxy.your-domain.com + path: /oauth2 + pathType: Prefix +``` + +### Kubernetes Dashboard Ingress + +**Critical**: The Ingress must include `Authorization` in the `auth-response-headers` annotation: + +```yaml +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: kubernetes-dashboard + namespace: kubernetes-dashboard + annotations: + nginx.ingress.kubernetes.io/backend-protocol: "HTTPS" + nginx.ingress.kubernetes.io/force-ssl-redirect: "true" + + # OAuth2 Proxy authentication + nginx.ingress.kubernetes.io/auth-url: "https://OAuth2 Proxy.your-domain.com/oauth2/auth" + nginx.ingress.kubernetes.io/auth-signin: "https://OAuth2 Proxy.your-domain.com/oauth2/start?rd=$scheme://$best_http_host$request_uri" + + # Include Authorization header with bearer token + nginx.ingress.kubernetes.io/auth-response-headers: "Authorization, X-Auth-Request-User, X-Auth-Request-Email" + + # Buffer sizes for large tokens (Entra tokens can exceed 4KB) + nginx.ingress.kubernetes.io/proxy-buffer-size: "256k" + nginx.ingress.kubernetes.io/proxy-buffers-number: "4" + nginx.ingress.kubernetes.io/proxy-busy-buffers-size: "256k" +spec: + ingressClassName: nginx + tls: + - hosts: + - dashboard.your-domain.com + secretName: dashboard-tls + rules: + - host: dashboard.your-domain.com + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: kubernetes-dashboard-kong-proxy + port: + number: 443 +``` + +### RBAC Configuration + +Assign Kubernetes permissions to Entra ID users or groups. + +**User-based:** +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: dashboard-user-admin +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: cluster-admin +subjects: + - kind: User + name: "user@your-domain.com" # Email from Entra ID token + apiGroup: rbac.authorization.k8s.io +``` + +**Group-based (recommended):** +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: dashboard-admins-group +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: cluster-admin +subjects: + - kind: Group + name: "YOUR_ENTRA_GROUP_OBJECT_ID" # Entra ID Group Object ID + apiGroup: rbac.authorization.k8s.io +``` + +For production, create custom roles with limited permissions instead of using `cluster-admin`. + +### Troubleshooting + +**Dashboard still asks for token after authentication** + +Verify that: +1. `injectResponseHeaders` in alphaConfig includes Authorization header with id_token claim +2. Dashboard Ingress includes `Authorization` in `auth-response-headers` annotation +3. Buffer sizes are sufficient for large tokens (set to 256k as shown above) +4. Check OAuth2 Proxy logs for successful token generation: `kubectl logs -n OAuth2 Proxy ` + +**"Unauthorized" or "Invalid token" errors** + +Common causes: +1. User/group not configured in Kubernetes RBAC + - Check: `kubectl get clusterrolebindings | grep ` +2. Token validation failed + - Verify AKS Entra ID integration is enabled + - Check Dashboard logs: `kubectl logs -n kubernetes-dashboard ` +3. Incorrect OAuth2 Proxy configuration + - Ensure `reverse-proxy: true` is set + - Verify issuer URL matches your tenant + +**Groups not included in token** + +To include groups in the token: +1. In Entra ID App Registration, go to **Token configuration** +2. Add **groups claim** and select security groups +3. Or edit the manifest and add: `"groupMembershipClaims": "SecurityGroup"` +4. For 200+ groups, ensure scope includes `User.Read` for group overage handling +5. Verify groups appear in token: check OAuth2 Proxy logs + +**Session expires too quickly** + +Configure cookie expiration: +```yaml +extraArgs: + cookie-expire: "24h" + cookie-refresh: "1h" +``` + +### Using Workload Identity (Passwordless) + +For production environments, use Workload Identity instead of client secrets: + +```yaml +config: + clientID: "YOUR_CLIENT_ID" + secretKeys: # Exclude client-secret + - client-id + - cookie-secret + cookieSecret: "YOUR_COOKIE_SECRET" + +serviceAccount: + annotations: + azure.workload.identity/client-id: YOUR_CLIENT_ID + azure.workload.identity/tenant-id: YOUR_TENANT_ID + +podLabels: + azure.workload.identity/use: "true" + +alphaConfig: + enabled: true + configData: + providers: + - id: azure-entra + provider: entra-id + clientID: YOUR_CLIENT_ID + oidcConfig: + issuerURL: https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0 + # ... other config + entraIdConfig: + federatedTokenAuth: true +``` + +This requires: +- AKS with OIDC issuer and Workload Identity enabled +- Federated identity credential configured in Entra ID App Registration +- Service account annotated with `azure.workload.identity/client-id` + +For detailed Workload Identity setup instructions, see the [Workload Identity section](../providers/ms_entra_id.md#workload-identity) in the Microsoft Entra ID provider documentation. + +## Integration with Other Providers + +While this guide focuses on Azure Entra ID, Kubernetes Dashboard can be integrated with other OAuth2 providers supported by OAuth2 Proxy. The key requirements remain the same: + +1. **Authorization Header**: Pass the bearer token via the `Authorization` header +2. **RBAC Configuration**: Configure Kubernetes RBAC for your authentication provider's users/groups +3. **Buffer Sizes**: Ensure adequate buffer sizes for tokens (especially important for OIDC providers) + +For provider-specific configuration examples, see the [OAuth Provider Configuration](../providers/index.md) documentation. diff --git a/docs/docs/configuration/integrations/nginx.md b/docs/docs/configuration/integrations/nginx.md new file mode 100644 index 0000000000..a36ed7622d --- /dev/null +++ b/docs/docs/configuration/integrations/nginx.md @@ -0,0 +1,107 @@ +--- +id: nginx +title: Nginx +--- + +Configure OAuth2 Proxy with Nginx using the `auth_request` directive. Includes examples for both standalone Nginx configurations and Kubernetes ingress-nginx with annotations. + +**Key features:** +- Support for `auth_request` directive +- Kubernetes Ingress annotations +- Multi-part cookie handling for large tokens +- Session refresh support + +## Configuring for use with the Nginx `auth_request` directive + +**This option requires `--reverse-proxy` option to be set.** + +The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: + +```nginx +server { + listen 443 ssl; + server_name ...; + include ssl/ssl.conf; + + location /oauth2/ { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Auth-Request-Redirect $request_uri; + # or, if you are handling multiple domains: + # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; + } + location = /oauth2/auth { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; + # nginx auth_request includes headers but not body + proxy_set_header Content-Length ""; + proxy_pass_request_body off; + } + + location / { + auth_request /oauth2/auth; + error_page 401 =403 /oauth2/sign_in; + + # pass information via X-User and X-Email headers to backend, + # requires running with --set-xauthrequest flag + auth_request_set $user $upstream_http_x_auth_request_user; + auth_request_set $email $upstream_http_x_auth_request_email; + proxy_set_header X-User $user; + proxy_set_header X-Email $email; + + # if you enabled --pass-access-token, this will pass the token to the backend + auth_request_set $token $upstream_http_x_auth_request_access_token; + proxy_set_header X-Access-Token $token; + + # if you enabled --cookie-refresh, this is needed for it to work with auth_request + auth_request_set $auth_cookie $upstream_http_set_cookie; + add_header Set-Cookie $auth_cookie; + + # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb + # limit and so the OAuth2 Proxy splits these into multiple parts. + # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, + # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. + auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; + + # Extract the Cookie attributes from the first Set-Cookie header and append them + # to the second part ($upstream_cookie_* variables only contain the raw cookie content) + if ($auth_cookie ~* "(; .*)") { + set $auth_cookie_name_0 $auth_cookie; + set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; + } + + # Send both Set-Cookie headers now if there was a second part + if ($auth_cookie_name_upstream_1) { + add_header Set-Cookie $auth_cookie_name_0; + add_header Set-Cookie $auth_cookie_name_1; + } + + proxy_pass http://backend/; + # or "root /path/to/site;" or "fastcgi_pass ..." etc + } +} +``` + +When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: + +```yaml +nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" +nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" +``` + +This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. + +It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). + +:::tip Kubernetes Dashboard with Azure Entra ID +For a complete example of integrating oauth2-proxy with Kubernetes Dashboard on AKS using Azure Entra ID, including RBAC configuration and troubleshooting, see the [Kubernetes Dashboard on AKS](../providers/ms_entra_id.md#kubernetes-dashboard-on-aks) section in the Microsoft Entra ID provider documentation. +::: + +You have to substitute *name* with the actual cookie name you configured via --cookie-name parameter. If you don't set a custom cookie name the variable should be "$upstream_cookie__oauth2_proxy_1" instead of "$upstream_cookie_name_1" and the new cookie-name should be "_oauth2_proxy_1=" instead of "name_1=". + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/docs/configuration/integrations/traefik.md b/docs/docs/configuration/integrations/traefik.md new file mode 100644 index 0000000000..e4b64b947b --- /dev/null +++ b/docs/docs/configuration/integrations/traefik.md @@ -0,0 +1,184 @@ +--- +id: traefik +title: Traefik +--- + +Set up OAuth2 Proxy with Traefik v2 using the `ForwardAuth` middleware. Includes examples for both error-based redirects and static upstream configurations. + +**Key features:** +- ForwardAuth middleware integration +- Error middleware for 401 redirects +- Static upstream configuration (202 responses) +- Dynamic file configuration examples + + +## Configuring for use with the Traefik (v2) `ForwardAuth` middleware + +**This option requires `--reverse-proxy` option to be set.** + +### ForwardAuth with 401 errors middleware + +The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: + +```yaml +http: + routers: + a-service: + rule: "Host(`a-service.example.com`)" + service: a-service-backend + middlewares: + - oauth-errors + - oauth-auth + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth: + rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + oauth-errors: + errors: + status: + - "401-403" + service: oauth-backend + query: "/oauth2/sign_in?rd={url}" +``` + +### ForwardAuth with static upstreams configuration + +Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint + +**Following options need to be set on `oauth2-proxy`:** +- `--upstream=static://202`: Configures a static response for authenticated sessions +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```yaml +http: + routers: + a-service-route-1: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" + service: a-service-backend + middlewares: + - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + a-service-route-2: + rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" + service: a-service-backend + middlewares: + - oauth-auth-wo-redirect # unauthenticated session will return a 401 + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + services-oauth2-route: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth2-proxy-route: + rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + b-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.3:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth-redirect: + forwardAuth: + address: https://oauth.example.com/ + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization + oauth-auth-wo-redirect: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/docs/configuration/providers/ms_entra_id.md b/docs/docs/configuration/providers/ms_entra_id.md index 95fb99bc60..b9b9e1f8e7 100644 --- a/docs/docs/configuration/providers/ms_entra_id.md +++ b/docs/docs/configuration/providers/ms_entra_id.md @@ -195,3 +195,7 @@ scope="openid profile email User.Read" entra_id_allowed_tenants=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant email_domains="*" ``` + +## Kubernetes Dashboard Integration + +For a complete guide on integrating oauth2-proxy with Kubernetes Dashboard on AKS using Azure Entra ID authentication, including detailed configuration examples, RBAC setup, troubleshooting, and Workload Identity setup, see the [Kubernetes Dashboard integration guide](../integrations/kubernetes-dashboard.md). diff --git a/docs/docs/features/endpoints.md b/docs/docs/features/endpoints.md index db00ba1e0b..5befce187c 100644 --- a/docs/docs/features/endpoints.md +++ b/docs/docs/features/endpoints.md @@ -15,7 +15,7 @@ OAuth2 Proxy responds directly to the following endpoints. All other endpoints w - /oauth2/start - a URL that will redirect to start the OAuth cycle - /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url. - /oauth2/userinfo - the URL is used to return user's email from the session in JSON format. -- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integration#configuring-for-use-with-the-nginx-auth_request-directive) +- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integrations/nginx) - /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages ### Sign out diff --git a/docs/sidebars.js b/docs/sidebars.js index 7af8cf4715..7bb410269d 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -22,7 +22,21 @@ const sidebars = { collapsed: false, items: [ 'configuration/overview', - 'configuration/integration', + { + type: 'category', + label: 'Integration Guides', + link: { + type: 'doc', + id: 'configuration/integrations/index', + }, + items: [ + "configuration/integrations/nginx", + "configuration/integrations/traefik", + "configuration/integrations/caddy", + "configuration/integrations/headlamp", + "configuration/integrations/kubernetes-dashboard" + ], + }, { type: 'category', label: 'OAuth Provider Configuration', From 1d6721f7ba94b5556cb7e07b93a31489a84bb7ec Mon Sep 17 00:00:00 2001 From: Pascal Date: Fri, 16 Jan 2026 20:30:16 +0100 Subject: [PATCH 104/125] fix: WebSocket proxy to respect PassHostHeader setting (#3290) * Fix WebSocket proxy to respect PassHostHeader setting When PassHostHeader is set to false, the regular HTTP proxy correctly sets the Host header to the upstream backend URL. However, the WebSocket proxy was not respecting this setting, causing WebSocket connections to fail when backend services validate the Host header. This commit: - Adds passHostHeader parameter to newWebSocketReverseProxy() - Applies setProxyUpstreamHostHeader() when PassHostHeader=false - Ensures consistent behavior between HTTP and WebSocket proxies Fixes #3288 Signed-off-by: Pascal Schmiel * chore(): add tests, update changelog Signed-off-by: Pascal Schmiel --------- Signed-off-by: Pascal Schmiel --- CHANGELOG.md | 1 + pkg/upstream/http.go | 9 ++++-- pkg/upstream/http_test.go | 49 ++++++++++++++++++++++++++--- pkg/upstream/upstream_suite_test.go | 2 ++ 4 files changed, 55 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1467837fe2..d0a800f11e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ ## Changes since v7.13.0 +- [#3290](https://github.com/oauth2-proxy/oauth2-proxy/pull/3290) fix: WebSocket proxy to respect PassHostHeader setting (@UnsignedLong) - [#3197](https://github.com/oauth2-proxy/oauth2-proxy/pull/3197) fix: NewRemoteKeySet is not using DefaultHTTPClient (@rsrdesarrollo / @tuunit) - [#3292](https://github.com/oauth2-proxy/oauth2-proxy/pull/3292) chore(deps): upgrade gomod and bump to golang v1.25.5 (@tuunit) - [#3304](https://github.com/oauth2-proxy/oauth2-proxy/pull/3304) fix: added conditional so default is not always set and env vars are honored fixes 3303 (@pixeldrew) diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index e8283144c8..b3c3ae7483 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -55,7 +55,7 @@ func newHTTPUpstreamProxy(upstream options.Upstream, u *url.URL, sigData *option // Set up a WebSocket proxy if required var wsProxy http.Handler if ptr.Deref(upstream.ProxyWebSockets, options.DefaultUpstreamProxyWebSockets) { - wsProxy = newWebSocketReverseProxy(u, upstream.InsecureSkipTLSVerify) + wsProxy = newWebSocketReverseProxy(u, upstream.InsecureSkipTLSVerify, upstream.PassHostHeader) } var auth hmacauth.HmacAuth @@ -201,7 +201,7 @@ func setProxyDirector(proxy *httputil.ReverseProxy) { } // newWebSocketReverseProxy creates a new reverse proxy for proxying websocket connections. -func newWebSocketReverseProxy(u *url.URL, skipTLSVerify *bool) http.Handler { +func newWebSocketReverseProxy(u *url.URL, skipTLSVerify *bool, passHostHeader *bool) http.Handler { wsProxy := httputil.NewSingleHostReverseProxy(u) // Inherit default transport options from Go's stdlib @@ -215,5 +215,10 @@ func newWebSocketReverseProxy(u *url.URL, skipTLSVerify *bool) http.Handler { // Apply the customized transport to our proxy before returning it wsProxy.Transport = transport + // Set upstream host header if PassHostHeader is false (same as regular HTTP proxy) + if !ptr.Deref(passHostHeader, options.DefaultUpstreamPassHostHeader) { + setProxyUpstreamHostHeader(wsProxy, u) + } + return wsProxy } diff --git a/pkg/upstream/http_test.go b/pkg/upstream/http_test.go index 79dc0e4aa6..a01d5c093f 100644 --- a/pkg/upstream/http_test.go +++ b/pkg/upstream/http_test.go @@ -519,10 +519,11 @@ var _ = Describe("HTTP Upstream Suite", func() { Expect(websocket.Message.Send(ws, []byte(message))).To(Succeed()) var response testWebSocketResponse Expect(websocket.JSON.Receive(ws, &response)).To(Succeed()) - Expect(response).To(Equal(testWebSocketResponse{ - Message: message, - Origin: origin, - })) + + // When PassHostHeader=true (default), the Host should be the client's original request host + Expect(response.Message).To(Equal(message)) + Expect(response.Origin).To(Equal(origin)) + Expect(response.Host).To(Equal(proxyURL.Host)) }) It("will proxy HTTP requests", func() { @@ -530,5 +531,45 @@ var _ = Describe("HTTP Upstream Suite", func() { Expect(err).ToNot(HaveOccurred()) Expect(response.StatusCode).To(Equal(200)) }) + + It("will proxy websockets respecting PassHostHeader=false", func() { + // Create a new proxy server with PassHostHeader=false + flush := 1 * time.Second + timeout := options.DefaultUpstreamTimeout + upstream := options.Upstream{ + ID: "websocketProxyNoPassHost", + PassHostHeader: ptr.To(false), + ProxyWebSockets: ptr.To(true), + InsecureSkipTLSVerify: ptr.To(false), + FlushInterval: &flush, + Timeout: &timeout, + } + + u, err := url.Parse(serverAddr) + Expect(err).ToNot(HaveOccurred()) + + handler := newHTTPUpstreamProxy(upstream, u, nil, nil) + noPassHostServer := httptest.NewServer(middleware.NewScope(false, "X-Request-Id")(handler)) + defer noPassHostServer.Close() + + origin := "http://example.localhost" + message := "Hello, world!" + + proxyURL, err := url.Parse(fmt.Sprintf("http://%s", noPassHostServer.Listener.Addr().String())) + Expect(err).ToNot(HaveOccurred()) + + wsAddr := fmt.Sprintf("ws://%s/", proxyURL.Host) + ws, err := websocket.Dial(wsAddr, "", origin) + Expect(err).ToNot(HaveOccurred()) + + Expect(websocket.Message.Send(ws, []byte(message))).To(Succeed()) + var response testWebSocketResponse + Expect(websocket.JSON.Receive(ws, &response)).To(Succeed()) + + // When PassHostHeader=false, the Host should be the upstream server address + Expect(response.Host).To(Equal(u.Host)) + Expect(response.Message).To(Equal(message)) + Expect(response.Origin).To(Equal(origin)) + }) }) }) diff --git a/pkg/upstream/upstream_suite_test.go b/pkg/upstream/upstream_suite_test.go index f34c8eaff0..56aa98b149 100644 --- a/pkg/upstream/upstream_suite_test.go +++ b/pkg/upstream/upstream_suite_test.go @@ -96,6 +96,7 @@ type testHTTPRequest struct { type testWebSocketResponse struct { Message string Origin string + Host string } type testHTTPUpstream struct{} @@ -138,6 +139,7 @@ func (t *testHTTPUpstream) websocketHandler() http.Handler { wsResponse := testWebSocketResponse{ Message: string(data), Origin: ws.Request().Header.Get("Origin"), + Host: ws.Request().Host, } err = websocket.JSON.Send(ws, wsResponse) if err != nil { From 86c246980697080bcb032b7e26f3efc7a39f3426 Mon Sep 17 00:00:00 2001 From: Shriya Kamat Tarcar <73349138+shri3016@users.noreply.github.com> Date: Sat, 17 Jan 2026 15:34:16 +0530 Subject: [PATCH 105/125] docs: clarify secret file format requirements (#3311) * docs: clarify secret file format requirements Signed-off-by: shri3016] * doc: backport to v7.13 and v7.12 Signed-off-by: Jan Larwig --------- Signed-off-by: shri3016] Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- docs/docs/configuration/overview.md | 4 ++-- docs/versioned_docs/version-7.12.x/configuration/overview.md | 4 ++-- docs/versioned_docs/version-7.13.x/configuration/overview.md | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index b159df09cc..7bd7bf0710 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -83,7 +83,7 @@ Provider specific options can be found on their respective subpages. | flag: `--approval-prompt`
toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` | | flag: `--backend-logout-url`
toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | | | flag: `--client-id`
toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | | -| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret | | +| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret. The file must contain the secret only, with no trailing newline | | | flag: `--client-secret`
toml: `client_secret` | string | the OAuth Client Secret | | | flag: `--code-challenge-method`
toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | | | flag: `--insecure-oidc-allow-unverified-email`
toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false | @@ -128,7 +128,7 @@ Provider specific options can be found on their respective subpages. | flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | | flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | | flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | -| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | For defining a separate cookie secret file to read the encryption key from | | +| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | File containing the cookie secret (must be raw binary, exactly 16, 24, or 32 bytes). Use dd if=/dev/urandom bs=32 count=1 > cookie.secret to generate | | | flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | [^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) diff --git a/docs/versioned_docs/version-7.12.x/configuration/overview.md b/docs/versioned_docs/version-7.12.x/configuration/overview.md index b159df09cc..7bd7bf0710 100644 --- a/docs/versioned_docs/version-7.12.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.12.x/configuration/overview.md @@ -83,7 +83,7 @@ Provider specific options can be found on their respective subpages. | flag: `--approval-prompt`
toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` | | flag: `--backend-logout-url`
toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | | | flag: `--client-id`
toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | | -| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret | | +| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret. The file must contain the secret only, with no trailing newline | | | flag: `--client-secret`
toml: `client_secret` | string | the OAuth Client Secret | | | flag: `--code-challenge-method`
toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | | | flag: `--insecure-oidc-allow-unverified-email`
toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false | @@ -128,7 +128,7 @@ Provider specific options can be found on their respective subpages. | flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | | flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | | flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | -| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | For defining a separate cookie secret file to read the encryption key from | | +| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | File containing the cookie secret (must be raw binary, exactly 16, 24, or 32 bytes). Use dd if=/dev/urandom bs=32 count=1 > cookie.secret to generate | | | flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | [^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) diff --git a/docs/versioned_docs/version-7.13.x/configuration/overview.md b/docs/versioned_docs/version-7.13.x/configuration/overview.md index b159df09cc..7bd7bf0710 100644 --- a/docs/versioned_docs/version-7.13.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.13.x/configuration/overview.md @@ -83,7 +83,7 @@ Provider specific options can be found on their respective subpages. | flag: `--approval-prompt`
toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` | | flag: `--backend-logout-url`
toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | | | flag: `--client-id`
toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | | -| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret | | +| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret. The file must contain the secret only, with no trailing newline | | | flag: `--client-secret`
toml: `client_secret` | string | the OAuth Client Secret | | | flag: `--code-challenge-method`
toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | | | flag: `--insecure-oidc-allow-unverified-email`
toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false | @@ -128,7 +128,7 @@ Provider specific options can be found on their respective subpages. | flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | | flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | | flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | -| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | For defining a separate cookie secret file to read the encryption key from | | +| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | File containing the cookie secret (must be raw binary, exactly 16, 24, or 32 bytes). Use dd if=/dev/urandom bs=32 count=1 > cookie.secret to generate | | | flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | [^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) From d16a0c4d47cfd4a89f0bbe7d4836915980c155e0 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 15 Jan 2026 09:41:40 +0000 Subject: [PATCH 106/125] add new docs version 7.14.x --- .../version-7.14.x/behaviour.md | 26 + .../version-7.14.x/community/contribution.md | 91 +++ .../version-7.14.x/community/security.md | 49 ++ .../configuration/alpha_config.md | 558 ++++++++++++++++++ .../configuration/alpha_config.md.tmpl | 139 +++++ .../configuration/integration.md | 310 ++++++++++ .../version-7.14.x/configuration/overview.md | 406 +++++++++++++ .../configuration/providers/adfs.md | 19 + .../configuration/providers/bitbucket.md | 25 + .../configuration/providers/cidaas.md | 37 ++ .../configuration/providers/cisco_duo.md | 44 ++ .../configuration/providers/digitalocean.md | 21 + .../configuration/providers/facebook.md | 7 + .../configuration/providers/gitea.md | 24 + .../configuration/providers/github.md | 81 +++ .../configuration/providers/gitlab.md | 49 ++ .../configuration/providers/google.md | 84 +++ .../configuration/providers/index.md | 46 ++ .../configuration/providers/keycloak.md | 36 ++ .../configuration/providers/keycloak_oidc.md | 151 +++++ .../configuration/providers/linkedin.md | 13 + .../configuration/providers/login_gov.md | 79 +++ .../configuration/providers/ms_azure_ad.md | 59 ++ .../configuration/providers/ms_entra_id.md | 197 +++++++ .../configuration/providers/nextcloud.md | 28 + .../configuration/providers/openid_connect.md | 146 +++++ .../configuration/providers/sourcehut.md | 25 + .../version-7.14.x/configuration/sessions.md | 99 ++++ .../configuration/systemd_socket.md | 43 ++ .../version-7.14.x/configuration/tls.md | 85 +++ .../version-7.14.x/features/endpoints.md | 59 ++ .../version-7.14.x/installation.md | 32 + docs/versioned_docs/version-7.14.x/welcome.md | 23 + .../version-7.14.x-sidebars.json | 86 +++ docs/versions.json | 1 + 35 files changed, 3178 insertions(+) create mode 100644 docs/versioned_docs/version-7.14.x/behaviour.md create mode 100644 docs/versioned_docs/version-7.14.x/community/contribution.md create mode 100644 docs/versioned_docs/version-7.14.x/community/security.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/alpha_config.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/alpha_config.md.tmpl create mode 100644 docs/versioned_docs/version-7.14.x/configuration/integration.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/overview.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/adfs.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/bitbucket.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/cidaas.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/cisco_duo.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/digitalocean.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/facebook.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/gitea.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/github.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/gitlab.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/google.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/index.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/keycloak.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/keycloak_oidc.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/linkedin.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/login_gov.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/ms_azure_ad.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/ms_entra_id.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/nextcloud.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/openid_connect.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/providers/sourcehut.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/sessions.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/systemd_socket.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/tls.md create mode 100644 docs/versioned_docs/version-7.14.x/features/endpoints.md create mode 100644 docs/versioned_docs/version-7.14.x/installation.md create mode 100644 docs/versioned_docs/version-7.14.x/welcome.md create mode 100644 docs/versioned_sidebars/version-7.14.x-sidebars.json diff --git a/docs/versioned_docs/version-7.14.x/behaviour.md b/docs/versioned_docs/version-7.14.x/behaviour.md new file mode 100644 index 0000000000..d0be452ec5 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/behaviour.md @@ -0,0 +1,26 @@ +--- +id: behaviour +title: Behaviour +--- + +1. Authentication Requirement: All requests passing through the proxy to upstream applications require authentication, excluding default proxy endpoints. + - Exception: If the request matches a skipped route (configured via `--skip-auth-route`): + - Authentication is not enforced, but the proxy will opportunistically attempt to validate a session cookie (`--cookie-name`) or JWT (`--skip-jwt-bearer-tokens`) if present in the request. + - Configured user info and authentication headers (e.g., `--pass-access-token`) are injected to upstream routes when validation succeeds. + +2. Unauthenticated Requests: When authentication is missing but required, the user is redirected to the configured Identity Provider (IdP) login page by default. + - Ajax Requests: If the request has `Accept: application/json` header: + - Returns `401 Unauthorized`. + - Invalid JWT Tokens: If `--skip-jwt-bearer-tokens` is set and the request includes an invalid JWT: + - Redirects to the login page by default. + - Returns `403 Forbidden` if `--bearer-token-login-fallback` is set to `false`. + +3. Post-Authentication: After successful authentication with the IdP, OAuth tokens are stored in the configured session store (cookie or Redis), and a cookie is set. + +4. Request Forwarding: The authenticated request is processed based on configuration: + - Forwarded to the configured upstream application with added user info and authentication headers, or + - Returns a valid status code for downstream processing by another proxy or load balancer (e.g., Nginx or Traefik). + +--- + +Note: The proxy also provides a number of useful [endpoints](features/endpoints.md) for monitoring and management. diff --git a/docs/versioned_docs/version-7.14.x/community/contribution.md b/docs/versioned_docs/version-7.14.x/community/contribution.md new file mode 100644 index 0000000000..a8e4734988 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/community/contribution.md @@ -0,0 +1,91 @@ +--- +id: contribution +title: Contribution Guide +--- + +We track bugs and issues using Github. + +If you find a bug, please open an Issue. When opening an Issue or Pull Request please follow the preconfigured template and take special note of the checkboxes. + +If you want to fix a bug, add a new feature or extend existing functionality, please create a fork, create a feature branch and open a PR back to this repo. +Please mention open bug issue number(s) within your PR if applicable. + +We suggest using [Visual Studio Code](https://code.visualstudio.com/docs/languages/go) with the official [Go for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=golang.go) extension. + + +# Go version + +See the `go.mod` file in the root of this repository for the version of Go used by this project. +You can follow [the installation guide for Go](https://go.dev/doc/install), +and you can find this specific Go version on [the Go downloads page](https://go.dev/dl/). + +# Preparing your fork +Clone your fork, create a feature branch and update the depedencies to get started. +```bash +git clone git@github.com:/oauth2-proxy +cd oauth2-proxy +git branch feature/ +git push --set-upstream origin feature/ +go mod download +``` + + +# Testing / Debugging +For starting oauth2-proxy locally open the debugging tab and create the `launch.json` and select `Go: Launch Package`. + +![Debugging Tab](/img/debug-tab.png) +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch OAuth2-Proxy with Dex", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and dex as an idetity provider + "contrib/local-environment/oauth2-proxy.cfg" + ] + }, + { + "name": "Launch OAuth2-Proxy with Keycloak", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}", + "args": [ + "--config", + // The following configuration contains settings for a locally deployed + // upstream and keycloak as an idetity provider + "contrib/local-environment/oauth2-proxy-keycloak.cfg" + ] + } + ] +} +``` + +Before you can start your local version of oauth2-proxy, you will have to use the provided docker compose files to start a local upstream service and identity provider. We suggest using [httpbin](https://hub.docker.com/r/kennethreitz/httpbin) as your upstream for testing as it allows for request and response introspection of all things HTTP. + +Inside the `contrib/local-environment` directory you can use the `Makefile` for +starting different example setups: + +- Dex as your IdP: `make up` or `make down` +- Dex as your IdP using the alpha-config: `make alpha-config-up` +- Keycloak as your IdP: `make keycloak-up` +- Dex as your IdP & nginx reverse proxy: `make nginx-up` +- and many more... + +Check out the `Makefile` to see what is available. + +The username and password for all setups is usually `admin@example.com` and `password`. + +The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me + +- OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 +- Upstream: http://httpbin.localtest.me:8080 +- Dex: http://dex.localtest.me:5556 + diff --git a/docs/versioned_docs/version-7.14.x/community/security.md b/docs/versioned_docs/version-7.14.x/community/security.md new file mode 100644 index 0000000000..c24b57d9e5 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/community/security.md @@ -0,0 +1,49 @@ +--- +id: security +title: Security +--- + +:::note +OAuth2 Proxy is a community project. +Maintainers do not work on this project full time, and as such, +while we endeavour to respond to disclosures as quickly as possible, +this may take longer than in projects with corporate sponsorship. +::: + +## Security Disclosures + +:::important +If you believe you have found a vulnerability within OAuth2 Proxy or any of its +dependencies, please do NOT open an issue or PR on GitHub, please do NOT post +any details publicly. +::: + +Security disclosures MUST be done in private. +If you have found an issue that you would like to bring to the attention of the +maintenance team for OAuth2 Proxy, please compose an email and send it to the +list of maintainers in our [MAINTAINERS](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS) file. + +Please include as much detail as possible. +Ideally, your disclosure should include: +- A reproducible case that can be used to demonstrate the exploit +- How you discovered this vulnerability +- A potential fix for the issue (if you have thought of one) +- Versions affected (if not present in master) +- Your GitHub ID + +### How will we respond to disclosures? + +We use [GitHub Security Advisories](https://docs.github.com/en/github/managing-security-vulnerabilities/about-github-security-advisories) +to privately discuss fixes for disclosed vulnerabilities. +If you include a GitHub ID with your disclosure we will add you as a collaborator +for the advisory so that you can join the discussion and validate any fixes +we may propose. + +For minor issues and previously disclosed vulnerabilities (typically for +dependencies), we may use regular PRs for fixes and forego the security advisory. + +Once a fix has been agreed upon, we will merge the fix and create a new release. +If we have multiple security issues in flight simultaneously, we may delay +merging fixes until all patches are ready. +We may also backport the fix to previous releases, +but this will be at the discretion of the maintainers. diff --git a/docs/versioned_docs/version-7.14.x/configuration/alpha_config.md b/docs/versioned_docs/version-7.14.x/configuration/alpha_config.md new file mode 100644 index 0000000000..495bc20691 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/alpha_config.md @@ -0,0 +1,558 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference + + + +### ADFSOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `skipScope` | _bool_ | Skip adding the scope parameter in login request
Default value is 'false' | + +### AlphaOptions + +AlphaOptions contains alpha structured configuration options. +Usage of these options allows users to access alpha features that are not +available as part of the primary configuration structure for OAuth2 Proxy. + +:::warning +The options within this structure are considered alpha. +They may change between releases without notice. +::: + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `upstreamConfig` | _[UpstreamConfig](#upstreamconfig)_ | UpstreamConfig is used to configure upstream servers.
Once a user is authenticated, requests to the server will be proxied to
these upstream servers based on the path mappings defined in this list. | +| `injectRequestHeaders` | _[[]Header](#header)_ | InjectRequestHeaders is used to configure headers that should be added
to requests to upstream servers.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `injectResponseHeaders` | _[[]Header](#header)_ | InjectResponseHeaders is used to configure headers that should be added
to responses from the proxy.
This is typically used when using the proxy as an external authentication
provider in conjunction with another proxy such as NGINX and its
auth_request module.
Headers may source values from either the authenticated user's session
or from a static secret value. | +| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.
You may choose to run both HTTP and HTTPS servers simultaneously.
This can be done by setting the BindAddress and the SecureBindAddress simultaneously.
To use the secure server you must configure a TLS certificate and key. | +| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not
yet working.** [This feature is tracked in
#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) | + +### AzureOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `tenant` | _string_ | Tenant directs to a tenant-specific or common (tenant-independent) endpoint
Default value is 'common' | +| `graphGroupField` | _string_ | GraphGroupField configures the group field to be used when building the groups list from Microsoft Graph
Default value is 'id' | + +### BitbucketOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repository` | _string_ | Repository sets restrict logins to user with access to this repository | + +### ClaimSource + +(**Appears on:** [HeaderValue](#headervalue)) + +ClaimSource allows loading a header value from a claim within the session + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### GitHubOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `org` | _string_ | Org sets restrict logins to members of this organisation | +| `team` | _string_ | Team sets restrict logins to members of this team | +| `repo` | _string_ | Repo sets restrict logins to collaborators of this repository | +| `token` | _string_ | Token is the token to use when verifying repository collaborators
it must have push access to the repository | +| `users` | _[]string_ | Users allows users with these usernames to login
even if they do not belong to the specified org and team or collaborators | + +### GitLabOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Group sets restrict logins to members of this group | +| `projects` | _[]string_ | Projects restricts logins to members of these projects | + +### GoogleOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `group` | _[]string_ | Groups sets restrict logins to members of this Google group | +| `adminEmail` | _string_ | AdminEmail is the Google admin to impersonate for api calls | +| `serviceAccountJson` | _string_ | ServiceAccountJSON is the path to the service account json credentials | +| `useApplicationDefaultCredentials` | _bool_ | UseApplicationDefaultCredentials is a boolean whether to use Application Default Credentials instead of a ServiceAccountJSON | +| `targetPrincipal` | _string_ | TargetPrincipal is the Google Service Account used for Application Default Credentials | +| `useOrganizationID` | _bool_ | UseOrganizationId indicates whether to use the organization ID as the UserName claim | +| `adminAPIUserScope` | _string_ | admin scope needed for fetching user organization information from admin api, can be one of cloud, user or defaults to readonly | + +### Header + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Header represents an individual header that will be added to a request or +response header. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name is the header name to be used for this set of values.
Names should be unique within a list of Headers. | +| `preserveRequestValue` | _bool_ | PreserveRequestValue determines whether any values for this header
should be preserved for the request to the upstream server.
This option only applies to injected request headers.
Defaults to false (headers that match this header will be stripped). | +| `InsecureSkipHeaderNormalization` | _bool_ | InsecureSkipHeaderNormalization disables normalizing the header name
According to RFC 7230 Section 3.2 there aren't any rules about
capitalization of header names, but the standard practice is to use
Title-Case (e.g. X-Forwarded-For). By default, header names will be
normalized to Title-Case and any incoming headers that match will be
treated as the same header. Additionally underscores (_) in header names
will be converted to dashes (-) when normalizing.
Defaults to false (header names will be normalized). | +| `values` | _[[]HeaderValue](#headervalue)_ | Values contains the desired values for this header | + +### HeaderValue + +(**Appears on:** [Header](#header)) + +HeaderValue represents a single header value and the sources that can +make up the header value + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | +| `claim` | _string_ | Claim is the name of the claim in the session that the value should be
loaded from. Available claims: `access_token` `id_token` `created_at`
`expires_on` `refresh_token` `email` `user` `groups` `preferred_username`. | +| `prefix` | _string_ | Prefix is an optional prefix that will be prepended to the value of the
claim if it is non-empty. | +| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.
Note the value of claim will become the basic auth username and the
basicAuthPassword will be used as the password value. | + +### KeycloakOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `groups` | _[]string_ | Group enables to restrict login to members of indicated group | +| `roles` | _[]string_ | Role enables to restrict login to users with role (only available when using the keycloak-oidc provider) | + +### LoginGovOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `jwtKey` | _string_ | JWTKey is a private key in PEM format used to sign JWT, | +| `jwtKeyFile` | _string_ | JWTKeyFile is a path to the private key file in PEM format used to sign the JWT | +| `pubjwkURL` | _string_ | PubJWKURL is the JWK pubkey access endpoint | + +### LoginURLParameter + +(**Appears on:** [Provider](#provider)) + +LoginURLParameter is the configuration for a single query parameter that +can be passed through from the `/oauth2/start` endpoint to the IdP login +URL. The "default" option specifies the default value or values (if any) +that will be passed to the IdP for this parameter, and "allow" is a list +of options for ways in which this parameter can be set or overridden via +the query string to `/oauth2/start`. +If _only_ a default is specified and no "allow" then the parameter is +effectively fixed - the default value will always be used and anything +passed to the start URL will be ignored. If _only_ "allow" is specified +but no default then the parameter will only be passed on to the IdP if +the caller provides it, and no value will be sent otherwise. + +Examples: + +# A parameter whose value is fixed + +``` +name: organization +default: +- myorg +``` + +A parameter that is not passed by default, but may be set to one of a +fixed set of values + +``` +name: prompt +allow: +- value: login +- value: consent +- value: select_account +``` + +A parameter that is passed by default but may be overridden by one of +a fixed set of values + +``` +name: prompt +default: ["login"] +allow: +- value: consent +- value: select_account +``` + +A parameter that may be overridden, but only by values that match a +regular expression. For example to restrict `login_hint` to email +addresses in your organization's domain: + +``` +name: login_hint +allow: +- pattern: '^[^@]*@example\.com$' +# this allows at most one "@" sign, and requires "example.com" domain. +``` + +Note that the YAML rules around exactly which characters are allowed +and/or require escaping in different types of string literals are +convoluted. For regular expressions the single quoted form is simplest +as backslash is not considered to be an escape character. Alternatively +use the "chomped block" format `|-`: + +``` + - pattern: |- + ^[^@]*@example\.com$ + +``` + +The hyphen is important, a `|` block would have a trailing newline +character. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `name` | _string_ | Name specifies the name of the query parameter. | +| `default` | _[]string_ | _(Optional)_ Default specifies a default value or values that will be
passed to the IdP if not overridden. | +| `allow` | _[[]URLParameterRule](#urlparameterrule)_ | _(Optional)_ Allow specifies rules about how the default (if any) may be
overridden via the query string to `/oauth2/start`. Only
values that match one or more of the allow rules will be
forwarded to the IdP. | + +### MicrosoftEntraIDOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `allowedTenants` | _[]string_ | AllowedTenants is a list of allowed tenants. In case of multi-tenant apps, incoming tokens are
issued by different issuers and OIDC issuer verification needs to be disabled.
When not specified, all tenants are allowed. Redundant for single-tenant apps
(regular ID token validation matches the issuer). | +| `federatedTokenAuth` | _bool_ | FederatedTokenAuth enable oAuth2 client authentication with federated token projected
by Entra Workload Identity plugin, instead of client secret. | + +### OIDCOptions + +(**Appears on:** [Provider](#provider)) + + + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `issuerURL` | _string_ | IssuerURL is the OpenID Connect issuer URL
eg: https://accounts.google.com | +| `insecureAllowUnverifiedEmail` | _bool_ | InsecureAllowUnverifiedEmail prevents failures if an email address in an id_token is not verified
default set to 'false' | +| `insecureSkipIssuerVerification` | _bool_ | InsecureSkipIssuerVerification skips verification of ID token issuers. When false, ID Token Issuers must match the OIDC discovery URL
default set to 'false' | +| `insecureSkipNonce` | _bool_ | InsecureSkipNonce skips verifying the ID Token's nonce claim that must match
the random nonce sent in the initial OAuth flow. Otherwise, the nonce is checked
after the initial OAuth redeem & subsequent token refreshes.
default set to 'true'
Warning: In a future release, this will change to 'false' by default for enhanced security. | +| `skipDiscovery` | _bool_ | SkipDiscovery allows to skip OIDC discovery and use manually supplied Endpoints
default set to 'false' | +| `jwksURL` | _string_ | JwksURL is the OpenID Connect JWKS URL
eg: https://www.googleapis.com/oauth2/v3/certs | +| `publicKeyFiles` | _[]string_ | PublicKeyFiles is a list of paths pointing to public key files in PEM format to use
for verifying JWT tokens | +| `emailClaim` | _string_ | EmailClaim indicates which claim contains the user email,
default set to 'email' | +| `groupsClaim` | _string_ | GroupsClaim indicates which claim contains the user groups
default set to 'groups' | +| `userIDClaim` | _string_ | UserIDClaim indicates which claim contains the user ID
default set to 'email' | +| `audienceClaims` | _[]string_ | AudienceClaim allows to define any claim that is verified against the client id
By default `aud` claim is used for verification. | +| `extraAudiences` | _[]string_ | ExtraAudiences is a list of additional audiences that are allowed
to pass verification in addition to the client id. | + +### Provider + +(**Appears on:** [Providers](#providers)) + +Provider holds all configuration for a single provider + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `clientID` | _string_ | ClientID is the OAuth Client ID that is defined in the provider
This value is required for all providers. | +| `clientSecret` | _string_ | ClientSecret is the OAuth Client Secret that is defined in the provider
This value is required for all providers. | +| `clientSecretFile` | _string_ | ClientSecretFile is the name of the file
containing the OAuth Client Secret, it will be used if ClientSecret is not set. | +| `keycloakConfig` | _[KeycloakOptions](#keycloakoptions)_ | KeycloakConfig holds all configurations for Keycloak provider. | +| `azureConfig` | _[AzureOptions](#azureoptions)_ | AzureConfig holds all configurations for Azure provider. | +| `microsoftEntraIDConfig` | _[MicrosoftEntraIDOptions](#microsoftentraidoptions)_ | MicrosoftEntraIDConfig holds all configurations for Entra ID provider. | +| `ADFSConfig` | _[ADFSOptions](#adfsoptions)_ | ADFSConfig holds all configurations for ADFS provider. | +| `bitbucketConfig` | _[BitbucketOptions](#bitbucketoptions)_ | BitbucketConfig holds all configurations for Bitbucket provider. | +| `githubConfig` | _[GitHubOptions](#githuboptions)_ | GitHubConfig holds all configurations for GitHubC provider. | +| `gitlabConfig` | _[GitLabOptions](#gitlaboptions)_ | GitLabConfig holds all configurations for GitLab provider. | +| `googleConfig` | _[GoogleOptions](#googleoptions)_ | GoogleConfig holds all configurations for Google provider. | +| `oidcConfig` | _[OIDCOptions](#oidcoptions)_ | OIDCConfig holds all configurations for OIDC provider
or providers utilize OIDC configurations. | +| `loginGovConfig` | _[LoginGovOptions](#logingovoptions)_ | LoginGovConfig holds all configurations for LoginGov provider. | +| `id` | _string_ | ID should be a unique identifier for the provider.
This value is required for all providers. | +| `provider` | _[ProviderType](#providertype)_ | Type is the OAuth provider
must be set from the supported providers group,
otherwise 'Google' is set as default | +| `name` | _string_ | Name is the providers display name
if set, it will be shown to the users in the login page. | +| `caFiles` | _[]string_ | CAFiles is a list of paths to CA certificates that should be used when connecting to the provider.
If not specified, the default Go trust sources are used instead | +| `useSystemTrustStore` | _bool_ | UseSystemTrustStore determines if your custom CA files and the system trust store are used
If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | +| `loginURL` | _string_ | LoginURL is the authentication endpoint | +| `loginURLParameters` | _[[]LoginURLParameter](#loginurlparameter)_ | LoginURLParameters defines the parameters that can be passed from the start URL to the IdP login URL | +| `authRequestResponseMode` | _string_ | AuthRequestResponseMode defines the response mode to request during authorization request | +| `redeemURL` | _string_ | RedeemURL is the token redemption endpoint | +| `profileURL` | _string_ | ProfileURL is the profile access endpoint | +| `skipClaimsFromProfileURL` | _bool_ | SkipClaimsFromProfileURL allows to skip request to Profile URL for resolving claims not present in id_token
default set to 'false' | +| `resource` | _string_ | ProtectedResource is the resource that is protected (Azure AD and ADFS only) | +| `validateURL` | _string_ | ValidateURL is the access token validation endpoint | +| `scope` | _string_ | Scope is the OAuth scope specification | +| `allowedGroups` | _[]string_ | AllowedGroups is a list of restrict logins to members of this group | +| `code_challenge_method` | _string_ | The code challenge method | +| `backendLogoutURL` | _string_ | URL to call to perform backend logout, `{id_token}` would be replaced by the actual `id_token` if available in the session | + +### ProviderType +#### (`string` alias) + +(**Appears on:** [Provider](#provider)) + +ProviderType is used to enumerate the different provider type options +Valid options are: adfs, azure, bitbucket, digitalocean facebook, github, +gitlab, google, keycloak, keycloak-oidc, linkedin, login.gov, nextcloud +and oidc. + +### Providers + +#### ([[]Provider](#provider) alias) + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +The provider can be selected using the `provider` configuration value, or +set in the [`providers` array using +AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). +However, [**the feature to implement multiple providers is not +complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +### SecretSource + +(**Appears on:** [ClaimSource](#claimsource), [HeaderValue](#headervalue), [TLS](#tls)) + +SecretSource references an individual secret value. +Only one source within the struct should be defined at any time. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _[]byte_ | Value expects a base64 encoded string value. | +| `fromEnv` | _string_ | FromEnv expects the name of an environment variable. | +| `fromFile` | _string_ | FromFile expects a path to a file containing the secret value. | + +### Server + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +Server represents the configuration for an HTTP(S) server + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `bindAddress` | _string_ | BindAddress is the address on which to serve traffic.
Leave blank or set to "-" to disable. | +| `secureBindAddress` | _string_ | SecureBindAddress is the address on which to serve secure traffic.
Leave blank or set to "-" to disable. | +| `tls` | _[TLS](#tls)_ | TLS contains the information for loading the certificate and key for the
secure traffic and further configuration for the TLS server. | + +### TLS + +(**Appears on:** [Server](#server)) + +TLS contains the information for loading a TLS certificate and key +as well as an optional minimal TLS version that is acceptable. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `key` | _[SecretSource](#secretsource)_ | Key is the TLS key data to use.
Typically this will come from a file. | +| `cert` | _[SecretSource](#secretsource)_ | Cert is the TLS certificate data to use.
Typically this will come from a file. | +| `minVersion` | _string_ | MinVersion is the minimal TLS version that is acceptable.
E.g. Set to "TLS1.3" to select TLS version 1.3 | +| `cipherSuites` | _[]string_ | CipherSuites is a list of TLS cipher suites that are allowed.
E.g.:
- TLS_RSA_WITH_RC4_128_SHA
- TLS_RSA_WITH_AES_256_GCM_SHA384
If not specified, the default Go safe cipher list is used.
List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | + +### URLParameterRule + +(**Appears on:** [LoginURLParameter](#loginurlparameter)) + +URLParameterRule represents a rule by which query parameters +passed to the `/oauth2/start` endpoint are checked to determine whether +they are valid overrides for the given parameter passed to the IdP's +login URL. Either Value or Pattern should be supplied, not both. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `value` | _string_ | A Value rule matches just this specific value | +| `pattern` | _string_ | A Pattern rule gives a regular expression that must be matched by
some substring of the value. The expression is _not_ automatically
anchored to the start and end of the value, if you _want_ to restrict
the whole parameter value you must anchor it yourself with `^` and `$`. | + +### Upstream + +(**Appears on:** [UpstreamConfig](#upstreamconfig)) + +Upstream represents the configuration for an upstream server. +Requests will be proxied to this upstream if the path matches the request path. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `id` | _string_ | ID should be a unique identifier for the upstream.
This value is required for all upstreams. | +| `path` | _string_ | Path is used to map requests to the upstream server.
The closest match will take precedence and all Paths must be unique.
Path can also take a pattern when used with RewriteTarget.
Path segments can be captured and matched using regular experessions.
Eg:
- `^/foo$`: Match only the explicit path `/foo`
- `^/bar/$`: Match any path prefixed with `/bar/`
- `^/baz/(.*)$`: Match any path prefixed with `/baz` and capture the remaining path for use with RewriteTarget | +| `rewriteTarget` | _string_ | RewriteTarget allows users to rewrite the request path before it is sent to
the upstream server (for an HTTP/HTTPS upstream) or mapped to the filesystem
(for a `file:` upstream).
Use the Path to capture segments for reuse within the rewrite target.
Eg: With a Path of `^/baz/(.*)`, a RewriteTarget of `/foo/$1` would rewrite
the request `/baz/abc/123` to `/foo/abc/123` before proxying to the
upstream server. Or if the upstream were `file:///app`, a request for
`/baz/info.html` would return the contents of the file `/app/foo/info.html`. | +| `uri` | _string_ | The URI of the upstream server. This may be an HTTP(S) server of a File
based URL. It may include a path, in which case all requests will be served
under that path.
Eg:
- http://localhost:8080
- https://service.localhost
- https://service.localhost/path
- file://host/path
If the URI's path is "/base" and the incoming request was for "/dir",
the upstream request will be for "/base/dir". | +| `insecureSkipTLSVerify` | _bool_ | InsecureSkipTLSVerify will skip TLS verification of upstream HTTPS hosts.
This option is insecure and will allow potential Man-In-The-Middle attacks
between OAuth2 Proxy and the upstream server.
Defaults to false. | +| `static` | _bool_ | Static will make all requests to this upstream have a static response.
The response will have a body of "Authenticated" and a response code
matching StaticCode.
If StaticCode is not set, the response will return a 200 response. | +| `staticCode` | _int_ | StaticCode determines the response code for the Static response.
This option can only be used with Static enabled. | +| `flushInterval` | _duration_ | FlushInterval is the period between flushing the response buffer when
streaming response from the upstream.
Defaults to 1 second. | +| `passHostHeader` | _bool_ | PassHostHeader determines whether the request host header should be proxied
to the upstream server.
Defaults to true. | +| `proxyWebSockets` | _bool_ | ProxyWebSockets enables proxying of websockets to upstream servers
Defaults to true. | +| `timeout` | _duration_ | Timeout is the maximum duration the server will wait for a response from the upstream server.
Defaults to 30 seconds. | +| `disableKeepAlives` | _bool_ | DisableKeepAlives disables HTTP keep-alive connections to the upstream server.
Defaults to false. | + +### UpstreamConfig + +(**Appears on:** [AlphaOptions](#alphaoptions)) + +UpstreamConfig is a collection of definitions for upstream servers. + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `proxyRawPath` | _bool_ | ProxyRawPath will pass the raw url path to upstream allowing for urls
like: "/%2F/" which would otherwise be redirected to "/" | +| `upstreams` | _[[]Upstream](#upstream)_ | Upstreams represents the configuration for the upstream servers.
Requests will be proxied to this upstream if the path matches the request path. | diff --git a/docs/versioned_docs/version-7.14.x/configuration/alpha_config.md.tmpl b/docs/versioned_docs/version-7.14.x/configuration/alpha_config.md.tmpl new file mode 100644 index 0000000000..8258201f2a --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/alpha_config.md.tmpl @@ -0,0 +1,139 @@ +--- +id: alpha-config +title: Alpha Configuration +--- + +:::warning +This page contains documentation for alpha features. +We reserve the right to make breaking changes to the features detailed within this page with no notice. + +Options described in this page may be changed, removed, renamed or moved without prior warning. +Please beware of this before you use alpha configuration options. +::: + +This page details a set of **alpha** configuration options in a new format. +Going forward we are intending to add structured configuration in YAML format to +replace the existing TOML based configuration file and flags. + +Below is a reference for the structure of the configuration, with +[AlphaOptions](#alphaoptions) as the root of the configuration. + +When using alpha configuration, your config file will look something like below: + +```yaml +upstreams: + - id: ... + ...: ... +injectRequestHeaders: + - name: ... + ...: ... +injectResponseHeaders: + - name: ... + ...: ... +``` + +Please browse the [reference](#configuration-reference) below for the structure +of the new configuration format. + +## Using Alpha Configuration + +To use the new **alpha** configuration, generate a YAML file based on the format +described in the [reference](#configuration-reference) below. + +Provide the path to this file using the `--alpha-config` flag. + +:::note +When using the `--alpha-config` flag, some options are no longer available. +See [removed options](#removed-options) below for more information. +::: + +### Converting configuration to the new structure + +Before adding the new `--alpha-config` option, start OAuth2 Proxy using the +`convert-config-to-alpha` flag to convert existing configuration to the new format. + +```bash +oauth2-proxy --convert-config-to-alpha --config ./path/to/existing/config.cfg +``` + +This will convert any options supported by the new format to YAML and print the +new configuration to `STDOUT`. + +Copy this to a new file, remove any options from your existing configuration +noted in [removed options](#removed-options) and then start OAuth2 Proxy using +the new config. + +```bash +oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg +``` + +## Using ENV variables in the alpha configuration + +The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +When using environment variables, your yaml will look like this: + +```yaml + providers: + - provider: azure + clientSecret: ${CLIENT_SECRET} + ... +``` +Where CLIENT_SECRET is an environment variable. +More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) + +## Removed options + +The following flags/options and their respective environment variables are no +longer available when using alpha configuration: + + +- `flush-interval`/`flush_interval` +- `pass-host-header`/`pass_host_header` +- `proxy-websockets`/`proxy_websockets` +- `ssl-upstream-insecure-skip-verify`/`ssl_upstream_insecure_skip_verify` +- `upstream`/`upstreams` + + +- `pass-basic-auth`/`pass_basic_auth` +- `pass-access-token`/`pass_access_token` +- `pass-user-headers`/`pass_user_headers` +- `pass-authorization-header`/`pass_authorization_header` +- `set-basic-auth`/`set_basic_auth` +- `set-xauthrequest`/`set_xauthrequest` +- `set-authorization-header`/`set_authorization_header` +- `prefer-email-to-user`/`prefer_email_to_user` +- `basic-auth-password`/`basic_auth_password` +- `skip-auth-strip-headers`/`skip_auth_strip_headers` + + +- `client-id`/`client_id` +- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file` +- `provider` +- `provider-display-name`/`provider_display_name` +- `provider-ca-file`/`provider_ca_files` +- `login-url`/`login_url` +- `redeem-url`/`redeem_url` +- `profile-url`/`profile_url` +- `resource` +- `validate-url`/`validate_url` +- `scope` +- `prompt` +- `approval-prompt`/`approval_prompt` +- `acr-values`/`acr_values` +- `user-id-claim`/`user_id_claim` +- `allowed-group`/`allowed_groups` +- `allowed-role`/`allowed_roles` +- `jwt-key`/`jwt_key` +- `jwt-key-file`/`jwt_key_file` +- `pubjwk-url`/`pubjwk_url` + +and all provider-specific options, i.e. any option whose name includes `oidc`, +`azure`, `bitbucket`, `github`, `gitlab`, `google` or `keycloak`. Attempting to +use any of these options via flags or via config when `--alpha-config` is +set will result in an error. + +:::important +You must remove these options before starting OAuth2 Proxy with `--alpha-config` +::: + +## Configuration Reference diff --git a/docs/versioned_docs/version-7.14.x/configuration/integration.md b/docs/versioned_docs/version-7.14.x/configuration/integration.md new file mode 100644 index 0000000000..c57cfa6b36 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/integration.md @@ -0,0 +1,310 @@ +--- +id: integration +title: Integration +--- + +## Configuring for use with the Nginx `auth_request` directive + +**This option requires `--reverse-proxy` option to be set.** + +The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: + +```nginx +server { + listen 443 ssl; + server_name ...; + include ssl/ssl.conf; + + location /oauth2/ { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Auth-Request-Redirect $request_uri; + # or, if you are handling multiple domains: + # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; + } + location = /oauth2/auth { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; + # nginx auth_request includes headers but not body + proxy_set_header Content-Length ""; + proxy_pass_request_body off; + } + + location / { + auth_request /oauth2/auth; + error_page 401 =403 /oauth2/sign_in; + + # pass information via X-User and X-Email headers to backend, + # requires running with --set-xauthrequest flag + auth_request_set $user $upstream_http_x_auth_request_user; + auth_request_set $email $upstream_http_x_auth_request_email; + proxy_set_header X-User $user; + proxy_set_header X-Email $email; + + # if you enabled --pass-access-token, this will pass the token to the backend + auth_request_set $token $upstream_http_x_auth_request_access_token; + proxy_set_header X-Access-Token $token; + + # if you enabled --cookie-refresh, this is needed for it to work with auth_request + auth_request_set $auth_cookie $upstream_http_set_cookie; + add_header Set-Cookie $auth_cookie; + + # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb + # limit and so the OAuth2 Proxy splits these into multiple parts. + # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, + # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. + auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; + + # Extract the Cookie attributes from the first Set-Cookie header and append them + # to the second part ($upstream_cookie_* variables only contain the raw cookie content) + if ($auth_cookie ~* "(; .*)") { + set $auth_cookie_name_0 $auth_cookie; + set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; + } + + # Send both Set-Cookie headers now if there was a second part + if ($auth_cookie_name_upstream_1) { + add_header Set-Cookie $auth_cookie_name_0; + add_header Set-Cookie $auth_cookie_name_1; + } + + proxy_pass http://backend/; + # or "root /path/to/site;" or "fastcgi_pass ..." etc + } +} +``` + +When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: + +```yaml +nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" +nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" +``` + +This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. + +It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). + +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=". + +## Configuring for use with the Traefik (v2) `ForwardAuth` middleware + +**This option requires `--reverse-proxy` option to be set.** + +### ForwardAuth with 401 errors middleware + +The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: + +```yaml +http: + routers: + a-service: + rule: "Host(`a-service.example.com`)" + service: a-service-backend + middlewares: + - oauth-errors + - oauth-auth + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth: + rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + oauth-errors: + errors: + status: + - "401-403" + service: oauth-backend + query: "/oauth2/sign_in?rd={url}" +``` + +### ForwardAuth with static upstreams configuration + +Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint + +**Following options need to be set on `oauth2-proxy`:** +- `--upstream=static://202`: Configures a static response for authenticated sessions +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```yaml +http: + routers: + a-service-route-1: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" + service: a-service-backend + middlewares: + - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + a-service-route-2: + rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" + service: a-service-backend + middlewares: + - oauth-auth-wo-redirect # unauthenticated session will return a 401 + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + services-oauth2-route: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth2-proxy-route: + rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + b-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.3:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth-redirect: + forwardAuth: + address: https://oauth.example.com/ + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization + oauth-auth-wo-redirect: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization +``` + +## Configuring for use with the Caddy (v2) `forward_auth` directive + +The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. + +This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. + +**Following options need to be set on `oauth2-proxy`:** +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```nginx title="Caddyfile" +example.com { + # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. + # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. + handle /oauth2/* { + reverse_proxy oauth2-proxy.internal:4180 { + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. + header_up X-Real-IP {remote_host} + header_up X-Forwarded-Uri {uri} + } + } + + # Requests to other paths are first processed by oauth2-proxy for authentication. + handle { + forward_auth oauth2-proxy.internal:4180 { + uri /oauth2/auth + + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. + header_up X-Real-IP {remote_host} + + # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. + # Make sure to configure the --set-xauthrequest flag to enable this feature. + #copy_headers X-Auth-Request-User X-Auth-Request-Email + + # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. + @error status 401 + handle_response @error { + redir * /oauth2/sign_in?rd={scheme}://{host}{uri} + } + } + + # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. + reverse_proxy upstream.internal:3000 + } +} +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.14.x/configuration/overview.md b/docs/versioned_docs/version-7.14.x/configuration/overview.md new file mode 100644 index 0000000000..b159df09cc --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/overview.md @@ -0,0 +1,406 @@ +--- +id: overview +title: Overview +--- + +`oauth2-proxy` can be configured via [command line options](#command-line-options), [environment variables](#environment-variables) or [config file](#config-file) (in decreasing order of precedence, i.e. command line options will overwrite environment variables and environment variables will overwrite configuration file settings). + +## Generating a Cookie Secret + +To generate a strong cookie secret use one of the below commands: + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + + +```shell +python -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(32)).decode())' +``` + + + + +```shell +dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64 | tr -d -- '\n' | tr -- '+/' '-_' ; echo +``` + + + + +```shell +openssl rand -base64 32 | tr -- '+/' '-_' +``` + + + + +```powershell +# Add System.Web assembly to session, just in case +Add-Type -AssemblyName System.Web +[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([System.Web.Security.Membership]::GeneratePassword(32,4))).Replace("+","-").Replace("/","_") +``` + + + + +```hcl +# Valid 32 Byte Base64 URL encoding set that will decode to 24 []byte AES-192 secret +resource "random_password" "cookie_secret" { + length = 32 + override_special = "-_" +} +``` + + + + +## Config File + +Every command line argument can be specified in a config file by replacing hyphens (-) with underscores (\_). If the argument can be specified multiple times, the config option should be plural (trailing s). + +An example [oauth2-proxy.cfg](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/oauth2-proxy.cfg.example) config file is in the contrib directory. It can be used by specifying `--config=/etc/oauth2-proxy.cfg` + +## Config Options + +### Command Line Options + +| Flag | Description | +| ----------- | -------------------- | +| `--config` | path to config file | +| `--version` | print version string | + + +### General Provider Options + +Provider specific options can be found on their respective subpages. + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| flag: `--acr-values`
toml: `acr_values` | string | optional, see [docs](https://openid.net/specs/openid-connect-eap-acr-values-1_0.html#acrValues) | `""` | +| flag: `--allowed-group`
toml: `allowed_groups` | string \| list | Restrict login to members of a group or list of groups. Furthermore, if you aren't setting the `scope` and use `allowed_groups` with the generic OIDC provider the scope `groups` gets added implicitly. | | +| flag: `--approval-prompt`
toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` | +| flag: `--backend-logout-url`
toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | | +| flag: `--client-id`
toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | | +| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret | | +| flag: `--client-secret`
toml: `client_secret` | string | the OAuth Client Secret | | +| flag: `--code-challenge-method`
toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | | +| flag: `--insecure-oidc-allow-unverified-email`
toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false | +| flag: `--insecure-oidc-skip-issuer-verification`
toml: `insecure_oidc_skip_issuer_verification` | bool | allow the OIDC issuer URL to differ from the expected (currently required for Azure multi-tenant compatibility) | false | +| flag: `--insecure-oidc-skip-nonce`
toml: `insecure_oidc_skip_nonce` | bool | skip verifying the OIDC ID Token's nonce claim | true | +| flag: `--jwt-key-file`
toml: `jwt_key_file` | string | path to the private key file in PEM format used to sign the JWT so that you can say something like `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem`: required by login.gov | | +| flag: `--jwt-key`
toml: `jwt_key` | string | private key in PEM format used to sign JWT, so that you can say something like `--jwt-key="${OAUTH2_PROXY_JWT_KEY}"`: required by login.gov | | +| flag: `--login-url`
toml: `login_url` | string | Authentication endpoint | | +| flag: `--auth-request-response-mode`
toml: `auth-request-response-mode` | string | Response mode to ask for during authentication request | | +| flag: `--oidc-audience-claim`
toml: `oidc_audience_claims` | string | which OIDC claim contains the audience | `"aud"` | +| flag: `--oidc-email-claim`
toml: `oidc_email_claim` | string | which OIDC claim contains the user's email | `"email"` | +| flag: `--oidc-extra-audience`
toml: `oidc_extra_audiences` | string \| list | additional audiences which are allowed to pass verification | `"[]"` | +| flag: `--oidc-groups-claim`
toml: `oidc_groups_claim` | string | which OIDC claim contains the user groups | `"groups"` | +| flag: `--oidc-issuer-url`
toml: `oidc_issuer_url` | string | the OpenID Connect issuer URL, e.g. `"https://accounts.google.com"` | | +| flag: `--oidc-jwks-url`
toml: `oidc_jwks_url` | string | OIDC JWKS URI for token verification; required if OIDC discovery is disabled and public key files are not provided | | +| flag: `--oidc-public-key-file`
toml: `oidc_public_key_files` | string | Path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times). Required if OIDC discovery is disabled na JWKS URL isn't provided | string \| list | +| flag: `--profile-url`
toml: `profile_url` | string | Profile access endpoint | | +| flag: `--prompt`
toml: `prompt` | string | [OIDC prompt](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest); if present, `approval-prompt` is ignored | `""` | +| flag: `--provider-ca-file`
toml: `provider_ca_files` | string \| list | Paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead. | +| flag: `--provider-display-name`
toml: `provider_display_name` | string | Override the provider's name with the given string; used for the sign-in page | (depends on provider) | +| flag: `--provider`
toml: `provider` | string | OAuth provider | google | +| flag: `--pubjwk-url`
toml: `pubjwk_url` | string | JWK pubkey access endpoint: required by login.gov | | +| flag: `--redeem-url`
toml: `redeem_url` | string | Token redemption endpoint | | +| flag: `--scope`
toml:`scope` | string | OAuth scope specification. Every provider has a default list of scopes which will be used in case no scope is configured. | | +| flag: `--skip-claims-from-profile-url`
toml: `skip_claims_from_profile_url` | bool | skip request to Profile URL for resolving claims not present in id_token | false | +| flag: `--skip-oidc-discovery`
toml: `skip_oidc_discovery` | bool | bypass OIDC endpoint discovery. `--login-url`, `--redeem-url` and `--oidc-jwks-url` must be configured in this case | false | +| flag: `--use-system-trust-store`
toml: `use_system_trust_store` | bool | Determines if `provider-ca-file` files and the system trust store are used. If set to true, your custom CA files and the system trust store are used otherwise only your custom CA files. | false | +| flag: `--validate-url`
toml: `validate_url` | string | Access token validation endpoint | | + +### Cookie Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | +| flag: `--cookie-csrf-expire`
toml: `cookie_csrf_expire` | duration | expire timeframe for CSRF cookie | 15m | +| flag: `--cookie-csrf-per-request`
toml:`cookie_csrf_per_request` | bool | Enable having different CSRF cookies per request, making it possible to have parallel requests. | false | +| flag: `--cookie-csrf-per-request-limit`
toml: `cookie_csrf_per_request_limit` | int | Sets a limit on the number of CSRF requests cookies that oauth2-proxy will create. The oldest cookie will be removed. Useful if users end up with 431 Request headers too large status codes. Only effective if --cookie-csrf-per-request is true | "infinite" | +| flag: `--cookie-domain`
toml: `cookie_domains` | string \| list | Optional cookie domains to force cookies to (e.g. `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match). | | +| flag: `--cookie-expire`
toml: `cookie_expire` | duration | expire timeframe for cookie. If set to 0, cookie becomes a session-cookie which will expire when the browser is closed. | 168h0m0s | +| flag: `--cookie-httponly`
toml: `cookie_httponly` | bool | set HttpOnly cookie flag | true | +| flag: `--cookie-name`
toml: `cookie_name` | string | the name of the cookie that the oauth_proxy creates. Should be changed to use a [cookie prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#cookie_prefixes) (`__Host-` or `__Secure-`) if `--cookie-secure` is set. | `"_oauth2_proxy"` | +| flag: `--cookie-path`
toml: `cookie_path` | string | an optional cookie path to force cookies to (e.g. `/poc/`) | `"/"` | +| flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | +| flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | +| flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | +| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | For defining a separate cookie secret file to read the encryption key from | | +| flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | + +[^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) + +### Header Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--basic-auth-password`
toml: `basic_auth_password` | string | the password to set when passing the HTTP Basic Auth header | | +| flag: `--set-xauthrequest`
toml: `set_xauthrequest` | bool | set X-Auth-Request-User, X-Auth-Request-Groups, X-Auth-Request-Email and X-Auth-Request-Preferred-Username response headers (useful in Nginx auth_request mode). When used with `--pass-access-token`, X-Auth-Request-Access-Token is added to response headers. | false | +| flag: `--set-authorization-header`
toml: `set_authorization_header` | bool | set Authorization Bearer response header (useful in Nginx auth_request mode) | false | +| flag: `--set-basic-auth`
toml: `set_basic_auth` | bool | set HTTP Basic Auth information in response (useful in Nginx auth_request mode) | false | +| flag: `--skip-auth-strip-headers`
toml: `skip_auth_strip_headers` | bool | strips `X-Forwarded-*` style authentication headers & `Authorization` header if they would be set by oauth2-proxy | true | +| flag: `--pass-access-token`
toml: `pass_access_token` | bool | pass OAuth access_token to upstream via X-Forwarded-Access-Token header. When used with `--set-xauthrequest` this adds the X-Auth-Request-Access-Token header to the response | false | +| flag: `--pass-authorization-header`
toml: `pass_authorization_header` | bool | pass OIDC IDToken to upstream via Authorization Bearer header | false | +| flag: `--pass-basic-auth`
toml: `pass_basic_auth` | bool | pass HTTP Basic Auth, X-Forwarded-User, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | +| flag: `--prefer-email-to-user`
toml: `prefer_email_to_user` | bool | Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, e.g. htaccess authentication. Used in conjunction with `--pass-basic-auth` and `--pass-user-headers` | false | +| flag: `--pass-user-headers`
toml: `pass_user_headers` | bool | pass X-Forwarded-User, X-Forwarded-Groups, X-Forwarded-Email and X-Forwarded-Preferred-Username information to upstream | true | + +### Logging Options + +| Flag / Config Field | Type | Description | Default | +| --------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------- | --------------------------------------------------- | +| flag: `--auth-logging-format`
toml: `auth_logging_format` | string | Template for authentication log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--auth-logging`
toml: `auth_logging` | bool | Log authentication attempts | true | +| flag: `--errors-to-info-log`
toml: `errors_to_info_log` | bool | redirects error-level logging to default log channel instead of stderr | false | +| flag: `--exclude-logging-path`
toml: `exclude_logging_paths` | string | comma separated list of paths to exclude from logging, e.g. `"/ping,/path2"` | `""` (no paths excluded) | +| flag: `--logging-compress`
toml: `logging_compress` | bool | Should rotated log files be compressed using gzip | false | +| flag: `--logging-filename`
toml: `logging_filename` | string | File to log requests to, empty for `stdout` | `""` (stdout) | +| flag: `--logging-local-time`
toml: `logging_local_time` | bool | Use local time in log files and backup filenames instead of UTC | true (local time) | +| flag: `--logging-max-age`
toml: `logging_max_age` | int | Maximum number of days to retain old log files | 7 | +| flag: `--logging-max-backups`
toml: `logging_max_backups` | int | Maximum number of old log files to retain; 0 to disable | 0 | +| flag: `--logging-max-size`
toml: `logging_max_size` | int | Maximum size in megabytes of the log file before rotation | 100 | +| flag: `--request-id-header`
toml: `request_id_header` | string | Request header to use as the request ID in logging | X-Request-Id | +| flag: `--request-logging-format`
toml: `request_logging_format` | string | Template for request log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--request-logging`
toml: `request_logging` | bool | Log requests | true | +| flag: `--silence-ping-logging`
toml: `silence_ping_logging` | bool | disable logging of requests to ping & ready endpoints | false | +| flag: `--standard-logging-format`
toml: `standard_logging_format` | string | Template for standard log lines | see [Logging Configuration](#logging-configuration) | +| flag: `--standard-logging`
toml: `standard_logging` | bool | Log standard runtime information | true | + +### Page Template Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--banner`
toml: `banner` | string | custom (html) banner string. Use `"-"` to disable default banner. | | +| flag: `--custom-sign-in-logo`
toml: `custom_sign_in_logo` | string | path or a URL to an custom image for the sign_in page logo. Use `"-"` to disable default logo. | +| flag: `--custom-templates-dir`
toml: `custom_templates_dir` | string | path to custom html templates | | +| flag: `--display-htpasswd-form`
toml: `display_htpasswd_form` | bool | display username / password login form if an htpasswd file is provided | true | +| flag: `--footer`
toml: `footer` | string | custom (html) footer string. Use `"-"` to disable default footer. (Can be used to obfuscate the version) | | +| flag: `--show-debug-on-error`
toml: `show_debug_on_error` | bool | show detailed error information on error pages (WARNING: this may contain sensitive information - do not use in production) | false | + +### Probe Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------- | ------ | ---------------------------------------------------------- | ----------------------------- | +| flag: `--ping-path`
toml: `ping_path` | string | the ping endpoint that can be used for basic health checks | `"/ping"` | +| flag: `--ping-user-agent`
toml: `ping_user_agent` | string | a User-Agent that can be used for basic health checks | `""` (don't check user agent) | +| flag: `--ready-path`
toml: `ready_path` | string | the ready endpoint that can be used for deep health checks | `"/ready"` | +| flag: `--gcp-healthchecks`
toml: `gcp_healthchecks` | bool | Enable GCP/GKE healthcheck endpoints (deprecated) | false | + +### Proxy Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| flag: `--allow-query-semicolons`
toml: `allow_query_semicolons` | bool | allow the use of semicolons in query args ([required for some legacy applications](https://github.com/golang/go/issues/25192)) | `false` | +| flag: `--api-route`
toml: `api_routes` | string \| list | Requests to these paths must already be authenticated with a cookie, or a JWT if `--skip-jwt-bearer-tokens` is set. No redirect to login will be done. Return 401 if not. Format: path_regex | | +| flag: `--authenticated-emails-file`
toml: `authenticated_emails_file` | string | authenticate against emails via file (one per line) | | +| flag: `--bearer-token-login-fallback`
toml: `bearer_token_login_fallback` | bool | if `--skip-jwt-bearer-tokens` is set, if a request includes an invalid JWT (expired, malformed, missing required audiences, etc), fall back to normal login redirect as if the token were not sent at all. If false, respond 403 | true | +| flag: `--email-domain`
toml: `email_domains` | string \| list | authenticate emails with the specified domain (may be given multiple times). Use `*` to authenticate any email | | +| flag: `--encode-state`
toml: `encode_state` | bool | encode the state parameter as UrlEncodedBase64 | false | +| flag: `--extra-jwt-issuers`
toml: `extra_jwt_issuers` | string | if `--skip-jwt-bearer-tokens` is set, a list of extra JWT `issuer=audience` (see a token's `iss`, `aud` fields) pairs (where the issuer URL has a `.well-known/openid-configuration` or a `.well-known/jwks.json`) | | +| flag: `--force-https`
toml: `force_https` | bool | enforce https redirect | `false` | +| flag: `--force-json-errors`
toml: `force_json_errors` | bool | force JSON errors instead of HTTP error pages or redirects | `false` | +| flag: `--htpasswd-file`
toml: `htpasswd_file` | string | additionally authenticate against a htpasswd file. Entries must be created with `htpasswd -B` for bcrypt encryption | | +| flag: `--htpasswd-user-group`
toml: `htpasswd_user_groups` | string \| list | the groups to be set on sessions for htpasswd users | | +| flag: `--proxy-prefix`
toml: `proxy_prefix` | string | the url root path that this proxy should be nested under (e.g. /`/sign_in`) | `"/oauth2"` | +| flag: `--real-client-ip-header`
toml: `real_client_ip_header` | string | Header used to determine the real IP of the client, requires `--reverse-proxy` to be set (one of: X-Forwarded-For, X-Real-IP, X-ProxyUser-IP, X-Envoy-External-Address, or CF-Connecting-IP) | X-Real-IP | +| flag: `--redirect-url`
toml: `redirect_url` | string | the OAuth Redirect URL, e.g. `"https://internalapp.yourcompany.com/oauth2/callback"` | | +| flag: `--relative-redirect-url`
toml: `relative_redirect_url` | bool | allow relative OAuth Redirect URL.` | false | +| flag: `--reverse-proxy`
toml: `reverse_proxy` | bool | are we running behind a reverse proxy, controls whether headers like X-Real-IP are accepted and allows X-Forwarded-\{Proto,Host,Uri\} headers to be used on redirect selection | false | +| flag: `--signature-key`
toml: `signature_key` | string | GAP-Signature request signature key (algorithm:secretkey) | | +| flag: `--skip-auth-preflight`
toml: `skip_auth_preflight` | bool | will skip authentication for OPTIONS requests | false | +| flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | +| flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | +| flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | +| flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | +| flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | + +[^2]: When using the `whitelist-domain` option, any domain prefixed with a `.` or a `*.` will allow any subdomain of the specified domain as a valid redirect URL. By default, only empty ports are allowed. This translates to allowing the default port of the URL's protocol (80 for HTTP, 443 for HTTPS, etc.) since browsers omit them. To allow only a specific port, add it to the whitelisted domain: `example.com:8080`. To allow any port, use `*`: `example.com:*`. + +### Server Options + +| Flag / Config Field | Type | Description | Default | +| ------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | +| flag: `--http-address`
toml: `http_address` | string | `[http://]:` or `unix://` or `fd:` (case insensitive) to listen on for HTTP clients. Square brackets are required for ipv6 address, e.g. `http://[::1]:4180` | `"127.0.0.1:4180"` | +| flag: `--https-address`
toml: `https_address` | string | `[https://]:` to listen on for HTTPS clients. Square brackets are required for ipv6 address, e.g. `https://[::1]:443` | `":443"` | +| flag: `--metrics-address`
toml: `metrics_address` | string | the address prometheus metrics will be scraped from | `""` | +| flag: `--metrics-secure-address`
toml: `metrics_secure_address` | string | the address prometheus metrics will be scraped from if using HTTPS | `""` | +| flag: `--metrics-tls-cert-file`
toml: `metrics_tls_cert_file` | string | path to certificate file for secure metrics server | `""` | +| flag: `--metrics-tls-key-file`
toml: `metrics_tls_key_file` | string | path to private key file for secure metrics server | `""` | +| flag: `--tls-cert-file`
toml: `tls_cert_file` | string | path to certificate file | | +| flag: `--tls-key-file`
toml: `tls_key_file` | string | path to private key file | | +| flag: `--tls-cipher-suite`
toml: `tls_cipher_suites` | string \| list | Restricts TLS cipher suites used by server to those listed (e.g. TLS_RSA_WITH_RC4_128_SHA) (may be given multiple times). If not specified, the default Go safe cipher list is used. List of valid cipher suites can be found in the [crypto/tls documentation](https://pkg.go.dev/crypto/tls#pkg-constants). | | +| flag: `--tls-min-version`
toml: `tls_min_version` | string | minimum TLS version that is acceptable, either `"TLS1.2"` or `"TLS1.3"` | `"TLS1.2"` | + +### Session Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| flag: `--session-cookie-minimal`
toml: `session_cookie_minimal` | bool | strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only) | false | +| flag: `--session-store-type`
toml: `session_store_type` | string | [Session data storage backend](sessions.md); redis or cookie | cookie | +| flag: `--redis-cluster-connection-urls`
toml: `redis_cluster_connection_urls` | string \| list | List of Redis cluster connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-cluster` | | +| flag: `--redis-connection-url`
toml: `redis_connection_url` | string | URL of redis server for redis session storage (e.g. `redis://HOST[:PORT]`) | | +| flag: `--redis-insecure-skip-tls-verify`
toml: `redis_insecure_skip_tls_verify` | bool | skip TLS verification when connecting to Redis | false | +| flag: `--redis-password`
toml: `redis_password` | string | Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url` | | +| flag: `--redis-sentinel-password`
toml: `redis_sentinel_password` | string | Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password` | | +| flag: `--redis-sentinel-master-name`
toml: `redis_sentinel_master_name` | string | Redis sentinel master name. Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-sentinel-connection-urls`
toml: `redis_sentinel_connection_urls` | string \| list | List of Redis sentinel connection URLs (e.g. `redis://HOST[:PORT]`). Used in conjunction with `--redis-use-sentinel` | | +| flag: `--redis-use-cluster`
toml: `redis_use_cluster` | bool | Connect to redis cluster. Must set `--redis-cluster-connection-urls` to use this feature | false | +| flag: `--redis-use-sentinel`
toml: `redis_use_sentinel` | bool | Connect to redis via sentinels. Must set `--redis-sentinel-master-name` and `--redis-sentinel-connection-urls` to use this feature | false | +| flag: `--redis-connection-idle-timeout`
toml: `redis_connection_idle_timeout` | int | Redis connection idle timeout seconds. If Redis [timeout](https://redis.io/docs/reference/clients/#client-timeouts) option is set to non-zero, the `--redis-connection-idle-timeout` must be less than Redis timeout option. Example: if either redis.conf includes `timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` | 0 | + +### Upstream Options + +| Flag / Config Field | Type | Description | Default | +| ----------------------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | +| flag: `--flush-interval`
toml: `flush_interval` | duration | period between flushing response buffers when streaming responses | `"1s"` | +| flag: `--pass-host-header`
toml: `pass_host_header` | bool | pass the request Host Header to upstream | true | +| flag: `--proxy-websockets`
toml: `proxy_websockets` | bool | enables WebSocket proxying | true | +| flag: `--ssl-upstream-insecure-skip-verify`
toml: `ssl_upstream_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS upstreams | false | +| flag: `--disable-keep-alives`
toml: `disable_keep_alives` | bool | disable HTTP keep-alive connections to the upstream server | false | +| flag: `--upstream-timeout`
toml: `upstream_timeout` | duration | maximum amount of time the server will wait for a response from the upstream | 30s | +| flag: `--upstream`
toml: `upstreams` | string \| list | the http url(s) of the upstream endpoint, file:// paths for static files or `static://` for static response. Routing is based on the path | | + +## Upstreams Configuration + +`oauth2-proxy` supports having multiple upstreams, and has the option to pass requests on to HTTP(S) servers, unix socket or serve static files from the file system. + +To configure **HTTP and HTTPS upstreams**, provide such a URL in `--upstream=URL`. The scheme+host portion and the path portion are extracted to configure proxying behavior. When processing incoming requests, the path portion becomes a lookup key for selecting the destination server of the proxied request. + +* Upstream URLs *without a trailing slash,* like in `--upstream=http://service2.internal/foo`, will match an incoming request exactly to `/foo` in `https://this.o2p.example.com/foo`, and forward the request on to service2.internal, but not match a request to `https://this.o2p.example.com/foo/more` nor ...`.com/food`. +* Upstream URLs *with a trailing slash,* like in `--upstream=http://service1.internal/foo/`, will match any incoming request to any incoming requests's path *starting with* `/foo/`, like `/foo/` and `/foo/more` and `/foo/lots/more?etc`. + +If multiple `--upstream` URLs' paths match an incoming request, the one with the longest matching path (the most specific match) takes priority over shorter (less specific) ones. + +**Unix socket upstreams** are configured as `unix:///path/to/unix.sock`. + +**Static file paths** are configured as a file:// URL. `file:///var/www/static/` will serve the files from that directory at `http://[oauth2-proxy url]/var/www/static/`, which may not be what you want. You can provide the path to where the files should be available by adding a fragment to the configured URL. The value of the fragment will then be used to specify which path the files are available at, e.g. `file:///var/www/static/#/static/` will make `/var/www/static/` available at `http://[oauth2-proxy url]/static/`. + +Multiple upstreams can either be configured by supplying a comma separated list to the `--upstream` parameter, supplying the parameter multiple times or providing a list in the [config file](#config-file). When multiple upstreams are used routing to them will be based on the path they are set up with. + +## Environment variables + +Every command line argument can be specified as an environment variable by +prefixing it with `OAUTH2_PROXY_`, capitalising it, and replacing hyphens (`-`) +with underscores (`_`). If the argument can be specified multiple times, the +environment variable should be plural (trailing `S`). + +This is particularly useful for storing secrets outside a configuration file +or the command line. + +For example, the `--cookie-secret` flag becomes `OAUTH2_PROXY_COOKIE_SECRET`. +If a flag has the type `string | list` like the `--email-domain` flag it is +available as an environment variable in plural form e.g. `OAUTH2_PROXY_EMAIL_DOMAINS` + +Values for type `string | list` usually have a plural environment variable name +and need to be seperated by `,` e.g. +`OAUTH2_PROXY_SKIP_AUTH_ROUTES="GET=^/api/status,POST=^/api/saved_objects/_import"` + +Please check the type for each [config option](#config-options) first. + +## Logging Configuration + +By default, OAuth2 Proxy logs all output to stdout. Logging can be configured to output to a rotating log file using the `--logging-filename` command. + +If logging to a file you can also configure the maximum file size (`--logging-max-size`), age (`--logging-max-age`), max backup logs (`--logging-max-backups`), and if backup logs should be compressed (`--logging-compress`). + +There are three different types of logging: standard, authentication, and HTTP requests. These can each be enabled or disabled with `--standard-logging`, `--auth-logging`, and `--request-logging`. + +Each type of logging has its own configurable format and variables. By default, these formats are similar to the Apache Combined Log. + +Logging of requests to the `/ping` endpoint (or using `--ping-user-agent`) and the `/ready` endpoint can be disabled with `--silence-ping-logging` reducing log volume. + +## Auth Log Format + +Authentication logs are logs which are guaranteed to contain a username or email address of a user attempting to authenticate. These logs are output by default in the below format: + +``` + - - [2015/03/19 17:20:19] [] +``` + +The status block will contain one of the below strings: + +- `AuthSuccess` If a user has authenticated successfully by any method +- `AuthFailure` If the user failed to authenticate explicitly +- `AuthError` If there was an unexpected error during authentication + +If you require a different format than that, you can configure it with the `--auth-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}} +``` + +Available variables for auth logging: + +| Variable | Example | Description | +| ------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Message | Authenticated via OAuth2 | The details of the auth attempt. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | +| Status | AuthSuccess | The status of the auth request. See above for details. | + +## Request Log Format + +HTTP request logs will output by default in the below format: + +``` + - - [2015/03/19 17:20:19] GET "/path/" HTTP/1.1 "" +``` + +If you require a different format than that, you can configure it with the `--request-logging-format` flag. +The default format is configured as follows: + +``` +{{.Client}} - {{.RequestID}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}} +``` + +Available variables for request logging: + +| Variable | Example | Description | +| --------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| Client | 74.125.224.72 | The client/remote IP address. Will use the X-Real-IP header it if exists & reverse-proxy is set to true. | +| Host | domain.com | The value of the Host header. | +| Protocol | HTTP/1.0 | The request protocol. | +| RequestDuration | 0.001 | The time in seconds that a request took to process. | +| RequestID | 00010203-0405-4607-8809-0a0b0c0d0e0f | The request ID pulled from the `--request-id-header`. Random UUID if empty | +| RequestMethod | GET | The request method. | +| RequestURI | "/oauth2/auth" | The URI path of the request. | +| ResponseSize | 12 | The size in bytes of the response. | +| StatusCode | 200 | The HTTP status code of the response. | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| Upstream | - | The upstream data of the HTTP request. | +| UserAgent | - | The full user agent as reported by the requesting client. | +| Username | username@email.com | The email or username of the auth request. | + +## Standard Log Format + +All other logging that is not covered by the above two types of logging will be output in this standard logging format. This includes configuration information at startup and errors that occur outside of a session. The default format is below: + +``` +[2015/03/19 17:20:19] [main.go:40] +``` + +If you require a different format than that, you can configure it with the `--standard-logging-format` flag. The default format is configured as follows: + +``` +[{{.Timestamp}}] [{{.File}}] {{.Message}} +``` + +Available variables for standard logging: + +| Variable | Example | Description | +| --------- | --------------------------------- | -------------------------------------------------- | +| Timestamp | 2015/03/19 17:20:19 | The date and time of the logging event. | +| File | main.go:40 | The file and line number of the logging statement. | +| Message | HTTP: listening on 127.0.0.1:4180 | The details of the log statement. | diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/adfs.md b/docs/versioned_docs/version-7.14.x/configuration/providers/adfs.md new file mode 100644 index 0000000000..ec8d72d2af --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/adfs.md @@ -0,0 +1,19 @@ +--- +id: adfs +title: ADFS +--- + +1. Open the ADFS administration console on your Windows Server and add a new Application Group +2. Provide a name for the integration, select Server Application from the Standalone applications section and click Next +3. Follow the wizard to get the client-id, client-secret and configure the application credentials +4. Configure the proxy with + +``` + --provider=adfs + --client-id= + --client-secret= +``` + +Note: When using the ADFS Auth provider with nginx and the cookie session store you may find the cookie is too large and +doesn't get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the +[redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/bitbucket.md b/docs/versioned_docs/version-7.14.x/configuration/providers/bitbucket.md new file mode 100644 index 0000000000..e31de7526c --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/bitbucket.md @@ -0,0 +1,25 @@ +--- +id: bitbucket +title: BitBucket +--- + +1. [Add a new OAuth consumer](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html) + * In "Callback URL" use `https:///oauth2/callback`, substituting `` with the actual + hostname that oauth2-proxy is running on. + * In Permissions section select: + * Account -> Email + * Team membership -> Read + * Repositories -> Read +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=bitbucket + --client-id= + --client-secret= +``` + +The default configuration allows everyone with Bitbucket account to authenticate. To restrict the access to the team +members use additional configuration option: `--bitbucket-team=`. To restrict the access to only these users +who have access to one selected repository use `--bitbucket-repository=`. diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/cidaas.md b/docs/versioned_docs/version-7.14.x/configuration/providers/cidaas.md new file mode 100644 index 0000000000..7a9870181f --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/cidaas.md @@ -0,0 +1,37 @@ +--- +id: cidaas +title: Cidaas +--- + +[Cidaas](https://www.cidaas.com/) is an Identity as a Service (IDaaS) solution that provides authentication and authorization services. +It supports various protocols including OpenID Connect, OAuth 2.0, and SAML. + +However, Cidaas provides groups and their roles as hierarchical claims, which are not supported by oauth2-proxy yet. +The Cidaas provider transforms the hierarchical claims into a flat list of groups, which can be used by oauth2-proxy. + +Example of groups and roles in Cidaas: + +```json +{ + "groups": [ + { + "groupId": "group1", + "roles": ["role1", "role2"] + }, + { + "groupId": "group2", + "roles": ["role3"] + } + ] +} +``` + +This will be transformed into a flat list of groups: + +```json +{ + "groups": ["group1:role1", "group2:role2", "group2:role3"] +} +``` + +Apart from that the Cidaas provider inherits all the features of the [OpenID Connect provider](openid_connect.md). \ No newline at end of file diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/cisco_duo.md b/docs/versioned_docs/version-7.14.x/configuration/providers/cisco_duo.md new file mode 100644 index 0000000000..a92eccdbb3 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/cisco_duo.md @@ -0,0 +1,44 @@ +--- +id: cisco_duo +title: Cisco Duo +--- + +Cisco Duo SSO can be configured with OAuth2 Proxy using the OIDC provider. + +1. Create a new **Generic OIDC Relying Party - Single Sign-On** application in the Duo Admin Portal +2. Configure OAuth2 Proxy with the following options: + +``` +provider = "oidc" +provider_display_name = "Duo SSO" +scope = "openid email profile" +pass_access_token = true +code_challenge_method = "S256" +``` + +3. Configure Provider endpoints. Copy the following values from the corresponding fields in the Duo Admin Portal: + +``` +# Copy from "Client ID" field +client_id = "XXXXXXXX" + +# Copy from "Client Secret" field +client_secret = "XXXXXXXX" + +# Copy from "Issuer" field +oidc_issuer_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx" + +# Copy from "JWKS URL" field +oidc_jwks_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/jwks" + +# Copy from "Token Introspection URL" field +validate_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/token_introspection" + +# Copy from "UserInfo" field +profile_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/userinfo" + +# Copy from "Token URL" field +redeem_url = "https://sso-xxxxxxxx.sso.duosecurity.com/oidc/xxxxxxxx/token" +``` + +4. Complete Configuration by filling in any remaining required fields and save your configuration. diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/digitalocean.md b/docs/versioned_docs/version-7.14.x/configuration/providers/digitalocean.md new file mode 100644 index 0000000000..f6a1e89181 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/digitalocean.md @@ -0,0 +1,21 @@ +--- +id: digitalocean +title: DigitalOcean +--- + +1. [Create a new OAuth application](https://cloud.digitalocean.com/account/api/applications) + * You can fill in the name, homepage, and description however you wish. + * In the "Application callback URL" field, enter: `https://oauth-proxy/oauth2/callback`, substituting `oauth2-proxy` + with the actual hostname that oauth2-proxy is running on. The URL must match oauth2-proxy's configured redirect URL. +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=digitalocean + --client-id= + --client-secret= +``` + +Alternatively, set the equivalent options in the config file. The redirect URL defaults to +`https:///oauth2/callback`. If you need to change it, you can use the `--redirect-url` command-line option. diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/facebook.md b/docs/versioned_docs/version-7.14.x/configuration/providers/facebook.md new file mode 100644 index 0000000000..352c95ce1e --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/facebook.md @@ -0,0 +1,7 @@ +--- +id: facebook +title: Facebook +--- + +1. Create a new FB App from https://developers.facebook.com/ +2. Under FB Login, set your Valid OAuth redirect URIs to `https://internal.yourcompany.com/oauth2/callback` diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/gitea.md b/docs/versioned_docs/version-7.14.x/configuration/providers/gitea.md new file mode 100644 index 0000000000..6c679dd0f4 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/gitea.md @@ -0,0 +1,24 @@ +--- +id: gitea +title: Gitea / Forgejo +--- + +:::note +This is not actually a fully serparate provider. For more details and options please refer to the [GitHub Provider Options](github.md) +::: + +1. Create a new application: `https://< your gitea host >/user/settings/applications` +2. Under `Redirect URI` enter the correct URL i.e. `https:///oauth2/callback` +3. Note the Client ID and Client Secret. +4. Pass the following options to the proxy: + +``` + --provider="github" + --redirect-url="https:///oauth2/callback" + --provider-display-name="Gitea" + --client-id="< client_id as generated by Gitea >" + --client-secret="< client_secret as generated by Gitea >" + --login-url="https://< your gitea host >/login/oauth/authorize" + --redeem-url="https://< your gitea host >/login/oauth/access_token" + --validate-url="https://< your gitea host >/api/v1/user/emails" +``` diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/github.md b/docs/versioned_docs/version-7.14.x/configuration/providers/github.md new file mode 100644 index 0000000000..cebca31411 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/github.md @@ -0,0 +1,81 @@ +--- +id: github +title: GitHub +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | -------------- | ------------------------------------------------------------------------------------------------------------- | ------- | +| `--github-org` | `github_org` | string | restrict logins to members of this organisation | | +| `--github-team` | `github_team` | string | restrict logins to members of any of these teams (slug) or (org:team), comma separated | | +| `--github-repo` | `github_repo` | string | restrict logins to collaborators of this repository formatted as `orgname/repo` | | +| `--github-token` | `github_token` | string | the token to use when verifying repository collaborators (must have push access to the repository) | | +| `--github-user` | `github_users` | string \| list | To allow users to login by username even if they do not belong to the specified org and team or collaborators | | + +## Usage + +1. Create a new project: https://github.com/settings/developers +2. Under `Authorization callback URL` enter the correct url ie `https://internal.yourcompany.com/oauth2/callback` + +The GitHub auth provider supports two additional ways to restrict authentication to either organization and optional +team level access, or to collaborators of a repository. Restricting by these options is normally accompanied with `--email-domain=*`. Additionally, all the organizations and teams a user belongs to are set as part of the `X-Forwarded-Groups` header. e.g. `org1:team1,org1:team2,org2:team1` + +NOTE: When `--github-user` is set, the specified users are allowed to log in even if they do not belong to the specified +org and team or collaborators. + +To restrict access to your organization: + +```shell + # restrict logins to members of this organisation + --github-org="your-org" +``` + +To restrict access to specific teams within an organization: + +```shell + --github-org="your-org" + # restrict logins to members of any of these teams (slug), comma separated + --github-team="team1,team2,team3" +``` + +To restrict to teams within different organizations, keep the organization flag empty and use `--github-team` like so: + +```shell + # keep empty + --github-org="" + # restrict logins to members to any of the following teams (format :, like octo:team1), comma separated + --github-team="org1:team1,org2:team1,org3:team42,octo:cat" +``` + +If you would rather restrict access to collaborators of a repository, those users must either have push access to a +public repository or any access to a private repository: + +```shell + # restrict logins to collaborators of this repository formatted as orgname/repo + --github-repo="" +``` + +If you'd like to allow access to users with **read only** access to a **public** repository you will need to provide a +[token](https://github.com/settings/tokens) for a user that has write access to the repository. The token must be +created with at least the `public_repo` scope: + +```shell + # the token to use when verifying repository collaborators + --github-token="" +``` + +To allow a user to log in with their username even if they do not belong to the specified org and team or collaborators: + +```shell + # allow logins by username, comma separated + --github-user="" +``` + +If you are using GitHub enterprise, make sure you set the following to the appropriate url: + +```shell + --login-url="http(s):///login/oauth/authorize" + --redeem-url="http(s):///login/oauth/access_token" + --validate-url="http(s):///api/v3" +``` diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/gitlab.md b/docs/versioned_docs/version-7.14.x/configuration/providers/gitlab.md new file mode 100644 index 0000000000..4cdbbbe1e0 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/gitlab.md @@ -0,0 +1,49 @@ +--- +id: gitlab +title: GitLab +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ------------------- | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--gitlab-group` | `gitlab_groups` | string \| list | restrict logins to members of any of these groups (slug), separated by a comma | | +| `--gitlab-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 | | + +## Usage + +This auth provider has been tested against Gitlab version 12.X. Due to Gitlab API changes, it may not work for version +prior to 12.X (see [994](https://github.com/oauth2-proxy/oauth2-proxy/issues/994)). + +Whether you are using GitLab.com or self-hosting GitLab, follow +[these steps to add an application](https://docs.gitlab.com/integration/oauth_provider/). Make sure to enable at +least the `openid`, `profile` and `email` scopes, and set the redirect url to your application url e.g. +https://myapp.com/oauth2/callback. + +If you need projects filtering, add the extra `read_api` scope to your application. + +The following config should be set to ensure that the oauth will work properly. To get a cookie secret follow +[these steps](../overview.md#generating-a-cookie-secret) + +``` + --provider="gitlab" + --redirect-url="https://myapp.com/oauth2/callback" // Should be the same as the redirect url for the application in gitlab + --client-id=GITLAB_CLIENT_ID + --client-secret=GITLAB_CLIENT_SECRET + --cookie-secret=COOKIE_SECRET +``` + +Restricting by group membership is possible with the following option: + +```shell + --gitlab-group="mygroup,myothergroup" # restrict logins to members of any of these groups (slug), separated by a comma +``` + +If you are using self-hosted GitLab, make sure you set the following to the appropriate URL: + +```shell + --oidc-issuer-url="" +``` + +If your self-hosted GitLab is on a subdirectory (e.g. domain.tld/gitlab), as opposed to its own subdomain +(e.g. gitlab.domain.tld), you may need to add a redirect from domain.tld/oauth pointing at e.g. domain.tld/gitlab/oauth. diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/google.md b/docs/versioned_docs/version-7.14.x/configuration/providers/google.md new file mode 100644 index 0000000000..0de5bb74a5 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/google.md @@ -0,0 +1,84 @@ +--- +id: google +title: Google (default) +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +|-------------------------------------------------|----------------------------------------------| ------ |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------| +| `--google-admin-email` | `google_admin_email` | string | the google admin to impersonate for api calls | | +| `--google-group` | `google_groups` | string | restrict logins to members of this google group (may be given multiple times). If not specified and service account or default credentials are configured, all user groups will be allowed. | | +| `--google-service-account-json` | `google_service_account_json` | string | the path to the service account json credentials | | +| `--google-use-application-default-credentials` | `google_use_application_default_credentials` | bool | use application default credentials instead of service account json (i.e. GKE Workload Identity) | | +| `--google-target-principal` | `google_target_principal` | bool | the target principal to impersonate when using ADC | defaults to the service account configured for ADC | +| `--google-use-organization-id` | `google_use_organization_id` | bool | use organization id as preferred username | false | +| `--google-admin-api-user-scope` | `google_admin_api_user_scope` | string | the OAuth scope to use when querying the Google Admin SDK for organization id, can be 'readonly', 'user' or 'cloud'
| `readonly` | + +## Usage + +For Google, the registration steps are: + +1. Create a new project: https://console.developers.google.com/project +2. Choose the new project from the top right project dropdown (only if another project is selected) +3. In the project Dashboard center pane, choose **"APIs & Services"** +4. In the left Nav pane, choose **"Credentials"** +5. In the center pane, choose **"OAuth consent screen"** tab. Fill in **"Product name shown to users"** and hit save. +6. In the center pane, choose **"Credentials"** tab. + - Open the **"New credentials"** drop down + - Choose **"OAuth client ID"** + - Choose **"Web application"** + - Application name is freeform, choose something appropriate + - Authorized JavaScript origins is your domain ex: `https://internal.yourcompany.com` + - Authorized redirect URIs is the location of oauth2/callback ex: `https://internal.yourcompany.com/oauth2/callback` + - Choose **"Create"** +7. Take note of the **Client ID** and **Client Secret** + +It's recommended to refresh sessions on a short interval (1h) with `cookie-refresh` setting which validates that the +account is still authorized. + +#### Restrict auth to specific Google groups on your domain. (optional) + +1. Create a [service account](https://developers.google.com/identity/protocols/oauth2/service-account) and configure it + to use [Application Default Credentials / Workload Identity / Workload Identity Federation (recommended)](#using-application-default-credentials-adc--workload-identity--workload-identity-federation-recommended) or, + alternatively download the JSON. +2. Make note of the Client ID for a future step. +3. Under "APIs & Auth", choose APIs. +4. Click on Admin SDK and then Enable API. +5. Follow the steps on [Set up domain-wide delegation for a service account](https://developers.google.com/workspace/guides/create-credentials#optional_set_up_domain-wide_delegation_for_a_service_account) + and give the client id from step 2 the following oauth scopes: + + ``` + https://www.googleapis.com/auth/admin.directory.group.member.readonly + ``` + +6. Follow the steps on https://support.google.com/a/answer/60757 to enable Admin API access. +7. Create or choose an existing administrative email address on the Gmail domain to assign to the `google-admin-email` + flag. This email will be impersonated by this client to make calls to the Admin SDK. See the note on the link from + step 5 for the reason why. +8. Create or choose an existing email group and set that email to the `google-group` flag. You can pass multiple instances + of this flag with different groups and the user will be checked against all the provided groups. + +(Only if using a JSON file (see step 1)) + +9. Lock down the permissions on the json file downloaded from step 1 so only oauth2-proxy is able to read the file and + set the path to the file in the `google-service-account-json` flag. +10. Restart oauth2-proxy. + +Note: The user is checked against the group members list on initial authentication and every time the token is +refreshed ( about once an hour ). + +##### Using Application Default Credentials (ADC) / Workload Identity / Workload Identity Federation (recommended) +oauth2-proxy can make use of [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials). +When deployed within GCP, this means that it can automatically use the service account attached to the resource. When deployed to GKE, ADC +can be leveraged through a feature called Workload Identity. Follow Google's [guide](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity) +to set up Workload Identity. + +When deployed outside of GCP, [Workload Identity Federation](https://cloud.google.com/docs/authentication/provide-credentials-adc#wlif) might be an option. + +##### Using Organization ID as Preferred Username (optional) +By default, the google provider uses the google id as username. If you would like to use an organization id instead, you can set the `google-use-organization-id` flag to true. +This requires that the service account used to query the Google Admin SDK has one of the following scopes granted in step 5 above: +- `https://www.googleapis.com/auth/admin.directory.user.readonly`, +- `https://www.googleapis.com/auth/admin.directory.user` +- `https://www.googleapis.com/auth/cloud-platform` diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/index.md b/docs/versioned_docs/version-7.14.x/configuration/providers/index.md new file mode 100644 index 0000000000..6f333e5af2 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/index.md @@ -0,0 +1,46 @@ +--- +id: index +title: OAuth Provider Configuration +--- + +You will need to register an OAuth application with a Provider (Google, GitHub or another provider), and configure it +with Redirect URI(s) for the domain you intend to run `oauth2-proxy` on. + +Valid providers are : + +- [ADFS](adfs.md) +- [Bitbucket](bitbucket.md) +- [Cidaas](cidaas.md) +- [CiscoDuo](cisco_duo.md) +- [DigitalOcean](digitalocean.md) +- [Facebook](facebook.md) +- [Gitea](gitea.md) +- [GitHub](github.md) +- [GitLab](gitlab.md) +- [Google](google.md) _default_ +- [Keycloak](keycloak.md) (Deprecated) +- [Keycloak OIDC](keycloak_oidc.md) +- [LinkedIn](linkedin.md) +- [login.gov](login_gov.md) +- [Microsoft Azure](ms_azure_ad.md) (Deprecated) +- [Microsoft Entra ID](ms_entra_id.md) +- [Nextcloud](nextcloud.md) +- [OpenID Connect](openid_connect.md) +- [SourceHut](sourcehut.md) + +The provider can be selected using the `provider` configuration value, or set in the [`providers` array using AlphaConfig](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#providers). However, [**the feature to implement multiple providers is not complete**](https://github.com/oauth2-proxy/oauth2-proxy/issues/926). + +Please note that not all providers support all claims. The `preferred_username` claim is currently only supported by the +OpenID Connect provider. + +## Email Authentication + +To authorize a specific email-domain use `--email-domain=yourcompany.com`. To authorize individual email addresses use +`--authenticated-emails-file=/path/to/file` with one email per line. To authorize all email addresses use `--email-domain=*`. + +## Adding a new Provider + +Follow the examples in the [`providers` package](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/) to define a new +`Provider` instance. Add a new `case` to +[`providers.New()`](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/providers/providers.go) to allow `oauth2-proxy` to use the +new `Provider`. diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/keycloak.md b/docs/versioned_docs/version-7.14.x/configuration/providers/keycloak.md new file mode 100644 index 0000000000..11a1abca1c --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/keycloak.md @@ -0,0 +1,36 @@ +--- +id: keycloak +title: Keycloak (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Keycloak, use [Keycloak OIDC Auth Provider](keycloak_oidc.md) if possible. +::: + +1. Create new client in your Keycloak realm with **Access Type** 'confidential' and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. + +Make sure you set the following to the appropriate url: + +``` + --provider=keycloak + --client-id= + --client-secret= + --login-url="http(s):///auth/realms//protocol/openid-connect/auth" + --redeem-url="http(s):///auth/realms//protocol/openid-connect/token" + --profile-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --validate-url="http(s):///auth/realms//protocol/openid-connect/userinfo" + --keycloak-group= + --keycloak-group= +``` + +For group based authorization, the optional `--keycloak-group` (legacy) or `--allowed-group` (global standard) +flags can be used to specify which groups to limit access to. + +If these are unset but a `groups` mapper is set up above in step (3), the provider will still +populate the `X-Forwarded-Groups` header to your upstream server with the `groups` data in the +Keycloak userinfo endpoint response. + +The group management in keycloak is using a tree. If you create a group named admin in keycloak +you should define the 'keycloak-group' value to /admin. diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/keycloak_oidc.md b/docs/versioned_docs/version-7.14.x/configuration/providers/keycloak_oidc.md new file mode 100644 index 0000000000..b29096e35d --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/keycloak_oidc.md @@ -0,0 +1,151 @@ +--- +id: keycloak_oidc +title: Keycloak OIDC +--- + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | --------------- | -------------- | ------------------------------------------------------------------------------------------------------------------ | ------- | +| `--allowed-role` | `allowed_roles` | string \| list | restrict logins to users with this role (may be given multiple times). Only works with the keycloak-oidc provider. | | + +## Usage + +``` + --provider=keycloak-oidc + --client-id= + --client-secret= + --redirect-url=https://internal.yourcompany.com/oauth2/callback + --oidc-issuer-url=https:///realms/ // For Keycloak versions <17: --oidc-issuer-url=https:///auth/realms/ + --email-domain= // Validate email domain for users, see option documentation + --allowed-role= // Optional, required realm role + --allowed-role=: // Optional, required client role + --allowed-group= // Optional, requires group client scope + --code-challenge-method=S256 // PKCE +``` + +:::note +Keycloak has updated its admin console and as of version 19.0.0, the new admin console is enabled by default. The +legacy admin console has been announced for removal with the release of version 21.0.0. +::: + +**Keycloak legacy admin console** + +1. Create new client in your Keycloak realm with **Access Type** 'confidential', **Client protocol** 'openid-connect' + and **Valid Redirect URIs** 'https://internal.yourcompany.com/oauth2/callback' +2. Take note of the Secret in the credential tab of the client +3. Create a mapper with **Mapper Type** 'Group Membership' and **Token Claim Name** 'groups'. +4. Create a mapper with **Mapper Type** 'Audience' and **Included Client Audience** and **Included Custom Audience** set + to your client name. + +**Keycloak new admin console (default as of v19.0.0)** + +The following example shows how to create a simple OIDC client using the new Keycloak admin2 console. However, for best +practices, it is recommended to consult the Keycloak documentation. + +The OIDC client must be configured with an _audience mapper_ to include the client's name in the `aud` claim of the JWT token. +The `aud` claim specifies the intended recipient of the token, and OAuth2 Proxy expects a match against the values of +either `--client-id` or `--oidc-extra-audience`. + +_In Keycloak, claims are added to JWT tokens through the use of mappers at either the realm level using "client scopes" or +through "dedicated" client mappers._ + +**Creating the client** + +1. Create a new OIDC client in your Keycloak realm by navigating to: + **Clients** -> **Create client** + * **Client Type** 'OpenID Connect' + * **Client ID** ``, please complete the remaining fields as appropriate and click **Next**. + * **Client authentication** 'On' + * **Authentication flow** + * **Standard flow** 'selected' + * **Direct access grants** 'deselect' + * _Save the configuration._ + * **Settings / Access settings**: + * **Valid redirect URIs** `https://internal.yourcompany.com/oauth2/callback` + * _Save the configuration._ + * Under the **Credentials** tab you will now be able to locate ``. +2. Configure a dedicated *audience mapper* for your client by navigating to **Clients** -> **\** -> **Client scopes**. +* Access the dedicated mappers pane by clicking **\-dedicated**, located under *Assigned client scope*. + _(It should have a description of "Dedicated scope and mappers for this client")_ + * Click **Configure a new mapper** and select **Audience** + * **Name** 'aud-mapper-\' + * **Included Client Audience** select `` from the dropdown. + * _OAuth2 proxy can be set up to pass both the access and ID JWT tokens to your upstream services. + If you require additional audience entries, you can use the **Included Custom Audience** field in addition + to the "Included Client Audience" dropdown. Note that the "aud" claim of a JWT token should be limited and + only specify its intended recipients._ + * **Add to ID token** 'On' + * **Add to access token** 'On' - [#1916](https://github.com/oauth2-proxy/oauth2-proxy/pull/1916) + * _Save the configuration._ +* Any subsequent dedicated client mappers can be defined by clicking **Dedicated scopes** -> **Add mapper** -> + **By configuration** -> *Select mapper* + +You should now be able to create a test user in Keycloak and get access to the OAuth2 Proxy instance, make sure to set +an email address matching `` and select _Email verified_. + +**Authorization** + +_OAuth2 Proxy will perform authorization by requiring a valid user, this authorization can be extended to take into +account a user's membership in Keycloak `groups`, `realm roles`, and `client roles` using the keycloak-oidc provider options +`--allowed-role` or `--allowed-group`_ + +**Roles** + +_A standard Keycloak installation comes with the required mappers for **realm roles** and **client roles** through the +pre-defined client scope "roles". This ensures that any roles assigned to a user are included in the `JWT` tokens when +using an OIDC client that has the "Full scope allowed" feature activated, the feature is enabled by default._ + +_Creating a realm role_ +* Navigate to **Realm roles** -> **Create role** + * **Role name**, *``* -> **save** + +_Creating a client role_ +* Navigate to **Clients** -> `` -> **Roles** -> **Create role** + * **Role name**, *``* -> **save** + + +_Assign a role to a user_ + +**Users** -> _Username_ -> **Role mapping** -> **Assign role** -> _filter by roles or clients and select_ -> **Assign**. + +Keycloak "realm roles" can be authorized using the `--allowed-role=` option, while "client roles" can be +evaluated using `--allowed-role=:`. + +You may limit the _realm roles_ included in the JWT tokens for any given client by navigating to: +**Clients** -> `` -> **Client scopes** -> _\-dedicated_ -> **Scope** +Disabling **Full scope allowed** activates the **Assign role** option, allowing you to select which roles, if assigned +to a user, will be included in the user's JWT tokens. This can be useful when a user has many associated roles, and you +want to reduce the size and impact of the JWT token. + + +**Groups** + +You may also do authorization on group memberships by using the OAuth2 Proxy option `--allowed-group`. +We will only do a brief description of creating the required _client scope_ **groups** and refer you to read the Keycloak +documentation. + +To summarize, the steps required to authorize Keycloak group membership with OAuth2 Proxy are as follows: + +* Create a new Client Scope with the name **groups** in Keycloak. + * Include a mapper of type **Group Membership**. + * Set the "Token Claim Name" to **groups** or customize by matching it to the `--oidc-groups-claim` option of OAuth2 Proxy. + * If the "Full group path" option is selected, you need to include a "/" separator in the group names defined in the + `--allowed-group` option of OAuth2 Proxy. Example: "/groupname" or "/groupname/child_group". + +After creating the _Client Scope_ named _groups_ you will need to attach it to your client. +**Clients** -> `` -> **Client scopes** -> **Add client scope** -> Select **groups** and choose Optional +and you should now have a client that maps group memberships into the JWT tokens so that Oauth2 Proxy may evaluate them. + +Create a group by navigating to **Groups** -> **Create group** and _add_ your test user as a member. + +The OAuth2 Proxy option `--allowed-group=/groupname` will now allow you to filter on group membership + +Keycloak also has the option of attaching roles to groups, please refer to the Keycloak documentation for more information. + +**Tip** + +To check if roles or groups are added to JWT tokens, you can preview a users token in the Keycloak console by following +these steps: **Clients** -> `` -> **Client scopes** -> **Evaluate**. +Select a _realm user_ and optional _scope parameters_ such as groups, and generate the JSON representation of an access +or id token to examine its contents. diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/linkedin.md b/docs/versioned_docs/version-7.14.x/configuration/providers/linkedin.md new file mode 100644 index 0000000000..7d26ec4334 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/linkedin.md @@ -0,0 +1,13 @@ +--- +id: linkedin +title: LinkedIn +--- + +For LinkedIn, the registration steps are: + +1. Create a new project: https://www.linkedin.com/secure/developer +2. In the OAuth User Agreement section: + - In default scope, select r_basicprofile and r_emailaddress. + - In "OAuth 2.0 Redirect URLs", enter `https://internal.yourcompany.com/oauth2/callback` +3. Fill in the remaining required fields and Save. +4. Take note of the **Consumer Key / API Key** and **Consumer Secret / Secret Key** diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/login_gov.md b/docs/versioned_docs/version-7.14.x/configuration/providers/login_gov.md new file mode 100644 index 0000000000..badbe48e69 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/login_gov.md @@ -0,0 +1,79 @@ +--- +id: login_gov +title: Login.gov +--- + +login.gov is an OIDC provider for the US Government. +If you are a US Government agency, you can contact the login.gov team through the contact information +that you can find on https://login.gov/developers/ and work with them to understand how to get login.gov +accounts for integration/test and production access. + +A developer guide is available here: https://developers.login.gov/, though this proxy handles everything +but the data you need to create to register your application in the login.gov dashboard. + +As a demo, we will assume that you are running your application that you want to secure locally on +http://localhost:3000/, that you will be starting your proxy up on http://localhost:4180/, and that +you have an agency integration account for testing. + +First, register your application in the dashboard. The important bits are: +* Identity protocol: make this `Openid connect` +* Issuer: do what they say for OpenID Connect. We will refer to this string as `${LOGINGOV_ISSUER}`. +* Public key: This is a self-signed certificate in .pem format generated from a 2048-bit RSA private key. + A quick way to do this is + `openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -nodes -subj '/C=US/ST=Washington/L=DC/O=GSA/OU=18F/CN=localhost'`. + The contents of the `key.pem` shall be referred to as `${OAUTH2_PROXY_JWT_KEY}`. +* Return to App URL: Make this be `http://localhost:4180/` +* Redirect URIs: Make this be `http://localhost:4180/oauth2/callback`. +* Attribute Bundle: Make sure that email is selected. + +Now start the proxy up with the following options: +``` +./oauth2-proxy -provider login.gov \ + -client-id=${LOGINGOV_ISSUER} \ + -redirect-url=http://localhost:4180/oauth2/callback \ + -oidc-issuer-url=https://idp.int.identitysandbox.gov/ \ + -cookie-secure=false \ + -email-domain=gsa.gov \ + -upstream=http://localhost:3000/ \ + -cookie-secret=somerandomstring12341234567890AB \ + -cookie-domain=localhost \ + -skip-provider-button=true \ + -pubjwk-url=https://idp.int.identitysandbox.gov/api/openid_connect/certs \ + -profile-url=https://idp.int.identitysandbox.gov/api/openid_connect/userinfo \ + -jwt-key="${OAUTH2_PROXY_JWT_KEY}" +``` +You can also set all these options with environment variables, for use in cloud/docker environments. +One tricky thing that you may encounter is that some cloud environments will pass in environment +variables in a docker env-file, which does not allow multiline variables like a PEM file. +If you encounter this, then you can create a `jwt_signing_key.pem` file in the top level +directory of the repo which contains the key in PEM format and then do your docker build. +The docker build process will copy that file into your image which you can then access by +setting the `OAUTH2_PROXY_JWT_KEY_FILE=/etc/ssl/private/jwt_signing_key.pem` +environment variable, or by setting `--jwt-key-file=/etc/ssl/private/jwt_signing_key.pem` on the commandline. + +Once it is running, you should be able to go to `http://localhost:4180/` in your browser, +get authenticated by the login.gov integration server, and then get proxied on to your +application running on `http://localhost:3000/`. In a real deployment, you would secure +your application with a firewall or something so that it was only accessible from the +proxy, and you would use real hostnames everywhere. + +#### Skip OIDC discovery + +Some providers do not support OIDC discovery via their issuer URL, so oauth2-proxy cannot simply grab the authorization, +token and jwks URI endpoints from the provider's metadata. + +In this case, you can set the `--skip-oidc-discovery` option, and supply those required endpoints manually: + +``` + -provider oidc + -client-id oauth2-proxy + -client-secret proxy + -redirect-url http://127.0.0.1:4180/oauth2/callback + -oidc-issuer-url http://127.0.0.1:5556 + -skip-oidc-discovery + -login-url http://127.0.0.1:5556/authorize + -redeem-url http://127.0.0.1:5556/token + -oidc-jwks-url http://127.0.0.1:5556/keys + -cookie-secure=false + -email-domain example.com +``` diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/ms_azure_ad.md b/docs/versioned_docs/version-7.14.x/configuration/providers/ms_azure_ad.md new file mode 100644 index 0000000000..4feefc6800 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/ms_azure_ad.md @@ -0,0 +1,59 @@ +--- +id: azure +title: Azure (Deprecated) +--- + +:::note +This is the legacy and deprecated provider for Azure, use [Microsoft Entra ID](ms_entra_id.md) if possible. +::: + +## Config Options + +| Flag | Toml Field | Type | Description | Default | +| ---------------- | -------------- | ------ | ---------------------------------------------------------------- | ---------- | +| `--azure-tenant` | `azure_tenant` | string | go to a tenant-specific or common (tenant-independent) endpoint. | `"common"` | +| `--resource` | `resource` | string | The resource that is protected (Azure AD only) | | + +## Usage + +1. Add an application: go to [https://portal.azure.com](https://portal.azure.com), choose **Azure Active Directory**, select + **App registrations** and then click on **New registration**. +2. Pick a name, check the supported account type(single-tenant, multi-tenant, etc). In the **Redirect URI** section create a new + **Web** platform entry for each app that you want to protect by the oauth2 proxy(e.g. + https://internal.yourcompanycom/oauth2/callback). Click **Register**. +3. Next we need to add group read permissions for the app registration, on the **API Permissions** page of the app, click on + **Add a permission**, select **Microsoft Graph**, then select **Application permissions**, then click on **Group** and select + **Group.Read.All**. Hit **Add permissions** and then on **Grant admin consent** (you might need an admin to do this). +
**IMPORTANT**: Even if this permission is listed with **"Admin consent required=No"** the consent might actually + be required, due to AAD policies you won't be able to see. If you get a **"Need admin approval"** during login, + most likely this is what you're missing! +4. Next, if you are planning to use v2.0 Azure Auth endpoint, go to the **Manifest** page and set `"accessTokenAcceptedVersion": 2` + in the App registration manifest file. +5. On the **Certificates & secrets** page of the app, add a new client secret and note down the value after hitting **Add**. +6. Configure the proxy with: +- for V1 Azure Auth endpoint (Azure Active Directory Endpoints - https://login.microsoftonline.com/common/oauth2/authorize) + +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://sts.windows.net/{tenant-id}/ +``` + +- for V2 Azure Auth endpoint (Microsoft Identity Platform Endpoints - https://login.microsoftonline.com/common/oauth2/v2.0/authorize) +``` + --provider=azure + --client-id= + --client-secret= + --azure-tenant={tenant-id} + --oidc-issuer-url=https://login.microsoftonline.com/{tenant-id}/v2.0 +``` + +***Notes***: +- When using v2.0 Azure Auth endpoint (`https://login.microsoftonline.com/{tenant-id}/v2.0`) as `--oidc_issuer_url`, in conjunction + with `--resource` flag, be sure to append `/.default` at the end of the resource name. See + https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#the-default-scope for more details. +- When using the Azure Auth provider with nginx and the cookie session store you may find the cookie is too large and doesn't + get passed through correctly. Increasing the proxy_buffer_size in nginx or implementing the + [redis session storage](../sessions.md#redis-storage) should resolve this. diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/ms_entra_id.md b/docs/versioned_docs/version-7.14.x/configuration/providers/ms_entra_id.md new file mode 100644 index 0000000000..95fb99bc60 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/ms_entra_id.md @@ -0,0 +1,197 @@ +--- +id: ms_entra_id +title: Microsoft Entra ID +--- + +Provider for Microsoft Entra ID. Fully compliant with OIDC, with support for group overage and multi-tenant apps. + +## Config Options + +The provider is OIDC-compliant, so all the OIDC parameters are honored. Additional provider-specific configuration parameters are: + +| Flag | Toml Field | Type | Description | Default | +| --------------------------- | -------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | +| `--entra-id-allowed-tenant` | `entra_id_allowed_tenants` | string \| list | List of allowed tenants. In case of multi-tenant apps, incoming tokens are issued by different issuers and OIDC issuer verification needs to be disabled. When not specified, all tenants are allowed. Redundant for single-tenant apps (regular ID token validation matches the issuer). | | +| `--entra-id-federated-token-auth` | `entra_id_federated_token_auth` | boolean | Enable oAuth2 client authentication with federated token projected by Entra Workload Identity plugin, instead of client secret. | false | + +## Configure App registration +To begin, create an App registration, set a redirect URI, and generate a secret. All account types are supported, including single-tenant, multi-tenant, multi-tenant with Microsoft accounts, and Microsoft accounts only. + +
+ See Azure Portal example +
+ +
+
+ +
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" # Others are also supported + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + // We don't specify any required API permissions - we allow user consent only + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Configure groups +If you want to make use of groups, you can configure *groups claim* to be present in ID Tokens issued by the App registration. +
+ See Azure Portal example +
+
+ +
+
+
+
+ See Terraform example +``` + resource "azuread_application" "auth" { + display_name = "oauth2-proxy" + sign_in_audience = "AzureADMyOrg" + + group_membership_claims = [ + "SecurityGroup" + ] + + web { + redirect_uris = [ + "https://podinfo.lakis.tech/oauth2/callback", + ] + } + } + + resource "azuread_service_principal" "sp" { + client_id = azuread_application.auth.client_id + app_role_assignment_required = false + } + + resource "azuread_service_principal_password" "pass" { + service_principal_id = azuread_service_principal.sp.id + } + +``` +
+ +### Scopes and claims +For single-tenant and multi-tenant apps without groups, the only required scope is `openid` (See: [Scopes and permissions](https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#the-openid-scope)). + +To make use of groups - for example use `allowed_groups` setting or authorize based on groups inside your service - you need to enable *groups claims* in the App Registration. When enabled, list of groups is present in the issued ID token. No additional scopes are required besides `openid`. This works up to 200 groups. + +When user has more than 200 group memberships, OAuth2-Proxy attempts to retrieve the complete list from Microsoft Graph API's [`transitiveMemberOf`](https://learn.microsoft.com/en-us/graph/api/user-list-transitivememberof). Endpoint requires `User.Read` scope (delegated permission). This permission can be by default consented by user during first login. Set scope to `openid User.Read` to request user consent. Without proper scope, user with 200+ groups will authenticate with 0 groups. See: [group overages](https://learn.microsoft.com/en-us/security/zero-trust/develop/configure-tokens-group-claims-app-roles#group-overages). + +Alternatively to user consent, both `openid` and `User.Read` permissions can be consented by admistrator. Then, user is not asked for consent on the first login, and group overage works with `openid` scope only. Admin consent can also be required for some tenants. It can be granted with [azuread_service_principal_delegated_permission_grant](https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/service_principal_delegated_permission_grant) terraform resource. + +For personal microsoft accounts, required scope is `openid profile email`. + +See: [Overview of permissions and consent in the Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview). + +### Multi-tenant apps +To authenticate apps from multiple tenants (including personal Microsoft accounts), set the common OIDC issuer url and disable verification: +```toml +oidc_issuer_url=https://login.microsoftonline.com/common/v2.0 +insecure_oidc_skip_issuer_verification=true +``` +`insecure_oidc_skip_issuer_verification` setting is required to disable following checks: +* Startup check for matching issuer URL returned from [discovery document](https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration) with `oidc_issuer_url` setting. Required, as document's `issuer` field doesn't equal to `https://login.microsoftonline.com/common/v2.0`. See [OIDC Discovery 4.3](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation). +* Matching ID token's `issuer` claim with `oidc_issuer_url` setting during ID token validation. Required to support tokens issued by different tenants. See [OIDC Core 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). + +To provide additional security, Entra ID provider performs check on the ID token's `issuer` claim to match the `https://login.microsoftonline.com/{tenant-id}/v2.0` template. + +### Workload Identity +Provider supports authentication with federated token, without need of using client secret. Following conditions have to be met: + +* Cluster has public OIDC provider URL. For major cloud providers, it can be enabled with a single flag, for example for [Azure Kubernetes Service deployed with Terraform](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster), it's `oidc_issuer_enabled`. +* Workload Identity admission webhook is deployed on the cluster. For AKS, it can be enabled with a flag (`workload_identity_enabled` in Terraform resource), for clusters outside of Azure, it can be installed from [helm chart](https://github.com/Azure/azure-workload-identity). +* Appropriate federated credential is added to application registration. +
+ See federated credential terraform example +``` + resource "azuread_application_federated_identity_credential" "fedcred" { + application_id = azuread_application.application.id # ID of your application + display_name = "federation-cred" + description = "Workload identity for oauth2-proxy" + audiences = ["api://AzureADTokenExchange"] # Fixed value + issuer = "https://cluster-oidc-issuer-url..." + subject = "system:serviceaccount:oauth2-proxy-namespace-name:oauth2-proxy-sa-name" # set proper NS and SA name + } +``` +
+ +* Kubernetes service account associated with oauth2-proxy deployment, is annotated with `azure.workload.identity/client-id: ` +* oauth2-proxy pod is labeled with `azure.workload.identity/use: "true"` +* oauth2-proxy is configured with `entra_id_federated_token_auth` set to `true`. + +`client_secret` setting can be omitted when using federated token authentication. + +See: [Azure Workload Identity documentation](https://azure.github.io/azure-workload-identity/docs/). + +### Example configurations +Single-tenant app without groups (*groups claim* not enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +``` + +Single-tenant app with up to 200 groups (*groups claim* enabled). Consider using generic OIDC provider: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid" +allowed_groups=["ac51800c-2679-4ecb-8130-636380a3b491"] +``` + +Single-tenant app with more than 200 groups: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +client_secret="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +``` + +Single-tenant app with more than 200 groups and workload identity enabled: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com//v2.0" +client_id="" +scope="openid User.Read" +allowed_groups=["968b4844-d5e7-4e18-a834-59927959369f"] +entra_id_federated_token_auth=true +``` + +Multi-tenant app with Microsoft personal accounts & one Entra tenant allowed, with group overage considered: +```toml +provider="entra-id" +oidc_issuer_url="https://login.microsoftonline.com/common/v2.0" +client_id="" +client_secret="" +insecure_oidc_skip_issuer_verification=true +scope="openid profile email User.Read" +entra_id_allowed_tenants=["9188040d-6c67-4c5b-b112-36a304b66dad",""] # Allow only and Personal MS Accounts tenant +email_domains="*" +``` diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/nextcloud.md b/docs/versioned_docs/version-7.14.x/configuration/providers/nextcloud.md new file mode 100644 index 0000000000..85ebff0398 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/nextcloud.md @@ -0,0 +1,28 @@ +--- +id: nextcloud +title: NextCloud +--- + +The Nextcloud provider allows you to authenticate against users in your +Nextcloud instance. + +When you are using the Nextcloud provider, you must specify the urls via +configuration, environment variable, or command line argument. Depending +on whether your Nextcloud instance is using pretty urls your urls may be of the +form `/index.php/apps/oauth2/*` or `/apps/oauth2/*`. + +Refer to the [OAuth2 +documentation](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/oauth2.html) +to set up the client id and client secret. Your "Redirection URI" will be +`https://internalapp.yourcompany.com/oauth2/callback`. + +``` + -provider nextcloud + -client-id + -client-secret + -login-url="/index.php/apps/oauth2/authorize" + -redeem-url="/index.php/apps/oauth2/api/v1/token" + -validate-url="/ocs/v2.php/cloud/user?format=json" +``` + +Note: in *all* cases the validate-url will *not* have the `index.php`. diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/openid_connect.md b/docs/versioned_docs/version-7.14.x/configuration/providers/openid_connect.md new file mode 100644 index 0000000000..de17005808 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/openid_connect.md @@ -0,0 +1,146 @@ +--- +id: openid_connect +title: OpenID Connect +--- + +OpenID Connect is a spec for OAUTH 2.0 + identity that is implemented by many major providers and several open source projects. + +This provider was originally built against CoreOS Dex, and we will use it as an example. +The OpenID Connect Provider (OIDC) can also be used to connect to other Identity Providers such as Okta, an example can be found below. + +#### Dex + +To configure the OIDC provider for Dex, perform the following steps: + +1. Download Dex: + + ``` + go get github.com/dexidp/dex + ``` + + See the [getting started guide](https://dexidp.io/docs/getting-started/) for more details. + +2. Setup oauth2-proxy with the correct provider and using the default ports and callbacks. Add a configuration block to + the `staticClients` section of `examples/config-dev.yaml`: + + ``` + - id: oauth2-proxy + redirectURIs: + - 'http://127.0.0.1:4180/oauth2/callback' + name: 'oauth2-proxy' + secret: proxy + ``` + +3. Launch Dex: from `$GOPATH/github.com/dexidp/dex`, run: + + ``` + bin/dex serve examples/config-dev.yaml + ``` + +4. In a second terminal, run the oauth2-proxy with the following args: + + ```shell + --provider oidc + --provider-display-name "My OIDC Provider" + --client-id oauth2-proxy + --client-secret proxy + --redirect-url http://127.0.0.1:4180/oauth2/callback + --oidc-issuer-url http://127.0.0.1:5556/dex + --cookie-secure=false + --cookie-secret=secret + --email-domain kilgore.trout + ``` + + To serve the current working directory as a website under the `/static` endpoint, add: + + ```shell + --upstream file://$PWD/#/static/ + ``` + +5. Test the setup by visiting http://127.0.0.1:4180 or http://127.0.0.1:4180/static . + +See also [our local testing environment](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/contrib/local-environment) for a self-contained example using Docker and etcd as storage for Dex. + +#### Okta + +To configure the OIDC provider for Okta, perform the following steps: + +1. Log in to Okta using an administrative account. It is suggested you try this in preview first, `example.oktapreview.com` +2. (OPTIONAL) If you want to configure authorization scopes and claims to be passed on to multiple applications, + you may wish to configure an authorization server for each application. Otherwise, the provided `default` will work. + * Navigate to **Security** then select **API** + * Click **Add Authorization Server**, if this option is not available you may require an additional license for a custom + authorization server. + * Fill out the **Name** with something to describe the application you are protecting. e.g. 'Example App'. + * For **Audience**, pick the URL of the application you wish to protect: https://example.corp.com + * Fill out a **Description** + * Add any **Access Policies** you wish to configure to limit application access. + * The default settings will work for other options. + [See Okta documentation for more information on Authorization Servers](https://developer.okta.com/docs/guides/customize-authz-server/overview/) +3. Navigate to **Applications** then select **Add Application**. + * Select **Web** for the **Platform** setting. + * Select **OpenID Connect** and click **Create** + * Pick an **Application Name** such as `Example App`. + * Set the **Login redirect URI** to `https://example.corp.com`. + * Under **General** set the **Allowed grant types** to `Authorization Code` and `Refresh Token`. + * Leave the rest as default, taking note of the `Client ID` and `Client Secret`. + * Under **Assignments** select the users or groups you wish to access your application. +4. Create a configuration file like the following: + + ``` + provider = "oidc" + redirect_url = "https://example.corp.com/oauth2/callback" + oidc_issuer_url = "https://corp.okta.com/oauth2/abCd1234" + upstreams = [ + "https://example.corp.com" + ] + email_domains = [ + "corp.com" + ] + client_id = "XXXXX" + client_secret = "YYYYY" + pass_access_token = true + cookie_secret = "ZZZZZ" + skip_provider_button = true + ``` + +The `oidc_issuer_url` is based on URL from your **Authorization Server**'s **Issuer** field in step 2, or simply +https://corp.okta.com. The `client_id` and `client_secret` are configured in the application settings. +Generate a unique `cookie_secret` to encrypt the cookie. + +Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/example.cfg` + +#### Okta - localhost + +1. Signup for developer account: https://developer.okta.com/signup/ +2. Create New `Web` Application: https://$\{your-okta-domain\}/dev/console/apps/new +3. Example Application Settings for localhost: + * **Name:** My Web App + * **Base URIs:** http://localhost:4180/ + * **Login redirect URIs:** http://localhost:4180/oauth2/callback + * **Logout redirect URIs:** http://localhost:4180/ + * **Group assignments:** `Everyone` + * **Grant type allowed:** `Authorization Code` and `Refresh Token` +4. Make note of the `Client ID` and `Client secret`, they are needed in a future step +5. Make note of the **default** Authorization Server Issuer URI from: https://$\{your-okta-domain\}/admin/oauth2/as +6. Example config file `/etc/localhost.cfg` + ```shell + provider = "oidc" + redirect_url = "http://localhost:4180/oauth2/callback" + oidc_issuer_url = "https://$\{your-okta-domain\}/oauth2/default" + upstreams = [ + "http://0.0.0.0:8080" + ] + email_domains = [ + "*" + ] + client_id = "XXX" + client_secret = "YYY" + pass_access_token = true + cookie_secret = "ZZZ" + cookie_secure = false + skip_provider_button = true + # Note: use the following for testing within a container + # http_address = "0.0.0.0:4180" + ``` +7. Then you can start the oauth2-proxy with `./oauth2-proxy --config /etc/localhost.cfg` diff --git a/docs/versioned_docs/version-7.14.x/configuration/providers/sourcehut.md b/docs/versioned_docs/version-7.14.x/configuration/providers/sourcehut.md new file mode 100644 index 0000000000..2c196bda4e --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/providers/sourcehut.md @@ -0,0 +1,25 @@ +--- +id: sourcehut +title: SourceHut +--- + +1. Create a new OAuth client: https://meta.sr.ht/oauth2 +2. Under `Redirection URI` enter the correct URL, i.e. + `https://internal.yourcompany.com/oauth2/callback` + +To use the provider, start with `--provider=sourcehut`. + +If you are hosting your own SourceHut instance, make sure you set the following +to the appropriate URLs: + +```shell + --login-url="https:///oauth2/authorize" + --redeem-url="https:///oauth2/access-token" + --profile-url="https:///query" + --validate-url="https:///profile" +``` + +The default configuration allows everyone with an account to authenticate. +Restricting access is currently only supported by +[email](index.md#email-authentication). + diff --git a/docs/versioned_docs/version-7.14.x/configuration/sessions.md b/docs/versioned_docs/version-7.14.x/configuration/sessions.md new file mode 100644 index 0000000000..e20378170a --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/sessions.md @@ -0,0 +1,99 @@ +--- +id: session_storage +title: Session Storage +--- + +Sessions allow a user's authentication to be tracked between multiple HTTP +requests to a service. + +The OAuth2 Proxy uses a Cookie to track user sessions and will store the session +data in one of the available session storage backends. + +At present the available backends are (as passed to `--session-store-type`): +- [cookie](#cookie-storage) (default) +- [redis](#redis-storage) + +### Cookie Storage + +The Cookie storage backend is the default backend implementation and has +been used in the OAuth2 Proxy historically. + +With the Cookie storage backend, all session information is stored in client +side cookies and transferred with each and every request. + +The following should be known when using this implementation: +- Since all state is stored client side, this storage backend means that the OAuth2 Proxy is completely stateless +- Cookies are signed server side to prevent modification client-side +- It is mandatory to set a `cookie-secret` which will ensure data is encrypted within the cookie data. +- Since multiple requests can be made concurrently to the OAuth2 Proxy, this session implementation +cannot lock sessions and while updating and refreshing sessions, there can be conflicts which force +users to re-authenticate + + +### Redis Storage + +The Redis Storage backend stores encrypted sessions in redis. Instead of sending all the information +back the client for storage, as in the [Cookie storage](#cookie-storage), a ticket is sent back +to the user as the cookie value instead. + +A ticket is composed as the following: + +`{CookieName}-{ticketID}.{secret}` + +Where: + +- The `CookieName` is the OAuth2 cookie name (_oauth2_proxy by default) +- The `ticketID` is a 128-bit random number, hex-encoded +- The `secret` is a 128-bit random number, base64url encoded (no padding). The secret is unique for every session. +- The pair of `{CookieName}-{ticketID}` comprises a ticket handle, and thus, the redis key +to which the session is stored. The encoded session is encrypted with the secret and stored +in redis via the `SETEX` command. + +Encrypting every session uniquely protects the refresh/access/id tokens stored in the session from +disclosure. Additionally, the browser only has to send a short Cookie with every request and not the whole JWT, +which can get quite big. + +Two settings are used to configure the OAuth2 Proxy cookie lifetime: + + --cookie-refresh duration refresh the cookie after this duration; 0 to disable + --cookie-expire duration expire timeframe for cookie 168h0m0s + +The "cookie-expire" value should be equal to the lifetime of the Refresh-Token that is issued by the OAuth2 authorization server. +If it expires earlier and is deleted by the browser, OAuth2 Proxy cannot find the stored Refresh-Tokens in Redis and thus cannot start +the refresh flow to get a new Access-Token. If it is longer, it might be that the old Refresh-Token will be found in Redis but has already +expired. + +The "cookie-refresh" value controls when OAuth2 Proxy tries to refresh an Access-Token. If it is set to "0", the +Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2-Proxy will +refresh the Access-Token after this many seconds whether it is still valid or not. According to the official OAuth2.0 specification +Access-Tokens are not required to follow a specific format. Therefore OAuth2-Proxy cannot check for any expiry date without an +introspection endpoint. If an Access-Token expires and you have not set a corresponding "cookie-refresh" value, you will likely +encounter expiry issues. + +Caveat: It can happen that the Access-Token is valid for e.g. "1m" and a request happens after exactly "59s". +It would pass OAuth2 Proxy and be forwarded to the backend but is just expired when the backend tries to validate +it. This is especially relevant if the backend uses the JWT to make requests to other backends. +For this reason, it's advised to set the cookie-refresh a couple of seconds less than the Access-Token lifespan. + +Recommended settings: + +* cookie_refresh := Access-Token lifespan - 1m +* cookie_expire := Refresh-Token lifespan (i.e. Keycloak client_session_idle) + +#### Usage + +When using the redis store, specify `--session-store-type=redis` as well as the Redis connection URL, via +`--redis-connection-url=redis://host[:port][/db-number]`. + +You may also configure the store for Redis Sentinel. In this case, you will want to use the +`--redis-use-sentinel=true` flag, as well as configure the flags `--redis-sentinel-master-name` +and `--redis-sentinel-connection-urls` appropriately. + +Redis Cluster is available to be the backend store as well. To leverage it, you will need to set the +`--redis-use-cluster=true` flag, and configure the flags `--redis-cluster-connection-urls` appropriately. + +Note that flags `--redis-use-sentinel=true` and `--redis-use-cluster=true` are mutually exclusive. + +Note, if Redis timeout option is set to non-zero, the `--redis-connection-idle-timeout` +must be less than [Redis timeout option](https://redis.io/docs/reference/clients/#client-timeouts). For example: if either redis.conf includes +`timeout 15` or using `CONFIG SET timeout 15` the `--redis-connection-idle-timeout` must be at least `--redis-connection-idle-timeout=14` diff --git a/docs/versioned_docs/version-7.14.x/configuration/systemd_socket.md b/docs/versioned_docs/version-7.14.x/configuration/systemd_socket.md new file mode 100644 index 0000000000..642e6f3f7b --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/systemd_socket.md @@ -0,0 +1,43 @@ +--- +id: systemd_socket +title: Systemd Socket Activation +--- + +Pass an existing listener created by systemd.socket to oauth2-proxy. + +To do this create a socket: + +oauth2-proxy.socket +``` +[Socket] +ListenStream=%t/oauth2.sock +SocketGroup=www-data +SocketMode=0660 +``` + +Now it's possible to call this socket from e.g. nginx: +``` +server { + location /oauth2/ { + proxy_pass http://unix:/run/oauth2-proxy/oauth2.sock; +} +``` + +The oauth2-proxy should have `--http-address=fd:3` as a parameter. +Here fd is case insensitive and means file descriptor. The number 3 refers to the first non-stdin/stdout/stderr file descriptor, +systemd-socket-activate (which is what systemd.socket uses), listens to what it is told and passes +the listener it created onto the process, starting with file descriptor 3. + +``` +./oauth2-proxy \ + --http-address="fd:3" \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... +``` + +Currently TLS is not supported (but it's doable). diff --git a/docs/versioned_docs/version-7.14.x/configuration/tls.md b/docs/versioned_docs/version-7.14.x/configuration/tls.md new file mode 100644 index 0000000000..68344b22d5 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/tls.md @@ -0,0 +1,85 @@ +--- +id: tls +title: TLS Configuration +--- + +There are two recommended configurations: +- [At OAuth2 Proxy](#terminate-tls-at-oauth2-proxy) +- [At Reverse Proxy](#terminate-tls-at-reverse-proxy-eg-nginx) + +### Terminate TLS at OAuth2 Proxy + +1. Configure SSL Termination with OAuth2 Proxy by providing a `--tls-cert-file=/path/to/cert.pem` and `--tls-key-file=/path/to/cert.key`. + + The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --tls-cert-file=/path/to/cert.pem \ + --tls-key-file=/path/to/cert.key \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --client-id=... \ + --client-secret=... + ``` + +2. With this configuration approach the customization of the TLS settings is limited. + + The minimal acceptable TLS version can be set with `--tls-min-version=TLS1.3`. + The defaults set `TLS1.2` as the minimal version. + Regardless of the minimum version configured, `TLS1.3` is currently always used as the maximal version. + + TLS server side cipher suites can be specified with `--tls-cipher-suite=TLS_RSA_WITH_RC4_128_SHA`. + If not specified, the defaults from [`crypto/tls`](https://pkg.go.dev/crypto/tls#CipherSuites) of the currently used `go` version for building `oauth2-proxy` will be used. + A complete list of valid TLS cipher suite names can be found in [`crypto/tls`](https://pkg.go.dev/crypto/tls#pkg-constants). + +### Terminate TLS at Reverse Proxy, e.g. Nginx + +1. Configure SSL Termination with [Nginx](http://nginx.org/) (example config below), Amazon ELB, Google Cloud Platform Load Balancing, or ... + + Because `oauth2-proxy` listens on `127.0.0.1:4180` by default, to listen on all interfaces (needed when using an + external load balancer like Amazon ELB or Google Platform Load Balancing) use `--http-address="0.0.0.0:4180"` or + `--http-address="http://:4180"`. + + Nginx will listen on port `443` and handle SSL connections while proxying to `oauth2-proxy` on port `4180`. + `oauth2-proxy` will then authenticate requests for an upstream application. The external endpoint for this example + would be `https://internal.yourcompany.com/`. + + An example Nginx config follows. Note the use of `Strict-Transport-Security` header to pin requests to SSL + via [HSTS](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security): + + ``` + server { + listen 443 default ssl; + server_name internal.yourcompany.com; + ssl_certificate /path/to/cert.pem; + ssl_certificate_key /path/to/cert.key; + add_header Strict-Transport-Security max-age=2592000; + + location / { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_connect_timeout 1; + proxy_send_timeout 30; + proxy_read_timeout 30; + } + } + ``` + +2. The command line to run `oauth2-proxy` in this configuration would look like this: + + ```bash + ./oauth2-proxy \ + --email-domain="yourcompany.com" \ + --upstream=http://127.0.0.1:8080/ \ + --cookie-secret=... \ + --cookie-secure=true \ + --provider=... \ + --reverse-proxy=true \ + --client-id=... \ + --client-secret=... + ``` diff --git a/docs/versioned_docs/version-7.14.x/features/endpoints.md b/docs/versioned_docs/version-7.14.x/features/endpoints.md new file mode 100644 index 0000000000..db00ba1e0b --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/features/endpoints.md @@ -0,0 +1,59 @@ +--- +id: endpoints +title: Endpoints +--- + +OAuth2 Proxy responds directly to the following endpoints. All other endpoints will be proxied upstream when authenticated. The `/oauth2` prefix can be changed with the `--proxy-prefix` config variable. + +- / - the proxy endpoint provides authentication and returns the appropriate 40x error if not authenticated or authorized then passes the request upstream. +- /robots.txt - returns a 200 OK response that disallows all User-agents from all paths; see [robotstxt.org](http://www.robotstxt.org/) for more info +- /ping - returns a 200 OK response, which is intended for use with health checks +- /ready - returns a 200 OK response if all the underlying connections (e.g., Redis store) are connected +- /metrics - Metrics endpoint for Prometheus to scrape, serve on the address specified by `--metrics-address`, disabled by default +- /oauth2/sign_in - the login page, which also doubles as a sign-out page (it clears cookies) +- /oauth2/sign_out - this URL is used to clear the session cookie +- /oauth2/start - a URL that will redirect to start the OAuth cycle +- /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url. +- /oauth2/userinfo - the URL is used to return user's email from the session in JSON format. +- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integration#configuring-for-use-with-the-nginx-auth_request-directive) +- /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages + +### Sign out + +To sign the user out, redirect them to `/oauth2/sign_out`. This endpoint only removes oauth2-proxy's own cookies, i.e. the user is still logged in with the authentication provider and may automatically re-login when accessing the application again. You will also need to redirect the user to the authentication provider's sign-out page afterward using the `rd` query parameter, i.e. redirect the user to something like (notice the url-encoding!): + +``` +/oauth2/sign_out?rd=https%3A%2F%2Fmy-oidc-provider.example.com%2Fsign_out_page +``` + +Alternatively, include the redirect URL in the `X-Auth-Request-Redirect` header: + +``` +GET /oauth2/sign_out HTTP/1.1 +X-Auth-Request-Redirect: https://my-oidc-provider/sign_out_page +... +``` + +(The "sign_out_page" should be the [`end_session_endpoint`](https://openid.net/specs/openid-connect-session-1_0.html#rfc.section.2.1) from [the metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) if your OIDC provider supports Session Management and Discovery.) + +BEWARE that the domain you want to redirect to (`my-oidc-provider.example.com` in the example) must be added to the [`--whitelist-domain`](../configuration/overview) configuration option otherwise the redirect will be ignored. Make sure to include the actual domain and port (if needed) and not the URL (e.g "localhost:8081" instead of "http://localhost:8081"). + +### Auth + +This endpoint returns 202 Accepted response or a 401 Unauthorized response. + +It can be configured using the following query parameters: +- `allowed_groups`: comma separated list of allowed groups +- `allowed_email_domains`: comma separated list of allowed email domains +- `allowed_emails`: comma separated list of allowed emails + +### Proxy (/) + +This endpoint returns the upstream response if authenticated. +If unauthenticated it returns a 401 Unauthorized. If the authenticatd user +is not in one of the allowed groups, or emails then it returns a 403 forbidden + +It can be configured using the following query parameters: +- `allowed_groups`: comma separated list of allowed groups +- `allowed_email_domains`: comma separated list of allowed email domains +- `allowed_emails`: comma separated list of allowed emails diff --git a/docs/versioned_docs/version-7.14.x/installation.md b/docs/versioned_docs/version-7.14.x/installation.md new file mode 100644 index 0000000000..20a6561471 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/installation.md @@ -0,0 +1,32 @@ +--- +id: installation +title: Installation +--- + +1. Choose how to deploy: + + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.13.0`) + + b. Using Go to install the latest release + ```bash + $ go install github.com/oauth2-proxy/oauth2-proxy/v7@latest + ``` + This will install the binary into `$GOPATH/bin`. Make sure you include `$GOPATH` in your `$PATH`. Otherwise your system won't find binaries installed via `go install` + + c. Using a [Prebuilt Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy) (AMD64, PPC64LE, S390x, ARMv6, ARMv7, and ARM64 available) + + d. Using a [Pre-Release Nightly Docker Image](https://quay.io/oauth2-proxy/oauth2-proxy-nightly) (AMD64, PPC64LE, ARMv6, ARMv7, and ARM64 available) + + e. Using the official [Kubernetes manifest](https://github.com/oauth2-proxy/manifests) (Helm) + + Prebuilt binaries can be validated by extracting the file and verifying it against the `sha256sum.txt` checksum file provided for each release starting with version `v3.0.0`. + + ``` + $ sha256sum -c sha256sum.txt + oauth2-proxy-x.y.z.linux-amd64: OK + ``` + +2. [Select a Provider and Register an OAuth Application with a Provider](configuration/providers/index.md) +3. [Configure OAuth2 Proxy using config file, command line options, or environment variables](configuration/overview.md) +4. [Configure SSL or Deploy behind an SSL endpoint](configuration/tls.md) (example provided for Nginx) +5. [Configure OAuth2 Proxy using systemd.socket](configuration/systemd_socket.md) (example provided for Nginx/Systemd) diff --git a/docs/versioned_docs/version-7.14.x/welcome.md b/docs/versioned_docs/version-7.14.x/welcome.md new file mode 100644 index 0000000000..7bceadd80e --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/welcome.md @@ -0,0 +1,23 @@ +--- +id: welcome +title: Welcome +hide_table_of_contents: true +slug: / +--- + +![OAuth2 Proxy](/img/logos/OAuth2_Proxy_horizontal.svg) + +A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others) +to validate accounts by email, domain or group. + +:::note +This repository was forked from [bitly/OAuth2_Proxy](https://github.com/bitly/oauth2_proxy) on 27/11/2018. +Versions v3.0.0 and up are from this fork and will have diverged from any changes in the original fork. +A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/CHANGELOG.md). +::: + +![Sign In Page](/img/sign-in-page.png) + +## Architecture + +![OAuth2 Proxy Architecture](/img/simplified-architecture.svg) diff --git a/docs/versioned_sidebars/version-7.14.x-sidebars.json b/docs/versioned_sidebars/version-7.14.x-sidebars.json new file mode 100644 index 0000000000..debf449177 --- /dev/null +++ b/docs/versioned_sidebars/version-7.14.x-sidebars.json @@ -0,0 +1,86 @@ +{ + "docs": [ + { + "type": "doc", + "id": "welcome" + }, + { + "type": "doc", + "id": "installation" + }, + { + "type": "doc", + "id": "behaviour" + }, + { + "type": "category", + "label": "Configuration", + "link": { + "type": "doc", + "id": "configuration/overview" + }, + "collapsed": false, + "items": [ + "configuration/overview", + "configuration/integration", + { + "type": "category", + "label": "OAuth Provider Configuration", + "link": { + "type": "doc", + "id": "configuration/providers/index" + }, + "items": [ + "configuration/providers/adfs", + "configuration/providers/azure", + "configuration/providers/bitbucket", + "configuration/providers/cidaas", + "configuration/providers/cisco_duo", + "configuration/providers/digitalocean", + "configuration/providers/facebook", + "configuration/providers/gitea", + "configuration/providers/github", + "configuration/providers/gitlab", + "configuration/providers/google", + "configuration/providers/keycloak", + "configuration/providers/keycloak_oidc", + "configuration/providers/linkedin", + "configuration/providers/login_gov", + "configuration/providers/ms_entra_id", + "configuration/providers/nextcloud", + "configuration/providers/openid_connect", + "configuration/providers/sourcehut" + ] + }, + "configuration/session_storage", + "configuration/tls", + "configuration/alpha-config" + ] + }, + { + "type": "category", + "label": "Features", + "link": { + "type": "doc", + "id": "features/endpoints" + }, + "collapsed": false, + "items": [ + "features/endpoints" + ] + }, + { + "type": "category", + "label": "Community", + "link": { + "type": "doc", + "id": "community/security" + }, + "collapsed": false, + "items": [ + "community/contribution", + "community/security" + ] + } + ] +} diff --git a/docs/versions.json b/docs/versions.json index 0d7ef6967f..8e8acf79f4 100644 --- a/docs/versions.json +++ b/docs/versions.json @@ -1,4 +1,5 @@ [ + "7.14.x", "7.13.x", "7.12.x", "7.11.x", From 3124bf7bda73a7fd3e0e25b1d75da601a1c82d0c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 15 Jan 2026 09:41:40 +0000 Subject: [PATCH 107/125] update to release version v7.14.0 --- CHANGELOG.md | 10 ++++++++++ .../local-environment/docker-compose-alpha-config.yaml | 2 +- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-keycloak.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/installation.md | 2 +- docs/versioned_docs/version-7.14.x/installation.md | 2 +- 9 files changed, 18 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d0a800f11e..9b604c1589 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,16 @@ ## Breaking Changes +## Changes since v7.14.0 + +# V7.14.0 + +## Release Highlights + +## Important Notes + +## Breaking Changes + ## Changes since v7.13.0 - [#3290](https://github.com/oauth2-proxy/oauth2-proxy/pull/3290) fix: WebSocket proxy to respect PassHostHeader setting (@UnsignedLong) diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index e524933ebc..5a13a9d535 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -14,7 +14,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index ea908106f6..f0bf246ccd 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index 3aa138973f..f3fd010783 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index f7dcb4d1a2..51d23b5892 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,7 +22,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 1399d829aa..fa2d490ec8 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index 631249abbf..ceb7da7861 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.13.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/installation.md b/docs/docs/installation.md index 20a6561471..09ad131140 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.13.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.0`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.14.x/installation.md b/docs/versioned_docs/version-7.14.x/installation.md index 20a6561471..09ad131140 100644 --- a/docs/versioned_docs/version-7.14.x/installation.md +++ b/docs/versioned_docs/version-7.14.x/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.13.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.0`) b. Using Go to install the latest release ```bash From 34c2712c99f0aef23240a276e9f7f6775269689f Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Thu, 15 Jan 2026 11:46:19 +0100 Subject: [PATCH 108/125] doc: add changelog and migration guide for v7.14.0 alpha config changes Signed-off-by: Jan Larwig --- CHANGELOG.md | 47 +++++++++- docs/docs/configuration/alpha_config.md | 91 +++++++++++++++++-- docs/docs/configuration/alpha_config.md.tmpl | 91 +++++++++++++++++-- .../configuration/alpha_config.md | 91 +++++++++++++++++-- .../configuration/alpha_config.md.tmpl | 91 +++++++++++++++++-- 5 files changed, 386 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b604c1589..332d1560d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,18 +12,63 @@ ## Release Highlights +- 🕵️‍♀️ Vulnerabilities have been addressed + - [CVE-2025-61729](https://access.redhat.com/security/cve/cve-2025-61729) + - [CVE-2025-61727](https://access.redhat.com/security/cve/cve-2025-61727) + - [CVE-2025-47914](https://access.redhat.com/security/cve/cve-2025-47914) + - [CVE-2025-58181](https://access.redhat.com/security/cve/cve-2025-58181) +- 🗂️ Alpha Config YAML parsing revamped using mapstructure with custom decoders +- 🐛 Squashed some bugs + ## Important Notes +This release introduces a breaking change for Alpha Config users and moves us significantly +closer to removing legacy configuration parameters, making the codebase of OAuth2 Proxy more +future proof and extensible. + +From v7.14.0 onward, header injection sources must be explicitly nested. If you +previously relied on squashed fields, update to the new structure before upgrading: + +```yaml +# before v7.14.0 +injectRequestHeaders: +- name: X-Forwarded-User + values: + - claim: user +- name: X-Custom-Secret-header + values: + - value: my-super-secret + +# v7.14.0 and later +injectRequestHeaders: +- name: X-Forwarded-User + values: + - claimSource: + claim: user +- name: X-Custom-Secret-header + values: + - secretSource: + value: my-super-secret +``` + +We are committed to Semantic Versioning and usually avoid breaking changes without a major version release. +Advancing Alpha Config toward its Beta stage required this exception, and even for the Alpha Config we try +to keep breaking changes in v7 to a minium. Thank you for understanding the need for this step to prepare +the project for future maintainability and future improvements like structured logging. + ## Breaking Changes +- Alpha Config: header injection no longer supports squashed claim/secret sources; they must now be set explicitly (see example above). + ## Changes since v7.13.0 -- [#3290](https://github.com/oauth2-proxy/oauth2-proxy/pull/3290) fix: WebSocket proxy to respect PassHostHeader setting (@UnsignedLong) +- [#2628](https://github.com/oauth2-proxy/oauth2-proxy/pull/2628) feat(structured config): revamp of yaml parsing using mapstructure decoder and custom decoders (@tuunit) - [#3197](https://github.com/oauth2-proxy/oauth2-proxy/pull/3197) fix: NewRemoteKeySet is not using DefaultHTTPClient (@rsrdesarrollo / @tuunit) - [#3292](https://github.com/oauth2-proxy/oauth2-proxy/pull/3292) chore(deps): upgrade gomod and bump to golang v1.25.5 (@tuunit) - [#3304](https://github.com/oauth2-proxy/oauth2-proxy/pull/3304) fix: added conditional so default is not always set and env vars are honored fixes 3303 (@pixeldrew) - [#3264](https://github.com/oauth2-proxy/oauth2-proxy/pull/3264) fix: more aggressively truncate logged access_token (@MartinNowak / @tuunit) - [#3267](https://github.com/oauth2-proxy/oauth2-proxy/pull/3267) fix: Session refresh handling in OIDC provider (@gysel) +- [#3290](https://github.com/oauth2-proxy/oauth2-proxy/pull/3290) fix: WebSocket proxy to respect PassHostHeader setting (@UnsignedLong) # V7.13.0 diff --git a/docs/docs/configuration/alpha_config.md b/docs/docs/configuration/alpha_config.md index 495bc20691..b4a7558246 100644 --- a/docs/docs/configuration/alpha_config.md +++ b/docs/docs/configuration/alpha_config.md @@ -24,17 +24,56 @@ When using alpha configuration, your config file will look something like below: upstreams: - id: ... ...: ... -injectRequestHeaders: - - name: ... +providers: + - id: ... ...: ... +cookie: + secret: ... + ...: ... +injectRequestHeaders: + - secretSource: + ...: ... injectResponseHeaders: - - name: ... - ...: ... + - claimSource: + ...: ... ``` Please browse the [reference](#configuration-reference) below for the structure of the new configuration format. +# Migration Guide + +This section details breaking changes and migration steps for moving to the new +alpha configuration format. + +## Migrating header injections in v7.14.0 + +From v7.14.0 onward, header injection sources must be explicitly nested. If you +previously relied on squashed fields, update to the new structure before +upgrading: + +```yaml +# before v7.14.0 +injectRequestHeaders: +- name: X-Forwarded-User + values: + - claim: user +- name: X-Custom-Secret-header + values: + - value: my-super-secret + +# v7.14.0 and later +injectRequestHeaders: +- name: X-Forwarded-User + values: + - claimSource: + claim: user +- name: X-Custom-Secret-header + values: + - secretSource: + value: my-super-secret +``` + ## Using Alpha Configuration To use the new **alpha** configuration, generate a YAML file based on the format @@ -67,9 +106,9 @@ the new config. oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg ``` -## Using ENV variables in the alpha configuration +### How to use environment variables -The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +The alpha package supports the use of environment variables in place of yaml values, allowing sensitive data to be pulled from somewhere other than the yaml file. When using environment variables, your yaml will look like this: ```yaml @@ -81,6 +120,46 @@ When using environment variables, your yaml will look like this: Where CLIENT_SECRET is an environment variable. More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) +### How to inject custom headers + +Configure `injectRequestHeaders` and `injectResponseHeaders` in alpha config YAML. + +```yaml +injectRequestHeaders: + - name: "X-User-Email" + values: + - claimSource: + claim: "email" # extract the email claim contents from the id token + - name: "X-Static-Secret" + values: + # secrets need to be encoded with base64 when directly in the yaml config but will be send decoded + - secretSource: + value: "c3VwZXItc2VjcmV0" + - name: "X-Static-File-Secret" + - secretSource: + fromFile: "/path/to/my/secret" + - name: "X-Static-Env-Secret" + - secretSource: + value: "${MY_SECRET_ENV}" # content still needs to be base64 encoded +injectResponseHeaders: + # Following will result in a header "Authorization: Basic (encoded)" + - name: "Authorization" + values: + - claimSource: + claim: user + prefix: "Basic " + basicAuthPassword: + value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk # base64 encoded password +``` + +**Value sources:** +* `claimSource` - `claim` (session claims either from id token or from profile URL) +* `secretSource` - `value` (base64), `fromFile` (file path) + +**Request option:** `preserveRequestValue: true` retains existing header values + +**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest` + ## Removed options The following flags/options and their respective environment variables are no diff --git a/docs/docs/configuration/alpha_config.md.tmpl b/docs/docs/configuration/alpha_config.md.tmpl index 8258201f2a..081657c4ac 100644 --- a/docs/docs/configuration/alpha_config.md.tmpl +++ b/docs/docs/configuration/alpha_config.md.tmpl @@ -24,17 +24,56 @@ When using alpha configuration, your config file will look something like below: upstreams: - id: ... ...: ... -injectRequestHeaders: - - name: ... +providers: + - id: ... ...: ... +cookie: + secret: ... + ...: ... +injectRequestHeaders: + - secretSource: + ...: ... injectResponseHeaders: - - name: ... - ...: ... + - claimSource: + ...: ... ``` Please browse the [reference](#configuration-reference) below for the structure of the new configuration format. +# Migration Guide + +This section details breaking changes and migration steps for moving to the new +alpha configuration format. + +## Migrating header injections in v7.14.0 + +From v7.14.0 onward, header injection sources must be explicitly nested. If you +previously relied on squashed fields, update to the new structure before +upgrading: + +```yaml +# before v7.14.0 +injectRequestHeaders: +- name: X-Forwarded-User + values: + - claim: user +- name: X-Custom-Secret-header + values: + - value: my-super-secret + +# v7.14.0 and later +injectRequestHeaders: +- name: X-Forwarded-User + values: + - claimSource: + claim: user +- name: X-Custom-Secret-header + values: + - secretSource: + value: my-super-secret +``` + ## Using Alpha Configuration To use the new **alpha** configuration, generate a YAML file based on the format @@ -67,9 +106,9 @@ the new config. oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg ``` -## Using ENV variables in the alpha configuration +### How to use environment variables -The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +The alpha package supports the use of environment variables in place of yaml values, allowing sensitive data to be pulled from somewhere other than the yaml file. When using environment variables, your yaml will look like this: ```yaml @@ -81,6 +120,46 @@ When using environment variables, your yaml will look like this: Where CLIENT_SECRET is an environment variable. More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) +### How to inject custom headers + +Configure `injectRequestHeaders` and `injectResponseHeaders` in alpha config YAML. + +```yaml +injectRequestHeaders: + - name: "X-User-Email" + values: + - claimSource: + claim: "email" # extract the email claim contents from the id token + - name: "X-Static-Secret" + values: + # secrets need to be encoded with base64 when directly in the yaml config but will be send decoded + - secretSource: + value: "c3VwZXItc2VjcmV0" + - name: "X-Static-File-Secret" + - secretSource: + fromFile: "/path/to/my/secret" + - name: "X-Static-Env-Secret" + - secretSource: + value: "${MY_SECRET_ENV}" # content still needs to be base64 encoded +injectResponseHeaders: + # Following will result in a header "Authorization: Basic (encoded)" + - name: "Authorization" + values: + - claimSource: + claim: user + prefix: "Basic " + basicAuthPassword: + value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk # base64 encoded password +``` + +**Value sources:** +* `claimSource` - `claim` (session claims either from id token or from profile URL) +* `secretSource` - `value` (base64), `fromFile` (file path) + +**Request option:** `preserveRequestValue: true` retains existing header values + +**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest` + ## Removed options The following flags/options and their respective environment variables are no diff --git a/docs/versioned_docs/version-7.14.x/configuration/alpha_config.md b/docs/versioned_docs/version-7.14.x/configuration/alpha_config.md index 495bc20691..b4a7558246 100644 --- a/docs/versioned_docs/version-7.14.x/configuration/alpha_config.md +++ b/docs/versioned_docs/version-7.14.x/configuration/alpha_config.md @@ -24,17 +24,56 @@ When using alpha configuration, your config file will look something like below: upstreams: - id: ... ...: ... -injectRequestHeaders: - - name: ... +providers: + - id: ... ...: ... +cookie: + secret: ... + ...: ... +injectRequestHeaders: + - secretSource: + ...: ... injectResponseHeaders: - - name: ... - ...: ... + - claimSource: + ...: ... ``` Please browse the [reference](#configuration-reference) below for the structure of the new configuration format. +# Migration Guide + +This section details breaking changes and migration steps for moving to the new +alpha configuration format. + +## Migrating header injections in v7.14.0 + +From v7.14.0 onward, header injection sources must be explicitly nested. If you +previously relied on squashed fields, update to the new structure before +upgrading: + +```yaml +# before v7.14.0 +injectRequestHeaders: +- name: X-Forwarded-User + values: + - claim: user +- name: X-Custom-Secret-header + values: + - value: my-super-secret + +# v7.14.0 and later +injectRequestHeaders: +- name: X-Forwarded-User + values: + - claimSource: + claim: user +- name: X-Custom-Secret-header + values: + - secretSource: + value: my-super-secret +``` + ## Using Alpha Configuration To use the new **alpha** configuration, generate a YAML file based on the format @@ -67,9 +106,9 @@ the new config. oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg ``` -## Using ENV variables in the alpha configuration +### How to use environment variables -The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +The alpha package supports the use of environment variables in place of yaml values, allowing sensitive data to be pulled from somewhere other than the yaml file. When using environment variables, your yaml will look like this: ```yaml @@ -81,6 +120,46 @@ When using environment variables, your yaml will look like this: Where CLIENT_SECRET is an environment variable. More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) +### How to inject custom headers + +Configure `injectRequestHeaders` and `injectResponseHeaders` in alpha config YAML. + +```yaml +injectRequestHeaders: + - name: "X-User-Email" + values: + - claimSource: + claim: "email" # extract the email claim contents from the id token + - name: "X-Static-Secret" + values: + # secrets need to be encoded with base64 when directly in the yaml config but will be send decoded + - secretSource: + value: "c3VwZXItc2VjcmV0" + - name: "X-Static-File-Secret" + - secretSource: + fromFile: "/path/to/my/secret" + - name: "X-Static-Env-Secret" + - secretSource: + value: "${MY_SECRET_ENV}" # content still needs to be base64 encoded +injectResponseHeaders: + # Following will result in a header "Authorization: Basic (encoded)" + - name: "Authorization" + values: + - claimSource: + claim: user + prefix: "Basic " + basicAuthPassword: + value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk # base64 encoded password +``` + +**Value sources:** +* `claimSource` - `claim` (session claims either from id token or from profile URL) +* `secretSource` - `value` (base64), `fromFile` (file path) + +**Request option:** `preserveRequestValue: true` retains existing header values + +**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest` + ## Removed options The following flags/options and their respective environment variables are no diff --git a/docs/versioned_docs/version-7.14.x/configuration/alpha_config.md.tmpl b/docs/versioned_docs/version-7.14.x/configuration/alpha_config.md.tmpl index 8258201f2a..081657c4ac 100644 --- a/docs/versioned_docs/version-7.14.x/configuration/alpha_config.md.tmpl +++ b/docs/versioned_docs/version-7.14.x/configuration/alpha_config.md.tmpl @@ -24,17 +24,56 @@ When using alpha configuration, your config file will look something like below: upstreams: - id: ... ...: ... -injectRequestHeaders: - - name: ... +providers: + - id: ... ...: ... +cookie: + secret: ... + ...: ... +injectRequestHeaders: + - secretSource: + ...: ... injectResponseHeaders: - - name: ... - ...: ... + - claimSource: + ...: ... ``` Please browse the [reference](#configuration-reference) below for the structure of the new configuration format. +# Migration Guide + +This section details breaking changes and migration steps for moving to the new +alpha configuration format. + +## Migrating header injections in v7.14.0 + +From v7.14.0 onward, header injection sources must be explicitly nested. If you +previously relied on squashed fields, update to the new structure before +upgrading: + +```yaml +# before v7.14.0 +injectRequestHeaders: +- name: X-Forwarded-User + values: + - claim: user +- name: X-Custom-Secret-header + values: + - value: my-super-secret + +# v7.14.0 and later +injectRequestHeaders: +- name: X-Forwarded-User + values: + - claimSource: + claim: user +- name: X-Custom-Secret-header + values: + - secretSource: + value: my-super-secret +``` + ## Using Alpha Configuration To use the new **alpha** configuration, generate a YAML file based on the format @@ -67,9 +106,9 @@ the new config. oauth2-proxy --alpha-config ./path/to/new/config.yaml --config ./path/to/existing/config.cfg ``` -## Using ENV variables in the alpha configuration +### How to use environment variables -The alpha package supports the use of environment variables in place of yaml keys, allowing sensitive values to be pulled from somewhere other than the yaml file. +The alpha package supports the use of environment variables in place of yaml values, allowing sensitive data to be pulled from somewhere other than the yaml file. When using environment variables, your yaml will look like this: ```yaml @@ -81,6 +120,46 @@ When using environment variables, your yaml will look like this: Where CLIENT_SECRET is an environment variable. More information and available patterns can be found [here](https://github.com/a8m/envsubst#docs) +### How to inject custom headers + +Configure `injectRequestHeaders` and `injectResponseHeaders` in alpha config YAML. + +```yaml +injectRequestHeaders: + - name: "X-User-Email" + values: + - claimSource: + claim: "email" # extract the email claim contents from the id token + - name: "X-Static-Secret" + values: + # secrets need to be encoded with base64 when directly in the yaml config but will be send decoded + - secretSource: + value: "c3VwZXItc2VjcmV0" + - name: "X-Static-File-Secret" + - secretSource: + fromFile: "/path/to/my/secret" + - name: "X-Static-Env-Secret" + - secretSource: + value: "${MY_SECRET_ENV}" # content still needs to be base64 encoded +injectResponseHeaders: + # Following will result in a header "Authorization: Basic (encoded)" + - name: "Authorization" + values: + - claimSource: + claim: user + prefix: "Basic " + basicAuthPassword: + value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk # base64 encoded password +``` + +**Value sources:** +* `claimSource` - `claim` (session claims either from id token or from profile URL) +* `secretSource` - `value` (base64), `fromFile` (file path) + +**Request option:** `preserveRequestValue: true` retains existing header values + +**Incompatibility:** Remove legacy flags `pass-user-headers`, `set-xauthrequest` + ## Removed options The following flags/options and their respective environment variables are no From f46dcc77a8202bf663ce66c1af2a16031e164ff5 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Thu, 15 Jan 2026 13:15:25 +0100 Subject: [PATCH 109/125] doc: cncf onboarding and sponsor update Signed-off-by: Jan Larwig --- ADOPTERS.md | 28 --- CODE_OF_CONDUCT.md | 184 ++++++++---------- DCO.md | 34 ++++ MAINTAINERS | 7 +- MAINTAINERS.md | 33 ++++ README.md | 47 +++-- docs/docs/community/contribution.md | 6 +- docs/docs/community/security.md | 2 +- docs/docs/configuration/sessions.md | 4 +- docs/docs/welcome.md | 10 + docs/docusaurus.config.js | 2 +- .../version-7.14.x/community/contribution.md | 6 +- .../version-7.14.x/community/security.md | 2 +- .../version-7.14.x/configuration/sessions.md | 4 +- docs/versioned_docs/version-7.14.x/welcome.md | 9 + 15 files changed, 213 insertions(+), 165 deletions(-) delete mode 100644 ADOPTERS.md create mode 100644 DCO.md create mode 100644 MAINTAINERS.md diff --git a/ADOPTERS.md b/ADOPTERS.md deleted file mode 100644 index b0a233e5cd..0000000000 --- a/ADOPTERS.md +++ /dev/null @@ -1,28 +0,0 @@ -# Adopters - -This list showcases organizations that leverage OAuth2-Proxy within their -infrastructure. If your organization uses OAuth2-Proxy and isn't yet listed, we -encourage you to add it! - -This list aims to be a comprehensive and trusted resource for the OAuth2-Proxy -community, demonstrating successful adoption across all kinds of industries. - -Contributing to this list is a simple way to impact the project's growth, -maturity, and momentum. Thank you to all adopters and contributors of the -OAuth2-Proxy project! - -## Updating this list - -To add your organization to this list, you can just [open a PR](https://github.com/oauth2-proxy/oauth2-proxy/pulls) -to directly update this list. - -Add your organization name, your github username and if you desire a short -description on how you utilize oauth2-proxy. - -## OAuth2-Proxy Adopters - -This list is sorted in the order that organizations were added to it. - -| Organization | Contact | Description of Use | -| ------------ | ------- | ------------------ | -| | | | diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 739a7f6af0..d036cf1d38 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,134 +1,112 @@ -# Contributor Covenant Code of Conduct +## CNCF Community Code of Conduct v1.3 + +Other languages available: +- [Arabic/العربية](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/ar.md) +- [Bengali/বাংলা](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/bn.md) +- [Bulgarian/Български](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/bg.md) +- [Chinese/中文](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/zh.md) +- [Czech/Česky](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/cs.md) +- [Farsi/فارسی](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/fa.md) +- [French/Français](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/fr.md) +- [German/Deutsch](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/de.md) +- [Hebrew/עברית](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/he.md) +- [Hindi/हिन्दी](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/hi.md) +- [Hungarian/Magyar](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/hu.md) +- [Indonesian/Bahasa Indonesia](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/id.md) +- [Italian/Italiano](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/it.md) +- [Japanese/日本語](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/ja.md) +- [Korean/한국어](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/ko.md) +- [Polish/Polski](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/pl.md) +- [Portuguese/Português](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/pt.md) +- [Russian/Русский](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/ru.md) +- [Spanish/Español](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/es.md) +- [Turkish/Türkçe](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/tr.md) +- [Ukrainian/Українська](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/uk.md) +- [Vietnamese/Tiếng Việt](https://github.com/cncf/foundation/blob/main/code-of-conduct-languages/vi.md) + +### Community Code of Conduct + +As contributors, maintainers, and participants in the CNCF community, and in the interest of fostering +an open and welcoming community, we pledge to respect all people who participate or contribute +through reporting issues, posting feature requests, updating documentation, +submitting pull requests or patches, attending conferences or events, or engaging in other community or project activities. + +We are committed to making participation in the CNCF community a harassment-free experience for everyone, regardless of age, body size, caste, disability, ethnicity, level of experience, family status, gender, gender identity and expression, marital status, military or veteran status, nationality, personal appearance, race, religion, sexual orientation, socioeconomic status, tribe, or any other dimension of diversity. -## Our Pledge +## Scope + +This code of conduct applies: +* within project and community spaces, +* in other spaces when an individual CNCF community participant's words or actions are directed at or are about a CNCF project, the CNCF community, or another CNCF community participant in the context of a CNCF activity. -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, caste, color, religion, or sexual -identity and orientation. +### CNCF Events -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. +CNCF events that are produced by the Linux Foundation with professional events staff are governed by the Linux Foundation [Events Code of Conduct](https://events.linuxfoundation.org/code-of-conduct/) available on the event page. This is designed to be used in conjunction with the CNCF Code of Conduct. ## Our Standards -Examples of behavior that contributes to a positive environment for our -community include: +The CNCF Community is open, inclusive and respectful. Every member of our community has the right to have their identity respected. + +Examples of behavior that contributes to a positive environment include but are not limited to: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience -* Focusing on what is best not just for us as individuals, but for the overall - community +* Focusing on what is best not just for us as individuals, but for the + overall community +* Using welcoming and inclusive language -Examples of unacceptable behavior include: -* The use of sexualized language or imagery, and sexual attention or advances of - any kind +Examples of unacceptable behavior include but are not limited to: + +* The use of sexualized language or imagery * Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email address, - without their explicit permission +* Public or private harassment in any form +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Violence, threatening violence, or encouraging others to engage in violent behavior +* Stalking or following someone without their consent +* Unwelcome physical contact +* Unwelcome sexual or romantic attention or advances +* Using CNCF projects or community spaces for political campaigning or promotion of political causes + that are unrelated to the advancement of cloud native technology. To clarify, this policy does not restrict individuals' personal attire, including attire that expresses personal beliefs or aspects of identity. * Other conduct which could reasonably be considered inappropriate in a professional setting -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official email address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. - -## Enforcement +The following behaviors are also prohibited: +* Providing knowingly false or misleading information in connection with a Code of Conduct investigation or otherwise intentionally tampering with an investigation. +* Retaliating against a person because they reported an incident or provided information about an incident as a witness. -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -https://gophers.slack.com/messages/CM2RSS25N or directly contacting one of the -maintainers from the MAINTAINERS file. -All complaints will be reviewed and investigated promptly and fairly. +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. +By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect +of managing a CNCF project. +Project maintainers who do not follow or enforce the Code of Conduct may be temporarily or permanently removed from the project team. -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. +## Reporting -## Enforcement Guidelines +For incidents occurring in the Kubernetes community, contact the [Kubernetes Code of Conduct Committee](https://git.k8s.io/community/committee-code-of-conduct) via . You can expect a response within three business days. -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: +For other projects, or for incidents that are project-agnostic or impact multiple CNCF projects, please contact the [CNCF Code of Conduct Committee](https://www.cncf.io/conduct/committee/) via . Alternatively, you can contact any of the individual members of the [CNCF Code of Conduct Committee](https://www.cncf.io/conduct/committee/) to submit your report. For more detailed instructions on how to submit a report, including how to submit a report anonymously, please see our [Incident Resolution Procedures](https://github.com/cncf/foundation/blob/main/code-of-conduct/coc-incident-resolution-procedures.md). You can expect a response within three business days. -### 1. Correction +For incidents occurring at CNCF event that is produced by the Linux Foundation, please contact . -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. +## Frequently asked questions +For more information about this Code of Conduct, please see the [CNCF Code of Conduct Frequently Asked Questions](https://www.cncf.io/conduct/faq/). -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series of -actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or permanent -ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within the -community. +## Enforcement -## Attribution +Upon review and investigation of a reported incident, the CoC response team that has jurisdiction will determine what action is appropriate based on this Code of Conduct and its related documentation. -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.1, available at -[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. +For information about which Code of Conduct incidents are handled by project leadership, which incidents are handled by the CNCF Code of Conduct Committee, and which incidents are handled by the Linux Foundation (including its events team), see our [Jurisdiction Policy](https://github.com/cncf/foundation/blob/main/code-of-conduct/coc-committee-jurisdiction-policy.md). -Community Impact Guidelines were inspired by -[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. +## Amendments -For answers to common questions about this code of conduct, see the FAQ at -[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at -[https://www.contributor-covenant.org/translations][translations]. +Consistent with the CNCF Charter, any substantive changes to this Code of Conduct must be approved by the Technical Oversight Committee. -[homepage]: https://www.contributor-covenant.org -[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html -[Mozilla CoC]: https://github.com/mozilla/diversity -[FAQ]: https://www.contributor-covenant.org/faq -[translations]: https://www.contributor-covenant.org/translations +## Acknowledgements +This Code of Conduct is adapted from the Contributor Covenant +(http://contributor-covenant.org), version 2.0 available at +http://contributor-covenant.org/version/2/0/code_of_conduct/ diff --git a/DCO.md b/DCO.md new file mode 100644 index 0000000000..49b8cb0549 --- /dev/null +++ b/DCO.md @@ -0,0 +1,34 @@ +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. diff --git a/MAINTAINERS b/MAINTAINERS index f54915e994..5a4c60cc25 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -1,5 +1,2 @@ -Joel Speed (@JoelSpeed) -Nick Meves (@NickMeves) -Braunson (@braunsonm) -Jan Larwig (@tuunit) -Koen van Zuijlen (@kvanzuijlen) + +Moved to https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS.md diff --git a/MAINTAINERS.md b/MAINTAINERS.md new file mode 100644 index 0000000000..71ec0fdced --- /dev/null +++ b/MAINTAINERS.md @@ -0,0 +1,33 @@ +# Maintainers + +The table below lists all current maintainers for the oauth2-proxy as defined +by our [project governance](GOVERNANCE.md). + +| Name | GitHub Handle | Domains of reponsibility | Email Alias | Affiliation | +| ---------------- | ------------------------------------------------------ | ------------------------ | -------------------------- | ----------- | +| Joel Speed | [@JoelSpeed](https://github.com/joelspeed) | Governance, Core | joel@oauth2-proxy.dev | Red Hat | +| Jan Larwig | [@tuunit](https://github.com/tuunit) | Governance, Core | jan@oauth2-proxy.dev | IONOS Cloud | +| JJ Łakis | [@jjlakis](https://github.com/jjlakis) | Provider | jj@oauth2-proxy.dev | - | +| Koen van Zuijlen | [@kvanzuijlen](https://github.com/kvanzuijlen) | CI | koen@oauth2-proxy.dev | - | +| Pierluigi Lenoci | [@pierluigilenoci](https://github.com/pierluigilenoci) | Helm | pierluigi@oauth2-proxy.dev | SAP | + +## Emeritus Maintainers + +We would like to highlight that this project does have prior maintainers and +core contributors that, if they so wished, could (and should) be granted the +status of emeritus maintainers. + +| Name | GitHub Handle | +| ------------- | ------------------------------------------------------ | +| Nick Meves | [@NickMeves](https://github.com/NickMeves) | +| Braunson | [@braunsonm](https://github.com/braunsonm) | +| Henry Jenkins | [@steakunderscore](https://github.com/steakunderscore) | + + +## Security Response Team and GitHub Organization Owners + +The following maintainers are members of the security response team and owners +of the GitHub organization. + +- Joel Speed +- Jan Larwig diff --git a/README.md b/README.md index 72e976fbc5..88849cb9c2 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,24 @@ [![Continuous Integration](https://github.com/oauth2-proxy/oauth2-proxy/actions/workflows/ci.yml/badge.svg)](https://github.com/oauth2-proxy/oauth2-proxy/actions/workflows/ci.yml) -[![Go Report Card](https://goreportcard.com/badge/github.com/oauth2-proxy/oauth2-proxy)](https://goreportcard.com/report/github.com/oauth2-proxy/oauth2-proxy) -[![GoDoc](https://godoc.org/github.com/oauth2-proxy/oauth2-proxy?status.svg)](https://godoc.org/github.com/oauth2-proxy/oauth2-proxy) +[![Go Report Card](https://goreportcard.com/badge/github.com/oauth2-proxy/oauth2-proxy)](https://goreportcard.com/report/github.com/oauth2-proxy/oauth2-proxy/v7) +[![GoDoc](https://godoc.org/github.com/oauth2-proxy/oauth2-proxy?status.svg)](https://godoc.org/github.com/oauth2-proxy/oauth2-proxy/v7) [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE) -[![Maintainability](https://api.codeclimate.com/v1/badges/a58ff79407212e2beacb/maintainability)](https://codeclimate.com/github/oauth2-proxy/oauth2-proxy/maintainability) -[![Test Coverage](https://api.codeclimate.com/v1/badges/a58ff79407212e2beacb/test_coverage)](https://codeclimate.com/github/oauth2-proxy/oauth2-proxy/test_coverage) +[![Maintainability](https://qlty.sh/gh/oauth2-proxy/projects/oauth2-proxy/maintainability.svg)](https://qlty.sh/gh/oauth2-proxy/projects/oauth2-proxy) +[![Code Coverage](https://qlty.sh/gh/oauth2-proxy/projects/oauth2-proxy/coverage.svg)](https://qlty.sh/gh/oauth2-proxy/projects/oauth2-proxy) +[![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/oauth2-proxy/oauth2-proxy/badge)](https://scorecard.dev/viewer/?uri=github.com/oauth2-proxy/oauth2-proxy) +[![OpenSSF Best Practices](https://www.bestpractices.dev/projects/11223/badge)](https://www.bestpractices.dev/projects/11223) [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Foauth2-proxy%2Foauth2-proxy.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Foauth2-proxy%2Foauth2-proxy?ref=badge_shield) ![OAuth2 Proxy](docs/static/img/logos/OAuth2_Proxy_horizontal.svg) -OAuth2-Proxy is a flexible, open-source tool that can act as either a standalone reverse proxy or a middleware component integrated into existing reverse proxy or load balancer setups. It provides a simple and secure way to protect your web applications with OAuth2 / OIDC authentication. As a reverse proxy, it intercepts requests to your application and redirects users to an OAuth2 provider for authentication. As a middleware, it can be seamlessly integrated into your existing infrastructure to handle authentication for multiple applications. +OAuth2 Proxy is a flexible, open-source tool that can act as either a standalone reverse proxy or a middleware component integrated into existing reverse proxy or load balancer setups. It provides a simple and secure way to protect your web applications with OAuth2 / OIDC authentication. As a reverse proxy, it intercepts requests to your application and redirects users to an OAuth2 provider for authentication. As a middleware, it can be seamlessly integrated into your existing infrastructure to handle authentication for multiple applications. -OAuth2-Proxy supports a lot of OAuth2 as well as OIDC providers. Either through a generic OIDC client or a specific implementation for Google, Microsoft Entra ID, GitHub, login.gov and others. Through specialised provider implementations oauth2-proxy can extract more details about the user like preferred usernames and groups. Those details can then be forwarded as HTTP headers to your upstream applications. +OAuth2 Proxy supports a lot of OAuth2 as well as OIDC providers. Either through a generic OIDC client or a specific implementation for Google, Microsoft Entra ID, GitHub, login.gov and others. Through specialised provider implementations oauth2-proxy can extract more details about the user like preferred usernames and groups. Those details can then be forwarded as HTTP headers to your upstream applications. ![Simplified Architecture](docs/static/img/simplified-architecture.svg) ## Get Started -OAuth2-Proxy's [Installation Docs](https://oauth2-proxy.github.io/oauth2-proxy/installation) cover how to install and configure your setup. Additionally you can take a further look at the [example setup files](https://github.com/oauth2-proxy/oauth2-proxy/tree/master/contrib/local-environment). +OAuth2 Proxy's [Installation Docs](https://oauth2-proxy.github.io/oauth2-proxy/installation) cover how to install and configure your setup. Additionally you can take a further look at the [example setup files](https://github.com/oauth2-proxy/oauth2-proxy/tree/master/contrib/local-environment). ## Releases @@ -35,24 +37,26 @@ Since 2023-11-18 we build nightly images directly from the `master` branch and p These images are considered unstable and therefore should **NOT** be used for production purposes unless you know what you're doing. ## Sponsors +Would you like to sponsor the project then please contact us at [sponsors@oauth2-proxy.dev](mailto:sponsors@oauth2-proxy.dev) -![Microsoft](https://upload.wikimedia.org/wikipedia/commons/9/96/Microsoft_logo_%282012%29.svg) -Microsoft Azure credits for open source projects +![SAP](https://avatars.githubusercontent.com/u/2531208?s=300&v=4) -Would you like to sponsor the project then please contact us at [sponsors@oauth2-proxy.dev](mailto:sponsors@oauth2-proxy.dev) +SAP Open Source Program + +## Former Sponsors +![Microsoft](https://avatars.githubusercontent.com/u/6154722?s=100&v=4) + +Microsoft Azure credits for open source projects ## Getting Involved [![Slack](https://img.shields.io/badge/slack-Gopher_%23oauth2--proxy-red?logo=slack)](https://gophers.slack.com/archives/CM2RSS25N) 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. -OAuth2-Proxy is a community-driven project. We rely on the contribut️ions of our users to continually improve it. While review times can vary, we appreciate your patience and understanding. As a volunteer-driven project, we strive to keep this project stable and might take longer to merge changes. +OAuth2 Proxy is a community-driven project. We rely on the contribut️ions of our users to continually improve it. While review times can vary, we appreciate your patience and understanding. As a volunteer-driven project, we strive to keep this project stable and might take longer to merge changes. If you want to contribute to the project. Please see our [Contributing](https://oauth2-proxy.github.io/oauth2-proxy/community/contribution) guide. -Who uses OAuth2-Proxy? Have a look at our new [ADOPTERS](ADOPTERS.md) file and -feel free to open a PR to add your organisation. - Thanks to all the people who already contributed ❤ @@ -66,7 +70,7 @@ Made with [contrib.rocks](https://contrib.rocks). If you believe you have found a vulnerability within OAuth2 Proxy or any of its dependencies, please do **NOT** open an issue or PR on GitHub, please do **NOT** post any details publicly. -Security disclosures **MUST** be done in private. If you have found an issue that you would like to bring to the attention of the maintainers, please compose an email and send it to the list of people listed in our [MAINTAINERS](MAINTAINERS) file. +Security disclosures **MUST** be done in private. If you have found an issue that you would like to bring to the attention of the maintainers, please compose an email and send it to the list of people listed in our [MAINTAINERS.md](MAINTAINERS.md) file. For more details read our full [Security Docs](https://oauth2-proxy.github.io/oauth2-proxy/community/security#security-disclosures) @@ -82,9 +86,20 @@ See [open redirect vulnerability](https://github.com/oauth2-proxy/oauth2-proxy/s **2020-03-29:** This project was formerly hosted as `pusher/oauth2_proxy` but has been renamed to `oauth2-proxy/oauth2-proxy`. Going forward, all images shall be available at `quay.io/oauth2-proxy/oauth2-proxy` and binaries will be named `oauth2-proxy`. +## Code of Conduct +Participation in the OAuth2 Proxy project is governed by the [CNCF Code of Conduct](CODE_OF_CONDUCT.md). + ## License -OAuth2-Proxy is distributed under [The MIT License](LICENSE). +OAuth2 Proxy is distributed under [The MIT License](LICENSE). [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Foauth2-proxy%2Foauth2-proxy.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Foauth2-proxy%2Foauth2-proxy?ref=badge_large) + +## Trademarks + +OAuth2 Proxy is a [Cloud Native Computing Foundation](https://cncf.io) Sandbox project. + +![CNCF](https://www.cncf.io/wp-content/uploads/2023/04/cncf-main-site-logo.svg) + +The Linux Foundation® (TLF) has registered trademarks and uses trademarks. For a list of TLF trademarks, see [Trademark Usage](https://www.linuxfoundation.org/legal/trademark-usage). diff --git a/docs/docs/community/contribution.md b/docs/docs/community/contribution.md index a8e4734988..a4f9dc167a 100644 --- a/docs/docs/community/contribution.md +++ b/docs/docs/community/contribution.md @@ -39,7 +39,7 @@ For starting oauth2-proxy locally open the debugging tab and create the `launch. "version": "0.2.0", "configurations": [ { - "name": "Launch OAuth2-Proxy with Dex", + "name": "Launch OAuth2 Proxy with Dex", "type": "go", "request": "launch", "mode": "auto", @@ -52,7 +52,7 @@ For starting oauth2-proxy locally open the debugging tab and create the `launch. ] }, { - "name": "Launch OAuth2-Proxy with Keycloak", + "name": "Launch OAuth2 Proxy with Keycloak", "type": "go", "request": "launch", "mode": "auto", @@ -85,7 +85,7 @@ The username and password for all setups is usually `admin@example.com` and `pas The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me -- OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 +- OAuth2 Proxy: http://oauth2-proxy.localtest.me:4180 - Upstream: http://httpbin.localtest.me:8080 - Dex: http://dex.localtest.me:5556 diff --git a/docs/docs/community/security.md b/docs/docs/community/security.md index c24b57d9e5..00cdb7240e 100644 --- a/docs/docs/community/security.md +++ b/docs/docs/community/security.md @@ -21,7 +21,7 @@ any details publicly. Security disclosures MUST be done in private. If you have found an issue that you would like to bring to the attention of the maintenance team for OAuth2 Proxy, please compose an email and send it to the -list of maintainers in our [MAINTAINERS](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS) file. +list of maintainers in our [MAINTAINERS.md](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS.md) file. Please include as much detail as possible. Ideally, your disclosure should include: diff --git a/docs/docs/configuration/sessions.md b/docs/docs/configuration/sessions.md index e20378170a..c1e5fc17e6 100644 --- a/docs/docs/configuration/sessions.md +++ b/docs/docs/configuration/sessions.md @@ -64,9 +64,9 @@ the refresh flow to get a new Access-Token. If it is longer, it might be that th expired. The "cookie-refresh" value controls when OAuth2 Proxy tries to refresh an Access-Token. If it is set to "0", the -Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2-Proxy will +Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2 Proxy will refresh the Access-Token after this many seconds whether it is still valid or not. According to the official OAuth2.0 specification -Access-Tokens are not required to follow a specific format. Therefore OAuth2-Proxy cannot check for any expiry date without an +Access-Tokens are not required to follow a specific format. Therefore OAuth2 Proxy cannot check for any expiry date without an introspection endpoint. If an Access-Token expires and you have not set a corresponding "cookie-refresh" value, you will likely encounter expiry issues. diff --git a/docs/docs/welcome.md b/docs/docs/welcome.md index 7bceadd80e..1cfd569f89 100644 --- a/docs/docs/welcome.md +++ b/docs/docs/welcome.md @@ -21,3 +21,13 @@ A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy ## Architecture ![OAuth2 Proxy Architecture](/img/simplified-architecture.svg) + + +## Cloud Native Computing Foundation + +OAuth2 Proxy is a [Cloud Native Computing Foundation](https://cncf.io) Sandbox project. + +![CNCF](https://www.cncf.io/wp-content/uploads/2023/04/cncf-main-site-logo.svg) + +The Linux Foundation® (TLF) has registered trademarks and uses trademarks. For a list of TLF trademarks, see [Trademark Usage](https://www.linuxfoundation.org/legal/trademark-usage). + diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index daf962261b..5123f9433f 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -118,7 +118,7 @@ const config = { }, footer: { style: 'dark', - copyright: `Copyright © ${new Date().getFullYear()} OAuth2 Proxy.`, + copyright: `Copyright © ${new Date().getFullYear()} OAuth2 Proxy a Series of LF Projects, LLC.
For website terms of use, trademark policy and other project policies please see lfprojects.org/policies/`, }, prism: { theme: prismThemes.github, diff --git a/docs/versioned_docs/version-7.14.x/community/contribution.md b/docs/versioned_docs/version-7.14.x/community/contribution.md index a8e4734988..a4f9dc167a 100644 --- a/docs/versioned_docs/version-7.14.x/community/contribution.md +++ b/docs/versioned_docs/version-7.14.x/community/contribution.md @@ -39,7 +39,7 @@ For starting oauth2-proxy locally open the debugging tab and create the `launch. "version": "0.2.0", "configurations": [ { - "name": "Launch OAuth2-Proxy with Dex", + "name": "Launch OAuth2 Proxy with Dex", "type": "go", "request": "launch", "mode": "auto", @@ -52,7 +52,7 @@ For starting oauth2-proxy locally open the debugging tab and create the `launch. ] }, { - "name": "Launch OAuth2-Proxy with Keycloak", + "name": "Launch OAuth2 Proxy with Keycloak", "type": "go", "request": "launch", "mode": "auto", @@ -85,7 +85,7 @@ The username and password for all setups is usually `admin@example.com` and `pas The docker compose setups expose the services with a dynamic reverse DNS resolver: localtest.me -- OAuth2-Proxy: http://oauth2-proxy.localtest.me:4180 +- OAuth2 Proxy: http://oauth2-proxy.localtest.me:4180 - Upstream: http://httpbin.localtest.me:8080 - Dex: http://dex.localtest.me:5556 diff --git a/docs/versioned_docs/version-7.14.x/community/security.md b/docs/versioned_docs/version-7.14.x/community/security.md index c24b57d9e5..00cdb7240e 100644 --- a/docs/versioned_docs/version-7.14.x/community/security.md +++ b/docs/versioned_docs/version-7.14.x/community/security.md @@ -21,7 +21,7 @@ any details publicly. Security disclosures MUST be done in private. If you have found an issue that you would like to bring to the attention of the maintenance team for OAuth2 Proxy, please compose an email and send it to the -list of maintainers in our [MAINTAINERS](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS) file. +list of maintainers in our [MAINTAINERS.md](https://github.com/oauth2-proxy/oauth2-proxy/blob/master/MAINTAINERS.md) file. Please include as much detail as possible. Ideally, your disclosure should include: diff --git a/docs/versioned_docs/version-7.14.x/configuration/sessions.md b/docs/versioned_docs/version-7.14.x/configuration/sessions.md index e20378170a..c1e5fc17e6 100644 --- a/docs/versioned_docs/version-7.14.x/configuration/sessions.md +++ b/docs/versioned_docs/version-7.14.x/configuration/sessions.md @@ -64,9 +64,9 @@ the refresh flow to get a new Access-Token. If it is longer, it might be that th expired. The "cookie-refresh" value controls when OAuth2 Proxy tries to refresh an Access-Token. If it is set to "0", the -Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2-Proxy will +Access-Token will never be refreshed, even if it is already expired and a valid Refresh-Token is available. If set, OAuth2 Proxy will refresh the Access-Token after this many seconds whether it is still valid or not. According to the official OAuth2.0 specification -Access-Tokens are not required to follow a specific format. Therefore OAuth2-Proxy cannot check for any expiry date without an +Access-Tokens are not required to follow a specific format. Therefore OAuth2 Proxy cannot check for any expiry date without an introspection endpoint. If an Access-Token expires and you have not set a corresponding "cookie-refresh" value, you will likely encounter expiry issues. diff --git a/docs/versioned_docs/version-7.14.x/welcome.md b/docs/versioned_docs/version-7.14.x/welcome.md index 7bceadd80e..8924fd954e 100644 --- a/docs/versioned_docs/version-7.14.x/welcome.md +++ b/docs/versioned_docs/version-7.14.x/welcome.md @@ -21,3 +21,12 @@ A list of changes can be seen in the [CHANGELOG](https://github.com/oauth2-proxy ## Architecture ![OAuth2 Proxy Architecture](/img/simplified-architecture.svg) + +## Cloud Native Computing Foundation + +OAuth2 Proxy is a [Cloud Native Computing Foundation](https://cncf.io) Sandbox project. + +![CNCF](https://www.cncf.io/wp-content/uploads/2023/04/cncf-main-site-logo.svg) + +The Linux Foundation® (TLF) has registered trademarks and uses trademarks. For a list of TLF trademarks, see [Trademark Usage](https://www.linuxfoundation.org/legal/trademark-usage). + From a360cb3875c7cfff13d5c04822eff9192236e460 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 16 Jan 2026 09:48:37 +0100 Subject: [PATCH 110/125] docs: backport integrations split to v7.14.x & v7.13.x Signed-off-by: Jan Larwig --- .../configuration/integration.md | 310 ------------------ .../configuration/integrations/caddy.md | 63 ++++ .../configuration/integrations/headlamp.md | 105 ++++++ .../configuration/integrations/index.md | 41 +++ .../integrations/kubernetes-dashboard.md | 289 ++++++++++++++++ .../configuration/integrations/nginx.md | 107 ++++++ .../configuration/integrations/traefik.md | 184 +++++++++++ .../version-7.13.x/features/endpoints.md | 2 +- .../configuration/integration.md | 310 ------------------ .../configuration/integrations/caddy.md | 63 ++++ .../configuration/integrations/headlamp.md | 105 ++++++ .../configuration/integrations/index.md | 41 +++ .../integrations/kubernetes-dashboard.md | 289 ++++++++++++++++ .../configuration/integrations/nginx.md | 107 ++++++ .../configuration/integrations/traefik.md | 184 +++++++++++ .../version-7.14.x/configuration/overview.md | 4 +- .../version-7.14.x/features/endpoints.md | 2 +- .../version-7.13.x-sidebars.json | 16 +- .../version-7.14.x-sidebars.json | 16 +- 19 files changed, 1612 insertions(+), 626 deletions(-) delete mode 100644 docs/versioned_docs/version-7.13.x/configuration/integration.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/integrations/caddy.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/integrations/headlamp.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/integrations/index.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/integrations/kubernetes-dashboard.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/integrations/nginx.md create mode 100644 docs/versioned_docs/version-7.13.x/configuration/integrations/traefik.md delete mode 100644 docs/versioned_docs/version-7.14.x/configuration/integration.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/integrations/caddy.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/integrations/headlamp.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/integrations/index.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/integrations/kubernetes-dashboard.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/integrations/nginx.md create mode 100644 docs/versioned_docs/version-7.14.x/configuration/integrations/traefik.md diff --git a/docs/versioned_docs/version-7.13.x/configuration/integration.md b/docs/versioned_docs/version-7.13.x/configuration/integration.md deleted file mode 100644 index c57cfa6b36..0000000000 --- a/docs/versioned_docs/version-7.13.x/configuration/integration.md +++ /dev/null @@ -1,310 +0,0 @@ ---- -id: integration -title: Integration ---- - -## Configuring for use with the Nginx `auth_request` directive - -**This option requires `--reverse-proxy` option to be set.** - -The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: - -```nginx -server { - listen 443 ssl; - server_name ...; - include ssl/ssl.conf; - - location /oauth2/ { - proxy_pass http://127.0.0.1:4180; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Auth-Request-Redirect $request_uri; - # or, if you are handling multiple domains: - # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; - } - location = /oauth2/auth { - proxy_pass http://127.0.0.1:4180; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-Uri $request_uri; - # nginx auth_request includes headers but not body - proxy_set_header Content-Length ""; - proxy_pass_request_body off; - } - - location / { - auth_request /oauth2/auth; - error_page 401 =403 /oauth2/sign_in; - - # pass information via X-User and X-Email headers to backend, - # requires running with --set-xauthrequest flag - auth_request_set $user $upstream_http_x_auth_request_user; - auth_request_set $email $upstream_http_x_auth_request_email; - proxy_set_header X-User $user; - proxy_set_header X-Email $email; - - # if you enabled --pass-access-token, this will pass the token to the backend - auth_request_set $token $upstream_http_x_auth_request_access_token; - proxy_set_header X-Access-Token $token; - - # if you enabled --cookie-refresh, this is needed for it to work with auth_request - auth_request_set $auth_cookie $upstream_http_set_cookie; - add_header Set-Cookie $auth_cookie; - - # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb - # limit and so the OAuth2 Proxy splits these into multiple parts. - # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, - # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. - auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; - - # Extract the Cookie attributes from the first Set-Cookie header and append them - # to the second part ($upstream_cookie_* variables only contain the raw cookie content) - if ($auth_cookie ~* "(; .*)") { - set $auth_cookie_name_0 $auth_cookie; - set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; - } - - # Send both Set-Cookie headers now if there was a second part - if ($auth_cookie_name_upstream_1) { - add_header Set-Cookie $auth_cookie_name_0; - add_header Set-Cookie $auth_cookie_name_1; - } - - proxy_pass http://backend/; - # or "root /path/to/site;" or "fastcgi_pass ..." etc - } -} -``` - -When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: - -```yaml -nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" -nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" -``` - -This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. - -It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). - -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=". - -## Configuring for use with the Traefik (v2) `ForwardAuth` middleware - -**This option requires `--reverse-proxy` option to be set.** - -### ForwardAuth with 401 errors middleware - -The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: - -```yaml -http: - routers: - a-service: - rule: "Host(`a-service.example.com`)" - service: a-service-backend - middlewares: - - oauth-errors - - oauth-auth - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - oauth: - rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" - middlewares: - - auth-headers - service: oauth-backend - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - - services: - a-service-backend: - loadBalancer: - servers: - - url: http://172.16.0.2:7555 - oauth-backend: - loadBalancer: - servers: - - url: http://172.16.0.1:4180 - - middlewares: - auth-headers: - headers: - sslRedirect: true - stsSeconds: 315360000 - browserXssFilter: true - contentTypeNosniff: true - forceSTSHeader: true - sslHost: example.com - stsIncludeSubdomains: true - stsPreload: true - frameDeny: true - oauth-auth: - forwardAuth: - address: https://oauth.example.com/oauth2/auth - trustForwardHeader: true - oauth-errors: - errors: - status: - - "401-403" - service: oauth-backend - query: "/oauth2/sign_in?rd={url}" -``` - -### ForwardAuth with static upstreams configuration - -Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint - -**Following options need to be set on `oauth2-proxy`:** -- `--upstream=static://202`: Configures a static response for authenticated sessions -- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly - -```yaml -http: - routers: - a-service-route-1: - rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" - service: a-service-backend - middlewares: - - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - a-service-route-2: - rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" - service: a-service-backend - middlewares: - - oauth-auth-wo-redirect # unauthenticated session will return a 401 - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - services-oauth2-route: - rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" - middlewares: - - auth-headers - service: oauth-backend - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - oauth2-proxy-route: - rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" - middlewares: - - auth-headers - service: oauth-backend - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - - services: - a-service-backend: - loadBalancer: - servers: - - url: http://172.16.0.2:7555 - b-service-backend: - loadBalancer: - servers: - - url: http://172.16.0.3:7555 - oauth-backend: - loadBalancer: - servers: - - url: http://172.16.0.1:4180 - - middlewares: - auth-headers: - headers: - sslRedirect: true - stsSeconds: 315360000 - browserXssFilter: true - contentTypeNosniff: true - forceSTSHeader: true - sslHost: example.com - stsIncludeSubdomains: true - stsPreload: true - frameDeny: true - oauth-auth-redirect: - forwardAuth: - address: https://oauth.example.com/ - trustForwardHeader: true - authResponseHeaders: - - X-Auth-Request-Access-Token - - Authorization - oauth-auth-wo-redirect: - forwardAuth: - address: https://oauth.example.com/oauth2/auth - trustForwardHeader: true - authResponseHeaders: - - X-Auth-Request-Access-Token - - Authorization -``` - -## Configuring for use with the Caddy (v2) `forward_auth` directive - -The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. - -This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. - -**Following options need to be set on `oauth2-proxy`:** -- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly - -```nginx title="Caddyfile" -example.com { - # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. - # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. - handle /oauth2/* { - reverse_proxy oauth2-proxy.internal:4180 { - # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. - # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. - header_up X-Real-IP {remote_host} - header_up X-Forwarded-Uri {uri} - } - } - - # Requests to other paths are first processed by oauth2-proxy for authentication. - handle { - forward_auth oauth2-proxy.internal:4180 { - uri /oauth2/auth - - # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. - # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. - header_up X-Real-IP {remote_host} - - # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. - # Make sure to configure the --set-xauthrequest flag to enable this feature. - #copy_headers X-Auth-Request-User X-Auth-Request-Email - - # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. - @error status 401 - handle_response @error { - redir * /oauth2/sign_in?rd={scheme}://{host}{uri} - } - } - - # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. - reverse_proxy upstream.internal:3000 - } -} -``` - -:::note -If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. -::: diff --git a/docs/versioned_docs/version-7.13.x/configuration/integrations/caddy.md b/docs/versioned_docs/version-7.13.x/configuration/integrations/caddy.md new file mode 100644 index 0000000000..1805e55996 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/integrations/caddy.md @@ -0,0 +1,63 @@ +--- +id: caddy +title: Caddy +--- + +Integrate OAuth2 Proxy with Caddy v2 using the `forward_auth` directive. + +**Key features:** +- Simple forward_auth setup +- Automatic header handling +- Custom error handling and redirects + +## Configuring for use with the Caddy (v2) `forward_auth` directive + +The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. + +This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. + +**Following options need to be set on `oauth2-proxy`:** +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```nginx title="Caddyfile" +example.com { + # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. + # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. + handle /oauth2/* { + reverse_proxy oauth2-proxy.internal:4180 { + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. + header_up X-Real-IP {remote_host} + header_up X-Forwarded-Uri {uri} + } + } + + # Requests to other paths are first processed by oauth2-proxy for authentication. + handle { + forward_auth oauth2-proxy.internal:4180 { + uri /oauth2/auth + + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. + header_up X-Real-IP {remote_host} + + # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. + # Make sure to configure the --set-xauthrequest flag to enable this feature. + #copy_headers X-Auth-Request-User X-Auth-Request-Email + + # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. + @error status 401 + handle_response @error { + redir * /oauth2/sign_in?rd={scheme}://{host}{uri} + } + } + + # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. + reverse_proxy upstream.internal:3000 + } +} +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.13.x/configuration/integrations/headlamp.md b/docs/versioned_docs/version-7.13.x/configuration/integrations/headlamp.md new file mode 100644 index 0000000000..a6f6ac7316 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/integrations/headlamp.md @@ -0,0 +1,105 @@ +--- +id: headlamp +title: Headlamp +--- + +Modern, actively maintained Kubernetes web UI with OAuth2 Proxy integration examples. + +**Key features:** +- Active development and maintenance +- Modern, intuitive interface +- Multi-cluster support +- Plugin system +- Works with all OAuth2 providers + +## Configuring for use with Headlamp + +[Headlamp](https://headlamp.dev/) is a modern, user-friendly Kubernetes web UI that can be integrated with OAuth2 Proxy for authentication. This is a recommended alternative to the deprecated Kubernetes Dashboard. + +### Architecture + +``` +User → Ingress → OAuth2 Proxy → Authentication Provider (e.g., Azure Entra ID) + ↓ + Headlamp +``` + +### Prerequisites + +- Kubernetes cluster (e.g., AKS, EKS, GKE, or self-hosted) +- Headlamp installed in the cluster +- OAuth2 provider configured (Azure Entra ID, Google, GitHub, etc.) +- Ingress controller (Nginx, Traefik, etc.) + +### Configuration Overview + +When integrating Headlamp with OAuth2 Proxy, the OAuth2 Proxy acts as a reverse proxy in front of Headlamp: + +1. User requests access to Headlamp +2. Ingress forwards to OAuth2 Proxy +3. OAuth2 Proxy authenticates the user via the OAuth2 provider +4. After successful authentication, OAuth2 Proxy proxies requests to Headlamp +5. Headlamp receives the authenticated user information via headers + +### OAuth2 Proxy Configuration + +Configure OAuth2 Proxy to proxy to the Headlamp service: + +```yaml +upstreamConfig: + upstreams: + - id: headlamp + path: / + uri: http://headlamp-service.headlamp-namespace.svc.cluster.local:4466 +``` + +Enable the necessary headers: + +```yaml +extraArgs: + reverse-proxy: true + pass-authorization-header: true + set-xauthrequest: true + email-domain: "*" # Or restrict to your organization +``` + +### Example with Azure Entra ID on AKS + +For detailed instructions on deploying Headlamp with OAuth2 Proxy on Azure Kubernetes Service using Azure Entra ID, see the official Headlamp documentation: + +https://headlamp.dev/docs/latest/installation/in-cluster/aks-cluster-oauth/ + +Key steps include: + +1. **Set up AKS with OIDC**: Enable Microsoft Entra ID authentication with Kubernetes RBAC +2. **Create Azure App Registration**: Configure redirect URI and create client secret +3. **Deploy Headlamp**: Install Headlamp via Helm in your cluster +4. **Deploy OAuth2 Proxy**: Configure OAuth2 Proxy with Entra ID provider settings and upstream pointing to Headlamp +5. **Configure Ingress**: Set up Ingress to route traffic through OAuth2 Proxy to Headlamp +6. **Set RBAC Policies**: Apply Kubernetes RBAC bindings based on users or groups + +### Integration with Other Providers + +The same integration pattern works with other OAuth2 providers supported by OAuth2 Proxy: + +- **Google**: Use the Google provider configuration +- **GitHub**: Use the GitHub provider configuration +- **GitLab**: Use the GitLab provider configuration +- **Keycloak**: Use the Keycloak OIDC provider configuration +- **Any OIDC Provider**: Use the generic OIDC provider configuration + +For provider-specific configuration examples, see the [OAuth Provider Configuration](../providers/index.md) documentation. + +### Benefits Over Kubernetes Dashboard + +Headlamp offers several advantages: + +- **Active Development**: Headlamp is actively maintained and developed +- **Modern UI**: Clean, intuitive interface with better UX +- **Plugin System**: Extensible with custom plugins +- **Multi-cluster Support**: Built-in support for managing multiple clusters +- **Desktop App**: Available as both web UI and desktop application + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.13.x/configuration/integrations/index.md b/docs/versioned_docs/version-7.13.x/configuration/integrations/index.md new file mode 100644 index 0000000000..b773910b05 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/integrations/index.md @@ -0,0 +1,41 @@ +--- +id: index +title: Integrations +--- + +This section provides configuration examples for integrating OAuth2 Proxy with various reverse proxies, ingress controllers, and Kubernetes web UIs. + +## Reverse Proxies and Ingress Controllers + +OAuth2 Proxy can be integrated with popular reverse proxies and ingress controllers to add authentication to your applications: + +- [Nginx](nginx.md) +- [Traefik](traefik.md) +- [caddy](caddy.md) + +## Kubernetes Web UIs + +OAuth2 Proxy can also be used to add authentication to Kubernetes web user interfaces: + +- [Headlamp](headlamp.md) ✨ *Recommended* +- [Kubernetes Dashboard](kubernetes-dashboard.md) ⚠️ *Deprecated* + +:::tip +When integrating with Kubernetes web UIs, make sure to: +1. Configure the Ingress to pass the Authorization header with the bearer token +2. Increase buffer sizes for large OIDC tokens (especially with Azure Entra ID) +3. Set up appropriate Kubernetes RBAC permissions for your users or groups +::: + +## General Requirements + +Most integrations require the following OAuth2 Proxy configuration: + +- `--reverse-proxy=true`: Required to correctly handle `X-Forwarded-*` headers +- **Session storage**: For production deployments with large tokens due to a lot of claims like AD groups, use `--session-store-type=redis` + +For provider-specific configuration, see the [OAuth Provider Configuration](../providers/index.md) documentation. + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.13.x/configuration/integrations/kubernetes-dashboard.md b/docs/versioned_docs/version-7.13.x/configuration/integrations/kubernetes-dashboard.md new file mode 100644 index 0000000000..5f21076872 --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/integrations/kubernetes-dashboard.md @@ -0,0 +1,289 @@ +--- +id: kubernetes-dashboard +title: Kubernetes Dashboard +--- + +:::warning Deprecated Project +Kubernetes Dashboard has been deprecated and discontinued as of January 2025. See the [official announcement](https://github.com/kubernetes/dashboard/commit/0ba796dce6916bb6ca5da5ca0b3ab22cecfd1e18) for more information. + +You may want to consider alternative solutions such as [Headlamp](./headlamp.md). +::: + +## Kubernetes Dashboard on AKS with Azure Entra ID + +Integration guide for the deprecated Kubernetes Dashboard, including comprehensive Azure Entra ID configuration on AKS with detailed troubleshooting and RBAC setup. + +### Architecture + +``` +User → Nginx Ingress → OAuth2 Proxy → Entra ID + ↓ + Kubernetes Dashboard +``` + +The integration flow: +1. Unauthenticated requests to Dashboard are intercepted by Nginx Ingress +2. Nginx redirects to OAuth2 Proxy for authentication +3. OAuth2 Proxy redirects to Entra ID login +4. After successful authentication, OAuth2 Proxy receives ID token from Entra ID +5. OAuth2 Proxy sets Authorization header with the bearer token +6. Nginx forwards the request with token to Kubernetes Dashboard +7. Dashboard validates the token and grants access based on AKS RBAC configuration + +### Prerequisites + +- AKS cluster with Entra ID integration enabled +- Kubernetes Dashboard installed (version 7.x or later) +- NGINX Ingress Controller installed +- Entra ID App Registration configured with: + - Redirect URI: `https://your-oauth2-domain.com/oauth2/callback` + - API Permissions: `openid`, `email`, `profile` + - Groups claim enabled (if using group-based RBAC) +- Users or groups assigned appropriate Kubernetes RBAC permissions + +### Alpha Configuration Example + +Using [Alpha Configuration](../alpha_config.md) with the OAuth2 Proxy Helm chart: + +```yaml +alphaConfig: + enabled: true + configData: + providers: + - id: azure-entra + provider: entra-id + clientID: YOUR_CLIENT_ID + clientSecret: YOUR_CLIENT_SECRET + oidcConfig: + issuerURL: https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0 + audienceClaims: + - aud + emailClaim: email + groupsClaim: groups + userIDClaim: oid + scope: openid email profile + + upstreamConfig: + upstreams: + - id: static + path: / + static: true + staticCode: 200 + + # Response headers passed to Dashboard via Nginx + injectResponseHeaders: + - name: Authorization + values: + - claim: id_token + prefix: "Bearer " + - name: X-Auth-Request-User + values: + - claim: email + - name: X-Auth-Request-Email + values: + - claim: email + - name: X-Auth-Request-Groups + values: + - claim: groups + + server: + BindAddress: "0.0.0.0:4180" + +extraArgs: + cookie-domain: ".your-domain.com" + whitelist-domain: ".your-domain.com" + email-domain: "*" # Or restrict to your organization + skip-provider-button: true + reverse-proxy: true + pass-authorization-header: true + set-xauthrequest: true + +sessionStorage: + type: redis + +redis: + enabled: true + auth: + enabled: true + +ingress: + enabled: true + className: nginx + hosts: + - OAuth2 Proxy.your-domain.com + path: /oauth2 + pathType: Prefix +``` + +### Kubernetes Dashboard Ingress + +**Critical**: The Ingress must include `Authorization` in the `auth-response-headers` annotation: + +```yaml +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: kubernetes-dashboard + namespace: kubernetes-dashboard + annotations: + nginx.ingress.kubernetes.io/backend-protocol: "HTTPS" + nginx.ingress.kubernetes.io/force-ssl-redirect: "true" + + # OAuth2 Proxy authentication + nginx.ingress.kubernetes.io/auth-url: "https://OAuth2 Proxy.your-domain.com/oauth2/auth" + nginx.ingress.kubernetes.io/auth-signin: "https://OAuth2 Proxy.your-domain.com/oauth2/start?rd=$scheme://$best_http_host$request_uri" + + # Include Authorization header with bearer token + nginx.ingress.kubernetes.io/auth-response-headers: "Authorization, X-Auth-Request-User, X-Auth-Request-Email" + + # Buffer sizes for large tokens (Entra tokens can exceed 4KB) + nginx.ingress.kubernetes.io/proxy-buffer-size: "256k" + nginx.ingress.kubernetes.io/proxy-buffers-number: "4" + nginx.ingress.kubernetes.io/proxy-busy-buffers-size: "256k" +spec: + ingressClassName: nginx + tls: + - hosts: + - dashboard.your-domain.com + secretName: dashboard-tls + rules: + - host: dashboard.your-domain.com + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: kubernetes-dashboard-kong-proxy + port: + number: 443 +``` + +### RBAC Configuration + +Assign Kubernetes permissions to Entra ID users or groups. + +**User-based:** +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: dashboard-user-admin +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: cluster-admin +subjects: + - kind: User + name: "user@your-domain.com" # Email from Entra ID token + apiGroup: rbac.authorization.k8s.io +``` + +**Group-based (recommended):** +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: dashboard-admins-group +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: cluster-admin +subjects: + - kind: Group + name: "YOUR_ENTRA_GROUP_OBJECT_ID" # Entra ID Group Object ID + apiGroup: rbac.authorization.k8s.io +``` + +For production, create custom roles with limited permissions instead of using `cluster-admin`. + +### Troubleshooting + +**Dashboard still asks for token after authentication** + +Verify that: +1. `injectResponseHeaders` in alphaConfig includes Authorization header with id_token claim +2. Dashboard Ingress includes `Authorization` in `auth-response-headers` annotation +3. Buffer sizes are sufficient for large tokens (set to 256k as shown above) +4. Check OAuth2 Proxy logs for successful token generation: `kubectl logs -n OAuth2 Proxy ` + +**"Unauthorized" or "Invalid token" errors** + +Common causes: +1. User/group not configured in Kubernetes RBAC + - Check: `kubectl get clusterrolebindings | grep ` +2. Token validation failed + - Verify AKS Entra ID integration is enabled + - Check Dashboard logs: `kubectl logs -n kubernetes-dashboard ` +3. Incorrect OAuth2 Proxy configuration + - Ensure `reverse-proxy: true` is set + - Verify issuer URL matches your tenant + +**Groups not included in token** + +To include groups in the token: +1. In Entra ID App Registration, go to **Token configuration** +2. Add **groups claim** and select security groups +3. Or edit the manifest and add: `"groupMembershipClaims": "SecurityGroup"` +4. For 200+ groups, ensure scope includes `User.Read` for group overage handling +5. Verify groups appear in token: check OAuth2 Proxy logs + +**Session expires too quickly** + +Configure cookie expiration: +```yaml +extraArgs: + cookie-expire: "24h" + cookie-refresh: "1h" +``` + +### Using Workload Identity (Passwordless) + +For production environments, use Workload Identity instead of client secrets: + +```yaml +config: + clientID: "YOUR_CLIENT_ID" + secretKeys: # Exclude client-secret + - client-id + - cookie-secret + cookieSecret: "YOUR_COOKIE_SECRET" + +serviceAccount: + annotations: + azure.workload.identity/client-id: YOUR_CLIENT_ID + azure.workload.identity/tenant-id: YOUR_TENANT_ID + +podLabels: + azure.workload.identity/use: "true" + +alphaConfig: + enabled: true + configData: + providers: + - id: azure-entra + provider: entra-id + clientID: YOUR_CLIENT_ID + oidcConfig: + issuerURL: https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0 + # ... other config + entraIdConfig: + federatedTokenAuth: true +``` + +This requires: +- AKS with OIDC issuer and Workload Identity enabled +- Federated identity credential configured in Entra ID App Registration +- Service account annotated with `azure.workload.identity/client-id` + +For detailed Workload Identity setup instructions, see the [Workload Identity section](../providers/ms_entra_id.md#workload-identity) in the Microsoft Entra ID provider documentation. + +## Integration with Other Providers + +While this guide focuses on Azure Entra ID, Kubernetes Dashboard can be integrated with other OAuth2 providers supported by OAuth2 Proxy. The key requirements remain the same: + +1. **Authorization Header**: Pass the bearer token via the `Authorization` header +2. **RBAC Configuration**: Configure Kubernetes RBAC for your authentication provider's users/groups +3. **Buffer Sizes**: Ensure adequate buffer sizes for tokens (especially important for OIDC providers) + +For provider-specific configuration examples, see the [OAuth Provider Configuration](../providers/index.md) documentation. diff --git a/docs/versioned_docs/version-7.13.x/configuration/integrations/nginx.md b/docs/versioned_docs/version-7.13.x/configuration/integrations/nginx.md new file mode 100644 index 0000000000..a36ed7622d --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/integrations/nginx.md @@ -0,0 +1,107 @@ +--- +id: nginx +title: Nginx +--- + +Configure OAuth2 Proxy with Nginx using the `auth_request` directive. Includes examples for both standalone Nginx configurations and Kubernetes ingress-nginx with annotations. + +**Key features:** +- Support for `auth_request` directive +- Kubernetes Ingress annotations +- Multi-part cookie handling for large tokens +- Session refresh support + +## Configuring for use with the Nginx `auth_request` directive + +**This option requires `--reverse-proxy` option to be set.** + +The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: + +```nginx +server { + listen 443 ssl; + server_name ...; + include ssl/ssl.conf; + + location /oauth2/ { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Auth-Request-Redirect $request_uri; + # or, if you are handling multiple domains: + # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; + } + location = /oauth2/auth { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; + # nginx auth_request includes headers but not body + proxy_set_header Content-Length ""; + proxy_pass_request_body off; + } + + location / { + auth_request /oauth2/auth; + error_page 401 =403 /oauth2/sign_in; + + # pass information via X-User and X-Email headers to backend, + # requires running with --set-xauthrequest flag + auth_request_set $user $upstream_http_x_auth_request_user; + auth_request_set $email $upstream_http_x_auth_request_email; + proxy_set_header X-User $user; + proxy_set_header X-Email $email; + + # if you enabled --pass-access-token, this will pass the token to the backend + auth_request_set $token $upstream_http_x_auth_request_access_token; + proxy_set_header X-Access-Token $token; + + # if you enabled --cookie-refresh, this is needed for it to work with auth_request + auth_request_set $auth_cookie $upstream_http_set_cookie; + add_header Set-Cookie $auth_cookie; + + # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb + # limit and so the OAuth2 Proxy splits these into multiple parts. + # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, + # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. + auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; + + # Extract the Cookie attributes from the first Set-Cookie header and append them + # to the second part ($upstream_cookie_* variables only contain the raw cookie content) + if ($auth_cookie ~* "(; .*)") { + set $auth_cookie_name_0 $auth_cookie; + set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; + } + + # Send both Set-Cookie headers now if there was a second part + if ($auth_cookie_name_upstream_1) { + add_header Set-Cookie $auth_cookie_name_0; + add_header Set-Cookie $auth_cookie_name_1; + } + + proxy_pass http://backend/; + # or "root /path/to/site;" or "fastcgi_pass ..." etc + } +} +``` + +When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: + +```yaml +nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" +nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" +``` + +This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. + +It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). + +:::tip Kubernetes Dashboard with Azure Entra ID +For a complete example of integrating oauth2-proxy with Kubernetes Dashboard on AKS using Azure Entra ID, including RBAC configuration and troubleshooting, see the [Kubernetes Dashboard on AKS](../providers/ms_entra_id.md#kubernetes-dashboard-on-aks) section in the Microsoft Entra ID provider documentation. +::: + +You have to substitute *name* with the actual cookie name you configured via --cookie-name parameter. If you don't set a custom cookie name the variable should be "$upstream_cookie__oauth2_proxy_1" instead of "$upstream_cookie_name_1" and the new cookie-name should be "_oauth2_proxy_1=" instead of "name_1=". + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.13.x/configuration/integrations/traefik.md b/docs/versioned_docs/version-7.13.x/configuration/integrations/traefik.md new file mode 100644 index 0000000000..e4b64b947b --- /dev/null +++ b/docs/versioned_docs/version-7.13.x/configuration/integrations/traefik.md @@ -0,0 +1,184 @@ +--- +id: traefik +title: Traefik +--- + +Set up OAuth2 Proxy with Traefik v2 using the `ForwardAuth` middleware. Includes examples for both error-based redirects and static upstream configurations. + +**Key features:** +- ForwardAuth middleware integration +- Error middleware for 401 redirects +- Static upstream configuration (202 responses) +- Dynamic file configuration examples + + +## Configuring for use with the Traefik (v2) `ForwardAuth` middleware + +**This option requires `--reverse-proxy` option to be set.** + +### ForwardAuth with 401 errors middleware + +The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: + +```yaml +http: + routers: + a-service: + rule: "Host(`a-service.example.com`)" + service: a-service-backend + middlewares: + - oauth-errors + - oauth-auth + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth: + rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + oauth-errors: + errors: + status: + - "401-403" + service: oauth-backend + query: "/oauth2/sign_in?rd={url}" +``` + +### ForwardAuth with static upstreams configuration + +Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint + +**Following options need to be set on `oauth2-proxy`:** +- `--upstream=static://202`: Configures a static response for authenticated sessions +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```yaml +http: + routers: + a-service-route-1: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" + service: a-service-backend + middlewares: + - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + a-service-route-2: + rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" + service: a-service-backend + middlewares: + - oauth-auth-wo-redirect # unauthenticated session will return a 401 + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + services-oauth2-route: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth2-proxy-route: + rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + b-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.3:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth-redirect: + forwardAuth: + address: https://oauth.example.com/ + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization + oauth-auth-wo-redirect: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.13.x/features/endpoints.md b/docs/versioned_docs/version-7.13.x/features/endpoints.md index 3ec1e2aa8a..6052a7d3e4 100644 --- a/docs/versioned_docs/version-7.13.x/features/endpoints.md +++ b/docs/versioned_docs/version-7.13.x/features/endpoints.md @@ -14,7 +14,7 @@ OAuth2 Proxy responds directly to the following endpoints. All other endpoints w - /oauth2/start - a URL that will redirect to start the OAuth cycle - /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url. - /oauth2/userinfo - the URL is used to return user's email from the session in JSON format. -- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integration#configuring-for-use-with-the-nginx-auth_request-directive) +- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integrations/nginx) - /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages ### Sign out diff --git a/docs/versioned_docs/version-7.14.x/configuration/integration.md b/docs/versioned_docs/version-7.14.x/configuration/integration.md deleted file mode 100644 index c57cfa6b36..0000000000 --- a/docs/versioned_docs/version-7.14.x/configuration/integration.md +++ /dev/null @@ -1,310 +0,0 @@ ---- -id: integration -title: Integration ---- - -## Configuring for use with the Nginx `auth_request` directive - -**This option requires `--reverse-proxy` option to be set.** - -The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: - -```nginx -server { - listen 443 ssl; - server_name ...; - include ssl/ssl.conf; - - location /oauth2/ { - proxy_pass http://127.0.0.1:4180; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Auth-Request-Redirect $request_uri; - # or, if you are handling multiple domains: - # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; - } - location = /oauth2/auth { - proxy_pass http://127.0.0.1:4180; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-Uri $request_uri; - # nginx auth_request includes headers but not body - proxy_set_header Content-Length ""; - proxy_pass_request_body off; - } - - location / { - auth_request /oauth2/auth; - error_page 401 =403 /oauth2/sign_in; - - # pass information via X-User and X-Email headers to backend, - # requires running with --set-xauthrequest flag - auth_request_set $user $upstream_http_x_auth_request_user; - auth_request_set $email $upstream_http_x_auth_request_email; - proxy_set_header X-User $user; - proxy_set_header X-Email $email; - - # if you enabled --pass-access-token, this will pass the token to the backend - auth_request_set $token $upstream_http_x_auth_request_access_token; - proxy_set_header X-Access-Token $token; - - # if you enabled --cookie-refresh, this is needed for it to work with auth_request - auth_request_set $auth_cookie $upstream_http_set_cookie; - add_header Set-Cookie $auth_cookie; - - # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb - # limit and so the OAuth2 Proxy splits these into multiple parts. - # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, - # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. - auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; - - # Extract the Cookie attributes from the first Set-Cookie header and append them - # to the second part ($upstream_cookie_* variables only contain the raw cookie content) - if ($auth_cookie ~* "(; .*)") { - set $auth_cookie_name_0 $auth_cookie; - set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; - } - - # Send both Set-Cookie headers now if there was a second part - if ($auth_cookie_name_upstream_1) { - add_header Set-Cookie $auth_cookie_name_0; - add_header Set-Cookie $auth_cookie_name_1; - } - - proxy_pass http://backend/; - # or "root /path/to/site;" or "fastcgi_pass ..." etc - } -} -``` - -When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: - -```yaml -nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" -nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" -``` - -This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. - -It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). - -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=". - -## Configuring for use with the Traefik (v2) `ForwardAuth` middleware - -**This option requires `--reverse-proxy` option to be set.** - -### ForwardAuth with 401 errors middleware - -The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: - -```yaml -http: - routers: - a-service: - rule: "Host(`a-service.example.com`)" - service: a-service-backend - middlewares: - - oauth-errors - - oauth-auth - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - oauth: - rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" - middlewares: - - auth-headers - service: oauth-backend - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - - services: - a-service-backend: - loadBalancer: - servers: - - url: http://172.16.0.2:7555 - oauth-backend: - loadBalancer: - servers: - - url: http://172.16.0.1:4180 - - middlewares: - auth-headers: - headers: - sslRedirect: true - stsSeconds: 315360000 - browserXssFilter: true - contentTypeNosniff: true - forceSTSHeader: true - sslHost: example.com - stsIncludeSubdomains: true - stsPreload: true - frameDeny: true - oauth-auth: - forwardAuth: - address: https://oauth.example.com/oauth2/auth - trustForwardHeader: true - oauth-errors: - errors: - status: - - "401-403" - service: oauth-backend - query: "/oauth2/sign_in?rd={url}" -``` - -### ForwardAuth with static upstreams configuration - -Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint - -**Following options need to be set on `oauth2-proxy`:** -- `--upstream=static://202`: Configures a static response for authenticated sessions -- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly - -```yaml -http: - routers: - a-service-route-1: - rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" - service: a-service-backend - middlewares: - - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - a-service-route-2: - rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" - service: a-service-backend - middlewares: - - oauth-auth-wo-redirect # unauthenticated session will return a 401 - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - services-oauth2-route: - rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" - middlewares: - - auth-headers - service: oauth-backend - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - oauth2-proxy-route: - rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" - middlewares: - - auth-headers - service: oauth-backend - tls: - certResolver: default - domains: - - main: "example.com" - sans: - - "*.example.com" - - services: - a-service-backend: - loadBalancer: - servers: - - url: http://172.16.0.2:7555 - b-service-backend: - loadBalancer: - servers: - - url: http://172.16.0.3:7555 - oauth-backend: - loadBalancer: - servers: - - url: http://172.16.0.1:4180 - - middlewares: - auth-headers: - headers: - sslRedirect: true - stsSeconds: 315360000 - browserXssFilter: true - contentTypeNosniff: true - forceSTSHeader: true - sslHost: example.com - stsIncludeSubdomains: true - stsPreload: true - frameDeny: true - oauth-auth-redirect: - forwardAuth: - address: https://oauth.example.com/ - trustForwardHeader: true - authResponseHeaders: - - X-Auth-Request-Access-Token - - Authorization - oauth-auth-wo-redirect: - forwardAuth: - address: https://oauth.example.com/oauth2/auth - trustForwardHeader: true - authResponseHeaders: - - X-Auth-Request-Access-Token - - Authorization -``` - -## Configuring for use with the Caddy (v2) `forward_auth` directive - -The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. - -This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. - -**Following options need to be set on `oauth2-proxy`:** -- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly - -```nginx title="Caddyfile" -example.com { - # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. - # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. - handle /oauth2/* { - reverse_proxy oauth2-proxy.internal:4180 { - # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. - # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. - header_up X-Real-IP {remote_host} - header_up X-Forwarded-Uri {uri} - } - } - - # Requests to other paths are first processed by oauth2-proxy for authentication. - handle { - forward_auth oauth2-proxy.internal:4180 { - uri /oauth2/auth - - # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. - # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. - header_up X-Real-IP {remote_host} - - # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. - # Make sure to configure the --set-xauthrequest flag to enable this feature. - #copy_headers X-Auth-Request-User X-Auth-Request-Email - - # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. - @error status 401 - handle_response @error { - redir * /oauth2/sign_in?rd={scheme}://{host}{uri} - } - } - - # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. - reverse_proxy upstream.internal:3000 - } -} -``` - -:::note -If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. -::: diff --git a/docs/versioned_docs/version-7.14.x/configuration/integrations/caddy.md b/docs/versioned_docs/version-7.14.x/configuration/integrations/caddy.md new file mode 100644 index 0000000000..1805e55996 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/integrations/caddy.md @@ -0,0 +1,63 @@ +--- +id: caddy +title: Caddy +--- + +Integrate OAuth2 Proxy with Caddy v2 using the `forward_auth` directive. + +**Key features:** +- Simple forward_auth setup +- Automatic header handling +- Custom error handling and redirects + +## Configuring for use with the Caddy (v2) `forward_auth` directive + +The [Caddy `forward_auth` directive](https://caddyserver.com/docs/caddyfile/directives/forward_auth) allows Caddy to authenticate requests via the `oauth2-proxy`'s `/auth`. + +This example is for a simple reverse proxy setup where the `/oauth2/` path is kept under the same domain and failed auth requests (401 status returned) will be caught and redirected to the `sign_in` endpoint. + +**Following options need to be set on `oauth2-proxy`:** +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```nginx title="Caddyfile" +example.com { + # Requests to /oauth2/* are proxied to oauth2-proxy without authentication. + # You can't use `reverse_proxy /oauth2/* oauth2-proxy.internal:4180` here because the reverse_proxy directive has lower precedence than the handle directive. + handle /oauth2/* { + reverse_proxy oauth2-proxy.internal:4180 { + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The reverse_proxy directive automatically sets X-Forwarded-{For,Proto,Host} headers. + header_up X-Real-IP {remote_host} + header_up X-Forwarded-Uri {uri} + } + } + + # Requests to other paths are first processed by oauth2-proxy for authentication. + handle { + forward_auth oauth2-proxy.internal:4180 { + uri /oauth2/auth + + # oauth2-proxy requires the X-Real-IP and X-Forwarded-{Proto,Host,Uri} headers. + # The forward_auth directive automatically sets the X-Forwarded-{For,Proto,Host,Method,Uri} headers. + header_up X-Real-IP {remote_host} + + # If needed, you can copy headers from the oauth2-proxy response to the request sent to the upstream. + # Make sure to configure the --set-xauthrequest flag to enable this feature. + #copy_headers X-Auth-Request-User X-Auth-Request-Email + + # If oauth2-proxy returns a 401 status, redirect the client to the sign-in page. + @error status 401 + handle_response @error { + redir * /oauth2/sign_in?rd={scheme}://{host}{uri} + } + } + + # If oauth2-proxy returns a 2xx status, the request is then proxied to the upstream. + reverse_proxy upstream.internal:3000 + } +} +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.14.x/configuration/integrations/headlamp.md b/docs/versioned_docs/version-7.14.x/configuration/integrations/headlamp.md new file mode 100644 index 0000000000..a6f6ac7316 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/integrations/headlamp.md @@ -0,0 +1,105 @@ +--- +id: headlamp +title: Headlamp +--- + +Modern, actively maintained Kubernetes web UI with OAuth2 Proxy integration examples. + +**Key features:** +- Active development and maintenance +- Modern, intuitive interface +- Multi-cluster support +- Plugin system +- Works with all OAuth2 providers + +## Configuring for use with Headlamp + +[Headlamp](https://headlamp.dev/) is a modern, user-friendly Kubernetes web UI that can be integrated with OAuth2 Proxy for authentication. This is a recommended alternative to the deprecated Kubernetes Dashboard. + +### Architecture + +``` +User → Ingress → OAuth2 Proxy → Authentication Provider (e.g., Azure Entra ID) + ↓ + Headlamp +``` + +### Prerequisites + +- Kubernetes cluster (e.g., AKS, EKS, GKE, or self-hosted) +- Headlamp installed in the cluster +- OAuth2 provider configured (Azure Entra ID, Google, GitHub, etc.) +- Ingress controller (Nginx, Traefik, etc.) + +### Configuration Overview + +When integrating Headlamp with OAuth2 Proxy, the OAuth2 Proxy acts as a reverse proxy in front of Headlamp: + +1. User requests access to Headlamp +2. Ingress forwards to OAuth2 Proxy +3. OAuth2 Proxy authenticates the user via the OAuth2 provider +4. After successful authentication, OAuth2 Proxy proxies requests to Headlamp +5. Headlamp receives the authenticated user information via headers + +### OAuth2 Proxy Configuration + +Configure OAuth2 Proxy to proxy to the Headlamp service: + +```yaml +upstreamConfig: + upstreams: + - id: headlamp + path: / + uri: http://headlamp-service.headlamp-namespace.svc.cluster.local:4466 +``` + +Enable the necessary headers: + +```yaml +extraArgs: + reverse-proxy: true + pass-authorization-header: true + set-xauthrequest: true + email-domain: "*" # Or restrict to your organization +``` + +### Example with Azure Entra ID on AKS + +For detailed instructions on deploying Headlamp with OAuth2 Proxy on Azure Kubernetes Service using Azure Entra ID, see the official Headlamp documentation: + +https://headlamp.dev/docs/latest/installation/in-cluster/aks-cluster-oauth/ + +Key steps include: + +1. **Set up AKS with OIDC**: Enable Microsoft Entra ID authentication with Kubernetes RBAC +2. **Create Azure App Registration**: Configure redirect URI and create client secret +3. **Deploy Headlamp**: Install Headlamp via Helm in your cluster +4. **Deploy OAuth2 Proxy**: Configure OAuth2 Proxy with Entra ID provider settings and upstream pointing to Headlamp +5. **Configure Ingress**: Set up Ingress to route traffic through OAuth2 Proxy to Headlamp +6. **Set RBAC Policies**: Apply Kubernetes RBAC bindings based on users or groups + +### Integration with Other Providers + +The same integration pattern works with other OAuth2 providers supported by OAuth2 Proxy: + +- **Google**: Use the Google provider configuration +- **GitHub**: Use the GitHub provider configuration +- **GitLab**: Use the GitLab provider configuration +- **Keycloak**: Use the Keycloak OIDC provider configuration +- **Any OIDC Provider**: Use the generic OIDC provider configuration + +For provider-specific configuration examples, see the [OAuth Provider Configuration](../providers/index.md) documentation. + +### Benefits Over Kubernetes Dashboard + +Headlamp offers several advantages: + +- **Active Development**: Headlamp is actively maintained and developed +- **Modern UI**: Clean, intuitive interface with better UX +- **Plugin System**: Extensible with custom plugins +- **Multi-cluster Support**: Built-in support for managing multiple clusters +- **Desktop App**: Available as both web UI and desktop application + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.14.x/configuration/integrations/index.md b/docs/versioned_docs/version-7.14.x/configuration/integrations/index.md new file mode 100644 index 0000000000..b773910b05 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/integrations/index.md @@ -0,0 +1,41 @@ +--- +id: index +title: Integrations +--- + +This section provides configuration examples for integrating OAuth2 Proxy with various reverse proxies, ingress controllers, and Kubernetes web UIs. + +## Reverse Proxies and Ingress Controllers + +OAuth2 Proxy can be integrated with popular reverse proxies and ingress controllers to add authentication to your applications: + +- [Nginx](nginx.md) +- [Traefik](traefik.md) +- [caddy](caddy.md) + +## Kubernetes Web UIs + +OAuth2 Proxy can also be used to add authentication to Kubernetes web user interfaces: + +- [Headlamp](headlamp.md) ✨ *Recommended* +- [Kubernetes Dashboard](kubernetes-dashboard.md) ⚠️ *Deprecated* + +:::tip +When integrating with Kubernetes web UIs, make sure to: +1. Configure the Ingress to pass the Authorization header with the bearer token +2. Increase buffer sizes for large OIDC tokens (especially with Azure Entra ID) +3. Set up appropriate Kubernetes RBAC permissions for your users or groups +::: + +## General Requirements + +Most integrations require the following OAuth2 Proxy configuration: + +- `--reverse-proxy=true`: Required to correctly handle `X-Forwarded-*` headers +- **Session storage**: For production deployments with large tokens due to a lot of claims like AD groups, use `--session-store-type=redis` + +For provider-specific configuration, see the [OAuth Provider Configuration](../providers/index.md) documentation. + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.14.x/configuration/integrations/kubernetes-dashboard.md b/docs/versioned_docs/version-7.14.x/configuration/integrations/kubernetes-dashboard.md new file mode 100644 index 0000000000..5f21076872 --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/integrations/kubernetes-dashboard.md @@ -0,0 +1,289 @@ +--- +id: kubernetes-dashboard +title: Kubernetes Dashboard +--- + +:::warning Deprecated Project +Kubernetes Dashboard has been deprecated and discontinued as of January 2025. See the [official announcement](https://github.com/kubernetes/dashboard/commit/0ba796dce6916bb6ca5da5ca0b3ab22cecfd1e18) for more information. + +You may want to consider alternative solutions such as [Headlamp](./headlamp.md). +::: + +## Kubernetes Dashboard on AKS with Azure Entra ID + +Integration guide for the deprecated Kubernetes Dashboard, including comprehensive Azure Entra ID configuration on AKS with detailed troubleshooting and RBAC setup. + +### Architecture + +``` +User → Nginx Ingress → OAuth2 Proxy → Entra ID + ↓ + Kubernetes Dashboard +``` + +The integration flow: +1. Unauthenticated requests to Dashboard are intercepted by Nginx Ingress +2. Nginx redirects to OAuth2 Proxy for authentication +3. OAuth2 Proxy redirects to Entra ID login +4. After successful authentication, OAuth2 Proxy receives ID token from Entra ID +5. OAuth2 Proxy sets Authorization header with the bearer token +6. Nginx forwards the request with token to Kubernetes Dashboard +7. Dashboard validates the token and grants access based on AKS RBAC configuration + +### Prerequisites + +- AKS cluster with Entra ID integration enabled +- Kubernetes Dashboard installed (version 7.x or later) +- NGINX Ingress Controller installed +- Entra ID App Registration configured with: + - Redirect URI: `https://your-oauth2-domain.com/oauth2/callback` + - API Permissions: `openid`, `email`, `profile` + - Groups claim enabled (if using group-based RBAC) +- Users or groups assigned appropriate Kubernetes RBAC permissions + +### Alpha Configuration Example + +Using [Alpha Configuration](../alpha_config.md) with the OAuth2 Proxy Helm chart: + +```yaml +alphaConfig: + enabled: true + configData: + providers: + - id: azure-entra + provider: entra-id + clientID: YOUR_CLIENT_ID + clientSecret: YOUR_CLIENT_SECRET + oidcConfig: + issuerURL: https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0 + audienceClaims: + - aud + emailClaim: email + groupsClaim: groups + userIDClaim: oid + scope: openid email profile + + upstreamConfig: + upstreams: + - id: static + path: / + static: true + staticCode: 200 + + # Response headers passed to Dashboard via Nginx + injectResponseHeaders: + - name: Authorization + values: + - claim: id_token + prefix: "Bearer " + - name: X-Auth-Request-User + values: + - claim: email + - name: X-Auth-Request-Email + values: + - claim: email + - name: X-Auth-Request-Groups + values: + - claim: groups + + server: + BindAddress: "0.0.0.0:4180" + +extraArgs: + cookie-domain: ".your-domain.com" + whitelist-domain: ".your-domain.com" + email-domain: "*" # Or restrict to your organization + skip-provider-button: true + reverse-proxy: true + pass-authorization-header: true + set-xauthrequest: true + +sessionStorage: + type: redis + +redis: + enabled: true + auth: + enabled: true + +ingress: + enabled: true + className: nginx + hosts: + - OAuth2 Proxy.your-domain.com + path: /oauth2 + pathType: Prefix +``` + +### Kubernetes Dashboard Ingress + +**Critical**: The Ingress must include `Authorization` in the `auth-response-headers` annotation: + +```yaml +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: kubernetes-dashboard + namespace: kubernetes-dashboard + annotations: + nginx.ingress.kubernetes.io/backend-protocol: "HTTPS" + nginx.ingress.kubernetes.io/force-ssl-redirect: "true" + + # OAuth2 Proxy authentication + nginx.ingress.kubernetes.io/auth-url: "https://OAuth2 Proxy.your-domain.com/oauth2/auth" + nginx.ingress.kubernetes.io/auth-signin: "https://OAuth2 Proxy.your-domain.com/oauth2/start?rd=$scheme://$best_http_host$request_uri" + + # Include Authorization header with bearer token + nginx.ingress.kubernetes.io/auth-response-headers: "Authorization, X-Auth-Request-User, X-Auth-Request-Email" + + # Buffer sizes for large tokens (Entra tokens can exceed 4KB) + nginx.ingress.kubernetes.io/proxy-buffer-size: "256k" + nginx.ingress.kubernetes.io/proxy-buffers-number: "4" + nginx.ingress.kubernetes.io/proxy-busy-buffers-size: "256k" +spec: + ingressClassName: nginx + tls: + - hosts: + - dashboard.your-domain.com + secretName: dashboard-tls + rules: + - host: dashboard.your-domain.com + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: kubernetes-dashboard-kong-proxy + port: + number: 443 +``` + +### RBAC Configuration + +Assign Kubernetes permissions to Entra ID users or groups. + +**User-based:** +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: dashboard-user-admin +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: cluster-admin +subjects: + - kind: User + name: "user@your-domain.com" # Email from Entra ID token + apiGroup: rbac.authorization.k8s.io +``` + +**Group-based (recommended):** +```yaml +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: dashboard-admins-group +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: cluster-admin +subjects: + - kind: Group + name: "YOUR_ENTRA_GROUP_OBJECT_ID" # Entra ID Group Object ID + apiGroup: rbac.authorization.k8s.io +``` + +For production, create custom roles with limited permissions instead of using `cluster-admin`. + +### Troubleshooting + +**Dashboard still asks for token after authentication** + +Verify that: +1. `injectResponseHeaders` in alphaConfig includes Authorization header with id_token claim +2. Dashboard Ingress includes `Authorization` in `auth-response-headers` annotation +3. Buffer sizes are sufficient for large tokens (set to 256k as shown above) +4. Check OAuth2 Proxy logs for successful token generation: `kubectl logs -n OAuth2 Proxy ` + +**"Unauthorized" or "Invalid token" errors** + +Common causes: +1. User/group not configured in Kubernetes RBAC + - Check: `kubectl get clusterrolebindings | grep ` +2. Token validation failed + - Verify AKS Entra ID integration is enabled + - Check Dashboard logs: `kubectl logs -n kubernetes-dashboard ` +3. Incorrect OAuth2 Proxy configuration + - Ensure `reverse-proxy: true` is set + - Verify issuer URL matches your tenant + +**Groups not included in token** + +To include groups in the token: +1. In Entra ID App Registration, go to **Token configuration** +2. Add **groups claim** and select security groups +3. Or edit the manifest and add: `"groupMembershipClaims": "SecurityGroup"` +4. For 200+ groups, ensure scope includes `User.Read` for group overage handling +5. Verify groups appear in token: check OAuth2 Proxy logs + +**Session expires too quickly** + +Configure cookie expiration: +```yaml +extraArgs: + cookie-expire: "24h" + cookie-refresh: "1h" +``` + +### Using Workload Identity (Passwordless) + +For production environments, use Workload Identity instead of client secrets: + +```yaml +config: + clientID: "YOUR_CLIENT_ID" + secretKeys: # Exclude client-secret + - client-id + - cookie-secret + cookieSecret: "YOUR_COOKIE_SECRET" + +serviceAccount: + annotations: + azure.workload.identity/client-id: YOUR_CLIENT_ID + azure.workload.identity/tenant-id: YOUR_TENANT_ID + +podLabels: + azure.workload.identity/use: "true" + +alphaConfig: + enabled: true + configData: + providers: + - id: azure-entra + provider: entra-id + clientID: YOUR_CLIENT_ID + oidcConfig: + issuerURL: https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0 + # ... other config + entraIdConfig: + federatedTokenAuth: true +``` + +This requires: +- AKS with OIDC issuer and Workload Identity enabled +- Federated identity credential configured in Entra ID App Registration +- Service account annotated with `azure.workload.identity/client-id` + +For detailed Workload Identity setup instructions, see the [Workload Identity section](../providers/ms_entra_id.md#workload-identity) in the Microsoft Entra ID provider documentation. + +## Integration with Other Providers + +While this guide focuses on Azure Entra ID, Kubernetes Dashboard can be integrated with other OAuth2 providers supported by OAuth2 Proxy. The key requirements remain the same: + +1. **Authorization Header**: Pass the bearer token via the `Authorization` header +2. **RBAC Configuration**: Configure Kubernetes RBAC for your authentication provider's users/groups +3. **Buffer Sizes**: Ensure adequate buffer sizes for tokens (especially important for OIDC providers) + +For provider-specific configuration examples, see the [OAuth Provider Configuration](../providers/index.md) documentation. diff --git a/docs/versioned_docs/version-7.14.x/configuration/integrations/nginx.md b/docs/versioned_docs/version-7.14.x/configuration/integrations/nginx.md new file mode 100644 index 0000000000..a36ed7622d --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/integrations/nginx.md @@ -0,0 +1,107 @@ +--- +id: nginx +title: Nginx +--- + +Configure OAuth2 Proxy with Nginx using the `auth_request` directive. Includes examples for both standalone Nginx configurations and Kubernetes ingress-nginx with annotations. + +**Key features:** +- Support for `auth_request` directive +- Kubernetes Ingress annotations +- Multi-part cookie handling for large tokens +- Session refresh support + +## Configuring for use with the Nginx `auth_request` directive + +**This option requires `--reverse-proxy` option to be set.** + +The [Nginx `auth_request` directive](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) allows Nginx to authenticate requests via the oauth2-proxy's `/auth` endpoint, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the request through. For example: + +```nginx +server { + listen 443 ssl; + server_name ...; + include ssl/ssl.conf; + + location /oauth2/ { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Auth-Request-Redirect $request_uri; + # or, if you are handling multiple domains: + # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; + } + location = /oauth2/auth { + proxy_pass http://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-Uri $request_uri; + # nginx auth_request includes headers but not body + proxy_set_header Content-Length ""; + proxy_pass_request_body off; + } + + location / { + auth_request /oauth2/auth; + error_page 401 =403 /oauth2/sign_in; + + # pass information via X-User and X-Email headers to backend, + # requires running with --set-xauthrequest flag + auth_request_set $user $upstream_http_x_auth_request_user; + auth_request_set $email $upstream_http_x_auth_request_email; + proxy_set_header X-User $user; + proxy_set_header X-Email $email; + + # if you enabled --pass-access-token, this will pass the token to the backend + auth_request_set $token $upstream_http_x_auth_request_access_token; + proxy_set_header X-Access-Token $token; + + # if you enabled --cookie-refresh, this is needed for it to work with auth_request + auth_request_set $auth_cookie $upstream_http_set_cookie; + add_header Set-Cookie $auth_cookie; + + # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb + # limit and so the OAuth2 Proxy splits these into multiple parts. + # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, + # so if your cookies are larger than 4kb, you will need to extract additional cookies manually. + auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; + + # Extract the Cookie attributes from the first Set-Cookie header and append them + # to the second part ($upstream_cookie_* variables only contain the raw cookie content) + if ($auth_cookie ~* "(; .*)") { + set $auth_cookie_name_0 $auth_cookie; + set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; + } + + # Send both Set-Cookie headers now if there was a second part + if ($auth_cookie_name_upstream_1) { + add_header Set-Cookie $auth_cookie_name_0; + add_header Set-Cookie $auth_cookie_name_1; + } + + proxy_pass http://backend/; + # or "root /path/to/site;" or "fastcgi_pass ..." etc + } +} +``` + +When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: + +```yaml +nginx.ingress.kubernetes.io/auth-url: "https:///oauth2/auth" +nginx.ingress.kubernetes.io/auth-signin: "https:///oauth2/start?rd=$escaped_request_uri" +``` + +This minimal configuration works for standard authentication flows. Lua/cookie handling is only needed for advanced scenarios (e.g., multi-part cookies, custom session logic). See the official ingress-nginx example: https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/. + +It is recommended to use `--session-store-type=redis` when expecting large sessions/OIDC tokens (_e.g._ with MS Azure). + +:::tip Kubernetes Dashboard with Azure Entra ID +For a complete example of integrating oauth2-proxy with Kubernetes Dashboard on AKS using Azure Entra ID, including RBAC configuration and troubleshooting, see the [Kubernetes Dashboard on AKS](../providers/ms_entra_id.md#kubernetes-dashboard-on-aks) section in the Microsoft Entra ID provider documentation. +::: + +You have to substitute *name* with the actual cookie name you configured via --cookie-name parameter. If you don't set a custom cookie name the variable should be "$upstream_cookie__oauth2_proxy_1" instead of "$upstream_cookie_name_1" and the new cookie-name should be "_oauth2_proxy_1=" instead of "name_1=". + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.14.x/configuration/integrations/traefik.md b/docs/versioned_docs/version-7.14.x/configuration/integrations/traefik.md new file mode 100644 index 0000000000..e4b64b947b --- /dev/null +++ b/docs/versioned_docs/version-7.14.x/configuration/integrations/traefik.md @@ -0,0 +1,184 @@ +--- +id: traefik +title: Traefik +--- + +Set up OAuth2 Proxy with Traefik v2 using the `ForwardAuth` middleware. Includes examples for both error-based redirects and static upstream configurations. + +**Key features:** +- ForwardAuth middleware integration +- Error middleware for 401 redirects +- Static upstream configuration (202 responses) +- Dynamic file configuration examples + + +## Configuring for use with the Traefik (v2) `ForwardAuth` middleware + +**This option requires `--reverse-proxy` option to be set.** + +### ForwardAuth with 401 errors middleware + +The [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) allows Traefik to authenticate requests via the oauth2-proxy's `/oauth2/auth` endpoint on every request, which only returns a 202 Accepted response or a 401 Unauthorized response without proxying the whole request through. For example, on Dynamic File (YAML) Configuration: + +```yaml +http: + routers: + a-service: + rule: "Host(`a-service.example.com`)" + service: a-service-backend + middlewares: + - oauth-errors + - oauth-auth + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth: + rule: "Host(`a-service.example.com`, `oauth.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + oauth-errors: + errors: + status: + - "401-403" + service: oauth-backend + query: "/oauth2/sign_in?rd={url}" +``` + +### ForwardAuth with static upstreams configuration + +Redirect to sign_in functionality provided without the use of `errors` middleware with [Traefik v2 `ForwardAuth` middleware](https://doc.traefik.io/traefik/middlewares/http/forwardauth/) pointing to oauth2-proxy service's `/` endpoint + +**Following options need to be set on `oauth2-proxy`:** +- `--upstream=static://202`: Configures a static response for authenticated sessions +- `--reverse-proxy=true`: Enables the use of `X-Forwarded-*` headers to determine redirects correctly + +```yaml +http: + routers: + a-service-route-1: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/`)" + service: a-service-backend + middlewares: + - oauth-auth-redirect # redirects all unauthenticated to oauth2 signin + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + a-service-route-2: + rule: "Host(`a-service.example.com`) && PathPrefix(`/no-auto-redirect`)" + service: a-service-backend + middlewares: + - oauth-auth-wo-redirect # unauthenticated session will return a 401 + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + services-oauth2-route: + rule: "Host(`a-service.example.com`, `b-service.example.com`) && PathPrefix(`/oauth2/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + oauth2-proxy-route: + rule: "Host(`oauth.example.com`) && PathPrefix(`/`)" + middlewares: + - auth-headers + service: oauth-backend + tls: + certResolver: default + domains: + - main: "example.com" + sans: + - "*.example.com" + + services: + a-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.2:7555 + b-service-backend: + loadBalancer: + servers: + - url: http://172.16.0.3:7555 + oauth-backend: + loadBalancer: + servers: + - url: http://172.16.0.1:4180 + + middlewares: + auth-headers: + headers: + sslRedirect: true + stsSeconds: 315360000 + browserXssFilter: true + contentTypeNosniff: true + forceSTSHeader: true + sslHost: example.com + stsIncludeSubdomains: true + stsPreload: true + frameDeny: true + oauth-auth-redirect: + forwardAuth: + address: https://oauth.example.com/ + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization + oauth-auth-wo-redirect: + forwardAuth: + address: https://oauth.example.com/oauth2/auth + trustForwardHeader: true + authResponseHeaders: + - X-Auth-Request-Access-Token + - Authorization +``` + +:::note +If you set up your OAuth2 provider to rotate your client secret, you can use the `client-secret-file` option to reload the secret when it is updated. +::: diff --git a/docs/versioned_docs/version-7.14.x/configuration/overview.md b/docs/versioned_docs/version-7.14.x/configuration/overview.md index b159df09cc..7bd7bf0710 100644 --- a/docs/versioned_docs/version-7.14.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.14.x/configuration/overview.md @@ -83,7 +83,7 @@ Provider specific options can be found on their respective subpages. | flag: `--approval-prompt`
toml: `approval_prompt` | string | OAuth approval_prompt | `"force"` | | flag: `--backend-logout-url`
toml: `backend_logout_url` | string | URL to perform backend logout, if you use `{id_token}` in the url it will be replaced by the actual `id_token` of the user session | | | flag: `--client-id`
toml: `client_id` | string | the OAuth Client ID, e.g. `"123456.apps.googleusercontent.com"` | | -| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret | | +| flag: `--client-secret-file`
toml: `client_secret_file` | string | the file with OAuth Client Secret. The file must contain the secret only, with no trailing newline | | | flag: `--client-secret`
toml: `client_secret` | string | the OAuth Client Secret | | | flag: `--code-challenge-method`
toml: `code_challenge_method` | string | use PKCE code challenges with the specified method. Either 'plain' or 'S256' (recommended) | | | flag: `--insecure-oidc-allow-unverified-email`
toml: `insecure_oidc_allow_unverified_email` | bool | don't fail if an email address in an id_token is not verified | false | @@ -128,7 +128,7 @@ Provider specific options can be found on their respective subpages. | flag: `--cookie-refresh`
toml: `cookie_refresh` | duration | refresh the cookie after this duration; `0` to disable; not supported by all providers [^1] | | | flag: `--cookie-samesite`
toml: `cookie_samesite` | string | set SameSite cookie attribute (`"lax"`, `"strict"`, `"none"`, or `""`). | `""` | | flag: `--cookie-secret`
toml: `cookie_secret` | string | the seed string for secure cookies (optionally base64 encoded) | | -| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | For defining a separate cookie secret file to read the encryption key from | | +| flag: `--cookie-secret-file`
toml: `cookie_secret_file` | string | File containing the cookie secret (must be raw binary, exactly 16, 24, or 32 bytes). Use dd if=/dev/urandom bs=32 count=1 > cookie.secret to generate | | | flag: `--cookie-secure`
toml: `cookie_secure` | bool | set [secure (HTTPS only) cookie flag](https://owasp.org/www-community/controls/SecureFlag) | true | [^1]: The following providers support `--cookie-refresh`: ADFS, Azure, GitLab, Google, Keycloak and all other Identity Providers which support the full [OIDC specification](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) diff --git a/docs/versioned_docs/version-7.14.x/features/endpoints.md b/docs/versioned_docs/version-7.14.x/features/endpoints.md index db00ba1e0b..5befce187c 100644 --- a/docs/versioned_docs/version-7.14.x/features/endpoints.md +++ b/docs/versioned_docs/version-7.14.x/features/endpoints.md @@ -15,7 +15,7 @@ OAuth2 Proxy responds directly to the following endpoints. All other endpoints w - /oauth2/start - a URL that will redirect to start the OAuth cycle - /oauth2/callback - the URL used at the end of the OAuth cycle. The oauth app will be configured with this as the callback url. - /oauth2/userinfo - the URL is used to return user's email from the session in JSON format. -- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integration#configuring-for-use-with-the-nginx-auth_request-directive) +- /oauth2/auth - only returns a 202 Accepted response or a 401 Unauthorized response; for use with the [Nginx `auth_request` directive](../configuration/integrations/nginx) - /oauth2/static/\* - stylesheets and other dependencies used in the sign_in and error pages ### Sign out diff --git a/docs/versioned_sidebars/version-7.13.x-sidebars.json b/docs/versioned_sidebars/version-7.13.x-sidebars.json index debf449177..cc52cf4899 100644 --- a/docs/versioned_sidebars/version-7.13.x-sidebars.json +++ b/docs/versioned_sidebars/version-7.13.x-sidebars.json @@ -22,7 +22,21 @@ "collapsed": false, "items": [ "configuration/overview", - "configuration/integration", + { + "type": "category", + "label": "Integration Guides", + "link": { + "type": "doc", + "id": "configuration/integrations/index" + }, + "items": [ + "configuration/integrations/nginx", + "configuration/integrations/traefik", + "configuration/integrations/caddy", + "configuration/integrations/headlamp", + "configuration/integrations/kubernetes-dashboard" + ] + }, { "type": "category", "label": "OAuth Provider Configuration", diff --git a/docs/versioned_sidebars/version-7.14.x-sidebars.json b/docs/versioned_sidebars/version-7.14.x-sidebars.json index debf449177..cc52cf4899 100644 --- a/docs/versioned_sidebars/version-7.14.x-sidebars.json +++ b/docs/versioned_sidebars/version-7.14.x-sidebars.json @@ -22,7 +22,21 @@ "collapsed": false, "items": [ "configuration/overview", - "configuration/integration", + { + "type": "category", + "label": "Integration Guides", + "link": { + "type": "doc", + "id": "configuration/integrations/index" + }, + "items": [ + "configuration/integrations/nginx", + "configuration/integrations/traefik", + "configuration/integrations/caddy", + "configuration/integrations/headlamp", + "configuration/integrations/kubernetes-dashboard" + ] + }, { "type": "category", "label": "OAuth Provider Configuration", From 3bc1a5373a9fecffdeb0b7c975e37d44a1c04912 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 16 Jan 2026 20:36:38 +0100 Subject: [PATCH 111/125] doc: extend the alpha config changelog notice Signed-off-by: Jan Larwig --- CHANGELOG.md | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 332d1560d9..9f814426b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ - [CVE-2025-61727](https://access.redhat.com/security/cve/cve-2025-61727) - [CVE-2025-47914](https://access.redhat.com/security/cve/cve-2025-47914) - [CVE-2025-58181](https://access.redhat.com/security/cve/cve-2025-58181) -- 🗂️ Alpha Config YAML parsing revamped using mapstructure with custom decoders +- 🗂️ AMajor Alpha Config YAML parsing revamped for better extensibility and preparing v8 - 🐛 Squashed some bugs ## Important Notes @@ -51,6 +51,38 @@ injectRequestHeaders: value: my-super-secret ``` +Furthermore, Alpha Config now fully supports configuring the `Server` struct using YAML. + +```yaml +// Server represents the configuration for the Proxy HTTP(S) configuration. +type Server struct { + // BindAddress is the address on which to serve traffic. + BindAddress string `yaml:"bindAddress,omitempty"` + + // SecureBindAddress is the address on which to serve secure traffic. + SecureBindAddress string `yaml:"secureBindAddress,omitempty"` + + // TLS contains the information for loading the certificate and key for the + // secure traffic and further configuration for the TLS server. + TLS *TLS `yaml:"tls,omitempty"` +} + +// TLS contains the information for loading a TLS certificate and key +// as well as an optional minimal TLS version that is acceptable. +type TLS struct { + // Key is the TLS key data to use. + Key *SecretSource `yaml:"key,omitempty"` + // Cert is the TLS certificate data to use. + Cert *SecretSource `yaml:"cert,omitempty"` + // MinVersion is the minimal TLS version that is acceptable. + MinVersion string `yaml:"minVersion,omitempty"` + // CipherSuites is a list of TLS cipher suites that are allowed. + CipherSuites []string `yaml:"cipherSuites,omitempty"` +} +``` + +More about how to use Alpha Config can be found in the [documentation](https://oauth2-proxy.github.io/oauth2-proxy/configuration/alpha-config#server). + We are committed to Semantic Versioning and usually avoid breaking changes without a major version release. Advancing Alpha Config toward its Beta stage required this exception, and even for the Alpha Config we try to keep breaking changes in v7 to a minium. Thank you for understanding the need for this step to prepare From 1f29953b7b28b053d7b8c5e18c8742f450cb7eb9 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Fri, 16 Jan 2026 20:37:46 +0100 Subject: [PATCH 112/125] docs: add todo for revamping the usage / naming of PassHostHeader Signed-off-by: Jan Larwig --- pkg/upstream/http.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pkg/upstream/http.go b/pkg/upstream/http.go index b3c3ae7483..9112756e80 100644 --- a/pkg/upstream/http.go +++ b/pkg/upstream/http.go @@ -157,6 +157,8 @@ func newReverseProxy(target *url.URL, upstream options.Upstream, errorHandler Pr // Ensure we always pass the original request path setProxyDirector(proxy) + // TODO (@tuunit) - this should be inverted or get a better name in the future to set the upstream host header + // only if PassHostHeader is explicitly set to true. Currently this would be a breaking change. if !ptr.Deref(upstream.PassHostHeader, options.DefaultUpstreamPassHostHeader) { setProxyUpstreamHostHeader(proxy, target) } @@ -215,6 +217,8 @@ func newWebSocketReverseProxy(u *url.URL, skipTLSVerify *bool, passHostHeader *b // Apply the customized transport to our proxy before returning it wsProxy.Transport = transport + // TODO (@tuunit) - this should be inverted or get a better name in the future to set the upstream host header + // only if PassHostHeader is explicitly set to true. Currently this would be a breaking change. // Set upstream host header if PassHostHeader is false (same as regular HTTP proxy) if !ptr.Deref(passHostHeader, options.DefaultUpstreamPassHostHeader) { setProxyUpstreamHostHeader(wsProxy, u) From 9c61c49ec29dce1c6bddfe209940bb406f42f8fc Mon Sep 17 00:00:00 2001 From: Stefan Markmann <50301139+StefanMarkmann@users.noreply.github.com> Date: Sat, 17 Jan 2026 14:35:44 +0100 Subject: [PATCH 113/125] fix: skip provider button auth only redirect (#3309) * fix: Return 302 redirect from AuthOnly when skip-provider-button is true When SkipProviderButton is enabled and a user needs to login, the AuthOnly endpoint now returns a 302 redirect directly to the OAuth provider instead of returning 401. This fixes an issue with nginx auth_request architecture where 401 triggers error_page handling, which can break redirect flows because nginx overrides the status code (e.g., to 403), and browsers don't follow Location headers for non-3xx responses. Fixes: #334 Signed-off-by: Stefan Markmann * update docs and changelog Signed-off-by: Stefan Markmann * test: Add specific OAuth redirect assertions per code review feedback Improve TestAuthOnlyEndpointRedirectWithSkipProviderButton to verify that the Location header actually redirects to the OAuth provider's authorize endpoint with required parameters (client_id, redirect_uri, state), not just that a Location header exists. Signed-off-by: Stefan Markmann * refactor: Flatten AuthOnly error handling structure Move the SkipProviderButton check outside of the nested err != nil block using an if-else structure. This makes the special case more visible and reduces nesting depth without changing behavior. Signed-off-by: Stefan Markmann * doc: backport to v7.14.x Signed-off-by: Jan Larwig --------- Signed-off-by: Stefan Markmann Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 2 + docs/docs/configuration/overview.md | 2 +- .../version-7.14.x/configuration/overview.md | 2 +- oauthproxy.go | 10 ++++- oauthproxy_test.go | 45 ++++++++++++++++++- 5 files changed, 56 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f814426b9..0041223477 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ ## Changes since v7.14.0 +- [#3309](https://github.com/oauth2-proxy/oauth2-proxy/pull/3309) fix: Return 302 redirect from AuthOnly endpoint when skip-provider-button is true (@StefanMarkmann) + # V7.14.0 ## Release Highlights diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index 7bd7bf0710..c545533675 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -214,7 +214,7 @@ Provider specific options can be found on their respective subpages. | flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | | flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | | flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | -| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--skip-provider-button`
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 | | flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | | flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | | flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | diff --git a/docs/versioned_docs/version-7.14.x/configuration/overview.md b/docs/versioned_docs/version-7.14.x/configuration/overview.md index 7bd7bf0710..c545533675 100644 --- a/docs/versioned_docs/version-7.14.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.14.x/configuration/overview.md @@ -214,7 +214,7 @@ Provider specific options can be found on their respective subpages. | flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | | flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | | flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | -| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | +| flag: `--skip-provider-button`
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 | | flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | | flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | | flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | diff --git a/oauthproxy.go b/oauthproxy.go index d933d930cc..dda1b34fcf 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -987,7 +987,15 @@ func (p *OAuthProxy) enrichSessionState(ctx context.Context, s *sessionsapi.Sess // and optional authorization). func (p *OAuthProxy) AuthOnly(rw http.ResponseWriter, req *http.Request) { session, err := p.getAuthenticatedSession(rw, req) - if err != nil { + // If SkipProviderButton is enabled and user needs login, redirect directly + // to OAuth provider instead of returning 401. This allows nginx auth_request + // to pass through the 302 redirect to the browser, bypassing error_page + // handling which can break redirect flows. + // See: https://github.com/oauth2-proxy/oauth2-proxy/issues/334 + if p.SkipProviderButton && err == ErrNeedsLogin { + p.doOAuthStart(rw, req, nil) + return + } else if err != nil { http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } diff --git a/oauthproxy_test.go b/oauthproxy_test.go index ccabdbbd01..489a1b69d3 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -834,8 +834,20 @@ func NewProcessCookieTest(opts ProcessCookieTestOpts, modifiers ...OptionsModifi return nil, err } testProvider := &TestProvider{ - ProviderData: &providers.ProviderData{}, - ValidToken: opts.providerValidateCookieResponse, + ProviderData: &providers.ProviderData{ + ProviderName: "Test Provider", + LoginURL: &url.URL{ + Scheme: "http", + Host: "localhost", + Path: "/oauth/authorize", + }, + RedeemURL: &url.URL{ + Scheme: "http", + Host: "localhost", + Path: "/oauth/token", + }, + }, + ValidToken: opts.providerValidateCookieResponse, } groups := pcTest.opts.Providers[0].AllowedGroups @@ -1112,6 +1124,35 @@ func TestAuthOnlyEndpointUnauthorizedOnNoCookieSetError(t *testing.T) { assert.Equal(t, "Unauthorized\n", string(bodyBytes)) } +// TestAuthOnlyEndpointRedirectWithSkipProviderButton tests that when SkipProviderButton +// is true and no session exists, the /auth endpoint should return a 302 redirect +// to the OAuth provider instead of 401. This is important for nginx auth_request +// architecture where 401 triggers error_page handling which can break the redirect flow. +// See: https://github.com/oauth2-proxy/oauth2-proxy/issues/334 +func TestAuthOnlyEndpointRedirectWithSkipProviderButton(t *testing.T) { + test, err := NewAuthOnlyEndpointTest("", func(opts *options.Options) { + opts.SkipProviderButton = true + }) + if err != nil { + t.Fatal(err) + } + + test.proxy.ServeHTTP(test.rw, test.req) + + // With SkipProviderButton=true and no session, should return 302 redirect + // to OAuth provider, NOT 401 Unauthorized + assert.Equal(t, http.StatusFound, test.rw.Code) + location := test.rw.Header().Get("Location") + assert.NotEmpty(t, location, "Expected Location header for redirect") + + // Verify the redirect points to the OAuth provider's authorize endpoint + // and contains key OAuth parameters + assert.Contains(t, location, "/oauth/authorize", "Expected redirect to OAuth authorize endpoint") + assert.Contains(t, location, "client_id=", "Expected client_id in redirect URL") + assert.Contains(t, location, "redirect_uri=", "Expected redirect_uri in redirect URL") + assert.Contains(t, location, "state=", "Expected state parameter in redirect URL") +} + func TestAuthOnlyEndpointUnauthorizedOnExpiration(t *testing.T) { test, err := NewAuthOnlyEndpointTest("", func(opts *options.Options) { opts.Cookie.Expire = time.Duration(24) * time.Hour From 59f4e42a5af56bc360cd38221451ac7f134b4856 Mon Sep 17 00:00:00 2001 From: Sourav Agrawal <146818014+sourava01@users.noreply.github.com> Date: Sat, 17 Jan 2026 19:45:19 +0530 Subject: [PATCH 114/125] fix: static upstreams failing validation due to `passHostHeader` and `proxyWebSockets` defaults being set incorrectly (#3302) * fix: static upstream validation failure Signed-off-by: Sourav Agrawal * fix: enforcement of defaults compatible with static upstreams Signed-off-by: Jan Larwig --------- Signed-off-by: Sourav Agrawal Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 1 + pkg/apis/options/legacy_options.go | 8 ++++---- pkg/apis/options/legacy_options_test.go | 24 ++++++++++++------------ pkg/apis/options/upstreams.go | 24 +++++++++++++++++++++--- pkg/validation/upstreams.go | 6 +++--- pkg/validation/upstreams_test.go | 20 +++++++++++++++++++- 6 files changed, 60 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0041223477..5de3022a0b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ## Changes since v7.14.0 - [#3309](https://github.com/oauth2-proxy/oauth2-proxy/pull/3309) fix: Return 302 redirect from AuthOnly endpoint when skip-provider-button is true (@StefanMarkmann) +- [#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) # V7.14.0 diff --git a/pkg/apis/options/legacy_options.go b/pkg/apis/options/legacy_options.go index 6ce730fd8e..b4f37aaf2f 100644 --- a/pkg/apis/options/legacy_options.go +++ b/pkg/apis/options/legacy_options.go @@ -179,10 +179,10 @@ func (l *LegacyUpstreams) convert() (UpstreamConfig, error) { upstream.URI = "" upstream.InsecureSkipTLSVerify = ptr.To(false) upstream.DisableKeepAlives = ptr.To(false) - upstream.PassHostHeader = nil - upstream.ProxyWebSockets = nil - upstream.FlushInterval = nil - upstream.Timeout = nil + upstream.PassHostHeader = ptr.To(false) + upstream.ProxyWebSockets = ptr.To(false) + upstream.FlushInterval = ptr.To(DefaultUpstreamFlushInterval) + upstream.Timeout = ptr.To(DefaultUpstreamTimeout) case "unix": upstream.Path = "/" } diff --git a/pkg/apis/options/legacy_options_test.go b/pkg/apis/options/legacy_options_test.go index ceba53afa1..d8d14bb0d4 100644 --- a/pkg/apis/options/legacy_options_test.go +++ b/pkg/apis/options/legacy_options_test.go @@ -204,12 +204,12 @@ var _ = Describe("Legacy Options", func() { URI: "", Static: ptr.To(true), StaticCode: &validStaticCode, - InsecureSkipTLSVerify: ptr.To(false), - PassHostHeader: nil, - ProxyWebSockets: nil, - FlushInterval: nil, - Timeout: nil, - DisableKeepAlives: ptr.To(false), + InsecureSkipTLSVerify: ptr.To(DefaultUpsteamInsecureSkipTLSVerify), + PassHostHeader: ptr.To(DefaultStaticPassHostHeader), + ProxyWebSockets: ptr.To(DefaultStaticProxyWebSockets), + FlushInterval: ptr.To(DefaultUpstreamFlushInterval), + Timeout: ptr.To(DefaultUpstreamTimeout), + DisableKeepAlives: ptr.To(DefaultUpstreamDisableKeepAlives), } invalidStatic := "static://abc" @@ -220,12 +220,12 @@ var _ = Describe("Legacy Options", func() { URI: "", Static: ptr.To(true), StaticCode: &invalidStaticCode, - InsecureSkipTLSVerify: ptr.To(false), - PassHostHeader: nil, - ProxyWebSockets: nil, - FlushInterval: nil, - Timeout: nil, - DisableKeepAlives: ptr.To(false), + InsecureSkipTLSVerify: ptr.To(DefaultUpsteamInsecureSkipTLSVerify), + PassHostHeader: ptr.To(DefaultStaticPassHostHeader), + ProxyWebSockets: ptr.To(DefaultStaticProxyWebSockets), + FlushInterval: ptr.To(DefaultUpstreamFlushInterval), + Timeout: ptr.To(DefaultUpstreamTimeout), + DisableKeepAlives: ptr.To(DefaultUpstreamDisableKeepAlives), } invalidHTTP := ":foo" diff --git a/pkg/apis/options/upstreams.go b/pkg/apis/options/upstreams.go index a56fca612b..578ab4548d 100644 --- a/pkg/apis/options/upstreams.go +++ b/pkg/apis/options/upstreams.go @@ -29,9 +29,15 @@ const ( // DefaultUpstreamPassHostHeader determines if upstreams will pass the host header by default. DefaultUpstreamPassHostHeader bool = true + // Static upstreams cannot pass the host header. + DefaultStaticPassHostHeader bool = false + // DefaultUpstreamProxyWebSockets determines if upstreams will proxy websockets by default. DefaultUpstreamProxyWebSockets bool = true + // Static upstreams cannot proxy websockets. + DefaultStaticProxyWebSockets bool = false + // DefaultUpstreamDisableKeepAlives determines if upstreams will disable keep-alives by default. DefaultUpstreamDisableKeepAlives bool = false ) @@ -143,19 +149,31 @@ func (u *Upstream) EnsureDefaults() { if u.Static == nil { u.Static = ptr.To(DefaultUpstreamStatic) } - if u.FlushInterval == nil { - u.FlushInterval = ptr.To(DefaultUpstreamFlushInterval) - } if u.PassHostHeader == nil { u.PassHostHeader = ptr.To(DefaultUpstreamPassHostHeader) } if u.ProxyWebSockets == nil { u.ProxyWebSockets = ptr.To(DefaultUpstreamProxyWebSockets) } + if u.FlushInterval == nil { + u.FlushInterval = ptr.To(DefaultUpstreamFlushInterval) + } if u.Timeout == nil { u.Timeout = ptr.To(DefaultUpstreamTimeout) } if u.DisableKeepAlives == nil { u.DisableKeepAlives = ptr.To(DefaultUpstreamDisableKeepAlives) } + + // Force defaults compatible with static upstreams. + // This overrides any user provided values to ensure static upstreams behave correctly. + if ptr.Deref(u.Static, DefaultUpstreamStatic) { + u.URI = "" + u.InsecureSkipTLSVerify = ptr.To(DefaultUpsteamInsecureSkipTLSVerify) + u.DisableKeepAlives = ptr.To(DefaultUpstreamDisableKeepAlives) + u.PassHostHeader = ptr.To(DefaultStaticPassHostHeader) + u.ProxyWebSockets = ptr.To(DefaultStaticProxyWebSockets) + u.FlushInterval = ptr.To(DefaultUpstreamFlushInterval) + u.Timeout = ptr.To(DefaultUpstreamTimeout) + } } diff --git a/pkg/validation/upstreams.go b/pkg/validation/upstreams.go index 9a3819180e..49edc32e31 100644 --- a/pkg/validation/upstreams.go +++ b/pkg/validation/upstreams.go @@ -70,13 +70,13 @@ func validateStaticUpstream(upstream options.Upstream) []string { if ptr.Deref(upstream.InsecureSkipTLSVerify, options.DefaultUpsteamInsecureSkipTLSVerify) { msgs = append(msgs, fmt.Sprintf("upstream %q has insecureSkipTLSVerify, but is a static upstream, this will have no effect.", upstream.ID)) } - if upstream.FlushInterval != nil && *upstream.FlushInterval != options.DefaultUpstreamFlushInterval { + if ptr.Deref(upstream.FlushInterval, options.DefaultUpstreamFlushInterval) != options.DefaultUpstreamFlushInterval { msgs = append(msgs, fmt.Sprintf("upstream %q has flushInterval, but is a static upstream, this will have no effect.", upstream.ID)) } - if upstream.PassHostHeader != nil { + if ptr.Deref(upstream.PassHostHeader, options.DefaultStaticPassHostHeader) != options.DefaultStaticPassHostHeader { msgs = append(msgs, fmt.Sprintf("upstream %q has passHostHeader, but is a static upstream, this will have no effect.", upstream.ID)) } - if upstream.ProxyWebSockets != nil { + if ptr.Deref(upstream.ProxyWebSockets, options.DefaultStaticProxyWebSockets) != options.DefaultStaticProxyWebSockets { msgs = append(msgs, fmt.Sprintf("upstream %q has proxyWebSockets, but is a static upstream, this will have no effect.", upstream.ID)) } diff --git a/pkg/validation/upstreams_test.go b/pkg/validation/upstreams_test.go index 79b29a2226..42ef467b5d 100644 --- a/pkg/validation/upstreams_test.go +++ b/pkg/validation/upstreams_test.go @@ -138,7 +138,7 @@ var _ = Describe("Upstreams", func() { }, errStrings: []string{invalidURISchemeMsg}, }), - Entry("with a static upstream and invalid optons", &validateUpstreamTableInput{ + Entry("with a static upstream and invalid options", &validateUpstreamTableInput{ upstreams: options.UpstreamConfig{ Upstreams: []options.Upstream{ { @@ -161,6 +161,24 @@ var _ = Describe("Upstreams", func() { staticWithProxyWebSocketsMsg, }, }), + Entry("with a static upstream and sane default options", &validateUpstreamTableInput{ + upstreams: options.UpstreamConfig{ + Upstreams: []options.Upstream{ + { + ID: "foo", + Path: "/foo", + URI: "ftp://foo", + Static: ptr.To(true), + PassHostHeader: ptr.To(false), + ProxyWebSockets: ptr.To(false), + InsecureSkipTLSVerify: ptr.To(false), + }, + }, + }, + errStrings: []string{ + staticWithURIMsg, + }, + }), Entry("with duplicate IDs", &validateUpstreamTableInput{ upstreams: options.UpstreamConfig{ Upstreams: []options.Upstream{ From 844e4e3b0ca32c7824e8ce93fcd269d7bf45b089 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 17 Jan 2026 14:52:13 +0100 Subject: [PATCH 115/125] chore(deps): upgrade to go1.25.6; upgrade all go dependencies Signed-off-by: Jan Larwig --- .github/workflows/ci.yml | 4 +--- .github/workflows/publish-release.yml | 4 +--- CHANGELOG.md | 1 + go.mod | 32 +++++++++++++-------------- go.sum | 30 +++++++++++++++++++++++++ 5 files changed, 49 insertions(+), 22 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aa77fbf4df..64d82af220 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,11 +25,9 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.7.2 + GOLANGCI_LINT_VERSION: v2.8.0 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} - curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter - chmod +x ./cc-test-reporter - name: Verify Code Generation run: | diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 64b334e572..d3a8115f94 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -50,11 +50,9 @@ jobs: - name: Get dependencies env: # renovate: datasource=github-tags depName=golangci/golangci-lint - GOLANGCI_LINT_VERSION: v2.7.2 + GOLANGCI_LINT_VERSION: v2.8.0 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} - curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter - chmod +x ./cc-test-reporter # Install go dependencies go mod download diff --git a/CHANGELOG.md b/CHANGELOG.md index 5de3022a0b..e6e8605ade 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - [#3309](https://github.com/oauth2-proxy/oauth2-proxy/pull/3309) fix: Return 302 redirect from AuthOnly endpoint when skip-provider-button is true (@StefanMarkmann) - [#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) +- [#3312](https://github.com/oauth2-proxy/oauth2-proxy/pull/3312) chore(deps): upgrade to go1.25.6 and latest dependencies (@tuunit) # V7.14.0 diff --git a/go.mod b/go.mod index 895f55fa91..f6eb45c264 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/oauth2-proxy/oauth2-proxy/v7 -go 1.25.5 +go 1.25.6 require ( cloud.google.com/go/compute/metadata v0.9.0 @@ -13,16 +13,16 @@ require ( github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf github.com/fsnotify/fsnotify v1.9.0 github.com/go-jose/go-jose/v3 v3.0.4 - github.com/go-viper/mapstructure/v2 v2.4.0 + github.com/go-viper/mapstructure/v2 v2.5.0 github.com/golang-jwt/jwt/v5 v5.3.0 github.com/google/go-cmp v0.7.0 github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 github.com/justinas/alice v1.2.0 github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 - github.com/onsi/ginkgo/v2 v2.27.3 - github.com/onsi/gomega v1.38.3 - github.com/pierrec/lz4/v4 v4.1.23 + github.com/onsi/ginkgo/v2 v2.27.5 + github.com/onsi/gomega v1.39.0 + github.com/pierrec/lz4/v4 v4.1.25 github.com/prometheus/client_golang v1.23.2 github.com/redis/go-redis/v9 v9.17.2 github.com/spf13/cast v1.10.0 @@ -31,11 +31,11 @@ require ( github.com/stretchr/testify v1.11.1 github.com/vmihailenco/msgpack/v5 v5.4.1 go.yaml.in/yaml/v3 v3.0.4 - golang.org/x/crypto v0.46.0 - golang.org/x/net v0.48.0 + golang.org/x/crypto v0.47.0 + golang.org/x/net v0.49.0 golang.org/x/oauth2 v0.34.0 golang.org/x/sync v0.19.0 - google.golang.org/api v0.258.0 + google.golang.org/api v0.260.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 k8s.io/apimachinery v0.35.0 ) @@ -53,16 +53,16 @@ require ( github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-task/slim-sprig/v3 v3.0.0 // indirect - github.com/google/pprof v0.0.0-20251213031049-b05bdaca462f // indirect + github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 // indirect github.com/google/s2a-go v0.1.9 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.7 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.11 // indirect github.com/googleapis/gax-go/v2 v2.16.0 // indirect github.com/kylelemons/godebug v1.1.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.67.4 // indirect + github.com/prometheus/common v0.67.5 // indirect github.com/prometheus/procfs v0.19.2 // indirect github.com/sagikazarmark/locafero v0.12.0 // indirect github.com/spf13/afero v1.15.0 // indirect @@ -75,11 +75,11 @@ require ( go.opentelemetry.io/otel/metric v1.39.0 // indirect go.opentelemetry.io/otel/trace v1.39.0 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect - golang.org/x/mod v0.31.0 // indirect - golang.org/x/sys v0.39.0 // indirect - golang.org/x/text v0.32.0 // indirect - golang.org/x/tools v0.40.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect + golang.org/x/mod v0.32.0 // indirect + golang.org/x/sys v0.40.0 // indirect + golang.org/x/text v0.33.0 // indirect + golang.org/x/tools v0.41.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260114163908-3f89685c29c3 // indirect google.golang.org/grpc v1.78.0 // indirect google.golang.org/protobuf v1.36.11 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index 3d6948ed85..d09db4d341 100644 --- a/go.sum +++ b/go.sum @@ -65,6 +65,8 @@ github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1v github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= +github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo= @@ -78,6 +80,8 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/pprof v0.0.0-20251213031049-b05bdaca462f h1:HU1RgM6NALf/KW9HEY6zry3ADbDKcmpQ+hJedoNGQYQ= github.com/google/pprof v0.0.0-20251213031049-b05bdaca462f/go.mod h1:67FPmZWbr+KDT/VlpWtw6sO9XSjpJmLuHpoLmWiTGgY= +github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 h1:z2ogiKUYzX5Is6zr/vP9vJGqPwcdqsWjOt+V8J7+bTc= +github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -85,6 +89,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/enterprise-certificate-proxy v0.3.7 h1:zrn2Ee/nWmHulBx5sAVrGgAa0f2/R35S4DJwfFaUPFQ= github.com/googleapis/enterprise-certificate-proxy v0.3.7/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= +github.com/googleapis/enterprise-certificate-proxy v0.3.11 h1:vAe81Msw+8tKUxi2Dqh/NZMz7475yUvmRIkXr4oN2ao= +github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8= github.com/googleapis/gax-go/v2 v2.16.0 h1:iHbQmKLLZrexmb0OSsNGTeSTS0HO4YvFOG8g5E4Zd0Y= github.com/googleapis/gax-go/v2 v2.16.0/go.mod h1:o1vfQjjNZn4+dPnRdl/4ZD7S9414Y4xA+a/6Icj6l14= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= @@ -113,12 +119,18 @@ github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3Tc github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw= github.com/onsi/ginkgo/v2 v2.27.3 h1:ICsZJ8JoYafeXFFlFAG75a7CxMsJHwgKwtO+82SE9L8= github.com/onsi/ginkgo/v2 v2.27.3/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= +github.com/onsi/ginkgo/v2 v2.27.5 h1:ZeVgZMx2PDMdJm/+w5fE/OyG6ILo1Y3e+QX4zSR0zTE= +github.com/onsi/ginkgo/v2 v2.27.5/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= github.com/onsi/gomega v1.38.3 h1:eTX+W6dobAYfFeGC2PV6RwXRu/MyT+cQguijutvkpSM= github.com/onsi/gomega v1.38.3/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4= +github.com/onsi/gomega v1.39.0 h1:y2ROC3hKFmQZJNFeGAMeHZKkjBL65mIZcvrLQBF9k6Q= +github.com/onsi/gomega v1.39.0/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pierrec/lz4/v4 v4.1.23 h1:oJE7T90aYBGtFNrI8+KbETnPymobAhzRrR8Mu8n1yfU= github.com/pierrec/lz4/v4 v4.1.23/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= +github.com/pierrec/lz4/v4 v4.1.25 h1:kocOqRffaIbU5djlIBr7Wh+cx82C0vtFb0fOurZHqD0= +github.com/pierrec/lz4/v4 v4.1.25/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -128,6 +140,8 @@ github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNw github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= github.com/prometheus/common v0.67.4 h1:yR3NqWO1/UyO1w2PhUvXlGQs/PtFmoveVO0KZ4+Lvsc= github.com/prometheus/common v0.67.4/go.mod h1:gP0fq6YjjNCLssJCQp0yk4M8W6ikLURwkdd/YKtTbyI= +github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4= +github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw= github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws= github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw= github.com/redis/go-redis/v9 v9.17.2 h1:P2EGsA4qVIM3Pp+aPocCJ7DguDHhqrXNhVcEp4ViluI= @@ -194,10 +208,14 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0= +golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8= +golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI= golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg= +golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c= +golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= @@ -205,6 +223,8 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= +golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o= +golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw= golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -223,6 +243,8 @@ golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= +golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -236,6 +258,8 @@ golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY= +golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE= +golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -244,17 +268,23 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA= golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc= +golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc= +golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= google.golang.org/api v0.258.0 h1:IKo1j5FBlN74fe5isA2PVozN3Y5pwNKriEgAXPOkDAc= google.golang.org/api v0.258.0/go.mod h1:qhOMTQEZ6lUps63ZNq9jhODswwjkjYYguA7fA3TBFww= +google.golang.org/api v0.260.0 h1:XbNi5E6bOVEj/uLXQRlt6TKuEzMD7zvW/6tNwltE4P4= +google.golang.org/api v0.260.0/go.mod h1:Shj1j0Phr/9sloYrKomICzdYgsSDImpTxME8rGLaZ/o= google.golang.org/genproto v0.0.0-20251202230838-ff82c1b0f217 h1:GvESR9BIyHUahIb0NcTum6itIWtdoglGX+rnGxm2934= google.golang.org/genproto v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:yJ2HH4EHEDTd3JiLmhds6NkJ17ITVYOdV3m3VKOnws0= google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls= google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:+rXWjjaukWZun3mLfjmVnQi18E1AsFbDN9QdJ5YXLto= google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU= google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260114163908-3f89685c29c3 h1:C4WAdL+FbjnGlpp2S+HMVhBeCq2Lcib4xZqfPNF6OoQ= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260114163908-3f89685c29c3/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ= google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc= google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= From cc0b48d5ec3193b0979485a8403a17b8a933cbb7 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 17 Jan 2026 15:19:21 +0100 Subject: [PATCH 116/125] ci: fix linter warnings for preallocation Signed-off-by: Jan Larwig --- .golangci.yml | 3 +++ go.mod | 2 +- go.sum | 30 ------------------------------ oauthproxy.go | 7 ++++--- pkg/validation/allowlist.go | 1 + pkg/validation/header.go | 1 + pkg/validation/upstreams.go | 1 + providers/azure.go | 1 + providers/keycloak_oidc.go | 1 + 9 files changed, 13 insertions(+), 34 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 62e1df8eda..31f4b033c1 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -53,6 +53,9 @@ linters: - revive path: util/.*\.go$ text: "var-naming: avoid meaningless package names" + - linters: + - prealloc + path: _test\.go paths: - third_party$ - builtin$ diff --git a/go.mod b/go.mod index f6eb45c264..c998b25f72 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,7 @@ require ( github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf github.com/fsnotify/fsnotify v1.9.0 github.com/go-jose/go-jose/v3 v3.0.4 - github.com/go-viper/mapstructure/v2 v2.5.0 + github.com/go-viper/mapstructure/v2 v2.4.0 github.com/golang-jwt/jwt/v5 v5.3.0 github.com/google/go-cmp v0.7.0 github.com/google/uuid v1.6.0 diff --git a/go.sum b/go.sum index d09db4d341..ac6b56d47e 100644 --- a/go.sum +++ b/go.sum @@ -65,8 +65,6 @@ github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1v github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= -github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= -github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo= @@ -78,8 +76,6 @@ github.com/gomodule/redigo v1.7.1-0.20190322064113-39e2c31b7ca3/go.mod h1:B4C85q github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/pprof v0.0.0-20251213031049-b05bdaca462f h1:HU1RgM6NALf/KW9HEY6zry3ADbDKcmpQ+hJedoNGQYQ= -github.com/google/pprof v0.0.0-20251213031049-b05bdaca462f/go.mod h1:67FPmZWbr+KDT/VlpWtw6sO9XSjpJmLuHpoLmWiTGgY= github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 h1:z2ogiKUYzX5Is6zr/vP9vJGqPwcdqsWjOt+V8J7+bTc= github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= @@ -87,8 +83,6 @@ github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0 github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.7 h1:zrn2Ee/nWmHulBx5sAVrGgAa0f2/R35S4DJwfFaUPFQ= -github.com/googleapis/enterprise-certificate-proxy v0.3.7/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= github.com/googleapis/enterprise-certificate-proxy v0.3.11 h1:vAe81Msw+8tKUxi2Dqh/NZMz7475yUvmRIkXr4oN2ao= github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8= github.com/googleapis/gax-go/v2 v2.16.0 h1:iHbQmKLLZrexmb0OSsNGTeSTS0HO4YvFOG8g5E4Zd0Y= @@ -117,18 +111,12 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk= github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw= -github.com/onsi/ginkgo/v2 v2.27.3 h1:ICsZJ8JoYafeXFFlFAG75a7CxMsJHwgKwtO+82SE9L8= -github.com/onsi/ginkgo/v2 v2.27.3/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= github.com/onsi/ginkgo/v2 v2.27.5 h1:ZeVgZMx2PDMdJm/+w5fE/OyG6ILo1Y3e+QX4zSR0zTE= github.com/onsi/ginkgo/v2 v2.27.5/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= -github.com/onsi/gomega v1.38.3 h1:eTX+W6dobAYfFeGC2PV6RwXRu/MyT+cQguijutvkpSM= -github.com/onsi/gomega v1.38.3/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4= github.com/onsi/gomega v1.39.0 h1:y2ROC3hKFmQZJNFeGAMeHZKkjBL65mIZcvrLQBF9k6Q= github.com/onsi/gomega v1.39.0/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= -github.com/pierrec/lz4/v4 v4.1.23 h1:oJE7T90aYBGtFNrI8+KbETnPymobAhzRrR8Mu8n1yfU= -github.com/pierrec/lz4/v4 v4.1.23/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= github.com/pierrec/lz4/v4 v4.1.25 h1:kocOqRffaIbU5djlIBr7Wh+cx82C0vtFb0fOurZHqD0= github.com/pierrec/lz4/v4 v4.1.25/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -138,8 +126,6 @@ github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= -github.com/prometheus/common v0.67.4 h1:yR3NqWO1/UyO1w2PhUvXlGQs/PtFmoveVO0KZ4+Lvsc= -github.com/prometheus/common v0.67.4/go.mod h1:gP0fq6YjjNCLssJCQp0yk4M8W6ikLURwkdd/YKtTbyI= github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4= github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw= github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws= @@ -206,14 +192,10 @@ go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= -golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= -golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0= golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8= golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI= -golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg= golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c= golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -221,8 +203,6 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= -golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o= golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw= @@ -241,8 +221,6 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= -golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= @@ -256,8 +234,6 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= -golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY= golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE= golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= @@ -266,23 +242,17 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA= -golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc= golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc= golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= -google.golang.org/api v0.258.0 h1:IKo1j5FBlN74fe5isA2PVozN3Y5pwNKriEgAXPOkDAc= -google.golang.org/api v0.258.0/go.mod h1:qhOMTQEZ6lUps63ZNq9jhODswwjkjYYguA7fA3TBFww= google.golang.org/api v0.260.0 h1:XbNi5E6bOVEj/uLXQRlt6TKuEzMD7zvW/6tNwltE4P4= google.golang.org/api v0.260.0/go.mod h1:Shj1j0Phr/9sloYrKomICzdYgsSDImpTxME8rGLaZ/o= google.golang.org/genproto v0.0.0-20251202230838-ff82c1b0f217 h1:GvESR9BIyHUahIb0NcTum6itIWtdoglGX+rnGxm2934= google.golang.org/genproto v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:yJ2HH4EHEDTd3JiLmhds6NkJ17ITVYOdV3m3VKOnws0= google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 h1:fCvbg86sFXwdrl5LgVcTEvNC+2txB5mgROGmRL5mrls= google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:+rXWjjaukWZun3mLfjmVnQi18E1AsFbDN9QdJ5YXLto= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ= google.golang.org/genproto/googleapis/rpc v0.0.0-20260114163908-3f89685c29c3 h1:C4WAdL+FbjnGlpp2S+HMVhBeCq2Lcib4xZqfPNF6OoQ= google.golang.org/genproto/googleapis/rpc v0.0.0-20260114163908-3f89685c29c3/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ= google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc= diff --git a/oauthproxy.go b/oauthproxy.go index dda1b34fcf..8c8bc56526 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -397,9 +397,10 @@ func buildSessionChain(opts *options.Options, provider providers.Provider, sessi chain := alice.New() if opts.SkipJwtBearerTokens { - sessionLoaders := []middlewareapi.TokenToSessionFunc{ - provider.CreateSessionFromToken, - } + verifiers := opts.GetJWTBearerVerifiers() + + sessionLoaders := make([]middlewareapi.TokenToSessionFunc, 0, len(verifiers)+1) + sessionLoaders = append(sessionLoaders, provider.CreateSessionFromToken) for _, verifier := range opts.GetJWTBearerVerifiers() { sessionLoaders = append(sessionLoaders, diff --git a/pkg/validation/allowlist.go b/pkg/validation/allowlist.go index 12f67aa7f8..a74f4ae9cb 100644 --- a/pkg/validation/allowlist.go +++ b/pkg/validation/allowlist.go @@ -11,6 +11,7 @@ import ( ) func validateAllowlists(o *options.Options) []string { + //nolint:prealloc msgs := []string{} msgs = append(msgs, validateAuthRoutes(o)...) diff --git a/pkg/validation/header.go b/pkg/validation/header.go index b125814465..09aedb8eb8 100644 --- a/pkg/validation/header.go +++ b/pkg/validation/header.go @@ -7,6 +7,7 @@ import ( ) func validateHeaders(headers []options.Header) []string { + //nolint:prealloc msgs := []string{} names := make(map[string]struct{}) diff --git a/pkg/validation/upstreams.go b/pkg/validation/upstreams.go index 49edc32e31..7ceaca1bb1 100644 --- a/pkg/validation/upstreams.go +++ b/pkg/validation/upstreams.go @@ -9,6 +9,7 @@ import ( ) func validateUpstreams(upstreams options.UpstreamConfig) []string { + //nolint:prealloc msgs := []string{} ids := make(map[string]struct{}) paths := make(map[string]struct{}) diff --git a/providers/azure.go b/providers/azure.go index 0eafdf6bfc..b5610cfad0 100644 --- a/providers/azure.go +++ b/providers/azure.go @@ -399,6 +399,7 @@ func (p *AzureProvider) getGroupsFromProfileAPI(ctx context.Context, s *sessions } func getGroupsFromJSON(json *simplejson.Json, graphGroupField string) []string { + //nolint:prealloc groups := []string{} for i := range json.Get("value").MustArray() { diff --git a/providers/keycloak_oidc.go b/providers/keycloak_oidc.go index 6b949f4569..284880ba5f 100644 --- a/providers/keycloak_oidc.go +++ b/providers/keycloak_oidc.go @@ -89,6 +89,7 @@ func (p *KeycloakOIDCProvider) extractRoles(s *sessions.SessionState) error { return err } + //nolint:prealloc var roles []string roles = append(roles, claims.RealmAccess.Roles...) roles = append(roles, getClientRoles(claims)...) From 5020c33124cfa0a19e6406835308eba27d012eb8 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 17 Jan 2026 15:52:46 +0100 Subject: [PATCH 117/125] ci: fix qlty coverage upload Signed-off-by: Jan Larwig --- .github/workflows/ci.yml | 23 +++++++++++++++++++---- .github/workflows/test.sh | 26 -------------------------- 2 files changed, 19 insertions(+), 30 deletions(-) delete mode 100755 .github/workflows/test.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 64d82af220..7521132570 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,6 +7,10 @@ on: pull_request: branches: - '**' +permissions: + contents: read + id-token: write + jobs: build: runs-on: ubuntu-latest @@ -22,13 +26,17 @@ jobs: go-version-file: go.mod id: go - - name: Get dependencies + - name: Install golangci-lint env: # renovate: datasource=github-tags depName=golangci/golangci-lint GOLANGCI_LINT_VERSION: v2.8.0 run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} + - name: Install gcov2lcov + run: | + go install github.com/jandelgado/gcov2lcov@latest + - name: Verify Code Generation run: | make verify-generate @@ -49,10 +57,17 @@ jobs: make release - name: Test - env: - CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }} run: | - ./.github/workflows/test.sh + make test + + - name: Generate Coverage Report + run: | + gcov2lcov -infile=c.out -outfile=lcov.info + + - uses: qltysh/qlty-action/coverage@v2 + with: + oidc: true + files: lcov.info docker: runs-on: ubuntu-latest diff --git a/.github/workflows/test.sh b/.github/workflows/test.sh deleted file mode 100755 index d1a1218296..0000000000 --- a/.github/workflows/test.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash -# manually exiting from script, because after-build needs to run always -set +e - -if [ -z $CC_TEST_REPORTER_ID ]; then - echo "1. CC_TEST_REPORTER_ID is unset, skipping" -else - echo "1. Running before-build" - ./cc-test-reporter before-build -fi - -echo "2. Running test" -make test -TEST_STATUS=$? - -if [ -z $CC_TEST_REPORTER_ID ]; then - echo "3. CC_TEST_REPORTER_ID is unset, skipping" -else - echo "3. Running after-build" - ./cc-test-reporter after-build --exit-code $TEST_STATUS --prefix $(go list -m) -fi - -if [ "$TEST_STATUS" -ne 0 ]; then - echo "Test failed, status code: $TEST_STATUS" - exit $TEST_STATUS -fi From 3ed3baf59f0fff8914c97f89e886e1dfae2193a7 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 17 Jan 2026 15:08:04 +0000 Subject: [PATCH 118/125] update to release version v7.14.1 --- CHANGELOG.md | 10 ++++++++++ .../local-environment/docker-compose-alpha-config.yaml | 2 +- contrib/local-environment/docker-compose-gitea.yaml | 2 +- contrib/local-environment/docker-compose-keycloak.yaml | 2 +- contrib/local-environment/docker-compose-nginx.yaml | 2 +- contrib/local-environment/docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/installation.md | 2 +- docs/versioned_docs/version-7.14.x/installation.md | 2 +- 9 files changed, 18 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e6e8605ade..a909816262 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,16 @@ ## Breaking Changes +## Changes since v7.14.1 + +# V7.14.1 + +## Release Highlights + +## Important Notes + +## Breaking Changes + ## Changes since v7.14.0 - [#3309](https://github.com/oauth2-proxy/oauth2-proxy/pull/3309) fix: Return 302 redirect from AuthOnly endpoint when skip-provider-button is true (@StefanMarkmann) diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index 5a13a9d535..bd64128d00 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -14,7 +14,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.1 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index f0bf246ccd..83847cc747 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.1 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index f3fd010783..435d8b3864 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.1 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 51d23b5892..599988010e 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -22,7 +22,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.1 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index fa2d490ec8..1358f839b5 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.1 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index ceb7da7861..c3ac36cc30 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.0 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.1 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/installation.md b/docs/docs/installation.md index 09ad131140..fcdf25cfae 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.1`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.14.x/installation.md b/docs/versioned_docs/version-7.14.x/installation.md index 09ad131140..fcdf25cfae 100644 --- a/docs/versioned_docs/version-7.14.x/installation.md +++ b/docs/versioned_docs/version-7.14.x/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.0`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.1`) b. Using Go to install the latest release ```bash From 8f52b14eda64f4261457c2dd84772030fd160a9a Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sat, 17 Jan 2026 16:15:54 +0100 Subject: [PATCH 119/125] doc: changelog entry for v7.14.1 Signed-off-by: Jan Larwig --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a909816262..5c21a99fb8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,11 @@ ## Release Highlights +- 🔵 Go1.25.6 and upgrade of dependencies to latest versions +- 🐛 Bug fixes + - AuthOnly now starts the auth flow and send status code 302 if no session exists and skip-provider-button is true + - Fixed static upstream validation issue due to incorrect defaults + ## Important Notes ## Breaking Changes From cf5d34acf60dc4e2a232e073bb906169be1dd32b Mon Sep 17 00:00:00 2001 From: Stefan Markmann <50301139+StefanMarkmann@users.noreply.github.com> Date: Sun, 18 Jan 2026 00:36:08 +0100 Subject: [PATCH 120/125] revert: "fix: skip provider button auth only redirect (#3309)" (#3314) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 9c61c49ec29dce1c6bddfe209940bb406f42f8fc. The original fix broke nginx deployments using `auth_request`. When `/oauth2/auth` returns 302, nginx's `auth_request` module treats this as an internal error: [error] auth request unexpected status: 302 while sending to client nginx then returns **500 Internal Server Error** to the browser. > If the subrequest returns a 2xx response code, the access is allowed. If it returns 401 or 403, > the access is denied with the corresponding error code. Any other response code returned by the > subrequest is considered an error. https://nginx.org/en/docs/http/ngx_http_auth_request_module.html The nginx `auth_request` module has strict semantics (non-negotiable): | Subrequest status | nginx behavior | |---|---| | 2xx | Allow request | | 401 / 403 | Deny → trigger `error_page` | | **Any other status** | **Internal error → 500** | The `/oauth2/auth` endpoint is used as a **policy oracle** (yes/no decision), not as a browser-facing endpoint. It cannot return redirects. Any nginx deployment with: - `skip-provider-button=true` - Using `auth_request` directive Will receive 500 errors instead of the expected authentication flow. The correct fix for #334 is a **documentation update**, not a code change: ```nginx error_page 401 = @oauth2_signin; location @oauth2_signin { return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; } ``` This keeps `/oauth2/auth` as a pure 401/2xx oracle and lets nginx perform the proper 302 redirect to the browser. - Original Issue: #334 - Regression introduced in PR: #3309 Signed-off-by: Stefan Markmann Signed-off-by: Jan Larwig Co-authored-by: Jan Larwig --- CHANGELOG.md | 2 + docs/docs/configuration/overview.md | 2 +- .../version-7.14.x/configuration/overview.md | 2 +- oauthproxy.go | 10 +---- oauthproxy_test.go | 45 +------------------ 5 files changed, 7 insertions(+), 54 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c21a99fb8..ab676530a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ ## Changes since v7.14.1 +- [#3314](https://github.com/oauth2-proxy/oauth2-proxy/pull/3314) revert: fix: skip provider button auth only redirect (#3309) + # V7.14.1 ## Release Highlights diff --git a/docs/docs/configuration/overview.md b/docs/docs/configuration/overview.md index c545533675..7bd7bf0710 100644 --- a/docs/docs/configuration/overview.md +++ b/docs/docs/configuration/overview.md @@ -214,7 +214,7 @@ Provider specific options can be found on their respective subpages. | flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | | flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | | flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | -| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start. 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 | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | | flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | | flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | | flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | diff --git a/docs/versioned_docs/version-7.14.x/configuration/overview.md b/docs/versioned_docs/version-7.14.x/configuration/overview.md index c545533675..7bd7bf0710 100644 --- a/docs/versioned_docs/version-7.14.x/configuration/overview.md +++ b/docs/versioned_docs/version-7.14.x/configuration/overview.md @@ -214,7 +214,7 @@ Provider specific options can be found on their respective subpages. | flag: `--skip-auth-regex`
toml: `skip_auth_regex` | string \| list | (DEPRECATED for `--skip-auth-route`) bypass authentication for requests paths that match (may be given multiple times) | | | flag: `--skip-auth-route`
toml: `skip_auth_routes` | string \| list | bypass authentication for requests that match the method & path. Format: method=path_regex OR method!=path_regex. For all methods: path_regex OR !=path_regex | | | flag: `--skip-jwt-bearer-tokens`
toml: `skip_jwt_bearer_tokens` | bool | will skip requests that have verified JWT bearer tokens (the token must have [`aud`](https://en.wikipedia.org/wiki/JSON_Web_Token#Standard_fields) that matches this client id or one of the extras from `extra-jwt-issuers`) | false | -| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start. 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 | +| flag: `--skip-provider-button`
toml: `skip_provider_button` | bool | will skip sign-in-page to directly reach the next step: oauth/start | false | | flag: `--ssl-insecure-skip-verify`
toml: `ssl_insecure_skip_verify` | bool | skip validation of certificates presented when using HTTPS providers | false | | flag: `--trusted-ip`
toml: `trusted_ips` | string \| list | list of IPs or CIDR ranges to allow to bypass authentication (may be given multiple times). When combined with `--reverse-proxy` and optionally `--real-client-ip-header` this will evaluate the trust of the IP stored in an HTTP header by a reverse proxy rather than the layer-3/4 remote address. WARNING: trusting IPs has inherent security flaws, especially when obtaining the IP address from an HTTP header (reverse-proxy mode). Use this option only if you understand the risks and how to manage them. | | | flag: `--whitelist-domain`
toml: `whitelist_domains` | string \| list | allowed domains for redirection after authentication. Prefix domain with a `.` or a `*.` to allow subdomains (e.g. `.example.com`, `*.example.com`) [^2] | | diff --git a/oauthproxy.go b/oauthproxy.go index 8c8bc56526..508084c8a0 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -988,15 +988,7 @@ func (p *OAuthProxy) enrichSessionState(ctx context.Context, s *sessionsapi.Sess // and optional authorization). func (p *OAuthProxy) AuthOnly(rw http.ResponseWriter, req *http.Request) { session, err := p.getAuthenticatedSession(rw, req) - // If SkipProviderButton is enabled and user needs login, redirect directly - // to OAuth provider instead of returning 401. This allows nginx auth_request - // to pass through the 302 redirect to the browser, bypassing error_page - // handling which can break redirect flows. - // See: https://github.com/oauth2-proxy/oauth2-proxy/issues/334 - if p.SkipProviderButton && err == ErrNeedsLogin { - p.doOAuthStart(rw, req, nil) - return - } else if err != nil { + if err != nil { http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } diff --git a/oauthproxy_test.go b/oauthproxy_test.go index 489a1b69d3..ccabdbbd01 100644 --- a/oauthproxy_test.go +++ b/oauthproxy_test.go @@ -834,20 +834,8 @@ func NewProcessCookieTest(opts ProcessCookieTestOpts, modifiers ...OptionsModifi return nil, err } testProvider := &TestProvider{ - ProviderData: &providers.ProviderData{ - ProviderName: "Test Provider", - LoginURL: &url.URL{ - Scheme: "http", - Host: "localhost", - Path: "/oauth/authorize", - }, - RedeemURL: &url.URL{ - Scheme: "http", - Host: "localhost", - Path: "/oauth/token", - }, - }, - ValidToken: opts.providerValidateCookieResponse, + ProviderData: &providers.ProviderData{}, + ValidToken: opts.providerValidateCookieResponse, } groups := pcTest.opts.Providers[0].AllowedGroups @@ -1124,35 +1112,6 @@ func TestAuthOnlyEndpointUnauthorizedOnNoCookieSetError(t *testing.T) { assert.Equal(t, "Unauthorized\n", string(bodyBytes)) } -// TestAuthOnlyEndpointRedirectWithSkipProviderButton tests that when SkipProviderButton -// is true and no session exists, the /auth endpoint should return a 302 redirect -// to the OAuth provider instead of 401. This is important for nginx auth_request -// architecture where 401 triggers error_page handling which can break the redirect flow. -// See: https://github.com/oauth2-proxy/oauth2-proxy/issues/334 -func TestAuthOnlyEndpointRedirectWithSkipProviderButton(t *testing.T) { - test, err := NewAuthOnlyEndpointTest("", func(opts *options.Options) { - opts.SkipProviderButton = true - }) - if err != nil { - t.Fatal(err) - } - - test.proxy.ServeHTTP(test.rw, test.req) - - // With SkipProviderButton=true and no session, should return 302 redirect - // to OAuth provider, NOT 401 Unauthorized - assert.Equal(t, http.StatusFound, test.rw.Code) - location := test.rw.Header().Get("Location") - assert.NotEmpty(t, location, "Expected Location header for redirect") - - // Verify the redirect points to the OAuth provider's authorize endpoint - // and contains key OAuth parameters - assert.Contains(t, location, "/oauth/authorize", "Expected redirect to OAuth authorize endpoint") - assert.Contains(t, location, "client_id=", "Expected client_id in redirect URL") - assert.Contains(t, location, "redirect_uri=", "Expected redirect_uri in redirect URL") - assert.Contains(t, location, "state=", "Expected state parameter in redirect URL") -} - func TestAuthOnlyEndpointUnauthorizedOnExpiration(t *testing.T) { test, err := NewAuthOnlyEndpointTest("", func(opts *options.Options) { opts.Cookie.Expire = time.Duration(24) * time.Hour From dcc7970a5f214ec83cecb438871945feebf07286 Mon Sep 17 00:00:00 2001 From: Stefan Markmann <50301139+StefanMarkmann@users.noreply.github.com> Date: Sun, 18 Jan 2026 00:55:46 +0100 Subject: [PATCH 121/125] docs: fix how to use skip-provider-button with proper auth redirect handling (#3315) * docs(nginx): Clarify auth_request redirect pattern with named location Update the nginx integration documentation to recommend using a named location (@oauth2_signin) for the error_page directive instead of the previous 'error_page 401 =403' approach. The named location pattern ensures the browser receives a proper 302 redirect, which is required for --skip-provider-button=true to work correctly. The previous pattern (error_page 401 =403 /oauth2/sign_in) returned a 403 status with a Location header. Browsers do not auto-follow redirects on 403 responses, causing users to see a 'Found.' link instead of being automatically redirected to the IdP. Changes: - Updated main nginx example to use @oauth2_signin named location - Added 'Understanding the error_page redirect pattern' section - Added warning about the limitations of 'error_page 401 =403' - Updated local test environment (contrib/local-environment/nginx.conf) Refs: #334 Signed-off-by: Stefan Markmann * docs: clarify browser vs API routes for nginx auth_request redirects Add new "Browser vs API Routes" section explaining: - Use 302 redirect to /oauth2/sign_in only for browser-facing routes - Use 401/403 without redirect for API/machine clients This ensures: - Browsers get a redirect and smooth login flow - API clients fail fast with appropriate HTTP status codes - /oauth2/auth remains a pure boolean oracle (2xx/401) Signed-off-by: Stefan Markmann Signed-off-by: Jan Larwig --------- Signed-off-by: Stefan Markmann Signed-off-by: Jan Larwig --- CHANGELOG.md | 3 +- contrib/local-environment/nginx.conf | 31 ++++---- docs/docs/configuration/integrations/nginx.md | 69 +++++++++++++++++- .../configuration/integration.md | 70 ++++++++++++++++++- .../configuration/integration.md | 70 ++++++++++++++++++- .../configuration/integration.md | 70 ++++++++++++++++++- .../configuration/integrations/nginx.md | 69 +++++++++++++++++- .../configuration/integrations/nginx.md | 69 +++++++++++++++++- 8 files changed, 431 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ab676530a1..e052c3db68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,8 @@ ## Changes since v7.14.1 -- [#3314](https://github.com/oauth2-proxy/oauth2-proxy/pull/3314) revert: fix: skip provider button auth only redirect (#3309) +- [#3314](https://github.com/oauth2-proxy/oauth2-proxy/pull/3314) revert: fix: skip provider button auth only redirect (#3309) (@StefanMarkmann / @tuunit) +- [#3315](https://github.com/oauth2-proxy/oauth2-proxy/pull/3315) docs: clarify browser vs API routes for nginx auth_request redirects (@StefanMarkmann) # V7.14.1 diff --git a/contrib/local-environment/nginx.conf b/contrib/local-environment/nginx.conf index ffb5f8e2cd..15005bf6ca 100644 --- a/contrib/local-environment/nginx.conf +++ b/contrib/local-environment/nginx.conf @@ -18,17 +18,20 @@ server { auth_request /internal-auth/oauth2/auth; - # If the auth_request denies the request (401), redirect to the sign_in page - # and include the final rd URL back to the user's original request. - error_page 401 =403 http://oauth2-proxy.oauth2-proxy.localhost/oauth2/sign_in?rd=$scheme://$host$request_uri; - - # Alternatively send the request to `start` to skip the provider button - # error_page 401 = http://oauth2-proxy.oauth2-proxy.localhost/oauth2/start?rd=$scheme://$host$request_uri; + # On 401, redirect to the sign_in page via a named location + # This ensures a proper 302 redirect that browsers will follow + error_page 401 = @oauth2_signin; location / { proxy_pass http://httpbin/; } + # Named location for OAuth2 sign-in redirect + # Returns a proper 302 that works with --skip-provider-button + location @oauth2_signin { + return 302 http://oauth2-proxy.oauth2-proxy.localhost/oauth2/sign_in?rd=$scheme://$host$request_uri; + } + # auth_request must be a URI so this allows an internal path to then proxy to # the real auth_request path. # The trailing /'s are required so that nginx strips the prefix before proxying. @@ -52,18 +55,20 @@ server { location / { auth_request /internal-auth/oauth2/auth; - # If the auth_request denies the request (401), redirect to the sign_in page - # and include the final rd URL back to the user's original request. - error_page 401 =403 http://oauth2-proxy.oauth2-proxy.localhost/oauth2/sign_in?rd=$scheme://$host$request_uri; - - # Alternatively send the request to `start` to skip the provider button - # error_page 401 = http://oauth2-proxy.oauth2-proxy.localhost/oauth2/start?rd=$scheme://$host$request_uri; - + # On 401, redirect to the sign_in page via a named location + # This ensures a proper 302 redirect that browsers will follow + error_page 401 = @oauth2_signin; root /usr/share/nginx/html; index index.html index.htm; } + # Named location for OAuth2 sign-in redirect + # Returns a proper 302 that works with --skip-provider-button + location @oauth2_signin { + return 302 http://oauth2-proxy.oauth2-proxy.localhost/oauth2/sign_in?rd=$scheme://$host$request_uri; + } + # redirect server error pages to the static page /50x.html error_page 500 502 503 504 /50x.html; location = /50x.html { diff --git a/docs/docs/configuration/integrations/nginx.md b/docs/docs/configuration/integrations/nginx.md index a36ed7622d..ca6402a9e8 100644 --- a/docs/docs/configuration/integrations/nginx.md +++ b/docs/docs/configuration/integrations/nginx.md @@ -43,7 +43,7 @@ server { location / { auth_request /oauth2/auth; - error_page 401 =403 /oauth2/sign_in; + error_page 401 = @oauth2_signin; # pass information via X-User and X-Email headers to backend, # requires running with --set-xauthrequest flag @@ -82,9 +82,76 @@ server { proxy_pass http://backend/; # or "root /path/to/site;" or "fastcgi_pass ..." etc } + + # Named location for handling OAuth2 sign-in redirects + # This ensures the browser receives a proper 302 redirect that it will follow + location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; + } +} +``` + +### Understanding the `error_page` redirect pattern + +The `auth_request` directive expects the authentication endpoint (`/oauth2/auth`) to return: +- **2xx**: Request is authenticated, allow access +- **401 or 403**: Request is not authenticated, deny access + +When a 401 is returned, nginx triggers the `error_page` directive. The recommended pattern uses a **named location** (`@oauth2_signin`) that returns a proper **302 redirect**: + +```nginx +error_page 401 = @oauth2_signin; + +location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; } ``` +:::warning Avoid `error_page 401 =403` with sign_in +Some older configurations use `error_page 401 =403 /oauth2/sign_in`. While this works for displaying the sign-in page, it returns a **403 status code** with a `Location` header. Browsers do not automatically follow redirects on 403 responses, which can cause issues when using `--skip-provider-button=true` (users see a "Found." link instead of being automatically redirected). + +The named location pattern above ensures the browser receives a standard **302 redirect** that works correctly with all oauth2-proxy configurations. +::: + +### Browser vs API Routes + +:::important When to use redirects +Redirecting authentication failures (302 to `/oauth2/sign_in`) should **only be used for browser-facing routes**. API or machine clients should receive a plain 401/403 response without redirect. +::: + +#### Browser-facing routes (HTML, UI) + +For interactive browser routes where users should be redirected to sign in: + +```nginx +location / { + auth_request /oauth2/auth; + error_page 401 = @oauth2_signin; + proxy_pass http://backend/; +} + +location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; +} +``` + +#### API / Machine routes (no redirect) + +For API endpoints where clients expect a 401/403 status code (not a redirect): + +```nginx +location /api/ { + auth_request /oauth2/auth; + error_page 401 =401; # Pass through the 401 status + proxy_pass http://backend/; +} +``` + +This ensures: +- ✅ Browsers get a redirect and smooth login flow +- ✅ API clients fail fast with appropriate HTTP status codes +- ✅ `/oauth2/auth` remains a pure boolean oracle (2xx/401) + When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: ```yaml diff --git a/docs/versioned_docs/version-7.10.x/configuration/integration.md b/docs/versioned_docs/version-7.10.x/configuration/integration.md index c57cfa6b36..a5afeda407 100644 --- a/docs/versioned_docs/version-7.10.x/configuration/integration.md +++ b/docs/versioned_docs/version-7.10.x/configuration/integration.md @@ -33,9 +33,15 @@ server { proxy_pass_request_body off; } + # Named location for handling OAuth2 sign-in redirects + # This ensures the browser receives a proper 302 redirect that it will follow + location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; + } + location / { auth_request /oauth2/auth; - error_page 401 =403 /oauth2/sign_in; + error_page 401 = @oauth2_signin; # pass information via X-User and X-Email headers to backend, # requires running with --set-xauthrequest flag @@ -77,6 +83,68 @@ server { } ``` +### Understanding the `error_page` redirect pattern + +The `auth_request` directive expects the authentication endpoint (`/oauth2/auth`) to return: +- **2xx**: Request is authenticated, allow access +- **401 or 403**: Request is not authenticated, deny access + +When a 401 is returned, nginx triggers the `error_page` directive. The recommended pattern uses a **named location** (`@oauth2_signin`) that returns a proper **302 redirect**: + + +```nginx +error_page 401 = @oauth2_signin; + +location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; +} +``` + +:::warning Avoid `error_page 401 =403` with sign_in +Some older configurations use `error_page 401 =403 /oauth2/sign_in`. While this works for displaying the sign-in page, it returns a **403 status code** with a `Location` header. Browsers do not automatically follow redirects on 403 responses, which can cause issues when using `--skip-provider-button=true` (users see a "Found." link instead of being automatically redirected). + +The named location pattern above ensures the browser receives a standard **302 redirect** that works correctly with all oauth2-proxy configurations. +::: + +### Browser vs API Routes + +:::important When to use redirects +Redirecting authentication failures (302 to `/oauth2/sign_in`) should **only be used for browser-facing routes**. API or machine clients should receive a plain 401/403 response without redirect. +::: + +#### Browser-facing routes (HTML, UI) + +For interactive browser routes where users should be redirected to sign in: + +```nginx +location / { + auth_request /oauth2/auth; + error_page 401 = @oauth2_signin; + proxy_pass http://backend/; +} + +location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; +} +``` + +#### API / Machine routes (no redirect) + +For API endpoints where clients expect a 401/403 status code (not a redirect): + +```nginx +location /api/ { + auth_request /oauth2/auth; + error_page 401 =401; # Pass through the 401 status + proxy_pass http://backend/; +} +``` + +This ensures: +- ✅ Browsers get a redirect and smooth login flow +- ✅ API clients fail fast with appropriate HTTP status codes +- ✅ `/oauth2/auth` remains a pure boolean oracle (2xx/401) + When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: ```yaml diff --git a/docs/versioned_docs/version-7.11.x/configuration/integration.md b/docs/versioned_docs/version-7.11.x/configuration/integration.md index c57cfa6b36..a5afeda407 100644 --- a/docs/versioned_docs/version-7.11.x/configuration/integration.md +++ b/docs/versioned_docs/version-7.11.x/configuration/integration.md @@ -33,9 +33,15 @@ server { proxy_pass_request_body off; } + # Named location for handling OAuth2 sign-in redirects + # This ensures the browser receives a proper 302 redirect that it will follow + location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; + } + location / { auth_request /oauth2/auth; - error_page 401 =403 /oauth2/sign_in; + error_page 401 = @oauth2_signin; # pass information via X-User and X-Email headers to backend, # requires running with --set-xauthrequest flag @@ -77,6 +83,68 @@ server { } ``` +### Understanding the `error_page` redirect pattern + +The `auth_request` directive expects the authentication endpoint (`/oauth2/auth`) to return: +- **2xx**: Request is authenticated, allow access +- **401 or 403**: Request is not authenticated, deny access + +When a 401 is returned, nginx triggers the `error_page` directive. The recommended pattern uses a **named location** (`@oauth2_signin`) that returns a proper **302 redirect**: + + +```nginx +error_page 401 = @oauth2_signin; + +location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; +} +``` + +:::warning Avoid `error_page 401 =403` with sign_in +Some older configurations use `error_page 401 =403 /oauth2/sign_in`. While this works for displaying the sign-in page, it returns a **403 status code** with a `Location` header. Browsers do not automatically follow redirects on 403 responses, which can cause issues when using `--skip-provider-button=true` (users see a "Found." link instead of being automatically redirected). + +The named location pattern above ensures the browser receives a standard **302 redirect** that works correctly with all oauth2-proxy configurations. +::: + +### Browser vs API Routes + +:::important When to use redirects +Redirecting authentication failures (302 to `/oauth2/sign_in`) should **only be used for browser-facing routes**. API or machine clients should receive a plain 401/403 response without redirect. +::: + +#### Browser-facing routes (HTML, UI) + +For interactive browser routes where users should be redirected to sign in: + +```nginx +location / { + auth_request /oauth2/auth; + error_page 401 = @oauth2_signin; + proxy_pass http://backend/; +} + +location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; +} +``` + +#### API / Machine routes (no redirect) + +For API endpoints where clients expect a 401/403 status code (not a redirect): + +```nginx +location /api/ { + auth_request /oauth2/auth; + error_page 401 =401; # Pass through the 401 status + proxy_pass http://backend/; +} +``` + +This ensures: +- ✅ Browsers get a redirect and smooth login flow +- ✅ API clients fail fast with appropriate HTTP status codes +- ✅ `/oauth2/auth` remains a pure boolean oracle (2xx/401) + When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: ```yaml diff --git a/docs/versioned_docs/version-7.12.x/configuration/integration.md b/docs/versioned_docs/version-7.12.x/configuration/integration.md index c57cfa6b36..a5afeda407 100644 --- a/docs/versioned_docs/version-7.12.x/configuration/integration.md +++ b/docs/versioned_docs/version-7.12.x/configuration/integration.md @@ -33,9 +33,15 @@ server { proxy_pass_request_body off; } + # Named location for handling OAuth2 sign-in redirects + # This ensures the browser receives a proper 302 redirect that it will follow + location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; + } + location / { auth_request /oauth2/auth; - error_page 401 =403 /oauth2/sign_in; + error_page 401 = @oauth2_signin; # pass information via X-User and X-Email headers to backend, # requires running with --set-xauthrequest flag @@ -77,6 +83,68 @@ server { } ``` +### Understanding the `error_page` redirect pattern + +The `auth_request` directive expects the authentication endpoint (`/oauth2/auth`) to return: +- **2xx**: Request is authenticated, allow access +- **401 or 403**: Request is not authenticated, deny access + +When a 401 is returned, nginx triggers the `error_page` directive. The recommended pattern uses a **named location** (`@oauth2_signin`) that returns a proper **302 redirect**: + + +```nginx +error_page 401 = @oauth2_signin; + +location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; +} +``` + +:::warning Avoid `error_page 401 =403` with sign_in +Some older configurations use `error_page 401 =403 /oauth2/sign_in`. While this works for displaying the sign-in page, it returns a **403 status code** with a `Location` header. Browsers do not automatically follow redirects on 403 responses, which can cause issues when using `--skip-provider-button=true` (users see a "Found." link instead of being automatically redirected). + +The named location pattern above ensures the browser receives a standard **302 redirect** that works correctly with all oauth2-proxy configurations. +::: + +### Browser vs API Routes + +:::important When to use redirects +Redirecting authentication failures (302 to `/oauth2/sign_in`) should **only be used for browser-facing routes**. API or machine clients should receive a plain 401/403 response without redirect. +::: + +#### Browser-facing routes (HTML, UI) + +For interactive browser routes where users should be redirected to sign in: + +```nginx +location / { + auth_request /oauth2/auth; + error_page 401 = @oauth2_signin; + proxy_pass http://backend/; +} + +location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; +} +``` + +#### API / Machine routes (no redirect) + +For API endpoints where clients expect a 401/403 status code (not a redirect): + +```nginx +location /api/ { + auth_request /oauth2/auth; + error_page 401 =401; # Pass through the 401 status + proxy_pass http://backend/; +} +``` + +This ensures: +- ✅ Browsers get a redirect and smooth login flow +- ✅ API clients fail fast with appropriate HTTP status codes +- ✅ `/oauth2/auth` remains a pure boolean oracle (2xx/401) + When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: ```yaml diff --git a/docs/versioned_docs/version-7.13.x/configuration/integrations/nginx.md b/docs/versioned_docs/version-7.13.x/configuration/integrations/nginx.md index a36ed7622d..ca6402a9e8 100644 --- a/docs/versioned_docs/version-7.13.x/configuration/integrations/nginx.md +++ b/docs/versioned_docs/version-7.13.x/configuration/integrations/nginx.md @@ -43,7 +43,7 @@ server { location / { auth_request /oauth2/auth; - error_page 401 =403 /oauth2/sign_in; + error_page 401 = @oauth2_signin; # pass information via X-User and X-Email headers to backend, # requires running with --set-xauthrequest flag @@ -82,9 +82,76 @@ server { proxy_pass http://backend/; # or "root /path/to/site;" or "fastcgi_pass ..." etc } + + # Named location for handling OAuth2 sign-in redirects + # This ensures the browser receives a proper 302 redirect that it will follow + location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; + } +} +``` + +### Understanding the `error_page` redirect pattern + +The `auth_request` directive expects the authentication endpoint (`/oauth2/auth`) to return: +- **2xx**: Request is authenticated, allow access +- **401 or 403**: Request is not authenticated, deny access + +When a 401 is returned, nginx triggers the `error_page` directive. The recommended pattern uses a **named location** (`@oauth2_signin`) that returns a proper **302 redirect**: + +```nginx +error_page 401 = @oauth2_signin; + +location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; } ``` +:::warning Avoid `error_page 401 =403` with sign_in +Some older configurations use `error_page 401 =403 /oauth2/sign_in`. While this works for displaying the sign-in page, it returns a **403 status code** with a `Location` header. Browsers do not automatically follow redirects on 403 responses, which can cause issues when using `--skip-provider-button=true` (users see a "Found." link instead of being automatically redirected). + +The named location pattern above ensures the browser receives a standard **302 redirect** that works correctly with all oauth2-proxy configurations. +::: + +### Browser vs API Routes + +:::important When to use redirects +Redirecting authentication failures (302 to `/oauth2/sign_in`) should **only be used for browser-facing routes**. API or machine clients should receive a plain 401/403 response without redirect. +::: + +#### Browser-facing routes (HTML, UI) + +For interactive browser routes where users should be redirected to sign in: + +```nginx +location / { + auth_request /oauth2/auth; + error_page 401 = @oauth2_signin; + proxy_pass http://backend/; +} + +location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; +} +``` + +#### API / Machine routes (no redirect) + +For API endpoints where clients expect a 401/403 status code (not a redirect): + +```nginx +location /api/ { + auth_request /oauth2/auth; + error_page 401 =401; # Pass through the 401 status + proxy_pass http://backend/; +} +``` + +This ensures: +- ✅ Browsers get a redirect and smooth login flow +- ✅ API clients fail fast with appropriate HTTP status codes +- ✅ `/oauth2/auth` remains a pure boolean oracle (2xx/401) + When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: ```yaml diff --git a/docs/versioned_docs/version-7.14.x/configuration/integrations/nginx.md b/docs/versioned_docs/version-7.14.x/configuration/integrations/nginx.md index a36ed7622d..ca6402a9e8 100644 --- a/docs/versioned_docs/version-7.14.x/configuration/integrations/nginx.md +++ b/docs/versioned_docs/version-7.14.x/configuration/integrations/nginx.md @@ -43,7 +43,7 @@ server { location / { auth_request /oauth2/auth; - error_page 401 =403 /oauth2/sign_in; + error_page 401 = @oauth2_signin; # pass information via X-User and X-Email headers to backend, # requires running with --set-xauthrequest flag @@ -82,9 +82,76 @@ server { proxy_pass http://backend/; # or "root /path/to/site;" or "fastcgi_pass ..." etc } + + # Named location for handling OAuth2 sign-in redirects + # This ensures the browser receives a proper 302 redirect that it will follow + location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; + } +} +``` + +### Understanding the `error_page` redirect pattern + +The `auth_request` directive expects the authentication endpoint (`/oauth2/auth`) to return: +- **2xx**: Request is authenticated, allow access +- **401 or 403**: Request is not authenticated, deny access + +When a 401 is returned, nginx triggers the `error_page` directive. The recommended pattern uses a **named location** (`@oauth2_signin`) that returns a proper **302 redirect**: + +```nginx +error_page 401 = @oauth2_signin; + +location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; } ``` +:::warning Avoid `error_page 401 =403` with sign_in +Some older configurations use `error_page 401 =403 /oauth2/sign_in`. While this works for displaying the sign-in page, it returns a **403 status code** with a `Location` header. Browsers do not automatically follow redirects on 403 responses, which can cause issues when using `--skip-provider-button=true` (users see a "Found." link instead of being automatically redirected). + +The named location pattern above ensures the browser receives a standard **302 redirect** that works correctly with all oauth2-proxy configurations. +::: + +### Browser vs API Routes + +:::important When to use redirects +Redirecting authentication failures (302 to `/oauth2/sign_in`) should **only be used for browser-facing routes**. API or machine clients should receive a plain 401/403 response without redirect. +::: + +#### Browser-facing routes (HTML, UI) + +For interactive browser routes where users should be redirected to sign in: + +```nginx +location / { + auth_request /oauth2/auth; + error_page 401 = @oauth2_signin; + proxy_pass http://backend/; +} + +location @oauth2_signin { + return 302 /oauth2/sign_in?rd=$scheme://$host$request_uri; +} +``` + +#### API / Machine routes (no redirect) + +For API endpoints where clients expect a 401/403 status code (not a redirect): + +```nginx +location /api/ { + auth_request /oauth2/auth; + error_page 401 =401; # Pass through the 401 status + proxy_pass http://backend/; +} +``` + +This ensures: +- ✅ Browsers get a redirect and smooth login flow +- ✅ API clients fail fast with appropriate HTTP status codes +- ✅ `/oauth2/auth` remains a pure boolean oracle (2xx/401) + When you use ingress-nginx in Kubernetes, you can configure the same behavior with the following annotations on your Ingress resource: ```yaml From d5ea33bea7a657f1d61917d794220eef956dcfa0 Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Sun, 18 Jan 2026 01:05:54 +0100 Subject: [PATCH 122/125] ci: avoid running qlty coverage report for PRs (#3316) Signed-off-by: Jan Larwig --- .github/workflows/ci.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7521132570..cd9b6dbe09 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,10 +33,6 @@ jobs: run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} - - name: Install gcov2lcov - run: | - go install github.com/jandelgado/gcov2lcov@latest - - name: Verify Code Generation run: | make verify-generate @@ -61,10 +57,14 @@ jobs: make test - name: Generate Coverage Report + if: github.event_name == 'push' run: | + go install github.com/jandelgado/gcov2lcov@latest gcov2lcov -infile=c.out -outfile=lcov.info - - uses: qltysh/qlty-action/coverage@v2 + - name: Upload Coverage Report + if: github.event_name == 'push' + uses: qltysh/qlty-action/coverage@v2 with: oidc: true files: lcov.info From 3a55dadbe8e34300ff38760b337418db1eaa1ff0 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 18 Jan 2026 01:19:17 +0100 Subject: [PATCH 123/125] release v7.14.2 (#3317) * update to release version v7.14.2 * doc: changelog entry for v7.14.2 Signed-off-by: Jan Larwig * doc: fix nginx example docker-compose Signed-off-by: Jan Larwig --------- Signed-off-by: Jan Larwig Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Jan Larwig --- CHANGELOG.md | 14 ++++++++++++++ .../docker-compose-alpha-config.yaml | 2 +- .../local-environment/docker-compose-gitea.yaml | 2 +- .../local-environment/docker-compose-keycloak.yaml | 2 +- .../local-environment/docker-compose-nginx.yaml | 6 +++--- .../local-environment/docker-compose-traefik.yaml | 2 +- contrib/local-environment/docker-compose.yaml | 2 +- docs/docs/installation.md | 2 +- docs/versioned_docs/version-7.14.x/installation.md | 2 +- 9 files changed, 24 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e052c3db68..ed40d05670 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,20 @@ ## Breaking Changes +## Changes since v7.14.2 + +# V7.14.2 + +## Release Highlights + +- Revert AuthOnly endpoint change from v7.14.1 that caused issues when using `skip-provider-button` enabled + +## Important Notes + +- 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. + +## Breaking Changes + ## Changes since v7.14.1 - [#3314](https://github.com/oauth2-proxy/oauth2-proxy/pull/3314) revert: fix: skip provider button auth only redirect (#3309) (@StefanMarkmann / @tuunit) diff --git a/contrib/local-environment/docker-compose-alpha-config.yaml b/contrib/local-environment/docker-compose-alpha-config.yaml index bd64128d00..595ce4e481 100644 --- a/contrib/local-environment/docker-compose-alpha-config.yaml +++ b/contrib/local-environment/docker-compose-alpha-config.yaml @@ -14,7 +14,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.2 command: --config /oauth2-proxy.cfg --alpha-config /oauth2-proxy-alpha-config.yaml hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-gitea.yaml b/contrib/local-environment/docker-compose-gitea.yaml index 83847cc747..65968fe8fb 100644 --- a/contrib/local-environment/docker-compose-gitea.yaml +++ b/contrib/local-environment/docker-compose-gitea.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.2 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-keycloak.yaml b/contrib/local-environment/docker-compose-keycloak.yaml index 435d8b3864..cc56f4aefb 100644 --- a/contrib/local-environment/docker-compose-keycloak.yaml +++ b/contrib/local-environment/docker-compose-keycloak.yaml @@ -14,7 +14,7 @@ version: '3.0' services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.2 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose-nginx.yaml b/contrib/local-environment/docker-compose-nginx.yaml index 599988010e..771815b154 100644 --- a/contrib/local-environment/docker-compose-nginx.yaml +++ b/contrib/local-environment/docker-compose-nginx.yaml @@ -19,10 +19,10 @@ # 127.0.0.1 oauth2-proxy.localhost # 127.0.0.1 httpbin.oauth2-proxy.localhost # 127.0.0.1 oauth2-proxy.oauth2-proxy.localhost -version: '3.0' +version: "3.0" services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.2 ports: [] hostname: oauth2-proxy container_name: oauth2-proxy @@ -62,7 +62,7 @@ services: - "./dex.yaml:/dex.yaml" restart: unless-stopped ports: - - 5556:4181/tcp + - 5556:5556/tcp networks: dex: aliases: diff --git a/contrib/local-environment/docker-compose-traefik.yaml b/contrib/local-environment/docker-compose-traefik.yaml index 1358f839b5..b5d25e2ff3 100644 --- a/contrib/local-environment/docker-compose-traefik.yaml +++ b/contrib/local-environment/docker-compose-traefik.yaml @@ -23,7 +23,7 @@ version: '3.0' services: oauth2-proxy: - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.2 ports: [] hostname: oauth2-proxy volumes: diff --git a/contrib/local-environment/docker-compose.yaml b/contrib/local-environment/docker-compose.yaml index c3ac36cc30..12ddeb6833 100644 --- a/contrib/local-environment/docker-compose.yaml +++ b/contrib/local-environment/docker-compose.yaml @@ -13,7 +13,7 @@ version: "3.0" services: oauth2-proxy: container_name: oauth2-proxy - image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.1 + image: quay.io/oauth2-proxy/oauth2-proxy:v7.14.2 command: --config /oauth2-proxy.cfg hostname: oauth2-proxy volumes: diff --git a/docs/docs/installation.md b/docs/docs/installation.md index fcdf25cfae..4bb94f4fea 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.1`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.2`) b. Using Go to install the latest release ```bash diff --git a/docs/versioned_docs/version-7.14.x/installation.md b/docs/versioned_docs/version-7.14.x/installation.md index fcdf25cfae..4bb94f4fea 100644 --- a/docs/versioned_docs/version-7.14.x/installation.md +++ b/docs/versioned_docs/version-7.14.x/installation.md @@ -5,7 +5,7 @@ title: Installation 1. Choose how to deploy: - a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.1`) + a. Using a [Prebuilt Binary](https://github.com/oauth2-proxy/oauth2-proxy/releases) (current release is `v7.14.2`) b. Using Go to install the latest release ```bash From e7724f3a745ac36225305f3d17b59931b647dc6e Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Thu, 12 Feb 2026 21:18:45 +0100 Subject: [PATCH 124/125] ci: ensure release branches originate from the local repository and reduce residual risk of command injection (#3337) Signed-off-by: Jan Larwig --- .github/workflows/publish-release.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index d3a8115f94..9f235fb611 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -14,7 +14,7 @@ permissions: jobs: publish: - if: github.event.pull_request.merged && startsWith(github.event.pull_request.head.ref, 'release/') + if: github.event.pull_request.merged && startsWith(github.event.pull_request.head.ref, 'release/') && github.event.pull_request.head.repo.full_name == github.repository runs-on: ubuntu-latest outputs: tag: ${{ steps.tag.outputs.version }} @@ -27,14 +27,15 @@ jobs: fetch-tags: true - name: Tag release + env: + BRANCH: ${{ github.event.pull_request.head.ref }} run: | # Set up github-actions[bot] user git config --local user.name "github-actions[bot]" git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com" # Get the version from the branch name - branch="${{ github.event.pull_request.head.ref }}" - version="${branch#release/}" + version="${BRANCH#release/}" echo ${version} # Tag and create release From 56eece361c3e621d9e4e6a90e3f2b757afa54beb Mon Sep 17 00:00:00 2001 From: Yann Lacroix Date: Mon, 15 Apr 2024 18:03:43 +0200 Subject: [PATCH 125/125] =?UTF-8?q?=E2=9C=A8=20Add=20Name=20and=20ObjectID?= =?UTF-8?q?=20claims=20for=20OIDC=20providers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Yann Lacroix --- oauthproxy.go | 4 ++++ pkg/apis/options/providers.go | 4 +++- pkg/apis/sessions/session_state.go | 8 +++++++- providers/oidc.go | 2 ++ providers/provider_data.go | 4 ++++ providers/providers.go | 2 ++ 6 files changed, 22 insertions(+), 2 deletions(-) diff --git a/oauthproxy.go b/oauthproxy.go index 508084c8a0..02530226c8 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -725,11 +725,15 @@ func (p *OAuthProxy) UserInfo(rw http.ResponseWriter, req *http.Request) { Email string `json:"email"` Groups []string `json:"groups,omitempty"` PreferredUsername string `json:"preferredUsername,omitempty"` + ObjectID string `json:"oid,omitempty"` + Name string `json:"name,omitempty"` }{ User: session.User, Email: session.Email, Groups: session.Groups, PreferredUsername: session.PreferredUsername, + ObjectID: session.ObjectID, + Name: session.Name, } if err := json.NewEncoder(rw).Encode(userInfo); err != nil { diff --git a/pkg/apis/options/providers.go b/pkg/apis/options/providers.go index 94bdb592bf..ae54b5c282 100644 --- a/pkg/apis/options/providers.go +++ b/pkg/apis/options/providers.go @@ -311,7 +311,9 @@ type OIDCOptions struct { GroupsClaim string `yaml:"groupsClaim,omitempty"` // UserIDClaim indicates which claim contains the user ID // default set to 'email' - UserIDClaim string `yaml:"userIDClaim,omitempty"` + UserIDClaim string `yaml:"userIDClaim,omitempty"` + NameClaim string `yaml:"nameClaim,omitempty"` + ObjecIDClaim string `yaml:"objectIDClaim,omitempty"` // AudienceClaim allows to define any claim that is verified against the client id // By default `aud` claim is used for verification. AudienceClaims []string `yaml:"audienceClaims,omitempty"` diff --git a/pkg/apis/sessions/session_state.go b/pkg/apis/sessions/session_state.go index a1f807aba9..cc9e7aaaf8 100644 --- a/pkg/apis/sessions/session_state.go +++ b/pkg/apis/sessions/session_state.go @@ -23,6 +23,8 @@ type SessionState struct { Nonce []byte `msgpack:"n,omitempty"` + ObjectID string `msgpack:"id,omitempty"` + Name string `msgpack:"name,omitempty"` Email string `msgpack:"e,omitempty"` User string `msgpack:"u,omitempty"` Groups []string `msgpack:"g,omitempty"` @@ -108,7 +110,7 @@ func (s *SessionState) Age() time.Duration { // String constructs a summary of the session state func (s *SessionState) String() string { - o := fmt.Sprintf("Session{email:%s user:%s PreferredUsername:%s", s.Email, s.User, s.PreferredUsername) + o := fmt.Sprintf("Session{email:%s user:%s PreferredUsername:%s oid:%s name:%s", s.Email, s.User, s.PreferredUsername, s.ObjectID, s.Name) if s.AccessToken != "" { o += " token:true" } @@ -135,6 +137,10 @@ func (s *SessionState) GetClaim(claim string) []string { return []string{} } switch claim { + case "name": + return []string{s.Name} + case "oid": + return []string{s.ObjectID} case "access_token": return []string{s.AccessToken} case "id_token": diff --git a/providers/oidc.go b/providers/oidc.go index aa022f63c7..3bdb2dd76a 100644 --- a/providers/oidc.go +++ b/providers/oidc.go @@ -196,6 +196,8 @@ func (p *OIDCProvider) redeemRefreshToken(ctx context.Context, s *sessions.Sessi s.User = newSession.User s.Groups = newSession.Groups s.PreferredUsername = newSession.PreferredUsername + s.Name = newSession.Name + s.ObjectID = newSession.ObjectID } s.AccessToken = newSession.AccessToken diff --git a/providers/provider_data.go b/providers/provider_data.go index 95de5c5032..a694d130b1 100644 --- a/providers/provider_data.go +++ b/providers/provider_data.go @@ -46,6 +46,8 @@ type ProviderData struct { // Common OIDC options for any OIDC-based providers to consume AllowUnverifiedEmail bool + ObjectIDClaim string + NameClaim string UserClaim string EmailClaim string GroupsClaim string @@ -260,6 +262,8 @@ func (p *ProviderData) buildSessionFromClaims(rawIDToken, accessToken string) (* {p.UserClaim, &ss.User}, {p.EmailClaim, &ss.Email}, {p.GroupsClaim, &ss.Groups}, + {p.ObjectIDClaim, &ss.ObjectID}, + {p.NameClaim, &ss.Name}, // TODO (@NickMeves) Deprecate for dynamic claim to session mapping {"preferred_username", &ss.PreferredUsername}, } { diff --git a/providers/providers.go b/providers/providers.go index 6af51ecf01..4119f3ce95 100644 --- a/providers/providers.go +++ b/providers/providers.go @@ -147,6 +147,8 @@ func newProviderDataFromConfig(providerConfig options.Provider) (*ProviderData, p.AllowUnverifiedEmail = ptr.Deref(providerConfig.OIDCConfig.InsecureAllowUnverifiedEmail, options.DefaultInsecureAllowUnverifiedEmail) p.EmailClaim = providerConfig.OIDCConfig.EmailClaim p.GroupsClaim = providerConfig.OIDCConfig.GroupsClaim + p.ObjectIDClaim = providerConfig.OIDCConfig.ObjecIDClaim + p.NameClaim = providerConfig.OIDCConfig.NameClaim p.SkipClaimsFromProfileURL = ptr.Deref(providerConfig.SkipClaimsFromProfileURL, options.DefaultSkipClaimsFromProfileURL) // Set PKCE enabled or disabled based on discovery and force options