Merge 2f24ff47d1 into e27921ee80
This commit is contained in:
commit
38aca4a60b
|
|
@ -1,6 +1,18 @@
|
|||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Config conversion",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "${workspaceFolder}",
|
||||
"args": [
|
||||
"--convert-config-to-alpha",
|
||||
"--config",
|
||||
"contrib/local-environment/oauth2-proxy.cfg"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "OAuth2 Proxy for Dex",
|
||||
"type": "go",
|
||||
|
|
@ -8,7 +20,8 @@
|
|||
"mode": "auto",
|
||||
"program": "${workspaceFolder}",
|
||||
"args": [
|
||||
"--config", "contrib/local-environment/oauth2-proxy.cfg"
|
||||
"--config",
|
||||
"contrib/local-environment/oauth2-proxy.cfg"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
|
@ -18,7 +31,8 @@
|
|||
"mode": "auto",
|
||||
"program": "${workspaceFolder}",
|
||||
"args": [
|
||||
"--config", "contrib/local-environment/oauth2-proxy-keycloak.cfg"
|
||||
"--config",
|
||||
"contrib/local-environment/oauth2-proxy-keycloak.cfg"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
|
@ -28,8 +42,10 @@
|
|||
"mode": "auto",
|
||||
"program": "${workspaceFolder}",
|
||||
"args": [
|
||||
"--config", "contrib/local-environment/oauth2-proxy-alpha-config.cfg",
|
||||
"--alpha-config", "contrib/local-environment/oauth2-proxy-alpha-config.yaml"
|
||||
"--config",
|
||||
"contrib/local-environment/oauth2-proxy-alpha-config.cfg",
|
||||
"--alpha-config",
|
||||
"contrib/local-environment/oauth2-proxy-alpha-config.yaml"
|
||||
]
|
||||
}
|
||||
]
|
||||
|
|
|
|||
|
|
@ -1,4 +1,2 @@
|
|||
cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w="
|
||||
email_domains="example.com"
|
||||
cookie_secure="false"
|
||||
redirect_url="http://oauth2-proxy.localtest.me:4180/oauth2/callback"
|
||||
|
|
|
|||
|
|
@ -1,5 +1,15 @@
|
|||
server:
|
||||
bindAddress: "0.0.0.0:4180"
|
||||
cookie:
|
||||
secret: OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w=
|
||||
secure: false
|
||||
providers:
|
||||
- id: oidc
|
||||
provider: oidc
|
||||
clientSecret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK
|
||||
clientID: oauth2-proxy
|
||||
oidcConfig:
|
||||
issuerURL: http://dex.localtest.me:5556/dex
|
||||
upstreamConfig:
|
||||
upstreams:
|
||||
- id: httpbin
|
||||
|
|
@ -14,10 +24,3 @@ injectRequestHeaders:
|
|||
values:
|
||||
- claimSource:
|
||||
claim: email
|
||||
providers:
|
||||
- id: oidc
|
||||
provider: oidc
|
||||
clientSecret: b2F1dGgyLXByb3h5LWNsaWVudC1zZWNyZXQK
|
||||
clientID: oauth2-proxy
|
||||
oidcConfig:
|
||||
issuerURL: http://dex.localtest.me:5556/dex
|
||||
|
|
|
|||
|
|
@ -86,14 +86,14 @@ More information and available patterns can be found [here](https://github.com/a
|
|||
The following flags/options and their respective environment variables are no
|
||||
longer available when using alpha configuration:
|
||||
|
||||
<!-- Legacy Upstream FlagSet -->
|
||||
### Legacy Upstream options
|
||||
- `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`
|
||||
|
||||
<!-- Legacy Headers FlagSet -->
|
||||
### Legacy Headers options
|
||||
- `pass-basic-auth`/`pass_basic_auth`
|
||||
- `pass-access-token`/`pass_access_token`
|
||||
- `pass-user-headers`/`pass_user_headers`
|
||||
|
|
@ -105,7 +105,7 @@ longer available when using alpha configuration:
|
|||
- `basic-auth-password`/`basic_auth_password`
|
||||
- `skip-auth-strip-headers`/`skip_auth_strip_headers`
|
||||
|
||||
<!-- Legacy provider FlagSet -->
|
||||
### Legacy Provider options
|
||||
- `client-id`/`client_id`
|
||||
- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file`
|
||||
- `provider`
|
||||
|
|
@ -127,6 +127,22 @@ longer available when using alpha configuration:
|
|||
- `jwt-key-file`/`jwt_key_file`
|
||||
- `pubjwk-url`/`pubjwk_url`
|
||||
|
||||
### Legacy Cookie options
|
||||
- `cookie-name`/`cookie_name`
|
||||
- `cookie-name`/`cookie_name`
|
||||
- `cookie-secret`/`cookie_secret`
|
||||
- `cookie-secret-file`/`cookie_secret_file`
|
||||
- `cookie-domain`/`cookie_domains`
|
||||
- `cookie-path`/`cookie_path`
|
||||
- `cookie-expire`/`cookie_expire`
|
||||
- `cookie-refresh`/`cookie_refresh`
|
||||
- `cookie-secure`/`cookie_secure`
|
||||
- `cookie-httponly`/`cookie_httponly`
|
||||
- `cookie-samesite`/`cookie_samesite`
|
||||
- `cookie-csrf-per-request`/`cookie_csrf_per_request`
|
||||
- `cookie-csrf-per-request-limit`/`cookie_csrf_per_request_limit`
|
||||
- `cookie-csrf-expire`/`cookie_csrf_expire`
|
||||
|
||||
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
|
||||
|
|
@ -169,6 +185,7 @@ They may change between releases without notice.
|
|||
| `server` | _[Server](#server)_ | Server is used to configure the HTTP(S) server for the proxy application.<br/>You may choose to run both HTTP and HTTPS servers simultaneously.<br/>This can be done by setting the BindAddress and the SecureBindAddress simultaneously.<br/>To use the secure server you must configure a TLS certificate and key. |
|
||||
| `metricsServer` | _[Server](#server)_ | MetricsServer is used to configure the HTTP(S) server for metrics.<br/>You may choose to run both HTTP and HTTPS servers simultaneously.<br/>This can be done by setting the BindAddress and the SecureBindAddress simultaneously.<br/>To use the secure server you must configure a TLS certificate and key. |
|
||||
| `providers` | _[Providers](#providers)_ | Providers is used to configure your provider. **Multiple-providers is not<br/>yet working.** [This feature is tracked in<br/>#925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926) |
|
||||
| `cookie` | _[Cookie](#cookie)_ | Cookie is used to configure the cookies used by OAuth2 Proxy.<br/>This includes session and CSRF cookies. |
|
||||
|
||||
### AzureOptions
|
||||
|
||||
|
|
@ -204,6 +221,28 @@ 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<br/>claim if it is non-empty. |
|
||||
| `basicAuthPassword` | _[SecretSource](#secretsource)_ | BasicAuthPassword converts this claim into a basic auth header.<br/>Note the value of claim will become the basic auth username and the<br/>basicAuthPassword will be used as the password value. |
|
||||
|
||||
### Cookie
|
||||
|
||||
(**Appears on:** [AlphaOptions](#alphaoptions))
|
||||
|
||||
Cookie contains configuration options relating session and CSRF cookies
|
||||
|
||||
| Field | Type | Description |
|
||||
| ----- | ---- | ----------- |
|
||||
| `name` | _string_ | Name is the name of the cookie |
|
||||
| `secret` | _string_ | Secret is the secret used to encrypt/sign the cookie value |
|
||||
| `secretFile` | _string_ | SecretFile is a file containing the secret used to encrypt/sign the cookie value<br/>instead of specifying it directly in the config. Secret takes precedence over SecretFile |
|
||||
| `domains` | _[]string_ | Domains is a list of domains for which the cookie is valid |
|
||||
| `path` | _string_ | Path is the path for which the cookie is valid |
|
||||
| `expire` | _duration_ | Expire is the duration before the cookie expires |
|
||||
| `refresh` | _duration_ | Refresh is the duration after which the cookie is refreshable |
|
||||
| `secure` | _bool_ | Secure indicates whether the cookie is only sent over HTTPS |
|
||||
| `httpOnly` | _bool_ | HTTPOnly indicates whether the cookie is inaccessible to JavaScript |
|
||||
| `sameSite` | _string_ | SameSite sets the SameSite attribute on the cookie |
|
||||
| `csrfPerRequest` | _bool_ | CSRFPerRequest indicates whether a unique CSRF token is generated for each request<br/>Enables parallel requests from clients (e.g., multiple tabs) |
|
||||
| `csrfPerRequestLimit` | _int_ | CSRFPerRequestLimit sets a limit on the number of valid CSRF tokens when CSRFPerRequest is enabled<br/>Used to prevent unbounded memory growth from storing too many tokens |
|
||||
| `csrfExpire` | _duration_ | CSRFExpire sets the duration before a CSRF token expires |
|
||||
|
||||
### GitHubOptions
|
||||
|
||||
(**Appears on:** [Provider](#provider))
|
||||
|
|
|
|||
|
|
@ -86,14 +86,14 @@ More information and available patterns can be found [here](https://github.com/a
|
|||
The following flags/options and their respective environment variables are no
|
||||
longer available when using alpha configuration:
|
||||
|
||||
<!-- Legacy Upstream FlagSet -->
|
||||
### Legacy Upstream options
|
||||
- `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`
|
||||
|
||||
<!-- Legacy Headers FlagSet -->
|
||||
### Legacy Headers options
|
||||
- `pass-basic-auth`/`pass_basic_auth`
|
||||
- `pass-access-token`/`pass_access_token`
|
||||
- `pass-user-headers`/`pass_user_headers`
|
||||
|
|
@ -105,7 +105,7 @@ longer available when using alpha configuration:
|
|||
- `basic-auth-password`/`basic_auth_password`
|
||||
- `skip-auth-strip-headers`/`skip_auth_strip_headers`
|
||||
|
||||
<!-- Legacy provider FlagSet -->
|
||||
### Legacy Provider options
|
||||
- `client-id`/`client_id`
|
||||
- `client-secret`/`client_secret`, and `client-secret-file`/`client_secret_file`
|
||||
- `provider`
|
||||
|
|
@ -127,6 +127,22 @@ longer available when using alpha configuration:
|
|||
- `jwt-key-file`/`jwt_key_file`
|
||||
- `pubjwk-url`/`pubjwk_url`
|
||||
|
||||
### Legacy Cookie options
|
||||
- `cookie-name`/`cookie_name`
|
||||
- `cookie-name`/`cookie_name`
|
||||
- `cookie-secret`/`cookie_secret`
|
||||
- `cookie-secret-file`/`cookie_secret_file`
|
||||
- `cookie-domain`/`cookie_domains`
|
||||
- `cookie-path`/`cookie_path`
|
||||
- `cookie-expire`/`cookie_expire`
|
||||
- `cookie-refresh`/`cookie_refresh`
|
||||
- `cookie-secure`/`cookie_secure`
|
||||
- `cookie-httponly`/`cookie_httponly`
|
||||
- `cookie-samesite`/`cookie_samesite`
|
||||
- `cookie-csrf-per-request`/`cookie_csrf_per_request`
|
||||
- `cookie-csrf-per-request-limit`/`cookie_csrf_per_request_limit`
|
||||
- `cookie-csrf-expire`/`cookie_csrf_expire`
|
||||
|
||||
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
|
||||
|
|
|
|||
24
main.go
24
main.go
|
|
@ -97,7 +97,7 @@ func loadLegacyOptions(config string, extraFlags *pflag.FlagSet, args []string)
|
|||
|
||||
legacyOpts := options.NewLegacyOptions()
|
||||
if err := options.Load(config, optionsFlagSet, legacyOpts); err != nil {
|
||||
return nil, fmt.Errorf("failed to load config: %v", err)
|
||||
return nil, fmt.Errorf("failed to load legacy config: %v", err)
|
||||
}
|
||||
|
||||
opts, err := legacyOpts.ToOptions()
|
||||
|
|
@ -150,6 +150,28 @@ func loadOptions(config string, extraFlags *pflag.FlagSet, args []string) (*opti
|
|||
func printConvertedConfig(opts *options.Options) error {
|
||||
alphaConfig := options.NewAlphaOptions(opts)
|
||||
|
||||
if len(alphaConfig.Providers) == 1 {
|
||||
providerType := alphaConfig.Providers[0].Type
|
||||
|
||||
if providerType != options.ADFSProvider {
|
||||
alphaConfig.Providers[0].ADFSConfig = options.ADFSOptions{}
|
||||
}
|
||||
|
||||
if providerType != options.AzureProvider {
|
||||
alphaConfig.Providers[0].AzureConfig = options.AzureOptions{}
|
||||
}
|
||||
|
||||
if providerType != options.GoogleProvider {
|
||||
alphaConfig.Providers[0].GoogleConfig = options.GoogleOptions{}
|
||||
}
|
||||
|
||||
if providerType != options.MicrosoftEntraIDProvider {
|
||||
alphaConfig.Providers[0].MicrosoftEntraIDConfig = options.MicrosoftEntraIDOptions{}
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("only single provider conversion is supported")
|
||||
}
|
||||
|
||||
// Generic interface for loading arbitrary yaml structure
|
||||
var buffer map[string]interface{}
|
||||
|
||||
|
|
|
|||
20
main_test.go
20
main_test.go
|
|
@ -15,18 +15,24 @@ import (
|
|||
|
||||
var _ = Describe("Configuration Loading Suite", func() {
|
||||
// For comparing the full configuration differences of our structs we need to increase the gomega limits
|
||||
format.MaxLength = 50000
|
||||
format.MaxLength = 0
|
||||
format.MaxDepth = 10
|
||||
|
||||
const testLegacyConfig = `
|
||||
http_address="127.0.0.1:4180"
|
||||
upstreams="http://httpbin"
|
||||
|
||||
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"
|
||||
|
||||
cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w="
|
||||
cookie_secure="false"
|
||||
`
|
||||
|
||||
const testAlphaConfig = `
|
||||
|
|
@ -80,6 +86,9 @@ injectResponseHeaders:
|
|||
value: c3VwZXItc2VjcmV0LXBhc3N3b3Jk
|
||||
server:
|
||||
bindAddress: "127.0.0.1:4180"
|
||||
cookie:
|
||||
secure: false
|
||||
secret: "OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w="
|
||||
providers:
|
||||
- id: google=oauth2-proxy
|
||||
provider: google
|
||||
|
|
@ -106,10 +115,7 @@ providers:
|
|||
`
|
||||
|
||||
const testCoreConfig = `
|
||||
cookie_secret="OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w="
|
||||
email_domains="example.com"
|
||||
cookie_secure="false"
|
||||
|
||||
redirect_url="http://localhost:4180/oauth2/callback"
|
||||
`
|
||||
|
||||
|
|
@ -119,7 +125,7 @@ redirect_url="http://localhost:4180/oauth2/callback"
|
|||
|
||||
opts.Cookie.Secret = "OQINaROshtE9TcZkNAm-5Zs2Pv3xaWytBmc5W7sPX7w="
|
||||
opts.EmailDomains = []string{"example.com"}
|
||||
opts.Cookie.Secure = false
|
||||
opts.Cookie.Secure = ptr.To(false)
|
||||
opts.RawRedirectURL = "http://localhost:4180/oauth2/callback"
|
||||
|
||||
opts.UpstreamServers = options.UpstreamConfig{
|
||||
|
|
@ -276,7 +282,7 @@ redirect_url="http://localhost:4180/oauth2/callback"
|
|||
Entry("with bad legacy configuration", loadConfigurationTableInput{
|
||||
configContent: testCoreConfig + "unknown_field=\"something\"",
|
||||
expectedOptions: func() *options.Options { return nil },
|
||||
expectedErr: errors.New("failed to load legacy options: failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"),
|
||||
expectedErr: errors.New("failed to load legacy options: failed to load legacy 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,
|
||||
|
|
@ -288,7 +294,7 @@ redirect_url="http://localhost:4180/oauth2/callback"
|
|||
configContent: testCoreConfig + "unknown_field=\"something\"",
|
||||
alphaConfigContent: testAlphaConfig,
|
||||
expectedOptions: func() *options.Options { return nil },
|
||||
expectedErr: errors.New("failed to load legacy options: failed to load config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"),
|
||||
expectedErr: errors.New("failed to load legacy options: failed to load legacy config: error unmarshalling config: decoding failed due to the following error(s):\n\n'' has invalid keys: unknown_field"),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ import (
|
|||
"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/util"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/version"
|
||||
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
|
||||
|
|
@ -175,11 +176,11 @@ func NewOAuthProxy(opts *options.Options, validator func(string) bool) (*OAuthPr
|
|||
|
||||
logger.Printf("OAuthProxy configured for %s Client ID: %s", provider.Data().ProviderName, opts.Providers[0].ClientID)
|
||||
refresh := "disabled"
|
||||
if opts.Cookie.Refresh != time.Duration(0) {
|
||||
refresh = fmt.Sprintf("after %s", opts.Cookie.Refresh)
|
||||
if opts.Session.Refresh != time.Duration(0) {
|
||||
refresh = fmt.Sprintf("after %s", opts.Session.Refresh)
|
||||
}
|
||||
|
||||
logger.Printf("Cookie settings: name:%s secure(https):%v httponly:%v expiry:%s domains:%s path:%s samesite:%s refresh:%s", opts.Cookie.Name, opts.Cookie.Secure, opts.Cookie.HTTPOnly, opts.Cookie.Expire, strings.Join(opts.Cookie.Domains, ","), opts.Cookie.Path, opts.Cookie.SameSite, refresh)
|
||||
logger.Printf("Cookie settings: name:%s insecure(http):%v nothttponly:%v expiry:%s domains:%s path:%s samesite:%s refresh:%s", opts.Cookie.Name, opts.Cookie.Insecure, opts.Cookie.NotHttpOnly, opts.Cookie.Expire, strings.Join(opts.Cookie.Domains, ","), opts.Cookie.Path, opts.Cookie.SameSite, refresh)
|
||||
|
||||
trustedIPs := ip.NewNetSet()
|
||||
for _, ipStr := range opts.TrustedIPs {
|
||||
|
|
@ -415,7 +416,7 @@ func buildSessionChain(opts *options.Options, provider providers.Provider, sessi
|
|||
|
||||
chain = chain.Append(middleware.NewStoredSessionLoader(&middleware.StoredSessionLoaderOptions{
|
||||
SessionStore: sessionStore,
|
||||
RefreshPeriod: opts.Cookie.Refresh,
|
||||
RefreshPeriod: opts.Session.Refresh,
|
||||
RefreshSession: provider.RefreshSession,
|
||||
ValidateSession: provider.ValidateSession,
|
||||
}))
|
||||
|
|
@ -1096,9 +1097,9 @@ func (p *OAuthProxy) getOAuthRedirectURI(req *http.Request) string {
|
|||
rd.Scheme = schemeHTTP
|
||||
}
|
||||
|
||||
// If CookieSecure is true, return `https` no matter what
|
||||
// If CookieInsecure is false, return `https` no matter what
|
||||
// Not all reverse proxies set X-Forwarded-Proto
|
||||
if p.CookieOptions.Secure {
|
||||
if !ptr.Deref(p.CookieOptions.Insecure, options.DefaultCookieInsecure) {
|
||||
rd.Scheme = schemeHTTPS
|
||||
}
|
||||
return rd.String()
|
||||
|
|
|
|||
|
|
@ -207,7 +207,7 @@ func TestBasicAuthPassword(t *testing.T) {
|
|||
},
|
||||
}
|
||||
|
||||
opts.Cookie.Secure = false
|
||||
opts.Cookie.Secure = ptr.To(false)
|
||||
opts.InjectRequestHeaders = []options.Header{
|
||||
{
|
||||
Name: "Authorization",
|
||||
|
|
@ -362,7 +362,7 @@ func NewPassAccessTokenTest(opts PassAccessTokenTestOptions) (*PassAccessTokenTe
|
|||
patt.opts.UpstreamServers.Upstreams = append(patt.opts.UpstreamServers.Upstreams, opts.ProxyUpstream)
|
||||
}
|
||||
|
||||
patt.opts.Cookie.Secure = false
|
||||
patt.opts.Cookie.Secure = ptr.To(false)
|
||||
if opts.PassAccessToken {
|
||||
patt.opts.InjectRequestHeaders = []options.Header{
|
||||
{
|
||||
|
|
@ -819,9 +819,9 @@ func NewProcessCookieTest(opts ProcessCookieTestOpts, modifiers ...OptionsModifi
|
|||
for _, modifier := range modifiers {
|
||||
modifier(pcTest.opts)
|
||||
}
|
||||
// First, set the CookieRefresh option so proxy.AesCipher is created,
|
||||
// First, set the Session Refresh option so proxy.AesCipher is created,
|
||||
// needed to encrypt the access_token.
|
||||
pcTest.opts.Cookie.Refresh = time.Hour
|
||||
pcTest.opts.Session.Refresh = time.Hour
|
||||
err := validation.Validate(pcTest.opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
@ -845,9 +845,9 @@ func NewProcessCookieTest(opts ProcessCookieTestOpts, modifiers ...OptionsModifi
|
|||
}
|
||||
pcTest.proxy.provider = testProvider
|
||||
|
||||
// Now, zero-out proxy.CookieRefresh for the cases that don't involve
|
||||
// Now, zero-out Session Refresh for the cases that don't involve
|
||||
// access_token validation.
|
||||
pcTest.proxy.CookieOptions.Refresh = time.Duration(0)
|
||||
pcTest.opts.Session.Refresh = time.Duration(0)
|
||||
pcTest.rw = httptest.NewRecorder()
|
||||
pcTest.req, _ = http.NewRequest("GET", "/", strings.NewReader(""))
|
||||
pcTest.validateUser = true
|
||||
|
|
@ -969,7 +969,7 @@ func TestProcessCookieFailIfRefreshSetAndCookieExpired(t *testing.T) {
|
|||
err = pcTest.SaveSession(startSession)
|
||||
assert.NoError(t, err)
|
||||
|
||||
pcTest.proxy.CookieOptions.Refresh = time.Hour
|
||||
pcTest.opts.Session.Refresh = time.Hour
|
||||
session, err := pcTest.LoadCookiedSession()
|
||||
assert.NotEqual(t, nil, err)
|
||||
if session != nil {
|
||||
|
|
@ -2073,6 +2073,8 @@ func baseTestOptions() *options.Options {
|
|||
},
|
||||
}
|
||||
|
||||
opts.EnsureDefaults()
|
||||
|
||||
return opts
|
||||
}
|
||||
|
||||
|
|
@ -3468,7 +3470,7 @@ func TestGetOAuthRedirectURI(t *testing.T) {
|
|||
{
|
||||
name: "redirect with http schema",
|
||||
setupOpts: func(baseOpts *options.Options) *options.Options {
|
||||
baseOpts.Cookie.Secure = false
|
||||
baseOpts.Cookie.Secure = ptr.To(false)
|
||||
return baseOpts
|
||||
},
|
||||
req: &http.Request{
|
||||
|
|
|
|||
|
|
@ -45,6 +45,10 @@ type AlphaOptions struct {
|
|||
// yet working.** [This feature is tracked in
|
||||
// #925](https://github.com/oauth2-proxy/oauth2-proxy/issues/926)
|
||||
Providers Providers `yaml:"providers,omitempty"`
|
||||
|
||||
// Cookie is used to configure the cookies used by OAuth2 Proxy.
|
||||
// This includes session and CSRF cookies.
|
||||
Cookie Cookie `yaml:"cookie,omitempty"`
|
||||
}
|
||||
|
||||
// Initialize alpha options with default values and settings of the core options
|
||||
|
|
@ -63,6 +67,7 @@ func (a *AlphaOptions) ExtractFrom(opts *Options) {
|
|||
a.Server = opts.Server
|
||||
a.MetricsServer = opts.MetricsServer
|
||||
a.Providers = opts.Providers
|
||||
a.Cookie = opts.Cookie
|
||||
}
|
||||
|
||||
// MergeOptionsWithDefaults replaces alpha options in the Options struct
|
||||
|
|
@ -74,4 +79,5 @@ func (a *AlphaOptions) MergeOptionsWithDefaults(opts *Options) {
|
|||
opts.Server = a.Server
|
||||
opts.MetricsServer = a.MetricsServer
|
||||
opts.Providers = a.Providers
|
||||
opts.Cookie = a.Cookie
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,80 +1,107 @@
|
|||
package options
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
|
||||
"github.com/spf13/pflag"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
"go.yaml.in/yaml/v3"
|
||||
)
|
||||
|
||||
// Cookie contains configuration options relating to Cookie configuration
|
||||
const (
|
||||
// DefaultCookieInsecure is the default value for Cookie.Insecure
|
||||
DefaultCookieInsecure bool = false
|
||||
// DefaultCookieNotHttpOnly is the default value for Cookie.NotHttpOnly
|
||||
DefaultCookieNotHttpOnly bool = false
|
||||
// DefaultCSRFPerRequest is the default value for Cookie.CSRFPerRequest
|
||||
DefaultCSRFPerRequest bool = false
|
||||
)
|
||||
|
||||
type SameSiteMode string
|
||||
|
||||
const (
|
||||
SameSiteLax SameSiteMode = "lax"
|
||||
SameSiteStrict SameSiteMode = "strict"
|
||||
SameSiteNone SameSiteMode = "none"
|
||||
SameSiteDefault SameSiteMode = ""
|
||||
)
|
||||
|
||||
// Cookie contains configuration options relating session and CSRF cookies
|
||||
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"`
|
||||
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"`
|
||||
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"`
|
||||
// Name is the name of the cookie
|
||||
Name string `yaml:"name,omitempty"`
|
||||
// Secret is the secret source used to encrypt/sign the cookie value
|
||||
Secret SecretSource `yaml:"secret,omitempty"`
|
||||
// Domains is a list of domains for which the cookie is valid
|
||||
Domains []string `yaml:"domains,omitempty"`
|
||||
// Path is the path for which the cookie is valid
|
||||
Path string `yaml:"path,omitempty"`
|
||||
// Expire is the duration before the cookie expires
|
||||
Expire time.Duration `yaml:"expire,omitempty"`
|
||||
// Insecure indicates whether the cookie allows to be sent over HTTP
|
||||
// Default is false, which requires HTTPS
|
||||
Insecure *bool `yaml:"insecure,omitempty"`
|
||||
// NotHttpOnly is the inverse of HTTPOnly; indicates whether the cookie is accessible to JavaScript
|
||||
// Default is false, which helps mitigate certain XSS attacks
|
||||
NotHttpOnly *bool `yaml:"notHttpOnly,omitempty"`
|
||||
// SameSite sets the SameSite attribute on the cookie
|
||||
SameSite SameSiteMode `yaml:"sameSite,omitempty"`
|
||||
// CSRFPerRequest indicates whether a unique CSRF token is generated for each request
|
||||
// Enables parallel requests from clients (e.g., multiple tabs)
|
||||
// Default is false, which uses a single CSRF token per session
|
||||
CSRFPerRequest *bool `yaml:"csrfPerRequest,omitempty"`
|
||||
// CSRFPerRequestLimit sets a limit on the number of valid CSRF tokens when CSRFPerRequest is enabled
|
||||
// Used to prevent unbounded memory growth from storing too many tokens
|
||||
CSRFPerRequestLimit int `yaml:"csrfPerRequestLimit,omitempty"`
|
||||
// CSRFExpire sets the duration before a CSRF token expires
|
||||
CSRFExpire time.Duration `yaml:"csrfExpire,omitempty"`
|
||||
}
|
||||
|
||||
func cookieFlagSet() *pflag.FlagSet {
|
||||
flagSet := pflag.NewFlagSet("cookie", pflag.ExitOnError)
|
||||
|
||||
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")
|
||||
flagSet.Duration("cookie-refresh", time.Duration(0), "refresh the cookie after this duration; 0 to disable")
|
||||
flagSet.Bool("cookie-secure", true, "set secure (HTTPS) cookie flag")
|
||||
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
|
||||
}
|
||||
|
||||
// cookieDefaults creates a Cookie populating each field with its default value
|
||||
func cookieDefaults() Cookie {
|
||||
return Cookie{
|
||||
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,
|
||||
func (m *SameSiteMode) UnmarshalYAML(value *yaml.Node) error {
|
||||
var s string
|
||||
if err := value.Decode(&s); err != nil {
|
||||
return err
|
||||
}
|
||||
switch SameSiteMode(s) {
|
||||
case SameSiteLax, SameSiteStrict, SameSiteNone, SameSiteDefault:
|
||||
*m = SameSiteMode(s)
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("invalid same site mode: %s", s)
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
// GetSecret returns the cookie secret as a string from the SecretSource
|
||||
func (c *Cookie) GetSecret() (string, error) {
|
||||
secret, err := c.Secret.GetSecretValue()
|
||||
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 "", fmt.Errorf("error getting cookie secret: %w", err)
|
||||
}
|
||||
|
||||
return string(fileSecret), nil
|
||||
return string(secret), nil
|
||||
}
|
||||
|
||||
// EnsureDefaults sets any default values for the Cookie configuration
|
||||
func (c *Cookie) EnsureDefaults() {
|
||||
if c.Name == "" {
|
||||
c.Name = "_oauth2_proxy"
|
||||
}
|
||||
if c.Path == "" {
|
||||
c.Path = "/"
|
||||
}
|
||||
if c.Expire == 0 {
|
||||
c.Expire = time.Duration(168) * time.Hour
|
||||
}
|
||||
if c.Insecure == nil {
|
||||
c.Insecure = ptr.To(DefaultCookieInsecure)
|
||||
}
|
||||
if c.NotHttpOnly == nil {
|
||||
c.NotHttpOnly = ptr.To(DefaultCookieNotHttpOnly)
|
||||
}
|
||||
if c.CSRFPerRequest == nil {
|
||||
c.CSRFPerRequest = ptr.To(DefaultCSRFPerRequest)
|
||||
}
|
||||
if c.CSRFExpire == 0 {
|
||||
c.CSRFExpire = time.Duration(15) * time.Minute
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,8 +10,10 @@ import (
|
|||
func TestCookieGetSecret(t *testing.T) {
|
||||
t.Run("returns secret when Secret is set", func(t *testing.T) {
|
||||
c := &Cookie{
|
||||
Secret: "my-secret",
|
||||
SecretFile: "",
|
||||
Secret: SecretSource{
|
||||
Value: []byte("my-secret"),
|
||||
FromFile: "",
|
||||
},
|
||||
}
|
||||
secret, err := c.GetSecret()
|
||||
assert.NoError(t, err)
|
||||
|
|
@ -20,8 +22,10 @@ func TestCookieGetSecret(t *testing.T) {
|
|||
|
||||
t.Run("returns secret when both Secret and SecretFile are set", func(t *testing.T) {
|
||||
c := &Cookie{
|
||||
Secret: "my-secret",
|
||||
SecretFile: "/some/file",
|
||||
Secret: SecretSource{
|
||||
Value: []byte("my-secret"),
|
||||
FromFile: "/some/file",
|
||||
},
|
||||
}
|
||||
secret, err := c.GetSecret()
|
||||
assert.NoError(t, err)
|
||||
|
|
@ -39,8 +43,10 @@ func TestCookieGetSecret(t *testing.T) {
|
|||
tmpfile.Close()
|
||||
|
||||
c := &Cookie{
|
||||
Secret: "",
|
||||
SecretFile: tmpfile.Name(),
|
||||
Secret: SecretSource{
|
||||
Value: []byte(""),
|
||||
FromFile: tmpfile.Name(),
|
||||
},
|
||||
}
|
||||
secret, err := c.GetSecret()
|
||||
assert.NoError(t, err)
|
||||
|
|
@ -49,19 +55,23 @@ func TestCookieGetSecret(t *testing.T) {
|
|||
|
||||
t.Run("returns error when file does not exist", func(t *testing.T) {
|
||||
c := &Cookie{
|
||||
Secret: "",
|
||||
SecretFile: "/nonexistent/file",
|
||||
Secret: SecretSource{
|
||||
Value: []byte(""),
|
||||
FromFile: "/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")
|
||||
assert.Contains(t, err.Error(), "error reading cookie secret file /nonexistent/file:")
|
||||
})
|
||||
|
||||
t.Run("returns empty when both Secret and SecretFile are empty", func(t *testing.T) {
|
||||
c := &Cookie{
|
||||
Secret: "",
|
||||
SecretFile: "",
|
||||
Secret: SecretSource{
|
||||
Value: []byte(""),
|
||||
FromFile: "",
|
||||
},
|
||||
}
|
||||
secret, err := c.GetSecret()
|
||||
assert.NoError(t, err)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,75 @@
|
|||
package options
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// LegacyCookie contains configuration options relating to Cookie configuration
|
||||
type LegacyCookie 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"`
|
||||
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"`
|
||||
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 legacyCookieFlagSet() *pflag.FlagSet {
|
||||
flagSet := pflag.NewFlagSet("cookie", pflag.ExitOnError)
|
||||
|
||||
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")
|
||||
flagSet.Duration("cookie-refresh", time.Duration(0), "refresh the cookie after this duration; 0 to disable")
|
||||
flagSet.Bool("cookie-secure", true, "set secure (HTTPS) cookie flag")
|
||||
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
|
||||
}
|
||||
|
||||
func (l *LegacyCookie) convert() Cookie {
|
||||
// Invert Secure and HTTPOnly to match the new Cookie struct
|
||||
// which uses Insecure and NotHttpOnly
|
||||
insecure := !l.Secure
|
||||
notHttpOnly := !l.HTTPOnly
|
||||
|
||||
secretValue := make([]byte, 0)
|
||||
|
||||
if l.Secret != "" {
|
||||
base64.StdEncoding.Encode([]byte(l.Secret), secretValue)
|
||||
}
|
||||
|
||||
return Cookie{
|
||||
Name: l.Name,
|
||||
Secret: SecretSource{
|
||||
Value: secretValue,
|
||||
FromFile: l.SecretFile,
|
||||
},
|
||||
Domains: l.Domains,
|
||||
Path: l.Path,
|
||||
Expire: l.Expire,
|
||||
Insecure: &insecure,
|
||||
NotHttpOnly: ¬HttpOnly,
|
||||
SameSite: SameSiteMode(l.SameSite),
|
||||
CSRFPerRequest: &l.CSRFPerRequest,
|
||||
CSRFPerRequestLimit: l.CSRFPerRequestLimit,
|
||||
CSRFExpire: l.CSRFExpire,
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,283 @@
|
|||
package options
|
||||
|
||||
import (
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
type LegacyHeaders struct {
|
||||
PassBasicAuth bool `flag:"pass-basic-auth" cfg:"pass_basic_auth"`
|
||||
PassAccessToken bool `flag:"pass-access-token" cfg:"pass_access_token"`
|
||||
PassUserHeaders bool `flag:"pass-user-headers" cfg:"pass_user_headers"`
|
||||
PassAuthorization bool `flag:"pass-authorization-header" cfg:"pass_authorization_header"`
|
||||
|
||||
SetBasicAuth bool `flag:"set-basic-auth" cfg:"set_basic_auth"`
|
||||
SetXAuthRequest bool `flag:"set-xauthrequest" cfg:"set_xauthrequest"`
|
||||
SetAuthorization bool `flag:"set-authorization-header" cfg:"set_authorization_header"`
|
||||
|
||||
PreferEmailToUser bool `flag:"prefer-email-to-user" cfg:"prefer_email_to_user"`
|
||||
BasicAuthPassword string `flag:"basic-auth-password" cfg:"basic_auth_password"`
|
||||
SkipAuthStripHeaders bool `flag:"skip-auth-strip-headers" cfg:"skip_auth_strip_headers"`
|
||||
}
|
||||
|
||||
func legacyHeadersFlagSet() *pflag.FlagSet {
|
||||
flagSet := pflag.NewFlagSet("headers", pflag.ExitOnError)
|
||||
|
||||
flagSet.Bool("pass-basic-auth", true, "pass HTTP Basic Auth, X-Forwarded-User and X-Forwarded-Email information to upstream")
|
||||
flagSet.Bool("pass-access-token", false, "pass OAuth access_token to upstream via X-Forwarded-Access-Token header")
|
||||
flagSet.Bool("pass-user-headers", true, "pass X-Forwarded-User and X-Forwarded-Email information to upstream")
|
||||
flagSet.Bool("pass-authorization-header", false, "pass the Authorization Header to upstream")
|
||||
|
||||
flagSet.Bool("set-basic-auth", false, "set HTTP Basic Auth information in response (useful in Nginx auth_request mode)")
|
||||
flagSet.Bool("set-xauthrequest", false, "set X-Auth-Request-User and X-Auth-Request-Email response headers (useful in Nginx auth_request mode)")
|
||||
flagSet.Bool("set-authorization-header", false, "set Authorization response headers (useful in Nginx auth_request mode)")
|
||||
|
||||
flagSet.Bool("prefer-email-to-user", false, "Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, eg. htaccess authentication. Used in conjunction with -pass-basic-auth and -pass-user-headers")
|
||||
flagSet.String("basic-auth-password", "", "the password to set when passing the HTTP Basic Auth header")
|
||||
flagSet.Bool("skip-auth-strip-headers", true, "strips X-Forwarded-* style authentication headers & Authorization header if they would be set by oauth2-proxy")
|
||||
|
||||
return flagSet
|
||||
}
|
||||
|
||||
// convert takes the legacy request/response headers and converts them to
|
||||
// the new format for InjectRequestHeaders and InjectResponseHeaders
|
||||
func (l *LegacyHeaders) convert() ([]Header, []Header) {
|
||||
return l.getRequestHeaders(), l.getResponseHeaders()
|
||||
}
|
||||
|
||||
func (l *LegacyHeaders) getRequestHeaders() []Header {
|
||||
requestHeaders := []Header{}
|
||||
|
||||
if l.PassBasicAuth && l.BasicAuthPassword != "" {
|
||||
requestHeaders = append(requestHeaders, getBasicAuthHeader(l.PreferEmailToUser, l.BasicAuthPassword))
|
||||
}
|
||||
|
||||
// In the old implementation, PassUserHeaders is a subset of PassBasicAuth
|
||||
if l.PassBasicAuth || l.PassUserHeaders {
|
||||
requestHeaders = append(requestHeaders, getPassUserHeaders(l.PreferEmailToUser)...)
|
||||
requestHeaders = append(requestHeaders, getPreferredUsernameHeader())
|
||||
}
|
||||
|
||||
if l.PassAccessToken {
|
||||
requestHeaders = append(requestHeaders, getPassAccessTokenHeader())
|
||||
}
|
||||
|
||||
if l.PassAuthorization {
|
||||
requestHeaders = append(requestHeaders, getAuthorizationHeader())
|
||||
}
|
||||
|
||||
for i := range requestHeaders {
|
||||
requestHeaders[i].PreserveRequestValue = ptr.To(!l.SkipAuthStripHeaders)
|
||||
}
|
||||
|
||||
return requestHeaders
|
||||
}
|
||||
|
||||
func (l *LegacyHeaders) getResponseHeaders() []Header {
|
||||
responseHeaders := []Header{}
|
||||
|
||||
if l.SetXAuthRequest {
|
||||
responseHeaders = append(responseHeaders, getXAuthRequestHeaders()...)
|
||||
if l.PassAccessToken {
|
||||
responseHeaders = append(responseHeaders, getXAuthRequestAccessTokenHeader())
|
||||
}
|
||||
}
|
||||
|
||||
if l.SetBasicAuth {
|
||||
responseHeaders = append(responseHeaders, getBasicAuthHeader(l.PreferEmailToUser, l.BasicAuthPassword))
|
||||
}
|
||||
|
||||
if l.SetAuthorization {
|
||||
responseHeaders = append(responseHeaders, getAuthorizationHeader())
|
||||
}
|
||||
|
||||
return responseHeaders
|
||||
}
|
||||
|
||||
func getBasicAuthHeader(preferEmailToUser bool, basicAuthPassword string) Header {
|
||||
claim := "user"
|
||||
if preferEmailToUser {
|
||||
claim = "email"
|
||||
}
|
||||
|
||||
return Header{
|
||||
Name: "Authorization",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: claim,
|
||||
Prefix: "Basic ",
|
||||
BasicAuthPassword: &SecretSource{
|
||||
Value: []byte(basicAuthPassword),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func getPassUserHeaders(preferEmailToUser bool) []Header {
|
||||
headers := []Header{
|
||||
{
|
||||
Name: "X-Forwarded-Groups",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "groups",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if preferEmailToUser {
|
||||
return append(headers,
|
||||
Header{
|
||||
Name: "X-Forwarded-User",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "email",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return append(headers,
|
||||
Header{
|
||||
Name: "X-Forwarded-User",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "user",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
Header{
|
||||
Name: "X-Forwarded-Email",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "email",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func getPassAccessTokenHeader() Header {
|
||||
return Header{
|
||||
Name: "X-Forwarded-Access-Token",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "access_token",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func getAuthorizationHeader() Header {
|
||||
return Header{
|
||||
Name: "Authorization",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "id_token",
|
||||
Prefix: "Bearer ",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func getPreferredUsernameHeader() Header {
|
||||
return Header{
|
||||
Name: "X-Forwarded-Preferred-Username",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "preferred_username",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func getXAuthRequestHeaders() []Header {
|
||||
headers := []Header{
|
||||
{
|
||||
Name: "X-Auth-Request-User",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "user",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "X-Auth-Request-Email",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "email",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "X-Auth-Request-Preferred-Username",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "preferred_username",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "X-Auth-Request-Groups",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "groups",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return headers
|
||||
}
|
||||
|
||||
func getXAuthRequestAccessTokenHeader() Header {
|
||||
return Header{
|
||||
Name: "X-Auth-Request-Access-Token",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "access_token",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -2,14 +2,8 @@ package options
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
|
|
@ -26,6 +20,12 @@ type LegacyOptions struct {
|
|||
// Legacy options for single provider
|
||||
LegacyProvider LegacyProvider `cfg:",squash"`
|
||||
|
||||
// Legacy options for cookie configuration
|
||||
LegacyCookie LegacyCookie `cfg:",squash"`
|
||||
|
||||
// Legacy options for session store configuration
|
||||
LegacySessionOptions LegacySessionOptions `cfg:",squash"`
|
||||
|
||||
Options Options `cfg:",squash"`
|
||||
}
|
||||
|
||||
|
|
@ -62,6 +62,28 @@ func NewLegacyOptions() *LegacyOptions {
|
|||
InsecureOIDCSkipNonce: true,
|
||||
},
|
||||
|
||||
LegacyCookie: LegacyCookie{
|
||||
Name: "_oauth2_proxy",
|
||||
Secret: "",
|
||||
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,
|
||||
},
|
||||
|
||||
LegacySessionOptions: LegacySessionOptions{
|
||||
Type: "cookie",
|
||||
Cookie: LegacyCookieStoreOptions{
|
||||
Minimal: false,
|
||||
},
|
||||
},
|
||||
|
||||
Options: *NewOptions(),
|
||||
}
|
||||
}
|
||||
|
|
@ -74,6 +96,8 @@ func NewLegacyFlagSet() *pflag.FlagSet {
|
|||
flagSet.AddFlagSet(legacyServerFlagset())
|
||||
flagSet.AddFlagSet(legacyProviderFlagSet())
|
||||
flagSet.AddFlagSet(legacyGoogleFlagSet())
|
||||
flagSet.AddFlagSet(legacyCookieFlagSet())
|
||||
flagSet.AddFlagSet(legacySessionFlagSet())
|
||||
|
||||
return flagSet
|
||||
}
|
||||
|
|
@ -88,7 +112,6 @@ func (l *LegacyOptions) ToOptions() (*Options, error) {
|
|||
l.Options.InjectRequestHeaders, l.Options.InjectResponseHeaders = l.LegacyHeaders.convert()
|
||||
|
||||
l.Options.Server, l.Options.MetricsServer = l.LegacyServer.convert()
|
||||
|
||||
l.Options.LegacyPreferEmailToUser = l.LegacyHeaders.PreferEmailToUser
|
||||
|
||||
providers, err := l.LegacyProvider.convert()
|
||||
|
|
@ -96,735 +119,10 @@ func (l *LegacyOptions) ToOptions() (*Options, error) {
|
|||
return nil, fmt.Errorf("error converting provider: %v", err)
|
||||
}
|
||||
l.Options.Providers = providers
|
||||
l.Options.Cookie = l.LegacyCookie.convert()
|
||||
l.Options.Session = l.LegacySessionOptions.convert(l.LegacyCookie.Refresh)
|
||||
|
||||
l.Options.EnsureDefaults()
|
||||
|
||||
return &l.Options, nil
|
||||
}
|
||||
|
||||
type LegacyUpstreams struct {
|
||||
FlushInterval time.Duration `flag:"flush-interval" cfg:"flush_interval"`
|
||||
PassHostHeader bool `flag:"pass-host-header" cfg:"pass_host_header"`
|
||||
ProxyWebSockets bool `flag:"proxy-websockets" cfg:"proxy_websockets"`
|
||||
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 {
|
||||
flagSet := pflag.NewFlagSet("upstreams", pflag.ExitOnError)
|
||||
|
||||
flagSet.Duration("flush-interval", DefaultUpstreamFlushInterval, "period between response flushing when streaming responses")
|
||||
flagSet.Bool("pass-host-header", true, "pass the request Host Header to upstream")
|
||||
flagSet.Bool("proxy-websockets", true, "enables WebSocket proxying")
|
||||
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://<status_code> 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
|
||||
}
|
||||
|
||||
func (l *LegacyUpstreams) convert() (UpstreamConfig, error) {
|
||||
upstreams := UpstreamConfig{}
|
||||
|
||||
for _, upstreamString := range l.Upstreams {
|
||||
u, err := url.Parse(upstreamString)
|
||||
if err != nil {
|
||||
return UpstreamConfig{}, fmt.Errorf("could not parse upstream %q: %v", upstreamString, err)
|
||||
}
|
||||
|
||||
if u.Path == "" {
|
||||
u.Path = "/"
|
||||
}
|
||||
|
||||
flushInterval := l.FlushInterval
|
||||
timeout := l.Timeout
|
||||
upstream := Upstream{
|
||||
ID: u.Path,
|
||||
Path: u.Path,
|
||||
URI: upstreamString,
|
||||
InsecureSkipTLSVerify: &l.SSLUpstreamInsecureSkipVerify,
|
||||
PassHostHeader: &l.PassHostHeader,
|
||||
ProxyWebSockets: &l.ProxyWebSockets,
|
||||
FlushInterval: &flushInterval,
|
||||
Timeout: &timeout,
|
||||
DisableKeepAlives: &l.DisableKeepAlives,
|
||||
}
|
||||
|
||||
switch u.Scheme {
|
||||
case "file":
|
||||
if u.Fragment != "" {
|
||||
upstream.ID = u.Fragment
|
||||
upstream.Path = u.Fragment
|
||||
// Trim the fragment from the end of the URI
|
||||
upstream.URI = strings.SplitN(upstreamString, "#", 2)[0]
|
||||
}
|
||||
case "static":
|
||||
responseCode, err := strconv.Atoi(u.Host)
|
||||
if err != nil {
|
||||
logger.Errorf("unable to convert %q to int, use default \"200\"", u.Host)
|
||||
responseCode = 200
|
||||
}
|
||||
upstream.Static = ptr.To(true)
|
||||
upstream.StaticCode = &responseCode
|
||||
|
||||
// This is not allowed to be empty and must be unique
|
||||
upstream.ID = upstreamString
|
||||
|
||||
// We only support the root path in the legacy config
|
||||
upstream.Path = "/"
|
||||
|
||||
// Force defaults compatible with static responses
|
||||
upstream.URI = ""
|
||||
upstream.InsecureSkipTLSVerify = ptr.To(false)
|
||||
upstream.DisableKeepAlives = ptr.To(false)
|
||||
upstream.PassHostHeader = nil
|
||||
upstream.ProxyWebSockets = nil
|
||||
upstream.FlushInterval = nil
|
||||
upstream.Timeout = nil
|
||||
case "unix":
|
||||
upstream.Path = "/"
|
||||
}
|
||||
|
||||
upstreams.Upstreams = append(upstreams.Upstreams, upstream)
|
||||
}
|
||||
|
||||
return upstreams, nil
|
||||
}
|
||||
|
||||
type LegacyHeaders struct {
|
||||
PassBasicAuth bool `flag:"pass-basic-auth" cfg:"pass_basic_auth"`
|
||||
PassAccessToken bool `flag:"pass-access-token" cfg:"pass_access_token"`
|
||||
PassUserHeaders bool `flag:"pass-user-headers" cfg:"pass_user_headers"`
|
||||
PassAuthorization bool `flag:"pass-authorization-header" cfg:"pass_authorization_header"`
|
||||
|
||||
SetBasicAuth bool `flag:"set-basic-auth" cfg:"set_basic_auth"`
|
||||
SetXAuthRequest bool `flag:"set-xauthrequest" cfg:"set_xauthrequest"`
|
||||
SetAuthorization bool `flag:"set-authorization-header" cfg:"set_authorization_header"`
|
||||
|
||||
PreferEmailToUser bool `flag:"prefer-email-to-user" cfg:"prefer_email_to_user"`
|
||||
BasicAuthPassword string `flag:"basic-auth-password" cfg:"basic_auth_password"`
|
||||
SkipAuthStripHeaders bool `flag:"skip-auth-strip-headers" cfg:"skip_auth_strip_headers"`
|
||||
}
|
||||
|
||||
func legacyHeadersFlagSet() *pflag.FlagSet {
|
||||
flagSet := pflag.NewFlagSet("headers", pflag.ExitOnError)
|
||||
|
||||
flagSet.Bool("pass-basic-auth", true, "pass HTTP Basic Auth, X-Forwarded-User and X-Forwarded-Email information to upstream")
|
||||
flagSet.Bool("pass-access-token", false, "pass OAuth access_token to upstream via X-Forwarded-Access-Token header")
|
||||
flagSet.Bool("pass-user-headers", true, "pass X-Forwarded-User and X-Forwarded-Email information to upstream")
|
||||
flagSet.Bool("pass-authorization-header", false, "pass the Authorization Header to upstream")
|
||||
|
||||
flagSet.Bool("set-basic-auth", false, "set HTTP Basic Auth information in response (useful in Nginx auth_request mode)")
|
||||
flagSet.Bool("set-xauthrequest", false, "set X-Auth-Request-User and X-Auth-Request-Email response headers (useful in Nginx auth_request mode)")
|
||||
flagSet.Bool("set-authorization-header", false, "set Authorization response headers (useful in Nginx auth_request mode)")
|
||||
|
||||
flagSet.Bool("prefer-email-to-user", false, "Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, eg. htaccess authentication. Used in conjunction with -pass-basic-auth and -pass-user-headers")
|
||||
flagSet.String("basic-auth-password", "", "the password to set when passing the HTTP Basic Auth header")
|
||||
flagSet.Bool("skip-auth-strip-headers", true, "strips X-Forwarded-* style authentication headers & Authorization header if they would be set by oauth2-proxy")
|
||||
|
||||
return flagSet
|
||||
}
|
||||
|
||||
// convert takes the legacy request/response headers and converts them to
|
||||
// the new format for InjectRequestHeaders and InjectResponseHeaders
|
||||
func (l *LegacyHeaders) convert() ([]Header, []Header) {
|
||||
return l.getRequestHeaders(), l.getResponseHeaders()
|
||||
}
|
||||
|
||||
func (l *LegacyHeaders) getRequestHeaders() []Header {
|
||||
requestHeaders := []Header{}
|
||||
|
||||
if l.PassBasicAuth && l.BasicAuthPassword != "" {
|
||||
requestHeaders = append(requestHeaders, getBasicAuthHeader(l.PreferEmailToUser, l.BasicAuthPassword))
|
||||
}
|
||||
|
||||
// In the old implementation, PassUserHeaders is a subset of PassBasicAuth
|
||||
if l.PassBasicAuth || l.PassUserHeaders {
|
||||
requestHeaders = append(requestHeaders, getPassUserHeaders(l.PreferEmailToUser)...)
|
||||
requestHeaders = append(requestHeaders, getPreferredUsernameHeader())
|
||||
}
|
||||
|
||||
if l.PassAccessToken {
|
||||
requestHeaders = append(requestHeaders, getPassAccessTokenHeader())
|
||||
}
|
||||
|
||||
if l.PassAuthorization {
|
||||
requestHeaders = append(requestHeaders, getAuthorizationHeader())
|
||||
}
|
||||
|
||||
for i := range requestHeaders {
|
||||
requestHeaders[i].PreserveRequestValue = ptr.To(!l.SkipAuthStripHeaders)
|
||||
}
|
||||
|
||||
return requestHeaders
|
||||
}
|
||||
|
||||
func (l *LegacyHeaders) getResponseHeaders() []Header {
|
||||
responseHeaders := []Header{}
|
||||
|
||||
if l.SetXAuthRequest {
|
||||
responseHeaders = append(responseHeaders, getXAuthRequestHeaders()...)
|
||||
if l.PassAccessToken {
|
||||
responseHeaders = append(responseHeaders, getXAuthRequestAccessTokenHeader())
|
||||
}
|
||||
}
|
||||
|
||||
if l.SetBasicAuth {
|
||||
responseHeaders = append(responseHeaders, getBasicAuthHeader(l.PreferEmailToUser, l.BasicAuthPassword))
|
||||
}
|
||||
|
||||
if l.SetAuthorization {
|
||||
responseHeaders = append(responseHeaders, getAuthorizationHeader())
|
||||
}
|
||||
|
||||
return responseHeaders
|
||||
}
|
||||
|
||||
func getBasicAuthHeader(preferEmailToUser bool, basicAuthPassword string) Header {
|
||||
claim := "user"
|
||||
if preferEmailToUser {
|
||||
claim = "email"
|
||||
}
|
||||
|
||||
return Header{
|
||||
Name: "Authorization",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: claim,
|
||||
Prefix: "Basic ",
|
||||
BasicAuthPassword: &SecretSource{
|
||||
Value: []byte(basicAuthPassword),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func getPassUserHeaders(preferEmailToUser bool) []Header {
|
||||
headers := []Header{
|
||||
{
|
||||
Name: "X-Forwarded-Groups",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "groups",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if preferEmailToUser {
|
||||
return append(headers,
|
||||
Header{
|
||||
Name: "X-Forwarded-User",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "email",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return append(headers,
|
||||
Header{
|
||||
Name: "X-Forwarded-User",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "user",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
Header{
|
||||
Name: "X-Forwarded-Email",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "email",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func getPassAccessTokenHeader() Header {
|
||||
return Header{
|
||||
Name: "X-Forwarded-Access-Token",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "access_token",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func getAuthorizationHeader() Header {
|
||||
return Header{
|
||||
Name: "Authorization",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "id_token",
|
||||
Prefix: "Bearer ",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func getPreferredUsernameHeader() Header {
|
||||
return Header{
|
||||
Name: "X-Forwarded-Preferred-Username",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "preferred_username",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func getXAuthRequestHeaders() []Header {
|
||||
headers := []Header{
|
||||
{
|
||||
Name: "X-Auth-Request-User",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "user",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "X-Auth-Request-Email",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "email",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "X-Auth-Request-Preferred-Username",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "preferred_username",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "X-Auth-Request-Groups",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "groups",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return headers
|
||||
}
|
||||
|
||||
func getXAuthRequestAccessTokenHeader() Header {
|
||||
return Header{
|
||||
Name: "X-Auth-Request-Access-Token",
|
||||
PreserveRequestValue: ptr.To(false),
|
||||
Values: []HeaderValue{
|
||||
{
|
||||
ClaimSource: &ClaimSource{
|
||||
Claim: "access_token",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type LegacyServer struct {
|
||||
MetricsAddress string `flag:"metrics-address" cfg:"metrics_address"`
|
||||
MetricsSecureAddress string `flag:"metrics-secure-address" cfg:"metrics_secure_address"`
|
||||
MetricsTLSCertFile string `flag:"metrics-tls-cert-file" cfg:"metrics_tls_cert_file"`
|
||||
MetricsTLSKeyFile string `flag:"metrics-tls-key-file" cfg:"metrics_tls_key_file"`
|
||||
HTTPAddress string `flag:"http-address" cfg:"http_address"`
|
||||
HTTPSAddress string `flag:"https-address" cfg:"https_address"`
|
||||
TLSCertFile string `flag:"tls-cert-file" cfg:"tls_cert_file"`
|
||||
TLSKeyFile string `flag:"tls-key-file" cfg:"tls_key_file"`
|
||||
TLSMinVersion string `flag:"tls-min-version" cfg:"tls_min_version"`
|
||||
TLSCipherSuites []string `flag:"tls-cipher-suite" cfg:"tls_cipher_suites"`
|
||||
}
|
||||
|
||||
func legacyServerFlagset() *pflag.FlagSet {
|
||||
flagSet := pflag.NewFlagSet("server", pflag.ExitOnError)
|
||||
|
||||
flagSet.String("metrics-address", "", "the address /metrics will be served on (e.g. \":9100\")")
|
||||
flagSet.String("metrics-secure-address", "", "the address /metrics will be served on for HTTPS clients (e.g. \":9100\")")
|
||||
flagSet.String("metrics-tls-cert-file", "", "path to certificate file for secure metrics server")
|
||||
flagSet.String("metrics-tls-key-file", "", "path to private key file for secure metrics server")
|
||||
flagSet.String("http-address", "127.0.0.1:4180", "[http://]<addr>:<port> or unix://<path> or fd:<int> (case insensitive) to listen on for HTTP clients")
|
||||
flagSet.String("https-address", ":443", "<addr>:<port> to listen on for HTTPS clients")
|
||||
flagSet.String("tls-cert-file", "", "path to certificate file")
|
||||
flagSet.String("tls-key-file", "", "path to private key file")
|
||||
flagSet.String("tls-min-version", "", "minimal TLS version for HTTPS clients (either \"TLS1.2\" or \"TLS1.3\")")
|
||||
flagSet.StringSlice("tls-cipher-suite", []string{}, "restricts TLS cipher suites to those listed (e.g. TLS_RSA_WITH_RC4_128_SHA) (may be given multiple times)")
|
||||
|
||||
return flagSet
|
||||
}
|
||||
|
||||
type LegacyProvider struct {
|
||||
ClientID string `flag:"client-id" cfg:"client_id"`
|
||||
ClientSecret string `flag:"client-secret" cfg:"client_secret"`
|
||||
ClientSecretFile string `flag:"client-secret-file" cfg:"client_secret_file"`
|
||||
|
||||
KeycloakGroups []string `flag:"keycloak-group" cfg:"keycloak_groups"`
|
||||
AzureTenant string `flag:"azure-tenant" cfg:"azure_tenant"`
|
||||
AzureGraphGroupField string `flag:"azure-graph-group-field" cfg:"azure_graph_group_field"`
|
||||
EntraIDAllowedTenants []string `flag:"entra-id-allowed-tenant" cfg:"entra_id_allowed_tenants"`
|
||||
EntraIDFederatedTokenAuth bool `flag:"entra-id-federated-token-auth" cfg:"entra_id_federated_token_auth"`
|
||||
BitbucketTeam string `flag:"bitbucket-team" cfg:"bitbucket_team"`
|
||||
BitbucketRepository string `flag:"bitbucket-repository" cfg:"bitbucket_repository"`
|
||||
GitHubOrg string `flag:"github-org" cfg:"github_org"`
|
||||
GitHubTeam string `flag:"github-team" cfg:"github_team"`
|
||||
GitHubRepo string `flag:"github-repo" cfg:"github_repo"`
|
||||
GitHubToken string `flag:"github-token" cfg:"github_token"`
|
||||
GitHubUsers []string `flag:"github-user" cfg:"github_users"`
|
||||
GitLabGroup []string `flag:"gitlab-group" cfg:"gitlab_groups"`
|
||||
GitLabProjects []string `flag:"gitlab-project" cfg:"gitlab_projects"`
|
||||
GoogleGroupsLegacy []string `flag:"google-group" cfg:"google_group"`
|
||||
GoogleGroups []string `flag:"google-group" cfg:"google_groups"`
|
||||
GoogleAdminEmail string `flag:"google-admin-email" cfg:"google_admin_email"`
|
||||
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.
|
||||
ProviderType string `flag:"provider" cfg:"provider"`
|
||||
ProviderName string `flag:"provider-display-name" cfg:"provider_display_name"`
|
||||
ProviderCAFiles []string `flag:"provider-ca-file" cfg:"provider_ca_files"`
|
||||
UseSystemTrustStore bool `flag:"use-system-trust-store" cfg:"use_system_trust_store"`
|
||||
OIDCIssuerURL string `flag:"oidc-issuer-url" cfg:"oidc_issuer_url"`
|
||||
InsecureOIDCAllowUnverifiedEmail bool `flag:"insecure-oidc-allow-unverified-email" cfg:"insecure_oidc_allow_unverified_email"`
|
||||
InsecureOIDCSkipIssuerVerification bool `flag:"insecure-oidc-skip-issuer-verification" cfg:"insecure_oidc_skip_issuer_verification"`
|
||||
InsecureOIDCSkipNonce bool `flag:"insecure-oidc-skip-nonce" cfg:"insecure_oidc_skip_nonce"`
|
||||
SkipOIDCDiscovery bool `flag:"skip-oidc-discovery" cfg:"skip_oidc_discovery"`
|
||||
OIDCJwksURL string `flag:"oidc-jwks-url" cfg:"oidc_jwks_url"`
|
||||
OIDCEmailClaim string `flag:"oidc-email-claim" cfg:"oidc_email_claim"`
|
||||
OIDCGroupsClaim string `flag:"oidc-groups-claim" cfg:"oidc_groups_claim"`
|
||||
OIDCAudienceClaims []string `flag:"oidc-audience-claim" cfg:"oidc_audience_claims"`
|
||||
OIDCExtraAudiences []string `flag:"oidc-extra-audience" cfg:"oidc_extra_audiences"`
|
||||
OIDCPublicKeyFiles []string `flag:"oidc-public-key-file" cfg:"oidc_public_key_files"`
|
||||
LoginURL string `flag:"login-url" cfg:"login_url"`
|
||||
AuthRequestResponseMode string `flag:"auth-request-response-mode" cfg:"auth_request_response_mode"`
|
||||
RedeemURL string `flag:"redeem-url" cfg:"redeem_url"`
|
||||
ProfileURL string `flag:"profile-url" cfg:"profile_url"`
|
||||
SkipClaimsFromProfileURL bool `flag:"skip-claims-from-profile-url" cfg:"skip_claims_from_profile_url"`
|
||||
ProtectedResource string `flag:"resource" cfg:"resource"`
|
||||
ValidateURL string `flag:"validate-url" cfg:"validate_url"`
|
||||
Scope string `flag:"scope" cfg:"scope"`
|
||||
Prompt string `flag:"prompt" cfg:"prompt"`
|
||||
ApprovalPrompt string `flag:"approval-prompt" cfg:"approval_prompt"` // Deprecated by OIDC 1.0
|
||||
UserIDClaim string `flag:"user-id-claim" cfg:"user_id_claim"`
|
||||
AllowedGroups []string `flag:"allowed-group" cfg:"allowed_groups"`
|
||||
AllowedRoles []string `flag:"allowed-role" cfg:"allowed_roles"`
|
||||
BackendLogoutURL string `flag:"backend-logout-url" cfg:"backend_logout_url"`
|
||||
|
||||
AcrValues string `flag:"acr-values" cfg:"acr_values"`
|
||||
JWTKey string `flag:"jwt-key" cfg:"jwt_key"`
|
||||
JWTKeyFile string `flag:"jwt-key-file" cfg:"jwt_key_file"`
|
||||
PubJWKURL string `flag:"pubjwk-url" cfg:"pubjwk_url"`
|
||||
// PKCE Code Challenge method to use (either S256 or plain)
|
||||
CodeChallengeMethod string `flag:"code-challenge-method" cfg:"code_challenge_method"`
|
||||
// Provided for legacy reasons, to be dropped in newer version see #1667
|
||||
ForceCodeChallengeMethod string `flag:"force-code-challenge-method" cfg:"force_code_challenge_method"`
|
||||
}
|
||||
|
||||
func legacyProviderFlagSet() *pflag.FlagSet {
|
||||
flagSet := pflag.NewFlagSet("provider", pflag.ExitOnError)
|
||||
|
||||
flagSet.StringSlice("keycloak-group", []string{}, "restrict logins to members of these groups (may be given multiple times)")
|
||||
flagSet.String("azure-tenant", "common", "go to a tenant-specific or common (tenant-independent) endpoint.")
|
||||
flagSet.String("azure-graph-group-field", "", "configures the group field to be used when building the groups list(`id` or `displayName`. Default is `id`) from Microsoft Graph(available only for v2.0 oidc url). Based on this value, the `allowed-group` config values should be adjusted accordingly. If using `id` as group field, `allowed-group` should contains groups IDs, if using `displayName` as group field, `allowed-group` should contains groups name")
|
||||
flagSet.StringSlice("entra-id-allowed-tenant", []string{}, "list of tenants allowed for MS Entra ID multi-tenant application")
|
||||
flagSet.Bool("entra-id-federated-token-auth", false, "enable oAuth client authentication with federated token projected by Azure Workload Identity plugin, instead of client secret.")
|
||||
flagSet.String("bitbucket-team", "", "restrict logins to members of this team")
|
||||
flagSet.String("bitbucket-repository", "", "restrict logins to user with access to this repository")
|
||||
flagSet.String("github-org", "", "restrict logins to members of this organisation")
|
||||
flagSet.String("github-team", "", "restrict logins to members of this team")
|
||||
flagSet.String("github-repo", "", "restrict logins to collaborators of this repository")
|
||||
flagSet.String("github-token", "", "the token to use when verifying repository collaborators (must have push access to the repository)")
|
||||
flagSet.StringSlice("github-user", []string{}, "allow users with these usernames to login even if they do not belong to the specified org and team or collaborators (may be given multiple times)")
|
||||
flagSet.StringSlice("gitlab-group", []string{}, "restrict logins to members of this group (may be given multiple times)")
|
||||
flagSet.StringSlice("gitlab-project", []string{}, "restrict logins to members of this project (may be given multiple times) (eg `group/project=accesslevel`). Access level should be a value matching Gitlab access levels (see https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent")
|
||||
flagSet.String("client-id", "", "the OAuth Client ID: ie: \"123456.apps.googleusercontent.com\"")
|
||||
flagSet.String("client-secret", "", "the OAuth Client Secret")
|
||||
flagSet.String("client-secret-file", "", "the file with OAuth Client Secret")
|
||||
|
||||
flagSet.String("provider", "google", "OAuth provider")
|
||||
flagSet.String("provider-display-name", "", "Provider display name")
|
||||
flagSet.StringSlice("provider-ca-file", []string{}, "One or more paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead.")
|
||||
flagSet.Bool("use-system-trust-store", false, "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.")
|
||||
flagSet.String("oidc-issuer-url", "", "OpenID Connect issuer URL (ie: https://accounts.google.com)")
|
||||
flagSet.Bool("insecure-oidc-allow-unverified-email", false, "Don't fail if an email address in an id_token is not verified")
|
||||
flagSet.Bool("insecure-oidc-skip-issuer-verification", false, "Do not verify if issuer matches OIDC discovery URL")
|
||||
flagSet.Bool("insecure-oidc-skip-nonce", true, "skip verifying the OIDC ID Token's nonce claim")
|
||||
flagSet.Bool("skip-oidc-discovery", false, "Skip OIDC discovery and use manually supplied Endpoints")
|
||||
flagSet.String("oidc-jwks-url", "", "OpenID Connect JWKS URL (ie: https://www.googleapis.com/oauth2/v3/certs)")
|
||||
flagSet.String("oidc-groups-claim", OIDCGroupsClaim, "which OIDC claim contains the user groups")
|
||||
flagSet.String("oidc-email-claim", OIDCEmailClaim, "which OIDC claim contains the user's email")
|
||||
flagSet.StringSlice("oidc-audience-claim", OIDCAudienceClaims, "which OIDC claims are used as audience to verify against client id")
|
||||
flagSet.StringSlice("oidc-extra-audience", []string{}, "additional audiences allowed to pass audience verification")
|
||||
flagSet.StringSlice("oidc-public-key-file", []string{}, "path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times)")
|
||||
flagSet.String("login-url", "", "Authentication endpoint")
|
||||
flagSet.String("redeem-url", "", "Token redemption endpoint")
|
||||
flagSet.String("profile-url", "", "Profile access endpoint")
|
||||
flagSet.String("auth-request-response-mode", "", "Authorization request response mode")
|
||||
flagSet.Bool("skip-claims-from-profile-url", false, "Skip loading missing claims from profile URL")
|
||||
flagSet.String("resource", "", "The resource that is protected (Azure AD only)")
|
||||
flagSet.String("validate-url", "", "Access token validation endpoint")
|
||||
flagSet.String("scope", "", "OAuth scope specification")
|
||||
flagSet.String("prompt", "", "OIDC prompt")
|
||||
flagSet.String("approval-prompt", "force", "OAuth approval_prompt")
|
||||
flagSet.String("code-challenge-method", "", "use PKCE code challenges with the specified method. Either 'plain' or 'S256'")
|
||||
flagSet.String("force-code-challenge-method", "", "Deprecated - use --code-challenge-method")
|
||||
|
||||
flagSet.String("acr-values", "", "acr values string: optional")
|
||||
flagSet.String("jwt-key", "", "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")
|
||||
flagSet.String("jwt-key-file", "", "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")
|
||||
flagSet.String("pubjwk-url", "", "JWK pubkey access endpoint: required by login.gov")
|
||||
|
||||
flagSet.String("user-id-claim", OIDCEmailClaim, "(DEPRECATED for `oidc-email-claim`) which claim contains the user ID")
|
||||
flagSet.StringSlice("allowed-group", []string{}, "restrict logins to members of this group (may be given multiple times)")
|
||||
flagSet.StringSlice("allowed-role", []string{}, "(keycloak-oidc) restrict logins to members of these roles (may be given multiple times)")
|
||||
flagSet.String("backend-logout-url", "", "url to perform a backend logout, {id_token} can be used as placeholder for the id_token")
|
||||
|
||||
return flagSet
|
||||
}
|
||||
|
||||
func legacyGoogleFlagSet() *pflag.FlagSet {
|
||||
flagSet := pflag.NewFlagSet("google", pflag.ExitOnError)
|
||||
|
||||
flagSet.StringSlice("google-group", []string{}, "restrict logins to members of this google group (may be given multiple times).")
|
||||
flagSet.String("google-admin-email", "", "the google admin to impersonate for api calls")
|
||||
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
|
||||
}
|
||||
|
||||
func (l LegacyServer) convert() (Server, Server) {
|
||||
appServer := Server{
|
||||
BindAddress: l.HTTPAddress,
|
||||
SecureBindAddress: l.HTTPSAddress,
|
||||
}
|
||||
if l.TLSKeyFile != "" || l.TLSCertFile != "" {
|
||||
appServer.TLS = &TLS{
|
||||
Key: &SecretSource{
|
||||
FromFile: l.TLSKeyFile,
|
||||
},
|
||||
Cert: &SecretSource{
|
||||
FromFile: l.TLSCertFile,
|
||||
},
|
||||
MinVersion: l.TLSMinVersion,
|
||||
}
|
||||
if len(l.TLSCipherSuites) != 0 {
|
||||
appServer.TLS.CipherSuites = l.TLSCipherSuites
|
||||
}
|
||||
// Preserve backwards compatibility, only run one server
|
||||
appServer.BindAddress = ""
|
||||
} else {
|
||||
// Disable the HTTPS server if there's no certificates.
|
||||
// This preserves backwards compatibility.
|
||||
appServer.SecureBindAddress = ""
|
||||
}
|
||||
|
||||
metricsServer := Server{
|
||||
BindAddress: l.MetricsAddress,
|
||||
SecureBindAddress: l.MetricsSecureAddress,
|
||||
}
|
||||
if l.MetricsTLSKeyFile != "" || l.MetricsTLSCertFile != "" {
|
||||
metricsServer.TLS = &TLS{
|
||||
Key: &SecretSource{
|
||||
FromFile: l.MetricsTLSKeyFile,
|
||||
},
|
||||
Cert: &SecretSource{
|
||||
FromFile: l.MetricsTLSCertFile,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return appServer, metricsServer
|
||||
}
|
||||
|
||||
func (l *LegacyProvider) convert() (Providers, error) {
|
||||
providers := Providers{}
|
||||
|
||||
provider := Provider{
|
||||
ClientID: l.ClientID,
|
||||
ClientSecret: l.ClientSecret,
|
||||
ClientSecretFile: l.ClientSecretFile,
|
||||
Type: ProviderType(l.ProviderType),
|
||||
CAFiles: l.ProviderCAFiles,
|
||||
UseSystemTrustStore: &l.UseSystemTrustStore,
|
||||
LoginURL: l.LoginURL,
|
||||
RedeemURL: l.RedeemURL,
|
||||
ProfileURL: l.ProfileURL,
|
||||
SkipClaimsFromProfileURL: &l.SkipClaimsFromProfileURL,
|
||||
ProtectedResource: l.ProtectedResource,
|
||||
ValidateURL: l.ValidateURL,
|
||||
Scope: l.Scope,
|
||||
AllowedGroups: l.AllowedGroups,
|
||||
CodeChallengeMethod: l.CodeChallengeMethod,
|
||||
BackendLogoutURL: l.BackendLogoutURL,
|
||||
AuthRequestResponseMode: l.AuthRequestResponseMode,
|
||||
}
|
||||
|
||||
// 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,
|
||||
JwksURL: l.OIDCJwksURL,
|
||||
UserIDClaim: l.UserIDClaim,
|
||||
EmailClaim: l.OIDCEmailClaim,
|
||||
GroupsClaim: l.OIDCGroupsClaim,
|
||||
AudienceClaims: l.OIDCAudienceClaims,
|
||||
ExtraAudiences: l.OIDCExtraAudiences,
|
||||
PublicKeyFiles: l.OIDCPublicKeyFiles,
|
||||
}
|
||||
|
||||
// Support for legacy configuration option
|
||||
if l.ForceCodeChallengeMethod != "" && l.CodeChallengeMethod == "" {
|
||||
provider.CodeChallengeMethod = l.ForceCodeChallengeMethod
|
||||
}
|
||||
|
||||
// This part is out of the switch section because azure has a default tenant
|
||||
// that needs to be added from legacy options
|
||||
provider.AzureConfig = AzureOptions{
|
||||
Tenant: l.AzureTenant,
|
||||
GraphGroupField: l.AzureGraphGroupField,
|
||||
}
|
||||
|
||||
switch provider.Type {
|
||||
case "github":
|
||||
provider.GitHubConfig = GitHubOptions{
|
||||
Org: l.GitHubOrg,
|
||||
Team: l.GitHubTeam,
|
||||
Repo: l.GitHubRepo,
|
||||
Token: l.GitHubToken,
|
||||
Users: l.GitHubUsers,
|
||||
}
|
||||
case "keycloak-oidc":
|
||||
provider.KeycloakConfig = KeycloakOptions{
|
||||
Groups: l.KeycloakGroups,
|
||||
Roles: l.AllowedRoles,
|
||||
}
|
||||
case "keycloak":
|
||||
provider.KeycloakConfig = KeycloakOptions{
|
||||
Groups: l.KeycloakGroups,
|
||||
}
|
||||
case "gitlab":
|
||||
provider.GitLabConfig = GitLabOptions{
|
||||
Group: l.GitLabGroup,
|
||||
Projects: l.GitLabProjects,
|
||||
}
|
||||
case "login.gov":
|
||||
provider.LoginGovConfig = LoginGovOptions{
|
||||
JWTKey: l.JWTKey,
|
||||
JWTKeyFile: l.JWTKeyFile,
|
||||
PubJWKURL: l.PubJWKURL,
|
||||
}
|
||||
case "bitbucket":
|
||||
provider.BitbucketConfig = BitbucketOptions{
|
||||
Team: l.BitbucketTeam,
|
||||
Repository: l.BitbucketRepository,
|
||||
}
|
||||
case "google":
|
||||
if len(l.GoogleGroupsLegacy) != 0 && !reflect.DeepEqual(l.GoogleGroupsLegacy, l.GoogleGroups) {
|
||||
// Log the deprecation notice
|
||||
logger.Error(
|
||||
"WARNING: The 'OAUTH2_PROXY_GOOGLE_GROUP' environment variable is deprecated and will likely be removed in the next major release. Use 'OAUTH2_PROXY_GOOGLE_GROUPS' instead.",
|
||||
)
|
||||
l.GoogleGroups = l.GoogleGroupsLegacy
|
||||
}
|
||||
provider.GoogleConfig = GoogleOptions{
|
||||
Groups: l.GoogleGroups,
|
||||
AdminEmail: l.GoogleAdminEmail,
|
||||
ServiceAccountJSON: l.GoogleServiceAccountJSON,
|
||||
UseApplicationDefaultCredentials: &l.GoogleUseApplicationDefaultCredentials,
|
||||
TargetPrincipal: l.GoogleTargetPrincipal,
|
||||
UseOrganizationID: &l.GoogleUseOrganizationID,
|
||||
AdminAPIUserScope: l.GoogleAdminAPIUserScope,
|
||||
}
|
||||
case "entra-id":
|
||||
provider.MicrosoftEntraIDConfig = MicrosoftEntraIDOptions{
|
||||
AllowedTenants: l.EntraIDAllowedTenants,
|
||||
FederatedTokenAuth: &l.EntraIDFederatedTokenAuth,
|
||||
}
|
||||
}
|
||||
|
||||
if l.ProviderName != "" {
|
||||
provider.ID = l.ProviderName
|
||||
provider.Name = l.ProviderName
|
||||
} else {
|
||||
provider.ID = l.ProviderType + "=" + l.ClientID
|
||||
}
|
||||
|
||||
// handle AcrValues, Prompt and ApprovalPrompt
|
||||
var urlParams []LoginURLParameter
|
||||
if l.AcrValues != "" {
|
||||
urlParams = append(urlParams, LoginURLParameter{Name: "acr_values", Default: []string{l.AcrValues}})
|
||||
}
|
||||
switch {
|
||||
case l.Prompt != "":
|
||||
urlParams = append(urlParams, LoginURLParameter{Name: "prompt", Default: []string{l.Prompt}})
|
||||
case l.ApprovalPrompt != "":
|
||||
urlParams = append(urlParams, LoginURLParameter{Name: "approval_prompt", Default: []string{l.ApprovalPrompt}})
|
||||
default:
|
||||
// match legacy behaviour by default - if neither prompt nor approval_prompt
|
||||
// specified, use approval_prompt=force
|
||||
urlParams = append(urlParams, LoginURLParameter{Name: "approval_prompt", Default: []string{"force"}})
|
||||
}
|
||||
|
||||
provider.LoginURLParameters = urlParams
|
||||
|
||||
providers = append(providers, provider)
|
||||
|
||||
return providers, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1084,4 +1084,53 @@ var _ = Describe("Legacy Options", func() {
|
|||
}),
|
||||
)
|
||||
})
|
||||
|
||||
Context("Legacy Cookie", func() {
|
||||
type convertCookieTableInput struct {
|
||||
legacyCookie LegacyCookie
|
||||
expectedCookie Cookie
|
||||
}
|
||||
|
||||
// Test cases and expected outcomes
|
||||
fullCookie := Cookie{
|
||||
Name: "_oauth2_proxy",
|
||||
Secret: SecretSource{},
|
||||
Domains: nil,
|
||||
Path: "/",
|
||||
Expire: time.Duration(168) * time.Hour,
|
||||
Insecure: ptr.To(false),
|
||||
NotHttpOnly: ptr.To(false),
|
||||
SameSite: "",
|
||||
CSRFPerRequest: ptr.To(false),
|
||||
CSRFPerRequestLimit: 0,
|
||||
CSRFExpire: time.Duration(15) * time.Minute,
|
||||
}
|
||||
|
||||
fullLegacyCookie := LegacyCookie{
|
||||
Name: "_oauth2_proxy",
|
||||
Secret: "",
|
||||
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,
|
||||
}
|
||||
|
||||
DescribeTable("convertLegacyCookie",
|
||||
func(in *convertCookieTableInput) {
|
||||
cookie := in.legacyCookie.convert()
|
||||
|
||||
Expect(cookie).To(BeEquivalentTo(in.expectedCookie))
|
||||
},
|
||||
Entry("with all attributes", &convertCookieTableInput{
|
||||
legacyCookie: fullLegacyCookie,
|
||||
expectedCookie: fullCookie,
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -0,0 +1,317 @@
|
|||
package options
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
type LegacyProvider struct {
|
||||
ClientID string `flag:"client-id" cfg:"client_id"`
|
||||
ClientSecret string `flag:"client-secret" cfg:"client_secret"`
|
||||
ClientSecretFile string `flag:"client-secret-file" cfg:"client_secret_file"`
|
||||
|
||||
KeycloakGroups []string `flag:"keycloak-group" cfg:"keycloak_groups"`
|
||||
AzureTenant string `flag:"azure-tenant" cfg:"azure_tenant"`
|
||||
AzureGraphGroupField string `flag:"azure-graph-group-field" cfg:"azure_graph_group_field"`
|
||||
EntraIDAllowedTenants []string `flag:"entra-id-allowed-tenant" cfg:"entra_id_allowed_tenants"`
|
||||
EntraIDFederatedTokenAuth bool `flag:"entra-id-federated-token-auth" cfg:"entra_id_federated_token_auth"`
|
||||
BitbucketTeam string `flag:"bitbucket-team" cfg:"bitbucket_team"`
|
||||
BitbucketRepository string `flag:"bitbucket-repository" cfg:"bitbucket_repository"`
|
||||
GitHubOrg string `flag:"github-org" cfg:"github_org"`
|
||||
GitHubTeam string `flag:"github-team" cfg:"github_team"`
|
||||
GitHubRepo string `flag:"github-repo" cfg:"github_repo"`
|
||||
GitHubToken string `flag:"github-token" cfg:"github_token"`
|
||||
GitHubUsers []string `flag:"github-user" cfg:"github_users"`
|
||||
GitLabGroup []string `flag:"gitlab-group" cfg:"gitlab_groups"`
|
||||
GitLabProjects []string `flag:"gitlab-project" cfg:"gitlab_projects"`
|
||||
GoogleGroupsLegacy []string `flag:"google-group" cfg:"google_group"`
|
||||
GoogleGroups []string `flag:"google-group" cfg:"google_groups"`
|
||||
GoogleAdminEmail string `flag:"google-admin-email" cfg:"google_admin_email"`
|
||||
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.
|
||||
ProviderType string `flag:"provider" cfg:"provider"`
|
||||
ProviderName string `flag:"provider-display-name" cfg:"provider_display_name"`
|
||||
ProviderCAFiles []string `flag:"provider-ca-file" cfg:"provider_ca_files"`
|
||||
UseSystemTrustStore bool `flag:"use-system-trust-store" cfg:"use_system_trust_store"`
|
||||
OIDCIssuerURL string `flag:"oidc-issuer-url" cfg:"oidc_issuer_url"`
|
||||
InsecureOIDCAllowUnverifiedEmail bool `flag:"insecure-oidc-allow-unverified-email" cfg:"insecure_oidc_allow_unverified_email"`
|
||||
InsecureOIDCSkipIssuerVerification bool `flag:"insecure-oidc-skip-issuer-verification" cfg:"insecure_oidc_skip_issuer_verification"`
|
||||
InsecureOIDCSkipNonce bool `flag:"insecure-oidc-skip-nonce" cfg:"insecure_oidc_skip_nonce"`
|
||||
SkipOIDCDiscovery bool `flag:"skip-oidc-discovery" cfg:"skip_oidc_discovery"`
|
||||
OIDCJwksURL string `flag:"oidc-jwks-url" cfg:"oidc_jwks_url"`
|
||||
OIDCEmailClaim string `flag:"oidc-email-claim" cfg:"oidc_email_claim"`
|
||||
OIDCGroupsClaim string `flag:"oidc-groups-claim" cfg:"oidc_groups_claim"`
|
||||
OIDCAudienceClaims []string `flag:"oidc-audience-claim" cfg:"oidc_audience_claims"`
|
||||
OIDCExtraAudiences []string `flag:"oidc-extra-audience" cfg:"oidc_extra_audiences"`
|
||||
OIDCPublicKeyFiles []string `flag:"oidc-public-key-file" cfg:"oidc_public_key_files"`
|
||||
LoginURL string `flag:"login-url" cfg:"login_url"`
|
||||
AuthRequestResponseMode string `flag:"auth-request-response-mode" cfg:"auth_request_response_mode"`
|
||||
RedeemURL string `flag:"redeem-url" cfg:"redeem_url"`
|
||||
ProfileURL string `flag:"profile-url" cfg:"profile_url"`
|
||||
SkipClaimsFromProfileURL bool `flag:"skip-claims-from-profile-url" cfg:"skip_claims_from_profile_url"`
|
||||
ProtectedResource string `flag:"resource" cfg:"resource"`
|
||||
ValidateURL string `flag:"validate-url" cfg:"validate_url"`
|
||||
Scope string `flag:"scope" cfg:"scope"`
|
||||
Prompt string `flag:"prompt" cfg:"prompt"`
|
||||
ApprovalPrompt string `flag:"approval-prompt" cfg:"approval_prompt"` // Deprecated by OIDC 1.0
|
||||
UserIDClaim string `flag:"user-id-claim" cfg:"user_id_claim"`
|
||||
AllowedGroups []string `flag:"allowed-group" cfg:"allowed_groups"`
|
||||
AllowedRoles []string `flag:"allowed-role" cfg:"allowed_roles"`
|
||||
BackendLogoutURL string `flag:"backend-logout-url" cfg:"backend_logout_url"`
|
||||
|
||||
AcrValues string `flag:"acr-values" cfg:"acr_values"`
|
||||
JWTKey string `flag:"jwt-key" cfg:"jwt_key"`
|
||||
JWTKeyFile string `flag:"jwt-key-file" cfg:"jwt_key_file"`
|
||||
PubJWKURL string `flag:"pubjwk-url" cfg:"pubjwk_url"`
|
||||
// PKCE Code Challenge method to use (either S256 or plain)
|
||||
CodeChallengeMethod string `flag:"code-challenge-method" cfg:"code_challenge_method"`
|
||||
// Provided for legacy reasons, to be dropped in newer version see #1667
|
||||
ForceCodeChallengeMethod string `flag:"force-code-challenge-method" cfg:"force_code_challenge_method"`
|
||||
}
|
||||
|
||||
func legacyProviderFlagSet() *pflag.FlagSet {
|
||||
flagSet := pflag.NewFlagSet("provider", pflag.ExitOnError)
|
||||
|
||||
flagSet.StringSlice("keycloak-group", []string{}, "restrict logins to members of these groups (may be given multiple times)")
|
||||
flagSet.String("azure-tenant", "common", "go to a tenant-specific or common (tenant-independent) endpoint.")
|
||||
flagSet.String("azure-graph-group-field", "", "configures the group field to be used when building the groups list(`id` or `displayName`. Default is `id`) from Microsoft Graph(available only for v2.0 oidc url). Based on this value, the `allowed-group` config values should be adjusted accordingly. If using `id` as group field, `allowed-group` should contains groups IDs, if using `displayName` as group field, `allowed-group` should contains groups name")
|
||||
flagSet.StringSlice("entra-id-allowed-tenant", []string{}, "list of tenants allowed for MS Entra ID multi-tenant application")
|
||||
flagSet.Bool("entra-id-federated-token-auth", false, "enable oAuth client authentication with federated token projected by Azure Workload Identity plugin, instead of client secret.")
|
||||
flagSet.String("bitbucket-team", "", "restrict logins to members of this team")
|
||||
flagSet.String("bitbucket-repository", "", "restrict logins to user with access to this repository")
|
||||
flagSet.String("github-org", "", "restrict logins to members of this organisation")
|
||||
flagSet.String("github-team", "", "restrict logins to members of this team")
|
||||
flagSet.String("github-repo", "", "restrict logins to collaborators of this repository")
|
||||
flagSet.String("github-token", "", "the token to use when verifying repository collaborators (must have push access to the repository)")
|
||||
flagSet.StringSlice("github-user", []string{}, "allow users with these usernames to login even if they do not belong to the specified org and team or collaborators (may be given multiple times)")
|
||||
flagSet.StringSlice("gitlab-group", []string{}, "restrict logins to members of this group (may be given multiple times)")
|
||||
flagSet.StringSlice("gitlab-project", []string{}, "restrict logins to members of this project (may be given multiple times) (eg `group/project=accesslevel`). Access level should be a value matching Gitlab access levels (see https://docs.gitlab.com/ee/api/members.html#valid-access-levels), defaulted to 20 if absent")
|
||||
flagSet.String("client-id", "", "the OAuth Client ID: ie: \"123456.apps.googleusercontent.com\"")
|
||||
flagSet.String("client-secret", "", "the OAuth Client Secret")
|
||||
flagSet.String("client-secret-file", "", "the file with OAuth Client Secret")
|
||||
|
||||
flagSet.String("provider", "google", "OAuth provider")
|
||||
flagSet.String("provider-display-name", "", "Provider display name")
|
||||
flagSet.StringSlice("provider-ca-file", []string{}, "One or more paths to CA certificates that should be used when connecting to the provider. If not specified, the default Go trust sources are used instead.")
|
||||
flagSet.Bool("use-system-trust-store", false, "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.")
|
||||
flagSet.String("oidc-issuer-url", "", "OpenID Connect issuer URL (ie: https://accounts.google.com)")
|
||||
flagSet.Bool("insecure-oidc-allow-unverified-email", false, "Don't fail if an email address in an id_token is not verified")
|
||||
flagSet.Bool("insecure-oidc-skip-issuer-verification", false, "Do not verify if issuer matches OIDC discovery URL")
|
||||
flagSet.Bool("insecure-oidc-skip-nonce", true, "skip verifying the OIDC ID Token's nonce claim")
|
||||
flagSet.Bool("skip-oidc-discovery", false, "Skip OIDC discovery and use manually supplied Endpoints")
|
||||
flagSet.String("oidc-jwks-url", "", "OpenID Connect JWKS URL (ie: https://www.googleapis.com/oauth2/v3/certs)")
|
||||
flagSet.String("oidc-groups-claim", OIDCGroupsClaim, "which OIDC claim contains the user groups")
|
||||
flagSet.String("oidc-email-claim", OIDCEmailClaim, "which OIDC claim contains the user's email")
|
||||
flagSet.StringSlice("oidc-audience-claim", OIDCAudienceClaims, "which OIDC claims are used as audience to verify against client id")
|
||||
flagSet.StringSlice("oidc-extra-audience", []string{}, "additional audiences allowed to pass audience verification")
|
||||
flagSet.StringSlice("oidc-public-key-file", []string{}, "path to public key file in PEM format to use for verifying JWT tokens (may be given multiple times)")
|
||||
flagSet.String("login-url", "", "Authentication endpoint")
|
||||
flagSet.String("redeem-url", "", "Token redemption endpoint")
|
||||
flagSet.String("profile-url", "", "Profile access endpoint")
|
||||
flagSet.String("auth-request-response-mode", "", "Authorization request response mode")
|
||||
flagSet.Bool("skip-claims-from-profile-url", false, "Skip loading missing claims from profile URL")
|
||||
flagSet.String("resource", "", "The resource that is protected (Azure AD only)")
|
||||
flagSet.String("validate-url", "", "Access token validation endpoint")
|
||||
flagSet.String("scope", "", "OAuth scope specification")
|
||||
flagSet.String("prompt", "", "OIDC prompt")
|
||||
flagSet.String("approval-prompt", "force", "OAuth approval_prompt")
|
||||
flagSet.String("code-challenge-method", "", "use PKCE code challenges with the specified method. Either 'plain' or 'S256'")
|
||||
flagSet.String("force-code-challenge-method", "", "Deprecated - use --code-challenge-method")
|
||||
|
||||
flagSet.String("acr-values", "", "acr values string: optional")
|
||||
flagSet.String("jwt-key", "", "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")
|
||||
flagSet.String("jwt-key-file", "", "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")
|
||||
flagSet.String("pubjwk-url", "", "JWK pubkey access endpoint: required by login.gov")
|
||||
|
||||
flagSet.String("user-id-claim", OIDCEmailClaim, "(DEPRECATED for `oidc-email-claim`) which claim contains the user ID")
|
||||
flagSet.StringSlice("allowed-group", []string{}, "restrict logins to members of this group (may be given multiple times)")
|
||||
flagSet.StringSlice("allowed-role", []string{}, "(keycloak-oidc) restrict logins to members of these roles (may be given multiple times)")
|
||||
flagSet.String("backend-logout-url", "", "url to perform a backend logout, {id_token} can be used as placeholder for the id_token")
|
||||
|
||||
return flagSet
|
||||
}
|
||||
|
||||
func legacyGoogleFlagSet() *pflag.FlagSet {
|
||||
flagSet := pflag.NewFlagSet("google", pflag.ExitOnError)
|
||||
|
||||
flagSet.StringSlice("google-group", []string{}, "restrict logins to members of this google group (may be given multiple times).")
|
||||
flagSet.String("google-admin-email", "", "the google admin to impersonate for api calls")
|
||||
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
|
||||
}
|
||||
|
||||
func (l *LegacyProvider) convert() (Providers, error) {
|
||||
providers := Providers{}
|
||||
|
||||
provider := Provider{
|
||||
ClientID: l.ClientID,
|
||||
ClientSecret: l.ClientSecret,
|
||||
ClientSecretFile: l.ClientSecretFile,
|
||||
Type: ProviderType(l.ProviderType),
|
||||
CAFiles: l.ProviderCAFiles,
|
||||
UseSystemTrustStore: &l.UseSystemTrustStore,
|
||||
LoginURL: l.LoginURL,
|
||||
RedeemURL: l.RedeemURL,
|
||||
ProfileURL: l.ProfileURL,
|
||||
SkipClaimsFromProfileURL: &l.SkipClaimsFromProfileURL,
|
||||
ProtectedResource: l.ProtectedResource,
|
||||
ValidateURL: l.ValidateURL,
|
||||
Scope: l.Scope,
|
||||
AllowedGroups: l.AllowedGroups,
|
||||
CodeChallengeMethod: l.CodeChallengeMethod,
|
||||
BackendLogoutURL: l.BackendLogoutURL,
|
||||
AuthRequestResponseMode: l.AuthRequestResponseMode,
|
||||
}
|
||||
|
||||
// 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,
|
||||
JwksURL: l.OIDCJwksURL,
|
||||
UserIDClaim: l.UserIDClaim,
|
||||
EmailClaim: l.OIDCEmailClaim,
|
||||
GroupsClaim: l.OIDCGroupsClaim,
|
||||
AudienceClaims: l.OIDCAudienceClaims,
|
||||
ExtraAudiences: l.OIDCExtraAudiences,
|
||||
PublicKeyFiles: l.OIDCPublicKeyFiles,
|
||||
}
|
||||
|
||||
// Support for legacy configuration option
|
||||
if l.ForceCodeChallengeMethod != "" && l.CodeChallengeMethod == "" {
|
||||
provider.CodeChallengeMethod = l.ForceCodeChallengeMethod
|
||||
}
|
||||
|
||||
// This part is out of the switch section because azure has a default tenant
|
||||
// that needs to be added from legacy options
|
||||
provider.AzureConfig = AzureOptions{
|
||||
Tenant: l.AzureTenant,
|
||||
GraphGroupField: l.AzureGraphGroupField,
|
||||
}
|
||||
|
||||
switch provider.Type {
|
||||
case "github":
|
||||
provider.GitHubConfig = GitHubOptions{
|
||||
Org: l.GitHubOrg,
|
||||
Team: l.GitHubTeam,
|
||||
Repo: l.GitHubRepo,
|
||||
Token: l.GitHubToken,
|
||||
Users: l.GitHubUsers,
|
||||
}
|
||||
case "keycloak-oidc":
|
||||
provider.KeycloakConfig = KeycloakOptions{
|
||||
Groups: l.KeycloakGroups,
|
||||
Roles: l.AllowedRoles,
|
||||
}
|
||||
case "keycloak":
|
||||
provider.KeycloakConfig = KeycloakOptions{
|
||||
Groups: l.KeycloakGroups,
|
||||
}
|
||||
case "gitlab":
|
||||
provider.GitLabConfig = GitLabOptions{
|
||||
Group: l.GitLabGroup,
|
||||
Projects: l.GitLabProjects,
|
||||
}
|
||||
case "login.gov":
|
||||
provider.LoginGovConfig = LoginGovOptions{
|
||||
JWTKey: l.JWTKey,
|
||||
JWTKeyFile: l.JWTKeyFile,
|
||||
PubJWKURL: l.PubJWKURL,
|
||||
}
|
||||
case "bitbucket":
|
||||
provider.BitbucketConfig = BitbucketOptions{
|
||||
Team: l.BitbucketTeam,
|
||||
Repository: l.BitbucketRepository,
|
||||
}
|
||||
case "google":
|
||||
if len(l.GoogleGroupsLegacy) != 0 && !reflect.DeepEqual(l.GoogleGroupsLegacy, l.GoogleGroups) {
|
||||
// Log the deprecation notice
|
||||
logger.Error(
|
||||
"WARNING: The 'OAUTH2_PROXY_GOOGLE_GROUP' environment variable is deprecated and will likely be removed in the next major release. Use 'OAUTH2_PROXY_GOOGLE_GROUPS' instead.",
|
||||
)
|
||||
l.GoogleGroups = l.GoogleGroupsLegacy
|
||||
}
|
||||
provider.GoogleConfig = GoogleOptions{
|
||||
Groups: l.GoogleGroups,
|
||||
AdminEmail: l.GoogleAdminEmail,
|
||||
ServiceAccountJSON: l.GoogleServiceAccountJSON,
|
||||
UseApplicationDefaultCredentials: &l.GoogleUseApplicationDefaultCredentials,
|
||||
TargetPrincipal: l.GoogleTargetPrincipal,
|
||||
UseOrganizationID: &l.GoogleUseOrganizationID,
|
||||
AdminAPIUserScope: l.GoogleAdminAPIUserScope,
|
||||
}
|
||||
case "entra-id":
|
||||
provider.MicrosoftEntraIDConfig = MicrosoftEntraIDOptions{
|
||||
AllowedTenants: l.EntraIDAllowedTenants,
|
||||
FederatedTokenAuth: &l.EntraIDFederatedTokenAuth,
|
||||
}
|
||||
}
|
||||
|
||||
if l.ProviderName != "" {
|
||||
provider.ID = l.ProviderName
|
||||
provider.Name = l.ProviderName
|
||||
} else {
|
||||
provider.ID = l.ProviderType + "=" + l.ClientID
|
||||
}
|
||||
|
||||
// handle AcrValues, Prompt and ApprovalPrompt
|
||||
var urlParams []LoginURLParameter
|
||||
if l.AcrValues != "" {
|
||||
urlParams = append(urlParams, LoginURLParameter{Name: "acr_values", Default: []string{l.AcrValues}})
|
||||
}
|
||||
switch {
|
||||
case l.Prompt != "":
|
||||
urlParams = append(urlParams, LoginURLParameter{Name: "prompt", Default: []string{l.Prompt}})
|
||||
case l.ApprovalPrompt != "":
|
||||
urlParams = append(urlParams, LoginURLParameter{Name: "approval_prompt", Default: []string{l.ApprovalPrompt}})
|
||||
default:
|
||||
// match legacy behaviour by default - if neither prompt nor approval_prompt
|
||||
// specified, use approval_prompt=force
|
||||
urlParams = append(urlParams, LoginURLParameter{Name: "approval_prompt", Default: []string{"force"}})
|
||||
}
|
||||
|
||||
provider.LoginURLParameters = urlParams
|
||||
|
||||
providers = append(providers, provider)
|
||||
|
||||
return providers, nil
|
||||
}
|
||||
|
||||
// Legacy default providers configuration
|
||||
func providerDefaults() Providers {
|
||||
providers := Providers{
|
||||
{
|
||||
Type: "google",
|
||||
AzureConfig: AzureOptions{
|
||||
Tenant: "common",
|
||||
},
|
||||
OIDCConfig: OIDCOptions{
|
||||
InsecureAllowUnverifiedEmail: ptr.To(DefaultInsecureAllowUnverifiedEmail),
|
||||
InsecureSkipNonce: ptr.To(DefaultInsecureSkipNonce),
|
||||
SkipDiscovery: ptr.To(DefaultSkipDiscovery),
|
||||
UserIDClaim: OIDCEmailClaim, // Deprecated: Use OIDCEmailClaim
|
||||
EmailClaim: OIDCEmailClaim,
|
||||
GroupsClaim: OIDCGroupsClaim,
|
||||
AudienceClaims: OIDCAudienceClaims,
|
||||
ExtraAudiences: []string{},
|
||||
},
|
||||
},
|
||||
}
|
||||
return providers
|
||||
}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
package options
|
||||
|
||||
import (
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
type LegacyServer struct {
|
||||
MetricsAddress string `flag:"metrics-address" cfg:"metrics_address"`
|
||||
MetricsSecureAddress string `flag:"metrics-secure-address" cfg:"metrics_secure_address"`
|
||||
MetricsTLSCertFile string `flag:"metrics-tls-cert-file" cfg:"metrics_tls_cert_file"`
|
||||
MetricsTLSKeyFile string `flag:"metrics-tls-key-file" cfg:"metrics_tls_key_file"`
|
||||
HTTPAddress string `flag:"http-address" cfg:"http_address"`
|
||||
HTTPSAddress string `flag:"https-address" cfg:"https_address"`
|
||||
TLSCertFile string `flag:"tls-cert-file" cfg:"tls_cert_file"`
|
||||
TLSKeyFile string `flag:"tls-key-file" cfg:"tls_key_file"`
|
||||
TLSMinVersion string `flag:"tls-min-version" cfg:"tls_min_version"`
|
||||
TLSCipherSuites []string `flag:"tls-cipher-suite" cfg:"tls_cipher_suites"`
|
||||
}
|
||||
|
||||
func legacyServerFlagset() *pflag.FlagSet {
|
||||
flagSet := pflag.NewFlagSet("server", pflag.ExitOnError)
|
||||
|
||||
flagSet.String("metrics-address", "", "the address /metrics will be served on (e.g. \":9100\")")
|
||||
flagSet.String("metrics-secure-address", "", "the address /metrics will be served on for HTTPS clients (e.g. \":9100\")")
|
||||
flagSet.String("metrics-tls-cert-file", "", "path to certificate file for secure metrics server")
|
||||
flagSet.String("metrics-tls-key-file", "", "path to private key file for secure metrics server")
|
||||
flagSet.String("http-address", "127.0.0.1:4180", "[http://]<addr>:<port> or unix://<path> or fd:<int> (case insensitive) to listen on for HTTP clients")
|
||||
flagSet.String("https-address", ":443", "<addr>:<port> to listen on for HTTPS clients")
|
||||
flagSet.String("tls-cert-file", "", "path to certificate file")
|
||||
flagSet.String("tls-key-file", "", "path to private key file")
|
||||
flagSet.String("tls-min-version", "", "minimal TLS version for HTTPS clients (either \"TLS1.2\" or \"TLS1.3\")")
|
||||
flagSet.StringSlice("tls-cipher-suite", []string{}, "restricts TLS cipher suites to those listed (e.g. TLS_RSA_WITH_RC4_128_SHA) (may be given multiple times)")
|
||||
|
||||
return flagSet
|
||||
}
|
||||
|
||||
func (l LegacyServer) convert() (Server, Server) {
|
||||
appServer := Server{
|
||||
BindAddress: l.HTTPAddress,
|
||||
SecureBindAddress: l.HTTPSAddress,
|
||||
}
|
||||
if l.TLSKeyFile != "" || l.TLSCertFile != "" {
|
||||
appServer.TLS = &TLS{
|
||||
Key: &SecretSource{
|
||||
FromFile: l.TLSKeyFile,
|
||||
},
|
||||
Cert: &SecretSource{
|
||||
FromFile: l.TLSCertFile,
|
||||
},
|
||||
MinVersion: l.TLSMinVersion,
|
||||
}
|
||||
if len(l.TLSCipherSuites) != 0 {
|
||||
appServer.TLS.CipherSuites = l.TLSCipherSuites
|
||||
}
|
||||
// Preserve backwards compatibility, only run one server
|
||||
appServer.BindAddress = ""
|
||||
} else {
|
||||
// Disable the HTTPS server if there's no certificates.
|
||||
// This preserves backwards compatibility.
|
||||
appServer.SecureBindAddress = ""
|
||||
}
|
||||
|
||||
metricsServer := Server{
|
||||
BindAddress: l.MetricsAddress,
|
||||
SecureBindAddress: l.MetricsSecureAddress,
|
||||
}
|
||||
if l.MetricsTLSKeyFile != "" || l.MetricsTLSCertFile != "" {
|
||||
metricsServer.TLS = &TLS{
|
||||
Key: &SecretSource{
|
||||
FromFile: l.MetricsTLSKeyFile,
|
||||
},
|
||||
Cert: &SecretSource{
|
||||
FromFile: l.MetricsTLSCertFile,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return appServer, metricsServer
|
||||
}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
package options
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// LegacySessionOptions contains configuration options for the SessionStore providers.
|
||||
type LegacySessionOptions struct {
|
||||
Type string `flag:"session-store-type" cfg:"session_store_type"`
|
||||
Cookie LegacyCookieStoreOptions `cfg:",squash"`
|
||||
Redis LegacyRedisStoreOptions `cfg:",squash"`
|
||||
}
|
||||
|
||||
// LegacyCookieStoreOptions contains configuration options for the CookieSessionStore.
|
||||
type LegacyCookieStoreOptions struct {
|
||||
Minimal bool `flag:"session-cookie-minimal" cfg:"session_cookie_minimal"`
|
||||
}
|
||||
|
||||
// RedisStoreOptions contains configuration options for the RedisSessionStore.
|
||||
type LegacyRedisStoreOptions struct {
|
||||
ConnectionURL string `flag:"redis-connection-url" cfg:"redis_connection_url"`
|
||||
Username string `flag:"redis-username" cfg:"redis_username"`
|
||||
Password string `flag:"redis-password" cfg:"redis_password"`
|
||||
UseSentinel bool `flag:"redis-use-sentinel" cfg:"redis_use_sentinel"`
|
||||
SentinelPassword string `flag:"redis-sentinel-password" cfg:"redis_sentinel_password"`
|
||||
SentinelMasterName string `flag:"redis-sentinel-master-name" cfg:"redis_sentinel_master_name"`
|
||||
SentinelConnectionURLs []string `flag:"redis-sentinel-connection-urls" cfg:"redis_sentinel_connection_urls"`
|
||||
UseCluster bool `flag:"redis-use-cluster" cfg:"redis_use_cluster"`
|
||||
ClusterConnectionURLs []string `flag:"redis-cluster-connection-urls" cfg:"redis_cluster_connection_urls"`
|
||||
CAPath string `flag:"redis-ca-path" cfg:"redis_ca_path"`
|
||||
InsecureSkipTLSVerify bool `flag:"redis-insecure-skip-tls-verify" cfg:"redis_insecure_skip_tls_verify"`
|
||||
IdleTimeout int `flag:"redis-connection-idle-timeout" cfg:"redis_connection_idle_timeout"`
|
||||
}
|
||||
|
||||
func legacySessionFlagSet() *pflag.FlagSet {
|
||||
flagSet := pflag.NewFlagSet("session", pflag.ExitOnError)
|
||||
|
||||
flagSet.String("session-store-type", "cookie", "the session storage provider to use")
|
||||
flagSet.Bool("session-cookie-minimal", false, "strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only)")
|
||||
flagSet.String("redis-connection-url", "", "URL of redis server for redis session storage (eg: redis://[USER[:PASSWORD]@]HOST[:PORT])")
|
||||
flagSet.String("redis-username", "", "Redis username. Applicable for Redis configurations where ACL has been configured. Will override any username set in `--redis-connection-url`")
|
||||
flagSet.String("redis-password", "", "Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url`")
|
||||
flagSet.Bool("redis-use-sentinel", false, "Connect to redis via sentinels. Must set --redis-sentinel-master-name and --redis-sentinel-connection-urls to use this feature")
|
||||
flagSet.String("redis-sentinel-password", "", "Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password`")
|
||||
flagSet.String("redis-sentinel-master-name", "", "Redis sentinel master name. Used in conjunction with --redis-use-sentinel")
|
||||
flagSet.String("redis-ca-path", "", "Redis custom CA path")
|
||||
flagSet.Bool("redis-insecure-skip-tls-verify", false, "Use insecure TLS connection to redis")
|
||||
flagSet.StringSlice("redis-sentinel-connection-urls", []string{}, "List of Redis sentinel connection URLs (eg redis://[USER[:PASSWORD]@]HOST[:PORT]). Used in conjunction with --redis-use-sentinel")
|
||||
flagSet.Bool("redis-use-cluster", false, "Connect to redis cluster. Must set --redis-cluster-connection-urls to use this feature")
|
||||
flagSet.StringSlice("redis-cluster-connection-urls", []string{}, "List of Redis cluster connection URLs (eg redis://[USER[:PASSWORD]@]HOST[:PORT]). Used in conjunction with --redis-use-cluster")
|
||||
flagSet.Int("redis-connection-idle-timeout", 0, "Redis connection idle timeout seconds, if Redis timeout option is non-zero, the --redis-connection-idle-timeout must be less then Redis timeout option")
|
||||
|
||||
return flagSet
|
||||
}
|
||||
|
||||
func (l *LegacySessionOptions) convert(legacyCookieRefresh time.Duration) SessionOptions {
|
||||
return SessionOptions{
|
||||
Type: SessionStoreType(l.Type),
|
||||
Refresh: legacyCookieRefresh,
|
||||
Cookie: CookieStoreOptions{
|
||||
Minimal: &l.Cookie.Minimal,
|
||||
},
|
||||
Redis: RedisStoreOptions{
|
||||
ConnectionURL: l.Redis.ConnectionURL,
|
||||
Password: l.Redis.Password,
|
||||
UseSentinel: &l.Redis.UseSentinel,
|
||||
SentinelPassword: l.Redis.SentinelPassword,
|
||||
SentinelMasterName: l.Redis.SentinelMasterName,
|
||||
SentinelConnectionURLs: l.Redis.SentinelConnectionURLs,
|
||||
UseCluster: &l.Redis.UseCluster,
|
||||
ClusterConnectionURLs: l.Redis.ClusterConnectionURLs,
|
||||
CAPath: l.Redis.CAPath,
|
||||
InsecureSkipTLSVerify: &l.Redis.InsecureSkipTLSVerify,
|
||||
IdleTimeout: l.Redis.IdleTimeout,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,105 @@
|
|||
package options
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
type LegacyUpstreams struct {
|
||||
FlushInterval time.Duration `flag:"flush-interval" cfg:"flush_interval"`
|
||||
PassHostHeader bool `flag:"pass-host-header" cfg:"pass_host_header"`
|
||||
ProxyWebSockets bool `flag:"proxy-websockets" cfg:"proxy_websockets"`
|
||||
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 {
|
||||
flagSet := pflag.NewFlagSet("upstreams", pflag.ExitOnError)
|
||||
|
||||
flagSet.Duration("flush-interval", DefaultUpstreamFlushInterval, "period between response flushing when streaming responses")
|
||||
flagSet.Bool("pass-host-header", true, "pass the request Host Header to upstream")
|
||||
flagSet.Bool("proxy-websockets", true, "enables WebSocket proxying")
|
||||
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://<status_code> 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
|
||||
}
|
||||
|
||||
func (l *LegacyUpstreams) convert() (UpstreamConfig, error) {
|
||||
upstreams := UpstreamConfig{}
|
||||
|
||||
for _, upstreamString := range l.Upstreams {
|
||||
u, err := url.Parse(upstreamString)
|
||||
if err != nil {
|
||||
return UpstreamConfig{}, fmt.Errorf("could not parse upstream %q: %v", upstreamString, err)
|
||||
}
|
||||
|
||||
if u.Path == "" {
|
||||
u.Path = "/"
|
||||
}
|
||||
|
||||
flushInterval := l.FlushInterval
|
||||
timeout := l.Timeout
|
||||
upstream := Upstream{
|
||||
ID: u.Path,
|
||||
Path: u.Path,
|
||||
URI: upstreamString,
|
||||
InsecureSkipTLSVerify: &l.SSLUpstreamInsecureSkipVerify,
|
||||
PassHostHeader: &l.PassHostHeader,
|
||||
ProxyWebSockets: &l.ProxyWebSockets,
|
||||
FlushInterval: &flushInterval,
|
||||
Timeout: &timeout,
|
||||
DisableKeepAlives: &l.DisableKeepAlives,
|
||||
}
|
||||
|
||||
switch u.Scheme {
|
||||
case "file":
|
||||
if u.Fragment != "" {
|
||||
upstream.ID = u.Fragment
|
||||
upstream.Path = u.Fragment
|
||||
// Trim the fragment from the end of the URI
|
||||
upstream.URI = strings.SplitN(upstreamString, "#", 2)[0]
|
||||
}
|
||||
case "static":
|
||||
responseCode, err := strconv.Atoi(u.Host)
|
||||
if err != nil {
|
||||
logger.Errorf("unable to convert %q to int, use default \"200\"", u.Host)
|
||||
responseCode = 200
|
||||
}
|
||||
upstream.Static = ptr.To(true)
|
||||
upstream.StaticCode = &responseCode
|
||||
|
||||
// This is not allowed to be empty and must be unique
|
||||
upstream.ID = upstreamString
|
||||
|
||||
// We only support the root path in the legacy config
|
||||
upstream.Path = "/"
|
||||
|
||||
// Force defaults compatible with static responses
|
||||
upstream.URI = ""
|
||||
upstream.InsecureSkipTLSVerify = ptr.To(false)
|
||||
upstream.DisableKeepAlives = ptr.To(false)
|
||||
upstream.PassHostHeader = nil
|
||||
upstream.ProxyWebSockets = nil
|
||||
upstream.FlushInterval = nil
|
||||
upstream.Timeout = nil
|
||||
case "unix":
|
||||
upstream.Path = "/"
|
||||
}
|
||||
|
||||
upstreams.Upstreams = append(upstreams.Upstreams, upstream)
|
||||
}
|
||||
|
||||
return upstreams, nil
|
||||
}
|
||||
|
|
@ -46,6 +46,27 @@ var _ = Describe("Load", func() {
|
|||
InsecureOIDCSkipNonce: true,
|
||||
},
|
||||
|
||||
LegacyCookie: LegacyCookie{
|
||||
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,
|
||||
},
|
||||
|
||||
LegacySessionOptions: LegacySessionOptions{
|
||||
Type: "cookie",
|
||||
Cookie: LegacyCookieStoreOptions{
|
||||
Minimal: false,
|
||||
},
|
||||
},
|
||||
|
||||
Options: Options{
|
||||
BearerTokenLoginFallback: true,
|
||||
ProxyPrefix: "/oauth2",
|
||||
|
|
@ -53,8 +74,6 @@ var _ = Describe("Load", func() {
|
|||
ReadyPath: "/ready",
|
||||
RealClientIPHeader: "X-Real-IP",
|
||||
ForceHTTPS: false,
|
||||
Cookie: cookieDefaults(),
|
||||
Session: sessionOptionsDefaults(),
|
||||
Templates: templatesDefaults(),
|
||||
SkipAuthPreflight: false,
|
||||
Logging: loggingDefaults(),
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ type Options struct {
|
|||
HtpasswdFile string `flag:"htpasswd-file" cfg:"htpasswd_file"`
|
||||
HtpasswdUserGroups []string `flag:"htpasswd-user-group" cfg:"htpasswd_user_groups"`
|
||||
|
||||
Cookie Cookie `cfg:",squash"`
|
||||
Cookie Cookie `cfg:",internal"`
|
||||
Session SessionOptions `cfg:",squash"`
|
||||
Logging Logging `cfg:",squash"`
|
||||
Templates Templates `cfg:",squash"`
|
||||
|
|
@ -105,8 +105,6 @@ func NewOptions() *Options {
|
|||
ReadyPath: "/ready",
|
||||
RealClientIPHeader: "X-Real-IP",
|
||||
ForceHTTPS: false,
|
||||
Cookie: cookieDefaults(),
|
||||
Session: sessionOptionsDefaults(),
|
||||
Templates: templatesDefaults(),
|
||||
SkipAuthPreflight: false,
|
||||
Logging: loggingDefaults(),
|
||||
|
|
@ -145,24 +143,9 @@ func NewFlagSet() *pflag.FlagSet {
|
|||
flagSet.String("ping-path", "/ping", "the ping endpoint that can be used for basic health checks")
|
||||
flagSet.String("ping-user-agent", "", "special User-Agent that will be used for basic health checks")
|
||||
flagSet.String("ready-path", "/ready", "the ready endpoint that can be used for deep health checks")
|
||||
flagSet.String("session-store-type", "cookie", "the session storage provider to use")
|
||||
flagSet.Bool("session-cookie-minimal", false, "strip OAuth tokens from cookie session stores if they aren't needed (cookie session store only)")
|
||||
flagSet.String("redis-connection-url", "", "URL of redis server for redis session storage (eg: redis://[USER[:PASSWORD]@]HOST[:PORT])")
|
||||
flagSet.String("redis-username", "", "Redis username. Applicable for Redis configurations where ACL has been configured. Will override any username set in `--redis-connection-url`")
|
||||
flagSet.String("redis-password", "", "Redis password. Applicable for all Redis configurations. Will override any password set in `--redis-connection-url`")
|
||||
flagSet.Bool("redis-use-sentinel", false, "Connect to redis via sentinels. Must set --redis-sentinel-master-name and --redis-sentinel-connection-urls to use this feature")
|
||||
flagSet.String("redis-sentinel-password", "", "Redis sentinel password. Used only for sentinel connection; any redis node passwords need to use `--redis-password`")
|
||||
flagSet.String("redis-sentinel-master-name", "", "Redis sentinel master name. Used in conjunction with --redis-use-sentinel")
|
||||
flagSet.String("redis-ca-path", "", "Redis custom CA path")
|
||||
flagSet.Bool("redis-insecure-skip-tls-verify", false, "Use insecure TLS connection to redis")
|
||||
flagSet.StringSlice("redis-sentinel-connection-urls", []string{}, "List of Redis sentinel connection URLs (eg redis://[USER[:PASSWORD]@]HOST[:PORT]). Used in conjunction with --redis-use-sentinel")
|
||||
flagSet.Bool("redis-use-cluster", false, "Connect to redis cluster. Must set --redis-cluster-connection-urls to use this feature")
|
||||
flagSet.StringSlice("redis-cluster-connection-urls", []string{}, "List of Redis cluster connection URLs (eg redis://[USER[:PASSWORD]@]HOST[:PORT]). Used in conjunction with --redis-use-cluster")
|
||||
flagSet.Int("redis-connection-idle-timeout", 0, "Redis connection idle timeout seconds, if Redis timeout option is non-zero, the --redis-connection-idle-timeout must be less then Redis timeout option")
|
||||
flagSet.String("signature-key", "", "GAP-Signature request signature key (algorithm:secretkey)")
|
||||
flagSet.Bool("gcp-healthchecks", false, "Enable GCP/GKE healthcheck endpoints")
|
||||
|
||||
flagSet.AddFlagSet(cookieFlagSet())
|
||||
flagSet.AddFlagSet(loggingFlagSet())
|
||||
flagSet.AddFlagSet(templatesFlagSet())
|
||||
|
||||
|
|
@ -182,9 +165,9 @@ func (o *Options) EnsureDefaults() {
|
|||
o.InjectResponseHeaders[i].EnsureDefaults()
|
||||
}
|
||||
|
||||
o.Cookie.EnsureDefaults()
|
||||
o.Session.EnsureDefaults()
|
||||
// TBD: Uncomment as we add EnsureDefaults methods
|
||||
// o.Cookie.EnsureDefaults()
|
||||
// o.Session.EnsureDefaults()
|
||||
// o.Templates.EnsureDefaults()
|
||||
// o.Logging.EnsureDefaults()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -329,29 +329,6 @@ type LoginGovOptions struct {
|
|||
PubJWKURL string `yaml:"pubjwkURL,omitempty"`
|
||||
}
|
||||
|
||||
// Legacy default providers configuration
|
||||
func providerDefaults() Providers {
|
||||
providers := Providers{
|
||||
{
|
||||
Type: "google",
|
||||
AzureConfig: AzureOptions{
|
||||
Tenant: "common",
|
||||
},
|
||||
OIDCConfig: OIDCOptions{
|
||||
InsecureAllowUnverifiedEmail: ptr.To(DefaultInsecureAllowUnverifiedEmail),
|
||||
InsecureSkipNonce: ptr.To(DefaultInsecureSkipNonce),
|
||||
SkipDiscovery: ptr.To(DefaultSkipDiscovery),
|
||||
UserIDClaim: OIDCEmailClaim, // Deprecated: Use OIDCEmailClaim
|
||||
EmailClaim: OIDCEmailClaim,
|
||||
GroupsClaim: OIDCGroupsClaim,
|
||||
AudienceClaims: OIDCAudienceClaims,
|
||||
ExtraAudiences: []string{},
|
||||
},
|
||||
},
|
||||
}
|
||||
return providers
|
||||
}
|
||||
|
||||
// EnsureDefaults sets any default values for Providers fields.
|
||||
func (p Providers) EnsureDefaults() {
|
||||
for i := range p {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,11 @@
|
|||
package options
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
// SecretSource references an individual secret value.
|
||||
// Only one source within the struct should be defined at any time.
|
||||
type SecretSource struct {
|
||||
|
|
@ -13,6 +19,31 @@ type SecretSource struct {
|
|||
FromFile string `yaml:"fromFile,omitempty"`
|
||||
}
|
||||
|
||||
func (ss *SecretSource) GetSecretValue() ([]byte, error) {
|
||||
if len(ss.Value) > 0 {
|
||||
var decoded []byte
|
||||
if _, err := base64.StdEncoding.Decode(decoded, ss.Value); err != nil {
|
||||
return nil, fmt.Errorf("error decoding secret value: %w", err)
|
||||
}
|
||||
return decoded, nil
|
||||
}
|
||||
|
||||
if ss.FromEnv != "" {
|
||||
envValue := os.Getenv(ss.FromEnv)
|
||||
return []byte(envValue), nil
|
||||
}
|
||||
|
||||
if ss.FromFile != "" {
|
||||
fileData, err := os.ReadFile(ss.FromFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error reading secret from file %q: %w", ss.FromFile, err)
|
||||
}
|
||||
return fileData, nil
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// EnsureDefaults sets any default values for SecretSource fields.
|
||||
func (ss *SecretSource) EnsureDefaults() {
|
||||
// No defaults to set currently
|
||||
|
|
|
|||
|
|
@ -1,46 +1,101 @@
|
|||
package options
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
)
|
||||
|
||||
type SessionStoreType string
|
||||
|
||||
const (
|
||||
// CookieSessionStoreType is used to indicate the CookieSessionStore should be
|
||||
// used for storing sessions.
|
||||
CookieSessionStoreType SessionStoreType = "cookie"
|
||||
|
||||
// RedisSessionStoreType is used to indicate the RedisSessionStore should be
|
||||
// used for storing sessions.
|
||||
RedisSessionStoreType SessionStoreType = "redis"
|
||||
|
||||
// DefaultCookieStoreMinimal is the default value for CookieStoreOptions.Minimal
|
||||
DefaultCookieStoreMinimal bool = false
|
||||
|
||||
// DefaultRedisStoreUseSentinel is the default value for RedisStoreOptions.UseSentinel
|
||||
DefaultRedisStoreUseSentinel bool = false
|
||||
|
||||
// DefaultRedisStoreUseCluster is the default value for RedisStoreOptions.UseCluster
|
||||
DefaultRedisStoreUseCluster bool = false
|
||||
|
||||
// DefaultRedisStoreInsecureSkipTLSVerify is the default value for RedisStoreOptions.InsecureSkipTLSVerify
|
||||
DefaultRedisStoreInsecureSkipTLSVerify bool = false
|
||||
)
|
||||
|
||||
// SessionOptions contains configuration options for the SessionStore providers.
|
||||
type SessionOptions struct {
|
||||
Type string `flag:"session-store-type" cfg:"session_store_type"`
|
||||
Cookie CookieStoreOptions `cfg:",squash"`
|
||||
Redis RedisStoreOptions `cfg:",squash"`
|
||||
// Type is the type of session store to use
|
||||
// Options are "cookie" or "redis"
|
||||
// Default is "cookie"
|
||||
Type SessionStoreType `yaml:"type,omitempty"`
|
||||
// Refresh is the duration after which the session is refreshable
|
||||
Refresh time.Duration `yaml:"refresh,omitempty"`
|
||||
// Cookie is the configuration options for the CookieSessionStore
|
||||
Cookie CookieStoreOptions `yaml:"cookie,omitempty"`
|
||||
// Redis is the configuration options for the RedisSessionStore
|
||||
Redis RedisStoreOptions `yaml:"redis,omitempty"`
|
||||
}
|
||||
|
||||
// CookieSessionStoreType is used to indicate the CookieSessionStore should be
|
||||
// used for storing sessions.
|
||||
var CookieSessionStoreType = "cookie"
|
||||
|
||||
// RedisSessionStoreType is used to indicate the RedisSessionStore should be
|
||||
// used for storing sessions.
|
||||
var RedisSessionStoreType = "redis"
|
||||
|
||||
// CookieStoreOptions contains configuration options for the CookieSessionStore.
|
||||
type CookieStoreOptions struct {
|
||||
Minimal bool `flag:"session-cookie-minimal" cfg:"session_cookie_minimal"`
|
||||
// Minimal indicates whether to use minimal cookies for session storage
|
||||
// Default is false
|
||||
Minimal *bool `yaml:"minimal,omitempty"`
|
||||
}
|
||||
|
||||
// RedisStoreOptions contains configuration options for the RedisSessionStore.
|
||||
type RedisStoreOptions struct {
|
||||
ConnectionURL string `flag:"redis-connection-url" cfg:"redis_connection_url"`
|
||||
Username string `flag:"redis-username" cfg:"redis_username"`
|
||||
Password string `flag:"redis-password" cfg:"redis_password"`
|
||||
UseSentinel bool `flag:"redis-use-sentinel" cfg:"redis_use_sentinel"`
|
||||
SentinelPassword string `flag:"redis-sentinel-password" cfg:"redis_sentinel_password"`
|
||||
SentinelMasterName string `flag:"redis-sentinel-master-name" cfg:"redis_sentinel_master_name"`
|
||||
SentinelConnectionURLs []string `flag:"redis-sentinel-connection-urls" cfg:"redis_sentinel_connection_urls"`
|
||||
UseCluster bool `flag:"redis-use-cluster" cfg:"redis_use_cluster"`
|
||||
ClusterConnectionURLs []string `flag:"redis-cluster-connection-urls" cfg:"redis_cluster_connection_urls"`
|
||||
CAPath string `flag:"redis-ca-path" cfg:"redis_ca_path"`
|
||||
InsecureSkipTLSVerify bool `flag:"redis-insecure-skip-tls-verify" cfg:"redis_insecure_skip_tls_verify"`
|
||||
IdleTimeout int `flag:"redis-connection-idle-timeout" cfg:"redis_connection_idle_timeout"`
|
||||
// ConnectionURL is the Redis connection URL
|
||||
ConnectionURL string `yaml:"connectionURL,omitempty"`
|
||||
// Username is the Redis username
|
||||
Username string `yaml:"username,omitempty"`
|
||||
// Password is the Redis password
|
||||
Password string `yaml:"password,omitempty"`
|
||||
// UseSentinel indicates whether to use Redis Sentinel
|
||||
// Default is false
|
||||
UseSentinel *bool `yaml:"useSentinel,omitempty"`
|
||||
// SentinelPassword is the Redis Sentinel password
|
||||
SentinelPassword string `yaml:"sentinelPassword,omitempty"`
|
||||
// SentinelMasterName is the Redis Sentinel master name
|
||||
SentinelMasterName string `yaml:"sentinelMasterName,omitempty"`
|
||||
// SentinelConnectionURLs is a list of Redis Sentinel connection URLs
|
||||
SentinelConnectionURLs []string `yaml:"sentinelConnectionURLs,omitempty"`
|
||||
// UseCluster indicates whether to use Redis Cluster
|
||||
// Default is false
|
||||
UseCluster *bool `yaml:"useCluster,omitempty"`
|
||||
// ClusterConnectionURLs is a list of Redis Cluster connection URLs
|
||||
ClusterConnectionURLs []string `yaml:"clusterConnectionURLs,omitempty"`
|
||||
// CAPath is the path to the CA certificate for Redis TLS connections
|
||||
CAPath string `yaml:"caPath,omitempty"`
|
||||
// InsecureSkipTLSVerify indicates whether to skip TLS verification for Redis connections
|
||||
InsecureSkipTLSVerify *bool `yaml:"insecureSkipTLSVerify,omitempty"`
|
||||
// IdleTimeout is the Redis connection idle timeout in seconds
|
||||
IdleTimeout int `yaml:"idleTimeout,omitempty"`
|
||||
}
|
||||
|
||||
func sessionOptionsDefaults() SessionOptions {
|
||||
return SessionOptions{
|
||||
Type: CookieSessionStoreType,
|
||||
Cookie: CookieStoreOptions{
|
||||
Minimal: false,
|
||||
},
|
||||
// EnsureDefaults sets default values for SessionOptions
|
||||
func (s *SessionOptions) EnsureDefaults() {
|
||||
if s.Type == "" {
|
||||
s.Type = CookieSessionStoreType
|
||||
}
|
||||
if s.Cookie.Minimal == nil {
|
||||
s.Cookie.Minimal = ptr.To(DefaultCookieStoreMinimal)
|
||||
}
|
||||
if s.Redis.UseSentinel == nil {
|
||||
s.Redis.UseSentinel = ptr.To(DefaultRedisStoreUseSentinel)
|
||||
}
|
||||
if s.Redis.UseCluster == nil {
|
||||
s.Redis.UseCluster = ptr.To(DefaultRedisStoreUseCluster)
|
||||
}
|
||||
if s.Redis.InsecureSkipTLSVerify == nil {
|
||||
s.Redis.InsecureSkipTLSVerify = ptr.To(DefaultRedisStoreInsecureSkipTLSVerify)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import (
|
|||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
|
||||
requestutil "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests/util"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
)
|
||||
|
||||
// MakeCookieFromOptions constructs a cookie based on the given *options.CookieOptions,
|
||||
|
|
@ -30,8 +31,8 @@ func MakeCookieFromOptions(req *http.Request, name string, value string, opts *o
|
|||
Value: value,
|
||||
Path: opts.Path,
|
||||
Domain: domain,
|
||||
HttpOnly: opts.HTTPOnly,
|
||||
Secure: opts.Secure,
|
||||
HttpOnly: !ptr.Deref(opts.NotHttpOnly, options.DefaultCookieNotHttpOnly),
|
||||
Secure: !ptr.Deref(opts.Insecure, options.DefaultCookieInsecure),
|
||||
SameSite: ParseSameSite(opts.SameSite),
|
||||
}
|
||||
|
||||
|
|
@ -59,7 +60,7 @@ func GetCookieDomain(req *http.Request, cookieDomains []string) string {
|
|||
}
|
||||
|
||||
// Parse a valid http.SameSite value from a user supplied string for use of making cookies.
|
||||
func ParseSameSite(v string) http.SameSite {
|
||||
func ParseSameSite(v options.SameSiteMode) http.SameSite {
|
||||
switch v {
|
||||
case "lax":
|
||||
return http.SameSiteLaxMode
|
||||
|
|
|
|||
|
|
@ -13,13 +13,16 @@ const (
|
|||
csrfNonce = "0987lkjh0987lkjh0987lkjh"
|
||||
|
||||
cookieName = "cookie_test_12345"
|
||||
cookieSecret = "3q48hmFH30FJ2HfJF0239UFJCVcl3kj3"
|
||||
cookieDomain = "o2p.cookies.test"
|
||||
cookiePath = "/cookie-tests"
|
||||
|
||||
nowEpoch = 1609366421
|
||||
)
|
||||
|
||||
var (
|
||||
cookieSecret = []byte("3q48hmFH30FJ2HfJF0239UFJCVcl3kj3")
|
||||
)
|
||||
|
||||
func TestProviderSuite(t *testing.T) {
|
||||
logger.SetOutput(GinkgoWriter)
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
|
||||
middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
|
|
@ -91,7 +92,7 @@ var _ = Describe("Cookie Tests", func() {
|
|||
}
|
||||
|
||||
validName := "_oauth2_proxy"
|
||||
validSecret := "secretthirtytwobytes+abcdefghijk"
|
||||
validSecret := []byte("secretthirtytwobytes+abcdefghijk")
|
||||
domains := []string{"www.cookies.test"}
|
||||
|
||||
now := time.Now()
|
||||
|
|
@ -113,15 +114,14 @@ var _ = Describe("Cookie Tests", func() {
|
|||
name: validName,
|
||||
value: "1",
|
||||
opts: options.Cookie{
|
||||
Name: validName,
|
||||
Secret: validSecret,
|
||||
Domains: domains,
|
||||
Path: "",
|
||||
Expire: time.Hour,
|
||||
Refresh: 15 * time.Minute,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
SameSite: "",
|
||||
Name: validName,
|
||||
Secret: options.SecretSource{Value: validSecret},
|
||||
Domains: domains,
|
||||
Path: "",
|
||||
Expire: time.Hour,
|
||||
Insecure: ptr.To(false),
|
||||
NotHttpOnly: ptr.To(true),
|
||||
SameSite: "",
|
||||
},
|
||||
expiration: 15 * time.Minute,
|
||||
now: now,
|
||||
|
|
@ -132,15 +132,14 @@ var _ = Describe("Cookie Tests", func() {
|
|||
name: validName,
|
||||
value: "1",
|
||||
opts: options.Cookie{
|
||||
Name: validName,
|
||||
Secret: validSecret,
|
||||
Domains: domains,
|
||||
Path: "",
|
||||
Expire: time.Hour * -1,
|
||||
Refresh: 15 * time.Minute,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
SameSite: "",
|
||||
Name: validName,
|
||||
Secret: options.SecretSource{Value: validSecret},
|
||||
Domains: domains,
|
||||
Path: "",
|
||||
Expire: time.Hour * -1,
|
||||
Insecure: ptr.To(false),
|
||||
NotHttpOnly: ptr.To(true),
|
||||
SameSite: "",
|
||||
},
|
||||
expiration: time.Hour * -1,
|
||||
now: now,
|
||||
|
|
@ -151,15 +150,14 @@ var _ = Describe("Cookie Tests", func() {
|
|||
name: validName,
|
||||
value: "1",
|
||||
opts: options.Cookie{
|
||||
Name: validName,
|
||||
Secret: validSecret,
|
||||
Domains: domains,
|
||||
Path: "",
|
||||
Expire: 0,
|
||||
Refresh: 15 * time.Minute,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
SameSite: "",
|
||||
Name: validName,
|
||||
Secret: options.SecretSource{Value: validSecret},
|
||||
Domains: domains,
|
||||
Path: "",
|
||||
Expire: 0,
|
||||
Insecure: ptr.To(false),
|
||||
NotHttpOnly: ptr.To(true),
|
||||
SameSite: "",
|
||||
},
|
||||
expiration: 0,
|
||||
now: now,
|
||||
|
|
|
|||
|
|
@ -11,6 +11,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/encryption"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
"github.com/vmihailenco/msgpack/v5"
|
||||
)
|
||||
|
||||
|
|
@ -96,7 +97,7 @@ func LoadCSRFCookie(req *http.Request, cookieName string, opts *options.Cookie)
|
|||
// build name based on the state
|
||||
func GenerateCookieName(opts *options.Cookie, state string) string {
|
||||
stateSubstring := ""
|
||||
if opts.CSRFPerRequest {
|
||||
if ptr.Deref(opts.CSRFPerRequest, options.DefaultCSRFPerRequest) {
|
||||
// csrfCookieName will include a substring of the state to enable multiple csrf cookies
|
||||
// in case of parallel requests
|
||||
stateSubstring = ExtractStateSubstring(state)
|
||||
|
|
@ -156,7 +157,7 @@ func (c *csrf) SetCookie(rw http.ResponseWriter, req *http.Request) (*http.Cooki
|
|||
// 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 {
|
||||
if !ptr.Deref(opts.CSRFPerRequest, options.DefaultCSRFPerRequest) || opts.CSRFPerRequestLimit <= 0 {
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -262,7 +263,7 @@ func unmarshalCSRF(decrypted []byte, opts *options.Cookie, csrfTime time.Time) (
|
|||
// cookieName returns the CSRF cookie's name
|
||||
func (c *csrf) cookieName() string {
|
||||
stateSubstring := ""
|
||||
if c.cookieOpts.CSRFPerRequest {
|
||||
if ptr.Deref(c.cookieOpts.CSRFPerRequest, options.DefaultCSRFPerRequest) {
|
||||
stateSubstring = encryption.HashNonce(c.OAuthState)[0 : csrfStateLength-1]
|
||||
}
|
||||
return csrfCookieName(c.cookieOpts, stateSubstring)
|
||||
|
|
|
|||
|
|
@ -10,6 +10,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/encryption"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
|
@ -24,13 +25,13 @@ var _ = Describe("CSRF Cookie with non-fixed name Tests", func() {
|
|||
BeforeEach(func() {
|
||||
cookieOpts = &options.Cookie{
|
||||
Name: cookieName,
|
||||
Secret: cookieSecret,
|
||||
Secret: options.SecretSource{Value: cookieSecret},
|
||||
Domains: []string{cookieDomain},
|
||||
Path: cookiePath,
|
||||
Expire: time.Hour,
|
||||
Secure: true,
|
||||
HTTPOnly: true,
|
||||
CSRFPerRequest: true,
|
||||
Insecure: ptr.To(false),
|
||||
NotHttpOnly: ptr.To(false),
|
||||
CSRFPerRequest: ptr.To(true),
|
||||
CSRFExpire: time.Duration(5) * time.Minute,
|
||||
}
|
||||
|
||||
|
|
@ -117,7 +118,10 @@ var _ = Describe("CSRF Cookie with non-fixed name Tests", func() {
|
|||
Value: encoded,
|
||||
}
|
||||
|
||||
_, _, valid := encryption.Validate(cookie, cookieOpts.Secret, cookieOpts.Expire)
|
||||
cookieSecret, err := cookieOpts.GetSecret()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, _, valid := encryption.Validate(cookie, cookieSecret, cookieOpts.Expire)
|
||||
Expect(valid).To(BeTrue())
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -10,6 +10,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/encryption"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
|
@ -25,13 +26,13 @@ var _ = Describe("CSRF Cookie Tests", func() {
|
|||
BeforeEach(func() {
|
||||
cookieOpts = &options.Cookie{
|
||||
Name: cookieName,
|
||||
Secret: cookieSecret,
|
||||
Secret: options.SecretSource{Value: cookieSecret},
|
||||
Domains: []string{cookieDomain},
|
||||
Path: cookiePath,
|
||||
Expire: time.Hour,
|
||||
Secure: true,
|
||||
HTTPOnly: true,
|
||||
CSRFPerRequest: false,
|
||||
Insecure: ptr.To(false),
|
||||
NotHttpOnly: ptr.To(false),
|
||||
CSRFPerRequest: ptr.To(false),
|
||||
CSRFExpire: time.Hour,
|
||||
}
|
||||
|
||||
|
|
@ -118,8 +119,10 @@ var _ = Describe("CSRF Cookie Tests", func() {
|
|||
Name: privateCSRF.cookieName(),
|
||||
Value: encoded,
|
||||
}
|
||||
cookieSecret, err := cookieOpts.GetSecret()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, _, valid := encryption.Validate(cookie, cookieOpts.Secret, cookieOpts.Expire)
|
||||
_, _, valid := encryption.Validate(cookie, cookieSecret, cookieOpts.Expire)
|
||||
Expect(valid).To(BeTrue())
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import (
|
|||
pkgcookies "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/cookies"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
)
|
||||
|
||||
const (
|
||||
|
|
@ -164,7 +165,7 @@ func NewCookieSessionStore(opts *options.SessionOptions, cookieOpts *options.Coo
|
|||
return &SessionStore{
|
||||
CookieCipher: cipher,
|
||||
Cookie: cookieOpts,
|
||||
Minimal: opts.Cookie.Minimal,
|
||||
Minimal: ptr.Deref(opts.Cookie.Minimal, options.DefaultCookieStoreMinimal),
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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/sessions/persistence"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
|
|
@ -82,13 +83,14 @@ func (store *SessionStore) VerifyConnection(ctx context.Context) error {
|
|||
// NewRedisClient makes a redis.Client (either standalone, sentinel aware, or
|
||||
// redis cluster)
|
||||
func NewRedisClient(opts options.RedisStoreOptions) (Client, error) {
|
||||
if opts.UseSentinel && opts.UseCluster {
|
||||
if ptr.Deref(opts.UseSentinel, options.DefaultRedisStoreUseSentinel) &&
|
||||
ptr.Deref(opts.UseCluster, options.DefaultRedisStoreUseCluster) {
|
||||
return nil, fmt.Errorf("options redis-use-sentinel and redis-use-cluster are mutually exclusive")
|
||||
}
|
||||
if opts.UseSentinel {
|
||||
if ptr.Deref(opts.UseSentinel, options.DefaultRedisStoreUseSentinel) {
|
||||
return buildSentinelClient(opts)
|
||||
}
|
||||
if opts.UseCluster {
|
||||
if ptr.Deref(opts.UseCluster, options.DefaultRedisStoreUseCluster) {
|
||||
return buildClusterClient(opts)
|
||||
}
|
||||
|
||||
|
|
@ -181,7 +183,7 @@ func buildStandaloneClient(opts options.RedisStoreOptions) (Client, error) {
|
|||
|
||||
// setupTLSConfig sets the TLSConfig if the TLS option is given in redis.Options
|
||||
func setupTLSConfig(opts options.RedisStoreOptions, opt *redis.Options) error {
|
||||
if opts.InsecureSkipTLSVerify {
|
||||
if ptr.Deref(opts.InsecureSkipTLSVerify, options.DefaultRedisStoreInsecureSkipTLSVerify) {
|
||||
if opt.TLSConfig == nil {
|
||||
/* #nosec */
|
||||
opt.TLSConfig = &tls.Config{}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import (
|
|||
sessionsapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/sessions/persistence"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/sessions/tests"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
|
@ -80,7 +81,7 @@ var _ = Describe("Redis SessionStore Tests", func() {
|
|||
sentinelAddr := redisProtocol + ms.Addr()
|
||||
opts.Type = options.RedisSessionStoreType
|
||||
opts.Redis.SentinelConnectionURLs = []string{sentinelAddr}
|
||||
opts.Redis.UseSentinel = true
|
||||
opts.Redis.UseSentinel = ptr.To(true)
|
||||
opts.Redis.SentinelMasterName = ms.MasterInfo().Name
|
||||
|
||||
// Capture the session store so that we can close the client
|
||||
|
|
@ -101,7 +102,7 @@ var _ = Describe("Redis SessionStore Tests", func() {
|
|||
clusterAddr := redisProtocol + mr.Addr()
|
||||
opts.Type = options.RedisSessionStoreType
|
||||
opts.Redis.ClusterConnectionURLs = []string{clusterAddr}
|
||||
opts.Redis.UseCluster = true
|
||||
opts.Redis.UseCluster = ptr.To(true)
|
||||
|
||||
// Capture the session store so that we can close the client
|
||||
var err error
|
||||
|
|
@ -156,7 +157,7 @@ var _ = Describe("Redis SessionStore Tests", func() {
|
|||
sentinelAddr := redisProtocol + ms.Addr()
|
||||
opts.Type = options.RedisSessionStoreType
|
||||
opts.Redis.SentinelConnectionURLs = []string{sentinelAddr}
|
||||
opts.Redis.UseSentinel = true
|
||||
opts.Redis.UseSentinel = ptr.To(true)
|
||||
opts.Redis.SentinelMasterName = ms.MasterInfo().Name
|
||||
opts.Redis.Password = redisPassword
|
||||
|
||||
|
|
@ -178,7 +179,7 @@ var _ = Describe("Redis SessionStore Tests", func() {
|
|||
clusterAddr := redisProtocol + mr.Addr()
|
||||
opts.Type = options.RedisSessionStoreType
|
||||
opts.Redis.ClusterConnectionURLs = []string{clusterAddr}
|
||||
opts.Redis.UseCluster = true
|
||||
opts.Redis.UseCluster = ptr.To(true)
|
||||
opts.Redis.Password = redisPassword
|
||||
|
||||
// Capture the session store so that we can close the client
|
||||
|
|
@ -227,7 +228,7 @@ var _ = Describe("Redis SessionStore Tests", func() {
|
|||
clusterAddr := "redis://" + redisUsername + "@" + mr.Addr()
|
||||
opts.Type = options.RedisSessionStoreType
|
||||
opts.Redis.ClusterConnectionURLs = []string{clusterAddr}
|
||||
opts.Redis.UseCluster = true
|
||||
opts.Redis.UseCluster = ptr.To(true)
|
||||
opts.Redis.Username = redisUsername
|
||||
opts.Redis.Password = redisPassword
|
||||
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import (
|
|||
sessionsapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/sessions/persistence"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/sessions/tests"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
|
@ -69,7 +70,7 @@ var _ = Describe("Redis SessionStore Tests", func() {
|
|||
clusterAddr := redissProtocol + mr.Addr()
|
||||
opts.Type = options.RedisSessionStoreType
|
||||
opts.Redis.ClusterConnectionURLs = []string{clusterAddr}
|
||||
opts.Redis.UseCluster = true
|
||||
opts.Redis.UseCluster = ptr.To(true)
|
||||
opts.Redis.CAPath = caPath
|
||||
|
||||
// Capture the session store so that we can close the client
|
||||
|
|
@ -92,7 +93,7 @@ var _ = Describe("Redis SessionStore Tests", func() {
|
|||
// Set the connection URL
|
||||
opts.Type = options.RedisSessionStoreType
|
||||
opts.Redis.ConnectionURL = redissProtocol + mr.Addr()
|
||||
opts.Redis.InsecureSkipTLSVerify = true
|
||||
opts.Redis.InsecureSkipTLSVerify = ptr.To(true)
|
||||
|
||||
// Capture the session store so that we can close the client
|
||||
ss, err := NewRedisSessionStore(opts, cookieOpts)
|
||||
|
|
@ -111,8 +112,8 @@ var _ = Describe("Redis SessionStore Tests", func() {
|
|||
clusterAddr := redissProtocol + mr.Addr()
|
||||
opts.Type = options.RedisSessionStoreType
|
||||
opts.Redis.ClusterConnectionURLs = []string{clusterAddr}
|
||||
opts.Redis.UseCluster = true
|
||||
opts.Redis.InsecureSkipTLSVerify = true
|
||||
opts.Redis.UseCluster = ptr.To(true)
|
||||
opts.Redis.InsecureSkipTLSVerify = ptr.To(true)
|
||||
|
||||
// Capture the session store so that we can close the client
|
||||
var err error
|
||||
|
|
@ -153,7 +154,7 @@ var _ = Describe("Redis SessionStore Tests", func() {
|
|||
// Set the connection URL
|
||||
opts.Type = options.RedisSessionStoreType
|
||||
opts.Redis.ConnectionURL = "redis://127.0.0.1:" + mr.Port() // func (*Miniredis) StartTLS listens on 127.0.0.1
|
||||
opts.Redis.InsecureSkipTLSVerify = true
|
||||
opts.Redis.InsecureSkipTLSVerify = ptr.To(true)
|
||||
|
||||
// Capture the session store so that we can close the client
|
||||
var err error
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import (
|
|||
sessionscookie "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/sessions/cookie"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/sessions/persistence"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/sessions/redis"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
|
@ -44,8 +45,8 @@ var _ = Describe("NewSessionStore", func() {
|
|||
Path: "/",
|
||||
Expire: time.Duration(168) * time.Hour,
|
||||
Refresh: time.Duration(1) * time.Hour,
|
||||
Secure: true,
|
||||
HTTPOnly: true,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(true),
|
||||
SameSite: "",
|
||||
}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import (
|
|||
sessionsapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
|
||||
cookiesapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/cookies"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
|
@ -23,6 +24,7 @@ import (
|
|||
// Interfaces have to be wrapped in closures otherwise nil pointers are thrown.
|
||||
type testInput struct {
|
||||
cookieOpts *options.Cookie
|
||||
sessionOpts *options.SessionOptions
|
||||
ss sessionStoreFunc
|
||||
session *sessionsapi.SessionState
|
||||
request *http.Request
|
||||
|
|
@ -43,7 +45,6 @@ type NewSessionStoreFunc func(sessionOpts *options.SessionOptions, cookieOpts *o
|
|||
|
||||
func RunSessionStoreTests(newSS NewSessionStoreFunc, persistentFastForward PersistentStoreFastForwardFunc) {
|
||||
Describe("Session Store Suite", func() {
|
||||
var opts *options.SessionOptions
|
||||
var ss sessionsapi.SessionStore
|
||||
var input testInput
|
||||
var cookieSecret []byte
|
||||
|
|
@ -54,7 +55,9 @@ func RunSessionStoreTests(newSS NewSessionStoreFunc, persistentFastForward Persi
|
|||
|
||||
BeforeEach(func() {
|
||||
ss = nil
|
||||
opts = &options.SessionOptions{}
|
||||
sessionOpts := &options.SessionOptions{
|
||||
Refresh: time.Duration(1) * time.Hour,
|
||||
}
|
||||
|
||||
// A secret is required to create a Cipher, validation ensures it is the correct
|
||||
// length before a session store is initialised.
|
||||
|
|
@ -64,14 +67,13 @@ func RunSessionStoreTests(newSS NewSessionStoreFunc, persistentFastForward Persi
|
|||
|
||||
// Set default options in CookieOptions
|
||||
cookieOpts := &options.Cookie{
|
||||
Name: "_oauth2_proxy",
|
||||
Path: "/",
|
||||
Expire: time.Duration(168) * time.Hour,
|
||||
Refresh: time.Duration(1) * time.Hour,
|
||||
Secure: true,
|
||||
HTTPOnly: true,
|
||||
SameSite: "",
|
||||
Secret: string(cookieSecret),
|
||||
Name: "_oauth2_proxy",
|
||||
Path: "/",
|
||||
Expire: time.Duration(168) * time.Hour,
|
||||
Insecure: ptr.To(false),
|
||||
NotHttpOnly: ptr.To(false),
|
||||
SameSite: options.SameSiteDefault,
|
||||
Secret: options.SecretSource{Value: cookieSecret},
|
||||
}
|
||||
|
||||
expires := time.Now().Add(1 * time.Hour)
|
||||
|
|
@ -89,6 +91,7 @@ func RunSessionStoreTests(newSS NewSessionStoreFunc, persistentFastForward Persi
|
|||
|
||||
input = testInput{
|
||||
cookieOpts: cookieOpts,
|
||||
sessionOpts: sessionOpts,
|
||||
ss: getSessionStore,
|
||||
session: session,
|
||||
request: request,
|
||||
|
|
@ -100,7 +103,7 @@ func RunSessionStoreTests(newSS NewSessionStoreFunc, persistentFastForward Persi
|
|||
Context("with default options", func() {
|
||||
BeforeEach(func() {
|
||||
var err error
|
||||
ss, err = newSS(opts, input.cookieOpts)
|
||||
ss, err = newSS(input.sessionOpts, input.cookieOpts)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
|
|
@ -112,20 +115,20 @@ func RunSessionStoreTests(newSS NewSessionStoreFunc, persistentFastForward Persi
|
|||
|
||||
Context("with non-default options", func() {
|
||||
BeforeEach(func() {
|
||||
input.sessionOpts.Refresh = time.Duration(2) * time.Hour
|
||||
input.cookieOpts = &options.Cookie{
|
||||
Name: "_cookie_name",
|
||||
Path: "/path",
|
||||
Expire: time.Duration(72) * time.Hour,
|
||||
Refresh: time.Duration(2) * time.Hour,
|
||||
Secure: false,
|
||||
HTTPOnly: false,
|
||||
Domains: []string{"example.com"},
|
||||
SameSite: "strict",
|
||||
Secret: string(cookieSecret),
|
||||
Name: "_cookie_name",
|
||||
Path: "/path",
|
||||
Expire: time.Duration(72) * time.Hour,
|
||||
Insecure: ptr.To(true),
|
||||
NotHttpOnly: ptr.To(true),
|
||||
Domains: []string{"example.com"},
|
||||
SameSite: options.SameSiteStrict,
|
||||
Secret: options.SecretSource{Value: cookieSecret},
|
||||
}
|
||||
|
||||
var err error
|
||||
ss, err = newSS(opts, input.cookieOpts)
|
||||
ss, err = newSS(input.sessionOpts, input.cookieOpts)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
|
|
@ -144,18 +147,17 @@ func RunSessionStoreTests(newSS NewSessionStoreFunc, persistentFastForward Persi
|
|||
tmpfile.Write(secretBytes)
|
||||
tmpfile.Close()
|
||||
|
||||
input.sessionOpts.Refresh = time.Duration(1) * time.Hour
|
||||
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(),
|
||||
Name: "_oauth2_proxy_file",
|
||||
Path: "/",
|
||||
Expire: time.Duration(168) * time.Hour,
|
||||
Insecure: ptr.To(false),
|
||||
NotHttpOnly: ptr.To(false),
|
||||
SameSite: options.SameSiteDefault,
|
||||
Secret: options.SecretSource{FromFile: tmpfile.Name()},
|
||||
}
|
||||
ss, err = newSS(opts, input.cookieOpts)
|
||||
ss, err = newSS(input.sessionOpts, input.cookieOpts)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
|
|
@ -208,13 +210,13 @@ func CheckCookieOptions(in *testInput) {
|
|||
|
||||
It("have the correct HTTPOnly set", func() {
|
||||
for _, cookie := range cookies {
|
||||
Expect(cookie.HttpOnly).To(Equal(in.cookieOpts.HTTPOnly))
|
||||
Expect(cookie.HttpOnly).To(Equal(!(*in.cookieOpts.NotHttpOnly)))
|
||||
}
|
||||
})
|
||||
|
||||
It("have the correct secure set", func() {
|
||||
for _, cookie := range cookies {
|
||||
Expect(cookie.Secure).To(Equal(in.cookieOpts.Secure))
|
||||
Expect(cookie.Secure).To(Equal(!(*in.cookieOpts.Insecure)))
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -297,7 +299,7 @@ func PersistentSessionStoreInterfaceTests(in *testInput) {
|
|||
|
||||
Context("after the refresh period, but before the cookie expire period", func() {
|
||||
BeforeEach(func() {
|
||||
Expect(in.persistentFastForward(in.cookieOpts.Refresh + time.Minute)).To(Succeed())
|
||||
Expect(in.persistentFastForward(in.sessionOpts.Refresh + time.Minute)).To(Succeed())
|
||||
})
|
||||
|
||||
LoadSessionTests(in)
|
||||
|
|
@ -420,8 +422,13 @@ func SessionStoreInterfaceTests(in *testInput) {
|
|||
BeforeEach(func() {
|
||||
By("Using a valid cookie with a different providers session encoding")
|
||||
broken := "BrokenSessionFromADifferentSessionImplementation"
|
||||
value, err := encryption.SignedValue(in.cookieOpts.Secret, in.cookieOpts.Name, []byte(broken), time.Now())
|
||||
|
||||
cookieSecret, err := in.cookieOpts.GetSecret()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
value, err := encryption.SignedValue(cookieSecret, in.cookieOpts.Name, []byte(broken), time.Now())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
cookie := cookiesapi.MakeCookieFromOptions(in.request, in.cookieOpts.Name, value, in.cookieOpts, in.cookieOpts.Expire)
|
||||
in.request.AddCookie(cookie)
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ package validation
|
|||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
|
|
@ -11,13 +10,13 @@ import (
|
|||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption"
|
||||
)
|
||||
|
||||
func validateCookie(o options.Cookie) []string {
|
||||
msgs := validateCookieSecret(o.Secret, o.SecretFile)
|
||||
func validateCookie(o options.Cookie, refresh time.Duration) []string {
|
||||
msgs := validateCookieSecret(o.Secret)
|
||||
|
||||
if o.Expire != time.Duration(0) && o.Refresh >= o.Expire {
|
||||
if o.Expire != time.Duration(0) && refresh >= o.Expire {
|
||||
msgs = append(msgs, fmt.Sprintf(
|
||||
"cookie_refresh (%q) must be less than cookie_expire (%q)",
|
||||
o.Refresh.String(),
|
||||
refresh.String(),
|
||||
o.Expire.String()))
|
||||
}
|
||||
|
||||
|
|
@ -50,30 +49,17 @@ func validateCookieName(name string) []string {
|
|||
return msgs
|
||||
}
|
||||
|
||||
func validateCookieSecret(secret string, secretFile string) []string {
|
||||
if secret == "" && secretFile == "" {
|
||||
func validateCookieSecret(secret options.SecretSource) []string {
|
||||
if len(secret.Value) == 0 && secret.FromFile == "" {
|
||||
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)),
|
||||
}
|
||||
|
||||
value, err := secret.GetSecretValue()
|
||||
if err != nil {
|
||||
return []string{fmt.Sprintf("error retrieving cookie secret: %v", err)}
|
||||
}
|
||||
|
||||
secretBytes := encryption.SecretBytes(secret)
|
||||
secretBytes := encryption.SecretBytes(string(value))
|
||||
// Check if the secret is a valid length
|
||||
switch len(secretBytes) {
|
||||
case 16, 24, 32:
|
||||
|
|
|
|||
|
|
@ -7,6 +7,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/gomega"
|
||||
)
|
||||
|
||||
|
|
@ -66,8 +67,8 @@ func TestValidateCookie(t *testing.T) {
|
|||
Path: "",
|
||||
Expire: time.Hour,
|
||||
Refresh: 15 * time.Minute,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(false),
|
||||
SameSite: "",
|
||||
},
|
||||
errStrings: []string{},
|
||||
|
|
@ -81,8 +82,8 @@ func TestValidateCookie(t *testing.T) {
|
|||
Path: "",
|
||||
Expire: time.Hour,
|
||||
Refresh: 15 * time.Minute,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(false),
|
||||
SameSite: "",
|
||||
},
|
||||
errStrings: []string{
|
||||
|
|
@ -98,8 +99,8 @@ func TestValidateCookie(t *testing.T) {
|
|||
Path: "",
|
||||
Expire: time.Hour,
|
||||
Refresh: 15 * time.Minute,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(false),
|
||||
SameSite: "",
|
||||
},
|
||||
errStrings: []string{
|
||||
|
|
@ -115,8 +116,8 @@ func TestValidateCookie(t *testing.T) {
|
|||
Path: "",
|
||||
Expire: time.Hour,
|
||||
Refresh: 15 * time.Minute,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(false),
|
||||
SameSite: "",
|
||||
},
|
||||
errStrings: []string{},
|
||||
|
|
@ -130,8 +131,8 @@ func TestValidateCookie(t *testing.T) {
|
|||
Path: "",
|
||||
Expire: time.Hour,
|
||||
Refresh: 15 * time.Minute,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(false),
|
||||
SameSite: "",
|
||||
},
|
||||
errStrings: []string{
|
||||
|
|
@ -147,8 +148,8 @@ func TestValidateCookie(t *testing.T) {
|
|||
Path: "",
|
||||
Expire: time.Hour,
|
||||
Refresh: 15 * time.Minute,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(false),
|
||||
SameSite: "",
|
||||
},
|
||||
errStrings: []string{
|
||||
|
|
@ -164,8 +165,8 @@ func TestValidateCookie(t *testing.T) {
|
|||
Path: "",
|
||||
Expire: time.Hour,
|
||||
Refresh: 15 * time.Minute,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(false),
|
||||
SameSite: "",
|
||||
},
|
||||
errStrings: []string{
|
||||
|
|
@ -181,8 +182,8 @@ func TestValidateCookie(t *testing.T) {
|
|||
Path: "",
|
||||
Expire: 15 * time.Minute,
|
||||
Refresh: time.Hour,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(false),
|
||||
SameSite: "",
|
||||
},
|
||||
errStrings: []string{
|
||||
|
|
@ -198,8 +199,8 @@ func TestValidateCookie(t *testing.T) {
|
|||
Path: "",
|
||||
Expire: time.Hour,
|
||||
Refresh: 15 * time.Minute,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(false),
|
||||
SameSite: "none",
|
||||
},
|
||||
errStrings: []string{},
|
||||
|
|
@ -213,8 +214,8 @@ func TestValidateCookie(t *testing.T) {
|
|||
Path: "",
|
||||
Expire: time.Hour,
|
||||
Refresh: 15 * time.Minute,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(false),
|
||||
SameSite: "none",
|
||||
},
|
||||
errStrings: []string{},
|
||||
|
|
@ -228,8 +229,8 @@ func TestValidateCookie(t *testing.T) {
|
|||
Path: "",
|
||||
Expire: time.Hour,
|
||||
Refresh: 15 * time.Minute,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(false),
|
||||
SameSite: "none",
|
||||
},
|
||||
errStrings: []string{},
|
||||
|
|
@ -243,8 +244,8 @@ func TestValidateCookie(t *testing.T) {
|
|||
Path: "",
|
||||
Expire: time.Hour,
|
||||
Refresh: 15 * time.Minute,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(false),
|
||||
SameSite: "invalid",
|
||||
},
|
||||
errStrings: []string{
|
||||
|
|
@ -260,8 +261,8 @@ func TestValidateCookie(t *testing.T) {
|
|||
Path: "",
|
||||
Expire: 15 * time.Minute,
|
||||
Refresh: time.Hour,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(false),
|
||||
SameSite: "invalid",
|
||||
},
|
||||
errStrings: []string{
|
||||
|
|
@ -280,8 +281,8 @@ func TestValidateCookie(t *testing.T) {
|
|||
Path: "",
|
||||
Expire: 0,
|
||||
Refresh: 15 * time.Minute,
|
||||
Secure: true,
|
||||
HTTPOnly: false,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(false),
|
||||
SameSite: "",
|
||||
},
|
||||
errStrings: []string{},
|
||||
|
|
@ -296,8 +297,8 @@ func TestValidateCookie(t *testing.T) {
|
|||
Path: "",
|
||||
Expire: 24 * time.Hour,
|
||||
Refresh: 0,
|
||||
Secure: true,
|
||||
HTTPOnly: true,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(true),
|
||||
SameSite: "",
|
||||
},
|
||||
errStrings: []string{},
|
||||
|
|
@ -312,8 +313,8 @@ func TestValidateCookie(t *testing.T) {
|
|||
Path: "",
|
||||
Expire: 24 * time.Hour,
|
||||
Refresh: 0,
|
||||
Secure: true,
|
||||
HTTPOnly: true,
|
||||
Secure: ptr.To(true),
|
||||
HTTPOnly: ptr.To(true),
|
||||
SameSite: "",
|
||||
},
|
||||
errStrings: []string{"could not read cookie secret file: /nonexistent/file.txt"},
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ import (
|
|||
// Validate checks that required options are set and validates those that they
|
||||
// are of the correct format
|
||||
func Validate(o *options.Options) error {
|
||||
msgs := validateCookie(o.Cookie)
|
||||
msgs := validateCookie(o.Cookie, o.Session.Refresh)
|
||||
msgs = append(msgs, validateSessionCookieMinimal(o)...)
|
||||
msgs = append(msgs, validateRedisSessionStore(o)...)
|
||||
msgs = append(msgs, prefixValues("injectRequestHeaders: ", validateHeaders(o.InjectRequestHeaders)...)...)
|
||||
|
|
@ -74,7 +74,7 @@ func Validate(o *options.Options) error {
|
|||
var redirectURL *url.URL
|
||||
redirectURL, msgs = parseURL(o.RawRedirectURL, "redirect", msgs)
|
||||
o.SetRedirectURL(redirectURL)
|
||||
if o.RawRedirectURL == "" && !o.Cookie.Secure && !o.ReverseProxy {
|
||||
if o.RawRedirectURL == "" && ptr.Deref(o.Cookie.Insecure, options.DefaultCookieInsecure) && !o.ReverseProxy {
|
||||
logger.Print("WARNING: no explicit redirect URL: redirects will default to insecure HTTP")
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ func testOptions() *options.Options {
|
|||
o.Providers[0].ClientID = clientID
|
||||
o.Providers[0].ClientSecret = clientSecret
|
||||
o.EmailDomains = []string{"*"}
|
||||
o.EnsureDefaults()
|
||||
return o
|
||||
}
|
||||
|
||||
|
|
@ -45,6 +46,8 @@ func errorMsg(msgs []string) string {
|
|||
func TestNewOptions(t *testing.T) {
|
||||
o := options.NewOptions()
|
||||
o.EmailDomains = []string{"*"}
|
||||
o.EnsureDefaults()
|
||||
|
||||
err := Validate(o)
|
||||
assert.NotEqual(t, nil, err)
|
||||
|
||||
|
|
@ -123,10 +126,10 @@ func TestCookieRefreshMustBeLessThanCookieExpire(t *testing.T) {
|
|||
assert.Equal(t, nil, Validate(o))
|
||||
|
||||
o.Cookie.Secret = "0123456789abcdef"
|
||||
o.Cookie.Refresh = o.Cookie.Expire
|
||||
o.Session.Refresh = o.Cookie.Expire
|
||||
assert.NotEqual(t, nil, Validate(o))
|
||||
|
||||
o.Cookie.Refresh -= time.Duration(1)
|
||||
o.Session.Refresh -= time.Duration(1)
|
||||
assert.Equal(t, nil, Validate(o))
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -9,10 +9,11 @@ import (
|
|||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/sessions/redis"
|
||||
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util/ptr"
|
||||
)
|
||||
|
||||
func validateSessionCookieMinimal(o *options.Options) []string {
|
||||
if !o.Session.Cookie.Minimal {
|
||||
if !ptr.Deref(o.Session.Cookie.Minimal, options.DefaultCookieStoreMinimal) {
|
||||
return []string{}
|
||||
}
|
||||
|
||||
|
|
@ -32,7 +33,7 @@ func validateSessionCookieMinimal(o *options.Options) []string {
|
|||
}
|
||||
}
|
||||
|
||||
if o.Cookie.Refresh != time.Duration(0) {
|
||||
if o.Session.Refresh != time.Duration(0) {
|
||||
msgs = append(msgs,
|
||||
"cookie_refresh > 0 requires oauth tokens in sessions. session_cookie_minimal cannot be set")
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue